diff --git "a/4471.jsonl" "b/4471.jsonl" new file mode 100644--- /dev/null +++ "b/4471.jsonl" @@ -0,0 +1,635 @@ +{"seq_id":"327386746","text":"\"\"\"使用requests和bs4 抓取豆瓣top250\"\"\"\n'''\n@Time : 2018/3/2 下午2:42\n@Author : scrappy_zhang\n@File : douban_top250_spider_requests_bs4.py\n'''\n\nimport codecs\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\nDOWNLOAD_URL = 'http://movie.douban.com/top250/'\n\n\ndef download_page(url):\n # 下载网页\n return requests.get(url, headers={\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36',\n }).content\n\n\ndef parse_html(html):\n \"\"\"\n 解析网页\n :param html:\n :return: 电影名称列表\n \"\"\"\n soup = BeautifulSoup(html, 'html')\n movie_list_soup = soup.find('ol', attrs={'class': 'grid_view'})\n\n movie_list = []\n\n for movie_li in movie_list_soup.find_all('li'):\n # 排名\n ranking = movie_li.find('div', attrs={'class': 'pic'}).find('em').getText()\n # 电影名称\n detail = movie_li.find('div', attrs={'class': 'hd'})\n movie_name = detail.find('span', attrs={'class': 'title'}).getText()\n # 电影得分\n detail = movie_li.find('div', attrs={'class': 'star'})\n movie_score = detail.find('span', attrs={'class': 'rating_num'}).getText()\n # 电影评论数\n comment = detail.getText()\n # print(comment)\n comment_num = re.search(r'(\\d+)人评价', comment).group(1)\n # 电影豆瓣链接\n movie_link = movie_li.find('div', attrs={'class': 'hd'}).find('a')['href']\n movie = [ranking, movie_name, movie_score, comment_num, movie_link,]\n movie_list.append(movie)\n\n next_page = soup.find('span', attrs={'class': 'next'}).find('a')\n if next_page:\n return movie_list, DOWNLOAD_URL + next_page['href']\n return movie_list, None\n\n\ndef main():\n url = DOWNLOAD_URL\n import time\n\n with codecs.open('douban_top250_info.csv', 'wb', encoding='utf-8') as fp:\n fp.write('排名,电影名称,豆瓣得分,评论数,电影豆瓣链接,\\n')\n while url:\n time.sleep(0.5)\n html = download_page(url)\n movie_list, url = parse_html(html)\n for movie_info in movie_list:\n line_info = ''\n for info in movie_info:\n line_info += info + ','\n print(line_info)\n fp.write(u'{line_info}\\n'.format(line_info=line_info))\n print('done!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"douban_top250_spider_requests_bs4.py","file_name":"douban_top250_spider_requests_bs4.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"388594284","text":"from rcon import train_rcon\nimport numpy as np\ndef forward(N,ans):\n tr=50\n EEE=np.zeros((6,tr))\n NN=np.zeros(tr)\n ac=np.zeros(tr)\n for i in range (0,tr):\n EE,NNN,Num,acc=train_rcon(200,N,ans)\n EEE[:,i]=EE\n NN[i]=NNN\n ac[i]=acc\n print(np.argsort(np.average(EEE,axis=1)))\n print(np.where(NN==ans)[0].size)\n print(np.average(EEE,axis=1)[ans]/EEE.mean())\n print(ac.mean())\n np.save('Data/'+N+str('EEE_rnn_1')+'.npy',EEE)\n np.save('Data/'+N+str('NN_rnn_1')+'.npy',NN)\n np.save('Data/'+N+str('ac_rnn_1')+'.npy',ac)","sub_path":"RNN integrated/rnn_forward.py","file_name":"rnn_forward.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"99188787","text":"\"\"\"\nType annotations for license-manager-user-subscriptions service client.\n\n[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html)\n\nUsage::\n\n ```python\n import boto3\n from mypy_boto3_license_manager_user_subscriptions import LicenseManagerUserSubscriptionsClient\n\n client: LicenseManagerUserSubscriptionsClient = boto3.client(\"license-manager-user-subscriptions\")\n ```\n\"\"\"\nimport sys\nfrom typing import Any, Dict, List, Type, overload\n\nfrom botocore.client import BaseClient, ClientMeta\n\nfrom .paginator import (\n ListIdentityProvidersPaginator,\n ListInstancesPaginator,\n ListProductSubscriptionsPaginator,\n ListUserAssociationsPaginator,\n)\nfrom .type_defs import (\n AssociateUserResponseTypeDef,\n DeregisterIdentityProviderResponseTypeDef,\n DisassociateUserResponseTypeDef,\n FilterTypeDef,\n IdentityProviderTypeDef,\n ListIdentityProvidersResponseTypeDef,\n ListInstancesResponseTypeDef,\n ListProductSubscriptionsResponseTypeDef,\n ListUserAssociationsResponseTypeDef,\n RegisterIdentityProviderResponseTypeDef,\n SettingsTypeDef,\n StartProductSubscriptionResponseTypeDef,\n StopProductSubscriptionResponseTypeDef,\n UpdateIdentityProviderSettingsResponseTypeDef,\n UpdateSettingsTypeDef,\n)\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\n__all__ = (\"LicenseManagerUserSubscriptionsClient\",)\n\nclass BotocoreClientError(BaseException):\n MSG_TEMPLATE: str\n\n def __init__(self, error_response: Dict[str, Any], operation_name: str) -> None:\n self.response: Dict[str, Any]\n self.operation_name: str\n\nclass Exceptions:\n AccessDeniedException: Type[BotocoreClientError]\n ClientError: Type[BotocoreClientError]\n ConflictException: Type[BotocoreClientError]\n InternalServerException: Type[BotocoreClientError]\n ResourceNotFoundException: Type[BotocoreClientError]\n ServiceQuotaExceededException: Type[BotocoreClientError]\n ThrottlingException: Type[BotocoreClientError]\n ValidationException: Type[BotocoreClientError]\n\nclass LicenseManagerUserSubscriptionsClient(BaseClient):\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html)\n \"\"\"\n\n meta: ClientMeta\n\n @property\n def exceptions(self) -> Exceptions:\n \"\"\"\n LicenseManagerUserSubscriptionsClient exceptions.\n \"\"\"\n def associate_user(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n InstanceId: str,\n Username: str,\n Domain: str = None\n ) -> AssociateUserResponseTypeDef:\n \"\"\"\n Associates the user to an EC2 instance to utilize user-based subscriptions.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.associate_user)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#associate_user)\n \"\"\"\n def can_paginate(self, operation_name: str) -> bool:\n \"\"\"\n Check if an operation can be paginated.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.can_paginate)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#can_paginate)\n \"\"\"\n def close(self) -> None:\n \"\"\"\n Closes underlying endpoint connections.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.close)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#close)\n \"\"\"\n def deregister_identity_provider(\n self, *, IdentityProvider: \"IdentityProviderTypeDef\", Product: str\n ) -> DeregisterIdentityProviderResponseTypeDef:\n \"\"\"\n Deregisters the identity provider from providing user-based subscriptions.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.deregister_identity_provider)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#deregister_identity_provider)\n \"\"\"\n def disassociate_user(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n InstanceId: str,\n Username: str,\n Domain: str = None\n ) -> DisassociateUserResponseTypeDef:\n \"\"\"\n Disassociates the user from an EC2 instance providing user-based subscriptions.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.disassociate_user)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#disassociate_user)\n \"\"\"\n def generate_presigned_url(\n self,\n ClientMethod: str,\n Params: Dict[str, Any] = None,\n ExpiresIn: int = 3600,\n HttpMethod: str = None,\n ) -> str:\n \"\"\"\n Generate a presigned url given a client, its method, and arguments.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.generate_presigned_url)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#generate_presigned_url)\n \"\"\"\n def list_identity_providers(\n self, *, MaxResults: int = None, NextToken: str = None\n ) -> ListIdentityProvidersResponseTypeDef:\n \"\"\"\n Lists the identity providers for user-based subscriptions.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.list_identity_providers)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#list_identity_providers)\n \"\"\"\n def list_instances(\n self,\n *,\n Filters: List[\"FilterTypeDef\"] = None,\n MaxResults: int = None,\n NextToken: str = None\n ) -> ListInstancesResponseTypeDef:\n \"\"\"\n Lists the EC2 instances providing user-based subscriptions.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.list_instances)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#list_instances)\n \"\"\"\n def list_product_subscriptions(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n Product: str,\n Filters: List[\"FilterTypeDef\"] = None,\n MaxResults: int = None,\n NextToken: str = None\n ) -> ListProductSubscriptionsResponseTypeDef:\n \"\"\"\n Lists the user-based subscription products available from an identity provider.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.list_product_subscriptions)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#list_product_subscriptions)\n \"\"\"\n def list_user_associations(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n InstanceId: str,\n Filters: List[\"FilterTypeDef\"] = None,\n MaxResults: int = None,\n NextToken: str = None\n ) -> ListUserAssociationsResponseTypeDef:\n \"\"\"\n Lists user associations for an identity provider.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.list_user_associations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#list_user_associations)\n \"\"\"\n def register_identity_provider(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n Product: str,\n Settings: \"SettingsTypeDef\" = None\n ) -> RegisterIdentityProviderResponseTypeDef:\n \"\"\"\n Registers an identity provider for user-based subscriptions.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.register_identity_provider)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#register_identity_provider)\n \"\"\"\n def start_product_subscription(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n Product: str,\n Username: str,\n Domain: str = None\n ) -> StartProductSubscriptionResponseTypeDef:\n \"\"\"\n Starts a product subscription for a user with the specified identity provider.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.start_product_subscription)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#start_product_subscription)\n \"\"\"\n def stop_product_subscription(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n Product: str,\n Username: str,\n Domain: str = None\n ) -> StopProductSubscriptionResponseTypeDef:\n \"\"\"\n Stops a product subscription for a user with the specified identity provider.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.stop_product_subscription)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#stop_product_subscription)\n \"\"\"\n def update_identity_provider_settings(\n self,\n *,\n IdentityProvider: \"IdentityProviderTypeDef\",\n Product: str,\n UpdateSettings: \"UpdateSettingsTypeDef\"\n ) -> UpdateIdentityProviderSettingsResponseTypeDef:\n \"\"\"\n Updates additional product configuration settings for the registered identity\n provider.\n\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Client.update_identity_provider_settings)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/client.html#update_identity_provider_settings)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_identity_providers\"]\n ) -> ListIdentityProvidersPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Paginator.ListIdentityProviders)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/paginators.html#listidentityproviderspaginator)\n \"\"\"\n @overload\n def get_paginator(self, operation_name: Literal[\"list_instances\"]) -> ListInstancesPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Paginator.ListInstances)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/paginators.html#listinstancespaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_product_subscriptions\"]\n ) -> ListProductSubscriptionsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Paginator.ListProductSubscriptions)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/paginators.html#listproductsubscriptionspaginator)\n \"\"\"\n @overload\n def get_paginator(\n self, operation_name: Literal[\"list_user_associations\"]\n ) -> ListUserAssociationsPaginator:\n \"\"\"\n [Show boto3 documentation](https://boto3.amazonaws.com/v1/documentation/api/1.26.45/reference/services/license-manager-user-subscriptions.html#LicenseManagerUserSubscriptions.Paginator.ListUserAssociations)\n [Show boto3-stubs documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_license_manager_user_subscriptions/paginators.html#listuserassociationspaginator)\n \"\"\"\n","sub_path":"typings/mypy_boto3_license_manager_user_subscriptions/client.pyi","file_name":"client.pyi","file_ext":"pyi","file_size_in_byte":14318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"345833675","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^connect/$', views.connect, name='connect'),\n url(r'^callback/$', views.callback, name='callback'),\n url(r'^blocked/$', views.blocked, name='blocked'),\n]\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"293587378","text":"from flask import url_for\n\ndef make_public_cust(cust):\n new_cust = {}\n for field in cust:\n if field == 'id':\n new_cust['uri'] = url_for('get_cust', cust_id = cust['id'], _external = True)\n new_cust['id'] = cust['id']\n else:\n new_cust[field] = cust[field]\n return new_cust\n\n\ndef values_missing(data):\n for key in ['name', 'street', 'city', 'state', 'contact1', 'phone1', 'zip']:\n if key not in data:\n return True\n return False\n","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"62794221","text":"from conans import ConanFile, CMake, tools\nimport os\n\nclass EmbreeConan(ConanFile):\n name = \"embree\"\n version = \"3.9.0\"\n license = \"Apache 2.0 license\"\n url = \"embree.org\"\n description = \"High Performance Ray Tracing Kernels\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False], \"fPIC\": [True, False]}\n requires = \"tbb/2020.02@mercseng/v2\"\n default_options = \"shared=True\", \"fPIC=True\", \"TBB:shared=True\"\n exports_sources = \"CMakeLists.txt\"\n generators = \"cmake\"\n _source_subfolder = \"source_subfolder\"\n recipe_version=\"v2\"\n\n def config_options(self):\n \"\"\"fPIC is linux only.\"\"\"\n if self.settings.os != \"Linux\":\n self.options.remove(\"fPIC\")\n\n def source(self):\n \"\"\"Retrieve source code.\"\"\"\n tools.get(\"https://github.com/embree/embree/archive/v%s.tar.gz\" % self.version)\n os.rename(\"embree-%s\" % self.version, self._source_subfolder)\n\n def cmake_definitions(self):\n \"\"\"Setup CMake definitions.\"\"\"\n definition_dict = {\n \"CMAKE_BUILD_TYPE\": self.settings.build_type,\n \"BUILD_TESTING\": False,\n \"EMBREE_TUTORIALS\": False, # Don't pull in GLFW and IMGUI\n \"EMBREE_STATIC_LIB\": not self.options.shared,\n \"EMBREE_IGNORE_CMAKE_CXX_FLAGS\": False,\n \"EMBREE_TASKING_SYSTEM\": \"TBB\",\n \"EMBREE_MAX_ISA\": \"AVX2\", # avx512KNL does not compile on windows\n \"EMBREE_ISPC_SUPPORT\": True,\n #\"EMBREE_RAY_MASK\": True,\n #\"EMBREE_BACKFACE_CULLING\": True,\n #\"EMBREE_FILTER_FUNCTION\": True,\n #\"EMBREE_IGNORE_INVALID_RAYS\": False,\n #\"EMBREE_GEOMETRY_TRIANGLE\": True,\n #\"EMBREE_GEOMETRY_QUAD\": True,\n #\"EMBREE_GEOMETRY_CURVE\": True,\n #\"EMBREE_GEOMETRY_SUBDIVISION\": True,\n #\"EMBREE_GEOMETRY_USER\": True,\n #\"EMBREE_GEOMETRY_INSTANCE\": True,\n #\"EMBREE_GEOMETRY_GRID\": True,\n #\"EMBREE_GEOMETRY_POINT\": True,\n #\"EMBREE_RAY_PACKETS\": True,\n #\"EMBREE_MAX_INSTANCE_LEVEL_COUNT\": \"1\",\n \"EMBREE_CURVE_SELF_INTERSECTION_AVOIDANCE_FACTOR\": \"0\",\n \"EMBREE_TBB_DEBUG_POSTFIX\" : \"\"\n }\n\n # Prevent compiler stack overflow: https://github.com/embree/embree/issues/157\n if self.settings.compiler == 'Visual Studio' and self.settings.compiler.version == 14 and self.settings.build_type == \"Release\":\n definition_dict[\"CMAKE_CXX_FLAGS\"] = \"-d2SSAOptimizer-\"\n\n return definition_dict \n\n def build(self):\n \"\"\"Build the elements to package.\"\"\"\n cmake = CMake(self)\n cmake.configure(defs = self.cmake_definitions())\n cmake.build()\n\n def package(self):\n \"\"\"Assemble the package.\"\"\"\n self.copy(\"*.h\", src=\"%s/include/embree3\" %self._source_subfolder, dst=\"include/embree3/\")\n self.copy(\"*.h\", src=\"%s/common\" %self._source_subfolder, dst=\"common\")\n self.copy(\"*.h\", src=\"%s/kernels\"%self._source_subfolder, dst=\"kernels\")\n\n if self.settings.os == \"Windows\":\n if self.options.shared:\n self.copy(\"*/embree3.dll\", dst=\"bin/\", keep_path=False)\n\n self.copy(\"*/algorithms.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/embree_avx.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/embree_avx2.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/embree_sse42.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/embree3.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/lexers.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/math.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/simd.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/sys.lib\", dst=\"lib/\", keep_path=False)\n self.copy(\"*/tasking.lib\", dst=\"lib/\", keep_path=False)\n else:\n if self.options.shared:\n self.copy(\"lib/libembree3.so*\", dst=\"lib/\", keep_path=False)\n else:\n self.copy(\"lib/libembree3.a\", dst=\"lib/\", keep_path=False)\n\n self.copy(\"lib/libembree_avx.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/libembree_avx2.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/libembree_sse42.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/liblexers.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/libmath.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/libsimd.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/libsys.a\", dst=\"lib/\", keep_path=False)\n self.copy(\"lib/libtasking.a\", dst=\"lib/\", keep_path=False)\n\n def package_info(self):\n \"\"\"Edit package info.\"\"\"\n self.cpp_info.libs = tools.collect_libs(self)\n self.cpp_info.defines.append(\"TASKING_TBB\")\n if self.options.shared:\n if self.settings.os == \"Windows\":\n self.env_info.PATH.append(os.path.join( self.package_folder, \"bin\"))\n else:\n self.env_info.LD_LIBRARY_PATH.append(os.path.join(self.package_folder, \"lib\")) \n","sub_path":"embree_3.9.0/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":5146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"565983880","text":"n = int(input())\nwork = []\nfor _ in range(n):\n work.append(tuple(map(int,input().split())))\n\ndp =[]\nworkfinish = 0\n\nfor i in range(n):\n money = work[i][2]\n workfinish = work[i][1]\n for j in range(i+1,n):\n if workfinish 0:\n cc.append(z)\n \n return cc \n \n############################################################### \n \n\n \nspectrum = readSpectrum(\"input.dat\")\ncc = convolution(spectrum)\nfor c in cc:\n print(c,end=\" \")\n \n\n","sub_path":"p2-6.py","file_name":"p2-6.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"172277319","text":"\"\"\"Support for tracking the moon phases.\"\"\"\nfrom astral import moon\nimport voluptuous as vol\n\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity\nfrom homeassistant.const import CONF_NAME\nimport homeassistant.helpers.config_validation as cv\nimport homeassistant.util.dt as dt_util\n\nDEFAULT_NAME = \"Moon\"\n\nSTATE_FIRST_QUARTER = \"first_quarter\"\nSTATE_FULL_MOON = \"full_moon\"\nSTATE_LAST_QUARTER = \"last_quarter\"\nSTATE_NEW_MOON = \"new_moon\"\nSTATE_WANING_CRESCENT = \"waning_crescent\"\nSTATE_WANING_GIBBOUS = \"waning_gibbous\"\nSTATE_WAXING_GIBBOUS = \"waxing_gibbous\"\nSTATE_WAXING_CRESCENT = \"waxing_crescent\"\n\nMOON_ICONS = {\n STATE_FIRST_QUARTER: \"mdi:moon-first-quarter\",\n STATE_FULL_MOON: \"mdi:moon-full\",\n STATE_LAST_QUARTER: \"mdi:moon-last-quarter\",\n STATE_NEW_MOON: \"mdi:moon-new\",\n STATE_WANING_CRESCENT: \"mdi:moon-waning-crescent\",\n STATE_WANING_GIBBOUS: \"mdi:moon-waning-gibbous\",\n STATE_WAXING_CRESCENT: \"mdi:moon-waxing-crescent\",\n STATE_WAXING_GIBBOUS: \"mdi:moon-waxing-gibbous\",\n}\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string}\n)\n\n\nasync def async_setup_platform(hass, config, async_add_entities, discovery_info=None):\n \"\"\"Set up the Moon sensor.\"\"\"\n name = config.get(CONF_NAME)\n\n async_add_entities([MoonSensor(name)], True)\n\n\nclass MoonSensor(SensorEntity):\n \"\"\"Representation of a Moon sensor.\"\"\"\n\n def __init__(self, name):\n \"\"\"Initialize the moon sensor.\"\"\"\n self._name = name\n self._state = None\n\n @property\n def name(self):\n \"\"\"Return the name of the entity.\"\"\"\n return self._name\n\n @property\n def device_class(self):\n \"\"\"Return the device class of the entity.\"\"\"\n return \"moon__phase\"\n\n @property\n def state(self):\n \"\"\"Return the state of the device.\"\"\"\n if self._state == 0:\n return STATE_NEW_MOON\n if self._state < 7:\n return STATE_WAXING_CRESCENT\n if self._state == 7:\n return STATE_FIRST_QUARTER\n if self._state < 14:\n return STATE_WAXING_GIBBOUS\n if self._state == 14:\n return STATE_FULL_MOON\n if self._state < 21:\n return STATE_WANING_GIBBOUS\n if self._state == 21:\n return STATE_LAST_QUARTER\n return STATE_WANING_CRESCENT\n\n @property\n def icon(self):\n \"\"\"Icon to use in the frontend, if any.\"\"\"\n return MOON_ICONS.get(self.state)\n\n async def async_update(self):\n \"\"\"Get the time and updates the states.\"\"\"\n today = dt_util.as_local(dt_util.utcnow()).date()\n self._state = moon.phase(today)\n","sub_path":"homeassistant/components/moon/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"652389468","text":"import functools\nimport logging\nimport math\nfrom datetime import datetime\nfrom binance.client import Client, AsyncClient\nfrom binance import enums\nfrom decimal import Decimal\nfrom project_core.vigilant_crypto.coin.crypto_coin import CrpytoCoin\nlogger = logging.getLogger(__name__)\n\n\nclass BinanceBase:\n def __init__(self, keyless=True, api_key=None, client_secret=None, compare_against=\"ETH\"):\n \"\"\"\n Instantiates a client object.\n :param keyless: bool, if the object only requires non-user specific info\n :param api_key: str, api_key from the user for authentication\n :param client_secret: client_Secret from the Binance user\n :param compare_against: str Reference coin (Typically BTC or ETH)\n \"\"\"\n if type(self) == BinanceAsync:\n binance_object = AsyncClient\n elif type(self) == BinanceSync:\n binance_object = Client\n else:\n raise ValueError(\"Unknown type of class object\")\n if keyless is True:\n self.client_object = binance_object(\"\", \"\")\n else:\n self.client_object = binance_object(api_key, client_secret)\n self.reference_coin = compare_against\n logger.info(\"Generated the binance object\")\n\n\nclass BinanceSync(BinanceBase):\n \"\"\"Binance Object which stores the binance client object.\n Warning: Do not store the api_key and client_secret in plain-text\n especially if you are uploading them in source-code repositories\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(BinanceSync, self).__init__(*args, **kwargs)\n\n @functools.lru_cache(maxsize=2)\n def get_all_tickers(self):\n \"\"\"\n Get all binance tickers (BTC, ETH and everything).\n Also returns the current price of that ticker\n :return: all binance tickers as a list of dicts {\"symbol: .. , \"price\": ..}\n \"\"\"\n return self.client_object.get_all_tickers()\n\n # TODO Deprecate this as it is too specific. And does 2 tasks\n @functools.lru_cache(maxsize=10)\n def get_eth_tickers(self):\n \"\"\"\n Filters out the xxxxETH tickers from the whole list\n :return: list of CryptoCoins coins with key as the coin name\n and value the current price against ETH in last of dicts\n \"\"\"\n all_tickers = self.get_all_tickers()\n all_eth_tickers = []\n for ticker in all_tickers:\n if ticker['symbol'][-3:] == self.reference_coin:\n all_eth_tickers.append(CrpytoCoin(ticker['symbol'][:-3], ticker['price']))\n return all_eth_tickers\n\n def get_tradeable_coins(self):\n all_available_tickers = self.client_object.get_all_tickers()\n tradeable_coins = []\n for ticker in all_available_tickers:\n if ticker['symbol'][-3:] == self.reference_coin:\n tradeable_coins.append(ticker['symbol'][:-3])\n return tradeable_coins\n\n def get_open_buy_sell_orders(self):\n \"\"\"Returns a tuple of list of all open buy orders and sell orders\"\"\"\n orders = self.client_object.get_open_orders()\n buy_orders = [order for order in orders if order['side'] == \"BUY\"]\n sell_orders = [order for order in orders if order['side'] == \"SELL\"]\n return buy_orders, sell_orders\n\n def cancel_order(self, ticker, order_id):\n \"\"\"Cancels an order by ticker and order_id\"\"\"\n cancel_response = self.client_object.cancel_order(symbol=ticker, orderId=order_id)\n if cancel_response['status'] == \"CANCELED\":\n logger.info(f\"The order for ticker {ticker} with orderId {order_id} was cancelled\")\n return cancel_response\n else:\n raise BrokenPipeError(f\"The order for ticker {ticker} with orderId {order_id} could not be cancelled\")\n\n def get_all_assets(self):\n \"\"\"Get the list of assets locked and free\"\"\"\n assets = self.client_object.get_account()['balances']\n assets = [asset for asset in assets if not (float(asset['free']) == 0 and float(asset['locked']) == 0)]\n return assets\n\n def get_significant_assets(self, btc_limit):\n \"\"\"Gets the list of assets worth more than btc_limit\"\"\"\n all_assets = self.get_all_assets()\n significant_assets = []\n tradable_coins = self.get_tradeable_coins()\n if \"ETH\" in tradable_coins: tradable_coins.remove(\"ETH\")\n for asset in all_assets:\n # We do not handle when ETH is held because ETH/BTC does not exist. Only the other way around\n if asset[\"asset\"] in tradable_coins or asset[\"asset\"] == self.reference_coin:\n if self.is_asset_significant(asset, btc_limit, [\"free\", \"locked\"]):\n significant_assets.append(asset)\n return significant_assets\n\n def get_total_worth_of_significant_assets(self, significant_assets):\n \"\"\"Gets the total worth of all significant assets in terms of ETH/BTC.\n Note that dust is not used for this calculation\"\"\"\n total_reference_asset = 0\n for significant_asset in significant_assets:\n asset_of_coin = float(significant_asset['free'])+float(significant_asset['locked'])\n total_reference_asset += asset_of_coin*self.get_live_price(significant_asset['asset'])\n logger.info(f\"You currently hold assets worth {total_reference_asset} {self.reference_coin}\")\n return total_reference_asset\n\n def get_all_orders(self, ticker):\n \"\"\"Gets all the orders made for the ticker\"\"\"\n all_orders = self.client_object.get_all_orders(symbol=ticker)\n return all_orders\n\n def sanitize_quantity_pre_order(self, coin_name, quantity):\n \"\"\"Sanitizes the quantity before setting the order\"\"\"\n coin_filters = self.client_object.get_symbol_info(f\"{coin_name}{self.reference_coin}\")['filters']\n for coin_filter in coin_filters:\n if coin_filter[\"filterType\"] == \"LOT_SIZE\":\n step_size = float(coin_filter[\"stepSize\"])\n minimum_quantity = float(coin_filter[\"minQty\"])\n maximum_quantity = float(coin_filter[\"maxQty\"])\n if quantity > maximum_quantity or quantity < minimum_quantity:\n raise ValueError(f\"An order of quantity: {quantity} is not going to work with coin {coin_name}\")\n round_up_int = math.floor((quantity - minimum_quantity) / step_size)\n corrected_quantity = round_up_int * step_size + minimum_quantity\n rounded_quantity = round(corrected_quantity, 8)\n return rounded_quantity\n\n def sanitize_price_pre_order(self, coin_name, price):\n \"\"\"Sanitizes the price before setting the order\"\"\"\n coin_filters = self.client_object.get_symbol_info(f\"{coin_name}{self.reference_coin}\")['filters']\n for coin_filter in coin_filters:\n if coin_filter[\"filterType\"] == \"PRICE_FILTER\":\n tick_size = float(coin_filter[\"tickSize\"])\n minimum_price = float(coin_filter[\"minPrice\"])\n maximum_price = float(coin_filter[\"maxPrice\"])\n if price >= maximum_price or price <= minimum_price:\n raise ValueError(f\"An order of price: {price} is not going to work with coin {coin_name}\")\n round_up_int = round((price - minimum_price) / tick_size)\n corrected_price = round_up_int * tick_size + minimum_price\n rounded_price = round(corrected_price, 8)\n decimal = Decimal(repr(float(rounded_price)))\n price_string = f\"{decimal:.16f}\".rstrip(\"0\")\n return price_string\n\n def confirm_min_notion(self, coin_name, quantity, price=None):\n if price is None:\n price = self.get_live_price(coin_name)\n notional_value = price * quantity\n coin_filters = self.client_object.get_symbol_info(f\"{coin_name}{self.reference_coin}\")['filters']\n for coin_filter in coin_filters:\n if coin_filter[\"filterType\"] == \"MIN_NOTIONAL\":\n if notional_value < float(coin_filter[\"minNotional\"]):\n raise ValueError(f\"The order being placed has a qty: {quantity}, price: {price}.\\n\"\n f\"Expected a min notional value of {coin_filter['minNotional']}\")\n\n def generate_arguments_for_order(self,\n ticker: str,\n quantity: float,\n order_side,\n type_of_order,\n order_id: str,\n price: str):\n \"\"\"\n Generate arguments for setting an order\n :param ticker: string for ticker\n :param quantity: float, the quantity of coin\n :param order_side: order-side (BUY/SELL)\n :param type_of_order: order-type (LIMIT, MARKET, STOP_LIMIT)\n :param order_id: order-id\n :param price: str, price of the order to set\n :return: dictionary of arguments to be sent to the binance client for setting the order\n \"\"\"\n sanitized_quantity = self.sanitize_quantity_pre_order(ticker[:-3], float(quantity))\n if type_of_order is enums.ORDER_TYPE_MARKET:\n self.confirm_min_notion(ticker[:-3], quantity=sanitized_quantity)\n arguments = dict(\n symbol=ticker,\n side=order_side,\n type=type_of_order,\n quantity=sanitized_quantity,\n newClientOrderId=order_id\n )\n else:\n sanitized_price = self.sanitize_price_pre_order(ticker[:-3], float(price))\n self.confirm_min_notion(ticker[:-3], quantity=sanitized_quantity, price=float(sanitized_price))\n if type_of_order == enums.ORDER_TYPE_LIMIT:\n arguments = dict(\n symbol=ticker,\n side=order_side,\n type=type_of_order,\n timeInForce=enums.TIME_IN_FORCE_GTC,\n quantity=sanitized_quantity,\n price=sanitized_price,\n newClientOrderId=order_id\n )\n elif type_of_order == enums.ORDER_TYPE_STOP_LOSS_LIMIT:\n arguments = dict(\n symbol=ticker,\n side=order_side,\n type=type_of_order,\n timeInForce=enums.TIME_IN_FORCE_GTC,\n quantity=sanitized_quantity,\n stopPrice=sanitized_price,\n price=sanitized_price,\n newClientOrderId=order_id)\n else:\n raise NotImplementedError\n return arguments\n\n def set_order(self,\n ticker,\n quantity,\n order_side,\n type_of_order,\n price=None,\n order_id=None):\n \"\"\"\n Sets an order after sanitizing the price and quantity. Returns the order dict\n\n :param ticker: str eg. AMBBTC\n :param quantity: float, it is sanitized before ordering\n :param order_side: enums.SIDE_BUY or enums.SIDE_SELL\n :param type_of_order: enums.ORDER_TYPE_LIMIT, enums.ORDER_TYPE_MARKET\n :param price: float, sanitized before ordering or None when market-order\n :param order_id: str, information to send in the order\n :return: order made\n \"\"\"\n arguments = self.generate_arguments_for_order(ticker,\n quantity,\n order_side,\n type_of_order,\n order_id,\n price)\n\n values = '\\n'.join(f\"{k}: {v}\" for k, v in arguments.items())\n logger.info(\n f\"Planning on executing \\n\"\n f\"{values}\"\n )\n order = self.client_object.create_order(\n **arguments\n )\n\n if order[\"orderId\"] > 1:\n logger.info(f\"Successfully set an order for {ticker},\"\n f\"quantity: {order.get('origQty')},\"\n f\"price: {order.get('price')},\"\n f\"type: {order.get('type')}\")\n return order\n raise EnvironmentError(f\"Failed to set order {locals().keys()}\")\n\n def is_asset_significant(self, asset, btc_limit, asset_types):\n \"\"\"Checks if the asset is signicant. i.e if it is more than the btc_limit.\n asset_types should a be a list of assets you want to add [\"free\", \"locked\"]\"\"\"\n total_quantity = sum([float(asset[asset_type]) for asset_type in asset_types])\n current_price = self.get_live_price(asset['asset'])\n value_in_reference_coin = total_quantity * current_price\n return value_in_reference_coin > btc_limit\n\n def get_live_price(self, coin_name):\n \"\"\"Gets the live price of the coin\"\"\"\n if coin_name == self.reference_coin:\n return 1\n else:\n returned_symbol_ticker = self.get_ticker_price_raw(\n ticker=f\"{coin_name}{self.reference_coin}\"\n )\n logger.info(f\"symbol ticker returned: {returned_symbol_ticker}\")\n return float(returned_symbol_ticker[\"price\"])\n\n def get_ticker_price_raw(self,\n ticker):\n return self.client_object.get_symbol_ticker(symbol=ticker)\n\n\nclass BinanceAsync(BinanceBase):\n \"\"\"Binance Object which stores the binance client object.\n Warning: Do not store the api_key and client_secret in plain-text\n especially if you are uploading them in source-code repositories\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n async def obtain_coin_history_asyncio(self, coin_to_query=CrpytoCoin(name=\"ETH\"),\n type_of_history=Client.KLINE_INTERVAL_1DAY,\n start_date=\"1 Jan, 2017\",\n end_date=str(datetime.now()),\n limit=1000):\n \"\"\"\n Obtains the KLINES for the coin for the appropriate type and for the expected length\n :param coin_to_query CryptoCoin object passed for the query\n :param type_of_history The frequency of the input\n :param start_date: str when does the data collection starts\n :param end_date: str when does the data collection ends\n :param limit int the number of items desired\n :return: list of klines #TODO\n \"\"\"\n\n try:\n import time\n start = time.time()\n coin_history = await self.client_object.get_historical_klines(f\"{coin_to_query.name}{self.reference_coin}\",\n type_of_history,\n start_date,\n end_date,\n limit=limit)\n end = time.time()\n logger.info(f\"Call took {end-start} time\")\n logger.info(f\"Obtained the coin {type_of_history} history for {coin_to_query.name:<5}\"\n f\" from {start_date} upto a limit of {limit}\")\n return coin_history\n except Exception as e:\n logger.warning(f\"Could not obtain coin history for {coin_to_query.name:<5}, starting from {start_date},\"\n f\"up to a limit of {limit}, type of history {type_of_history}.\\nReason {e}\")\n\n","sub_path":"project_core/vigilant_crypto/exchange/binance_low_level.py","file_name":"binance_low_level.py","file_ext":"py","file_size_in_byte":15793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"461931316","text":"import itertools\nimport random\nimport Player\n\nclass Dealer:\n\n def __init__(self, nb_deck, nb_player):\n self.deck = []\n self.hand = []\n self.create_deck(nb_player)\n self.busted = False\n self.players = [Player.Player(i) for i in range(nb_player)]\n\n\n def init_game(self):\n self.hand = []\n self.busted = False\n for player in self.players:\n player.hand = []\n player.hand2 = []\n for i in range(2):\n for player in self.players:\n self.deal_card_to_players(player)\n self.deal_card_to_dealer()\n\n def create_deck(self, nb_deck):\n suits = 'cdhs'\n ranks = '23456789TJQKA'\n self.deck = []\n for i in range(nb_deck):\n self.deck.extend(''.join(card) for card in itertools.product(ranks, suits))\n self.shuffle_deck()\n\n def deal_card_to_players(self, player):\n player.receive_card(self.deal_card())\n\n def deal_card_to_dealer(self):\n self.hand.append(self.deal_card())\n\n def deal_card_to_split(self, player):\n player.receive_split(self.deal_card())\n\n def shuffle_deck(self):\n random.shuffle(self.deck)\n\n def deal_card(self):\n card = random.choice(self.deck)\n self.deck.remove(card)\n return card\n\n def get_nb_cards(self):\n return len(self.deck)\n\n def hit_card(self, player):\n self.deal_card_to_players(player)\n\n def check_busted(self, hand):\n if self.get_hand_value(hand) > 21:\n return True\n return False\n\n def hit_dealer_cards(self):\n while self.get_hand_value(self.hand) < 17:\n self.hand.append(self.deal_card())\n\n def check_win(self, player):\n if self.get_hand_value(self.hand) > self.get_hand_value(self.player.hand):\n return -1\n elif self.get_hand_value(self.hand) < self.get_hand_value(self.player.hand):\n return 1\n else:\n return 0\n\n def get_hand_value(self, hand):\n value = 0\n for card in hand:\n if card[0] is not 'A':\n if card[0].isdigit():\n value += int(card[0])\n else:\n value += 10\n for card in hand:\n if card[0] is 'A':\n if value >= 11:\n value += 1\n else:\n value += 11\n return value\n","sub_path":"Dealer.py","file_name":"Dealer.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"258485400","text":"import asyncio\nfrom asyncio import Protocol, transports\nfrom time import sleep\nfrom typing import Optional, List\n\nfrom tarpn.ax25 import AX25Call, AX25StateType, L3Protocol\nfrom tarpn.ax25.datalink import DataLinkManager, L3Handler\nfrom tarpn.events import EventListener, EventBus\nfrom tarpn.netrom import NetRom\nfrom tarpn.netrom.statemachine import NetRomStateType\n\n\n\n\nclass SysopL3Handler(L3Handler):\n def __init__(self, transport):\n self.transport = transport\n\n def can_handle(self, protocol: L3Protocol) -> bool:\n return protocol == L3Protocol.NoLayer3\n\n def handle(self, port: int, remote_call: AX25Call, data: bytes) -> bool:\n print(data)\n return True\n\n\nclass SysopInternalApp(Protocol):\n \"\"\"\n This is the default application for the packet engine. If configured, it runs as a NoLayer3 L2 application as\n well as a NetRom application for the engine's node.call. Unlike other applications, this one runs within\n the packet engine since it needs access to internal things like the active links, routing table, etc.\n \"\"\"\n def __init__(self, links: List[DataLinkManager], network: NetRom):\n self.transport = None\n self.links: List[DataLinkManager] = links\n self.network: NetRom = network\n self.attached_link = None\n self.attached_call = None\n\n def _link_data_callback(self, remote_call, protocol):\n def inner(inner_remote_call, inner_protocol, data):\n if inner_remote_call == remote_call and inner_protocol == protocol:\n self.transport.write(f\"{remote_call}: \".encode(\"ASCII\"))\n self.transport.write(data)\n return inner\n\n def _link_connect_callback(self, remote_call, link):\n def inner(inner_remote_call):\n if inner_remote_call == remote_call:\n self.attached_link = link\n self.attached_call = remote_call\n self.transport.write(f\"Connected to {remote_call}\\r\\n\".encode(\"ASCII\"))\n return inner\n\n def _link_disconnect_callback(self, remote_call, link):\n def inner(inner_remote_call):\n if inner_remote_call == remote_call:\n self.attached_link = None\n self.attached_call = None\n self.transport.write(f\"Disconnected from {remote_call}\\r\\n\".encode(\"ASCII\"))\n EventBus.remove(f\"sysop-{link.link_call}-{remote_call}-connect\")\n EventBus.remove(f\"sysop-{link.link_call}-{remote_call}-disconnect\")\n EventBus.remove(f\"sysop-{link.link_call}-{remote_call}-inbound\")\n return inner\n\n def data_received(self, data: bytes) -> None:\n s = data.decode(\"ASCII\").strip().upper()\n\n if self.attached_link is not None:\n if s == \"B\" or s == \"BYE\":\n self.attached_link.dl_disconnect_request(self.attached_call)\n self.attached_link = None\n self.attached_call = None\n else:\n fut = self.attached_link.dl_data_request(self.attached_call, L3Protocol.NoLayer3, data)\n self.transport.write(f\"You sent: {data}\\r\\n\".encode(\"ASCII\"))\n return\n\n tokens = s.split(\" \")\n cmd = tokens[0]\n if cmd == \"P\" or cmd == \"PORTS\":\n resp = \"Ports:\\r\\n\"\n for dlm in self.links:\n resp += f\"{dlm.link_port}: {dlm.link_call}\\r\\n\"\n self.transport.write(resp.encode(\"ASCII\"))\n elif cmd == \"L\" or cmd == \"LINKS\":\n resp = \"Links:\\r\\n\"\n for dlm in self.links:\n for remote_call in dlm.state_machine.get_sessions().keys():\n if dlm.state_machine.get_state(str(remote_call)) == AX25StateType.Connected:\n resp += f\"L2 {dlm.link_call} > {str(remote_call)} on port {dlm.link_port}\\r\\n\"\n for circuit_id in self.network.get_circuit_ids():\n circuit = self.network.get_circuit(circuit_id)\n if circuit.state == NetRomStateType.Connected:\n resp += f\"L3 {circuit.local_call} > {circuit.remote_call} on circuit {circuit_id}\\r\\n\"\n self.transport.write(resp.encode(\"ASCII\"))\n elif cmd == \"C\" or cmd == \"CONNECT\":\n port = int(tokens[1])\n remote_call = AX25Call.parse(tokens[2])\n found = None\n for link in self.links:\n if link.link_port == port:\n found = link\n break\n if found is not None:\n state = found.link_state(remote_call)\n if state == AX25StateType.Disconnected:\n found.add_l3_handler(SysopL3Handler(self.transport))\n self.attached_link = found\n self.attached_call = remote_call\n self.transport.write(f\"Connecting to {remote_call}...\\r\\n\".encode(\"ASCII\"))\n EventBus.bind(EventListener(\n f\"link.{found.link_call}.connect\",\n f\"sysop-{found.link_call}-{remote_call}-connect\",\n self._link_connect_callback(remote_call, found)\n ))\n EventBus.bind(EventListener(\n f\"link.{found.link_call}.disconnect\",\n f\"sysop-{found.link_call}-{remote_call}-disconnect\",\n self._link_disconnect_callback(remote_call, found)\n ))\n found.dl_connect_request(remote_call)\n elif state == AX25StateType.Connected:\n found.add_l3_handler(SysopL3Handler(self.transport))\n self.attached_link = found\n self.attached_call = remote_call\n self.transport.write(f\"Attaching to open link to {remote_call}\\r\\n\".encode(\"ASCII\"))\n EventBus.bind(EventListener(\n f\"link.{found.link_call}.inbound\",\n f\"sysop-{found.link_call}-{remote_call}-inbound\",\n self._link_data_callback(remote_call, L3Protocol.NoLayer3)\n ))\n EventBus.bind(EventListener(\n f\"link.{found.link_call}.disconnect\",\n f\"sysop-{found.link_call}-{remote_call}-disconnect\",\n self._link_disconnect_callback(remote_call, found)\n ))\n else:\n self.transport.write(f\"Link to {remote_call} is busy\\r\\n\".encode(\"ASCII\"))\n\n else:\n self.transport.write(f\"Unknown command {cmd}\\r\\n\".encode(\"ASCII\"))\n\n def connection_made(self, transport: transports.BaseTransport) -> None:\n self.transport = transport\n\n def connection_lost(self, exc: Optional[Exception]) -> None:\n self.transport = None\n","sub_path":"tarpn/app/sysop.py","file_name":"sysop.py","file_ext":"py","file_size_in_byte":6843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"77800569","text":"\"\"\"\nTools for integration with miscellaneous non-required packages.\n\"\"\"\n\ndef error_if_no(name, package_name, has_package):\n if not has_package:\n raise RuntimeError(name + \" requires \" + package_name\n + \", which is not installed\")\n\n# simtk.unit ########################################################\ntry:\n from simtk import unit\nexcept ImportError:\n unit = None\n is_simtk_quantity = lambda obj: False\n is_simtk_quantity_type = lambda obj: False\n is_simtk_unit_type = lambda obj: False\n HAS_SIMTK_UNIT = False\nelse:\n is_simtk_quantity = lambda obj: obj.__class__ is unit.Quantity\n is_simtk_quantity_type = lambda obj: type(obj) is unit.Quantity\n is_simtk_unit_type = lambda obj: type(obj) is unit.Unit\n HAS_SIMTK_UNIT = True\n\ndef error_if_no_simtk_unit(name):\n return error_if_no(name, \"simtk.unit\", HAS_SIMTK_UNIT)\n\n# mdtraj ############################################################\ntry:\n import mdtraj as md\nexcept ImportError:\n md = None\n HAS_MDTRAJ = False\nelse:\n HAS_MDTRAJ = True\n\ndef error_if_no_mdtraj(name):\n return error_if_no(name, \"mdtraj\", HAS_MDTRAJ)\n\n# openmm ############################################################\ntry:\n from simtk import openmm\nexcept ImportError:\n openmm = None\n HAS_OPENMM = False\nelse:\n HAS_OPENMM = True\n\ndef error_if_to_openmm(name):\n return error_if_no(name, \"openmm\", HAS_OPENMM)\n","sub_path":"openpathsampling/integration_tools.py","file_name":"integration_tools.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"314644208","text":"import numpy as np\nfrom scipy.io import wavfile\nfrom python_speech_features.base import fbank\nimport os\nimport warnings\n\n\ndef read_wav(fname):\n # Converts to [-1, 1] range.\n rate, data = wavfile.read(fname)\n assert rate == 44100, f\"WHY ARE YOU NOT USING 44.1K @ {fname}\"\n return rate, data / 32767\n\ndef write_wav(fname, data, rate=44100):\n # Assumes that data is a numpy array.\n # Normalize to 0 dBfs.\n wavfile.write(fname, rate, (32767 * data / np.max(data)).astype(np.int16))\n\ndef play_wav(data):\n write_wav('temp/playwav.wav', data)\n os.system('play temp/playwav.wav')\n\n\ndef test_alignment(wav, times):\n \"\"\"\n Creates a 'ding' at each time specified.\n \"\"\"\n\n out = wav.copy()\n\n ts = np.arange(44100/2) / 44100\n f = 500\n ding = np.sin(2 * np.pi * ts * f) * np.exp(-15 * ts)\n\n for time in times:\n time = int(time * 44100)\n\n dinglen = min(22050, len(wav) - time)\n\n if dinglen <= 0:\n continue\n\n out[time:time+dinglen] += ding[:dinglen]\n\n return out\n\n\ndef pad_wav(first_frame, last_frame, wav, step=512):\n \"\"\"\n Aligns the wav file and the frames to be correctly padded for fft processing.\n Assumes that max fft feature length is 4096!\n \"\"\"\n\n N_samples = len(wav)\n\n # If we need frames from before the start of the song, pad.\n # Need 7 frames of space from first note.\n n_front_pad = -min((first_frame - 7) * step, 0)\n\n # Need 7 frames + (4096 samples=8 frames) of space after the last note.\n n_back_pad = max(0, (last_frame + 7 + 8) * step - N_samples)\n\n padded_wav = np.r_[np.zeros(n_front_pad), wav, np.zeros(n_back_pad)]\n\n # Returns the frame adjustment required for the frames due to front padding.\n # Add this to all frames.\n return (n_front_pad // step, padded_wav)\n\n\ndef gen_fft_features(wav, step=512, nfft=[2048,4096], n_bands=80, log=True):\n features = []\n # Ignoring warnings here.\n # Will warn about issues calculating MEL filters when nfft = 1024.\n # Causes a strange black band at band 5ish. Will ignore for now.\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n for fft_size in nfft:\n # mel_features is of shape [T, F]\n mel_features, mel_energy = fbank(\n wav, nfft=fft_size,\n samplerate=44100, nfilt=n_bands, winfunc=np.hamming,\n lowfreq=27.5, highfreq=8000.0,\n winstep=512/44100)\n\n if log:\n features.append(np.log10(mel_features + 1e-4))\n else:\n features.append(mel_features)\n\n # Reutnrs shape [Channels, Time, Frequency]\n # return np.log10(np.stack(features))\n return np.stack(features)\n","sub_path":"deepSM/wavutils.py","file_name":"wavutils.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"591141007","text":"import random\n\nimport cv2\n\nfrom .utils import *\n\ndef blur(img, num_img, op_type=\"avg\", *param):\n #print(\"blur get {} {}\".format(op_type, str(param)))\n new_imgs = globals()[\"_\"+op_type+\"_blur\"](img, num_img, *param)\n\n return new_imgs\n\n\ndef _scale_blur(img, num_img, min_scale=0.2, max_scale=0.4):\n assert min_scale>=0 and min_scale <=1, \\\n \"scale must be in range (0,1), current is {}\".format(str(min_scale))\n assert max_scale>=0 and max_scale <=1, \\\n \"scale must be in range (0,1), current is {}\".format(str(max_scale))\n\n assert max_scale-min_scale>=0, \\\n \"max_scale must >= min_scale, current: max_scale={}, min_scale={}\".format(str(max_scale), str(min_scale))\n\n height, width = img.shape[:2]\n\n scale_list = generate_scales(min_scale, max_scale, num_img)\n result_imgs = []\n\n for scale in scale_list:\n new_img = cv2.resize(img, (0,0), fx=scale, fy=scale)\n result_img = cv2.resize(new_img, (width, height))\n result_imgs.append(result_img)\n\n return result_imgs\n\ndef _gaussian_blur(img, num_img, min_size=3, max_size=3, min_sigmaX=0.5, max_sigmaX=1, min_sigmaY=0.5, max_sigmaY=1):\n min_size, max_size = correct_ksize(min_size, max_size)\n\n #assert int((max_size-min_size)/2)+1>=num_img, \\\n # \"the number of image to be generated must less or equal to int((max_size({:d}) - min_size({:d}))/2) + 1 = {:d}\" \\\n # .format(max_size, min_size, int((max_size-min_size)/2)+1)\n assert max_sigmaX-min_sigmaX>=0, \\\n \"max_sigmaX must >= min_sigmaX, current: max_sigmaX={}, min_sigmaX={}\".format(str(max_sigmaX), str(min_sigmaX))\n assert max_sigmaY-min_sigmaY>=0, \\\n \"max_sigmaY must >= min_sigmaY, current: max_sigmaY={}, min_sigmaY={}\".format(str(max_sigmaY), str(min_sigmaY))\n\n ksize_list = random.sample(range(min_size, max_size+1, 2),num_img)\n sigmaX_list = generate_scales(min_sigmaX, max_sigmaX, num_img)\n sigmaY_list = generate_scales(min_sigmaY, max_sigmaY, num_img)\n result_imgs = []\n\n for ksize, sigmaX, sigmaY in zip(ksize_list, sigmaX_list, sigmaY_list):\n result_img = cv2.GaussianBlur(img,(ksize,ksize), sigmaX, sigmaY)\n result_imgs.append(result_img)\n\n return result_imgs\n\n\ndef _avg_blur(img, num_img, min_size=3, max_size=3):\n min_size, max_size = correct_ksize(min_size, max_size)\n assert int((max_size-min_size)/2)+1>=num_img, \\\n \"the number of image to be generated must less or equal to int((max_size({:d}) - min_size({:d}))/2) + 1 = {:d}\" \\\n .format(max_size, min_size, int((max_size-min_size)/2)+1)\n\n ksize_list = random.sample(range(min_size, max_size+1, 2),num_img)\n result_imgs = []\n\n for ksize in ksize_list:\n result_img = cv2.blur(img,(ksize,ksize))\n result_imgs.append(result_img)\n\n return result_imgs\n\ndef _median_blur(img, num_img, min_size=3, max_size=3):\n min_size, max_size = correct_ksize(min_size, max_size)\n assert int((max_size-min_size)/2)+1>=num_img, \\\n \"the number of image to be generated must less or equal to int((max_size({:d}) - min_size({:d}))/2) + 1 = {:d}\" \\\n .format(max_size, min_size, int((max_size-min_size)/2)+1)\n\n ksize_list = random.sample(range(min_size, max_size+1, 2),num_img)\n result_imgs = []\n\n for ksize in ksize_list:\n result_img = cv2.medianBlur(img,ksize)\n result_imgs.append(result_img)\n\n return result_imgs\n\n","sub_path":"infer_core/rcnn_infer/rcnn/io/data_process/blur.py","file_name":"blur.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"368286821","text":"#!/usr/bin/python3.4\n\"\"\"Google Analytics Reporting API V4.\"\"\"\n\nfrom googleapiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport csv\nimport os\nimport time\nimport socket\n\n\nstart_time = time.time()\nprint('------------< Social Network Referral >------------')\n\nscript_path = os.path.dirname(os.path.abspath(__file__))\n\nwith open(os.path.join(script_path, 'configFile', 'config.txt')) as f:\n config = f.readlines()\n config = {i.split(\"=\")[0]: i.split(\"=\")[1].replace(\"\\n\", \"\") for i in config if '#' not in i and i != '\\n'}\n\n\nSCOPES = ['https://www.googleapis.com/auth/analytics.readonly']\nKEY_FILE_LOCATION = os.path.join(script_path, 'configFile', 'client_secrets.json')\nVIEW_ID = config[\"VIEW_ID\"] # user define\n\nstartDate = config[\"startDate\"] # user define, e.g.'2018-09-01', 'yesterday', '30daysAgo'\nendDate = config[\"endDate\"] #time.strftime('%Y-%m-%d') # endDate is set to today\n\nfilepath = os.path.join(script_path, 'outputs')\nfilename = 'Social_Network_Referral.csv'\n\nif not os.path.exists(filepath):\n os.makedirs(filepath)\n\n# GA parameters of metrics and dimensions\nmetrics_list = [{'expression': 'ga:sessions'}, {'expression': 'ga:pageviews'},\n {'expression': 'ga:avgSessionDuration'}, {'expression': 'ga:pageviewsPerSession'}]\ndimensions_list = [{'name': 'ga:date'}, {'name': 'ga:socialNetwork'}]\nmetrics_dimensions_list = [[metrics_list, dimensions_list]]\n\n# Headers for csv output\nheader_row = ['Date', 'Social_Network', 'Sessions', 'Pageviews', 'Avg_Session_Duration', 'Pages_Session']\n\n\ndef initialize_analyticsreporting():\n \"\"\"Initializes an Analytics Reporting API V4 service object.\n\n Returns:\n An authorized Analytics Reporting API V4 service object.\n \"\"\"\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n KEY_FILE_LOCATION, SCOPES)\n\n # Build the service object.\n analytics = build('analyticsreporting', 'v4', credentials=credentials)\n\n return analytics\n\n\ndef get_report(analytics):\n \"\"\"Queries the Analytics Reporting API V4.\n\n Args:\n analytics: An authorized Analytics Reporting API V4 service object.\n Returns:\n The Analytics Reporting API V4 response.\n \"\"\"\n return analytics.reports().batchGet(\n body={\n 'reportRequests': [\n {\n 'viewId': VIEW_ID,\n 'pageSize': 1000000,\n 'dateRanges': [{'startDate': startDate, 'endDate': endDate}],\n 'metrics': metrics_dimensions_list[i][0],\n 'dimensions': metrics_dimensions_list[i][1],\n 'includeEmptyRows': 'true'\n } for i in range(len(metrics_dimensions_list))\n ]\n }\n ).execute()\n\n\ndef print_response(response):\n \"\"\"Parses and prints the Analytics Reporting API V4 response.\n\n Args:\n response: An Analytics Reporting API V4 response.\n \"\"\"\n\n for report in response.get('reports', []):\n create_header = True\n if os.path.isfile(filepath):\n create_header = False\n\n f = open(os.path.join(filepath, filename), 'wt')\n\n # Wrap file with a csv.writer\n writer = csv.writer(f, lineterminator='\\n')\n\n columnHeader = report.get('columnHeader', {})\n #dimensionHeaders = columnHeader.get('dimensions', [])\n metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])\n rows = report.get('data', {}).get('rows', [])\n\n if create_header:\n writer.writerow(header_row)\n\n # Write row data\n row_count = 0\n if rows:\n for row in rows:\n dimensions = row.get('dimensions', [])\n metrics = [m['values'] for m in row.get('metrics', [])][0]\n data_row = []\n data_row.extend(dimensions)\n data_row.extend(metrics)\n\n writer.writerow(data_row)\n row_count += 1\n\n print('filepath = ' + filepath)\n print('filename = ' + filename)\n print('Number of rows = %d' % row_count)\n\n else:\n print('No Rows Found')\n\n # Close the file\n f.close()\n\n\ndef main():\n try:\n analytics = initialize_analyticsreporting()\n response = get_report(analytics)\n print_response(response)\n except socket.timeout:\n print('Timeout Error: The read operation timed out')\n\n\nif __name__ == '__main__':\n main()\n\nprint('Execution time = %s seconds' % (time.time() - start_time))\n","sub_path":"AnalyticsReporting_SocialNetworkReferral.py","file_name":"AnalyticsReporting_SocialNetworkReferral.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"59583920","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/emencia_django_admin/templatetags/admin_emencia.py\n# Compiled at: 2008-10-06 11:14:34\nfrom django.template import Library\nfrom django.contrib.admin.templatetags.admin_list import items_for_result, result_headers\nregister = Library()\n\ndef results(cl):\n for res in cl.result_list:\n yield {'id': res.id, 'items': list(items_for_result(cl, res))}\n\n\n@register.inclusion_tag('admin/change_list_results.html')\ndef emencia_result_list(cl):\n return {'cl': cl, 'result_headers': list(result_headers(cl)), \n 'type': cl.model.__name__.lower(), \n 'results': list(results(cl))}","sub_path":"pycfiles/emencia_django_admin-0.3dev_r2314-py2.5/admin_emencia.py","file_name":"admin_emencia.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"255883740","text":"# -*- coding: utf-8 -*-\nfrom fabric.api import env, roles, run, cd, local\n\nADDITIONAL_DATABASES = ('raw_statistics', )\nPROJECT_DIR = ''\n\nenv.roledefs = {\n 'lin-kmclient-stat': [\n '',\n ],\n}\n\n\ndef local_migrate_databases():\n local('../bin/manage migrate')\n for database in ADDITIONAL_DATABASES:\n local('../bin/manage migrate --database={0}'.format(database))\n\n\ndef deploy_production():\n local('fab update_project')\n local('fab migrate_databases')\n local('fab collect_static')\n local('fab restart_project')\n\n\n@roles('lin-kmclient-stat')\ndef update_project():\n with cd(PROJECT_DIR):\n run('git pull')\n\n\n@roles('lin-kmclient-stat')\ndef restart_project():\n run('supervisorctl restart kmclient-statistics:gunicorn')\n run('supervisorctl restart kmclient-statistics:celery')\n run('kill -HUP `cat ~/www/gunicorn-api.pid`')\n\n\n@roles('lin-kmclient-stat')\ndef collect_static():\n with cd(PROJECT_DIR):\n run('echo \"yes\" | bin/manage collectstatic')\n\n\n@roles('lin-kmclient-stat')\ndef migrate_databases():\n with cd(PROJECT_DIR):\n run('bin/manage migrate')\n for database in ADDITIONAL_DATABASES:\n run('bin/manage migrate --database={0}'.format(database))\n\n\n@roles('lin-kmclient-stat')\ndef install_requirements(update=False):\n with cd(PROJECT_DIR):\n if update:\n run('bin/pip install -U -r requirements.txt')\n else:\n run('bin/pip install -r requirements.txt')\n\n\n@roles('lin-kmclient-stat')\ndef uninstall_requirements(packages=None):\n if packages:\n with cd(PROJECT_DIR):\n run('bin/pip uninstall -y %s' % packages)","sub_path":"misc/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"98883519","text":"from django.contrib import admin\nfrom django.conf.urls import patterns, include, url\nfrom reading_assistant.common import view_index\nfrom reading_assistant.common import view_login\nfrom reading_assistant.user import view_user\nfrom reading_assistant.book import view_book\nfrom reading_assistant.bestword import view_best_word\nfrom reading_assistant.review import view_review\nfrom reading_assistant import models\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\nadmin.autodiscover()\n'''\nadmin.site.register(models.User)\nadmin.site.register(models.Book)\nadmin.site.register(models.BestWord)\nadmin.site.register(models.Review)\nadmin.site.register(models.ReadingNow)\n'''\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'reading_assistant.views.home', name='home'),\n # url(r'^reading_assistant/', include('reading_assistant.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n ('^$', view_index.index),\n ('^login/$', view_login.login),\n ('^user/user_list/$', view_user.list),\n ('^user/user_insert_form/$', view_user.insert_form),\n ('^user/user_insert/$', view_user.insert),\n ('^user/user_update_form/$', view_user.update_form),\n ('^user/user_update/$', view_user.update),\n ('^user/user_delete/$', view_user.delete),\n ('^book/book_list/$', view_book.list),\n ('^book/book_insert_form/$', view_book.insert_form),\n ('^book/book_insert/$', view_book.insert),\n ('^book/book_search_result/$', view_book.search_result),\n ('^book/book_detail/$', view_book.detail),\n ('^book/book_delete/$', view_book.delete),\n ('^book/book_current_page_update/$', view_book.update_current_page),\n ('^bestword/bestword_insert_form/$', view_best_word.insert_form),\n ('^bestword/bestword_insert/$', view_best_word.insert),\n ('^bestword/bestword_delete/$', view_best_word.delete),\n ('^review/review_insert_form/$', view_review.insert_form),\n ('^review/review_insert/$', view_review.insert),\n ('^review/review_delete/$', view_review.delete),\n)\n","sub_path":"reading_assistant/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"388138923","text":"str1 = input()\nstr2 = input()\na = int(str1[0])\nif str1[2]=='-':\n b =-int(str1[3])\nelse:\n b = int(str1[2])\n\nc = int(str2[0])\nif str2[2]=='-':\n d =-int(str2[3])\nelse:\n d = int(str2[2])\n\nx = a*c-b*d\ny = a*d+b*c\nprint(x,end='')\n\nprint(\"+\",end='')\nprint(y,end='')\nprint(\"i\")","sub_path":"Code/CodeRecords/2214/60900/287606.py","file_name":"287606.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"539591748","text":"import logging\nimport os\n\nfrom dotenv import load_dotenv\n\n\ndef get_logger(name):\n load_dotenv()\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n env = os.getenv('environment', 'development')\n if env == 'production':\n handler = logging.FileHandler('logs/controller.log')\n else:\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n","sub_path":"temperature_controller/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"512861683","text":"import pytest\n\nfrom examples import config_examples as conf_ex\nfrom examples import request_examples as req_ex\nfrom examples import response_examples as resp_ex\nfrom leexportpy import queryresponse\n\n\ndef test_queryleql():\n leql = queryresponse.QueryLeql(req_ex.FROM_TIMESTAMP, req_ex.TO_TIMESTAMP, conf_ex.QUERY)\n assert \"during\" in leql.to_json()\n assert \"statement\" in leql.to_json()\n during = leql.during\n assert \"from\" in during\n assert \"to\" in during\n\n\ndef test_queryresponse():\n response = queryresponse.QueryResponse(resp_ex.LOGS, resp_ex.LEQL,\n resp_ex.GROUP_STATISTICS)\n\n expected_count = 1234\n assert \"leql\" in response.to_json()\n assert \"logs\" in response.to_json()\n assert \"statistics\" in response.to_json()\n assert response.get_count() == expected_count\n with pytest.raises(NotImplementedError):\n response.get_keys()\n with pytest.raises(NotImplementedError):\n response.get_values()\n\n\ndef test_timeseriesresponse():\n ts_response = queryresponse.TimeseriesQueryResponse(resp_ex.LOGS, resp_ex.LEQL,\n resp_ex.TIMESERIES_STATISTICS)\n expected_data_length = 10\n assert ts_response.get_values() is not None\n assert ts_response.get_data_length() == expected_data_length\n assert ts_response.get_keys() is not None\n\n\ndef test_groupresponse():\n group_response = queryresponse.GroupbyQueryResponse(resp_ex.LOGS, resp_ex.LEQL,\n resp_ex.GROUP_STATISTICS)\n expected_group_count = 4\n assert group_response.get_data_length() == expected_group_count\n assert group_response.get_values() is not None\n assert group_response.get_keys() is not None\n","sub_path":"tests/test_query_response.py","file_name":"test_query_response.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"209401297","text":"import msvcrt\r\nimport keyboard\r\nimport pyperclip\r\n\r\nTEXT = str()\r\nwhile True:\r\n if msvcrt.kbhit():\r\n key_stroke = msvcrt.getch()\r\n if key_stroke == b'\\x02': #Ctrl + B\r\n keyboard.send(\"ctrl + c\")\r\n\r\n cur_TEXT = pyperclip.paste()\r\n TEXT += cur_TEXT\r\n pyperclip.copy(TEXT)\r\n else:\r\n print(\"Press again\")\r\n","sub_path":"MultiCopying.py","file_name":"MultiCopying.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"57309110","text":"# -*- coding: utf-'8' \"-*-\"\ntry:\n import simplejson as json\nexcept ImportError:\n import json\nimport hmac\nimport hashlib\nimport logging\nfrom urllib.parse import urljoin\nfrom odoo import models, fields, api, _\nfrom odoo.addons.payment.models.payment_acquirer import ValidationError\nfrom odoo.addons.payment_payu_com.controllers.main import PayuController\nimport time\n\n_logger = logging.getLogger(__name__)\n\n\nclass AcquirerPayu(models.Model):\n _inherit = 'payment.acquirer'\n\n provider = fields.Selection(selection_add=[('payu', 'payu')])\n payu_email_account = fields.Char('Payu Email ID', required_if_provider='payu')\n payu_seller_account = fields.Char('Payu Merchant ID',\n help='The Merchant ID is used to ensure communications coming from Payu are valid and secured.')\n payu_api_username = fields.Char('Rest API Username')\n payu_api_password = fields.Char('Rest API Password')\n\n def _get_payu_urls(self, environment):\n \"\"\" Paypal URLS \"\"\"\n if environment == 'prod':\n return {\n 'payu_form_url': '/shop/redirect_payu',\n\n }\n # return {'payumoney_form_url': 'https://secure.payu.in/_payment'}\n else:\n return {\n 'payu_form_url': '/shop/redirect_payu',\n }\n\n def _get_providers(self, *args, **kwargs):\n providers = super(AcquirerPayu, self)._get_providers()\n providers.append(('payu', 'payu'))\n return providers\n\n '''payu_email_account = fields.Char('Payu Email ID', required_if_provider='payu_com')\n payu_seller_account = fields.Char('Payu Merchant ID',\n help='The Merchant ID is used to ensure communications coming from Payu are valid and secured.')\n payu_api_username = fields.Char('Rest API Username')\n payu_api_password = fields.Char('Rest API Password')\n provider = fields.Selection(selection_add=[('payu', 'payu')])'''\n\n def _migrate_payu_account(self):\n \"\"\" COMPLETE ME \"\"\"\n self.env.cr.execute('SELECT id, paypal_account FROM res_company')\n res = self.env.cr.fetchall()\n for (company_id, company_payu_account) in res:\n if company_payu_account:\n company_payu_ids = self.search([('company_id', '=', company_id), ('name', 'ilike', 'payu')], limit=1).ids\n if company_payu_ids:\n self.write(company_payu_ids, {'payu_email_account': company_payu_account})\n else:\n payu_view = self.env['ir.model.data'].get_object('payment_payu_com', 'payu_button')\n self.create({\n 'name': 'payu.com',\n 'payu_email_account': company_payu_account,\n 'view_template_id': payu_view.id,\n })\n return True\n \n def _payu_generate_hashing(self, values):\n data = '^'.join([\n values['x_login'],\n values['x_fp_sequence'],\n values['x_fp_timestamp'],\n ])\n return hmac.new(values['x_trans_key'].encode('utf-8'), data.encode('utf-8'), hashlib.md5).hexdigest()\n\n @api.multi\n def payu_form_generate_values(self, values):\n base_url = self.env['ir.config_parameter'].get_param('web.base.url')\n acquirer = self\n payu_tx_values = dict(values)\n if payu_tx_values.get('inputPaymonths'):\n payu_tx_values['x_fp_hash'] = self._payu_generate_hashing(payu_tx_values)\n return payu_tx_values\n else:\n payu_tx_values.update({\n 'x_login': self.payu_api_username,\n 'x_merchant_id': self.payu_seller_account,\n 'x_trans_key': self.payu_api_password,\n 'x_fp_timestamp': str(int(time.time())),\n 'x_fp_sequence': '%s%s' % (self.id, int(time.time())),\n 'item_name': values['reference'],\n 'item_number': values['reference'],\n 'amount': values['amount'],\n 'currency_code': values['currency'] and values['currency'].name or '',\n 'address1': values['partner_address'],\n 'city': values.get('partner_city'),\n 'country': values.get('partner_country') and values.get('partner_country').code or '',\n 'state': values.get('partner_state') and (values.get('partner_state').code or values.get('partner_state').name) or '',\n 'email': values.get('partner_email'),\n 'zip_code': values.get('partner_zip'),\n 'first_name': values.get('partner_first_name'),\n 'last_name': values.get('partner_last_name'),\n 'return': '%s' % urljoin(base_url, PayuController._return_url),\n })\n if acquirer.fees_active:\n payu_tx_values['handling'] = '%.2f' % payu_tx_values.pop('fees', 0.0)\n if payu_tx_values.get('return_url'):\n payu_tx_values['custom'] = json.dumps({'return_url': '%s' % payu_tx_values.pop('return_url')})\n payu_tx_values['x_fp_hash'] = self._payu_generate_hashing(payu_tx_values)\n return payu_tx_values\n\n def payu_get_form_action_url(self):\n acquirer = self\n self.ensure_one()\n return self._get_payu_urls(acquirer.environment)['payu_form_url']\n\n\nclass Payu(models.Model):\n _inherit = 'payment.transaction'\n\n# @api.model\n# def create(self, vals):\n# res = super(Payu, self).create(vals)\n# print '\\n\\nres>>>>>',res, '\\n\\n'\n# order_id = res.sale_order_id\n# print '\\n\\norder_id',order_id\n# account_payment_id = self.env['account.payment'].search([('communication', '=', order_id.name)])\n# print '\\n\\naccount_payment_id',account_payment_id\n# journal_id = self.env['account.journal'].search([('name', '=', 'FNB - Cheque Account 6208585815143')], limit=1, order=\"id desc\")\n# print '\\n\\njournal_id', journal_id\n# print '\\n\\norder_id.payment_tx_id' ,order_id.payment_tx_id\n# if not account_payment_id and journal_id and order_id:\n# print '\\n\\nin if>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'\n# account_payment = {\n# 'partner_id': order_id.partner_id.id,\n# 'partner_type': 'customer',\n# 'journal_id': journal_id.id,\n# #'invoice_ids':[(4,inv_obj.id,0)],\n# 'amount': order_id.amount_total,\n# 'communication': order_id.name,\n# # 'currency_id': currency.id,\n# 'payment_type': 'inbound',\n# 'payment_method_id': journal_id.inbound_payment_method_ids.id,\n# 'payment_transaction_id': order_id.payment_tx_id.id,\n# }\n# acc_payment_id = self.env['account.payment'].create(account_payment)\n# print '\\n\\nacc_payment_id', acc_payment_id, '\\n\\n'\n# return res\n @api.model\n def create(self, vals):\n # The reference is used in the Authorize form to fill a field (invoiceNumber) which is\n # limited to 20 characters. We truncate the reference now, since it will be reused at\n # payment validation to find back the transaction.\n if 'reference' in vals and 'acquirer_id' in vals:\n acquier = self.env['payment.acquirer'].browse(vals['acquirer_id'])\n if acquier.provider == 'payu':\n vals['reference'] = vals.get('reference', '')[:20]\n return super(Payu, self).create(vals)\n\n\n @api.model\n def _payu_form_get_tx_from_data(self, data):\n \"\"\" Given a data dict coming from payu, verify it and find the related\n transaction record. \"\"\"\n reference = data.get('REFERENCE')\n transaction = self.search([('reference', '=', reference)])\n if not transaction:\n error_msg = (_('PayU: received data for reference %s; no order found') % (reference))\n raise ValidationError(error_msg)\n elif len(transaction) > 1:\n error_msg = (_('PayU: received data for reference %s; multiple orders found') % (reference))\n raise ValidationError(error_msg)\n return transaction\n\n @api.multi\n def _payu_form_get_invalid_parameters(self, data):\n invalid_parameters = []\n if self.acquirer_reference and data.get('PAYUREFERENCE') != self.acquirer_reference:\n invalid_parameters.append(('Transaction Id', data.get('PAYUREFERENCE'), self.acquirer_reference))\n # check what is buyed\n amount = data.get('AMOUNT', 0)\n if int(amount) != int(self.amount * 100): # payu send amount in cent\n invalid_parameters.append(('Amount', data.get('AMOUNT'), '%.2f' % self.amount))\n if data.get('CURRENCYCODE') != self.currency_id.name:\n invalid_parameters.append(('Currency', data.get('CURRENCYCODE'), self.currency_id.name))\n return invalid_parameters\n\n @api.multi\n def _payu_form_validate(self, data):\n status = data.get('TRANSACTION_STATUS')\n data = {\n 'acquirer_reference': data.get('PAYUREFERENCE'),\n 'state_message': data.get('RESULTMESSAGE', ''),\n 'date_validate': fields.Datetime.now()\n }\n if status == 'SUCCESSFUL':\n self.write(dict(data, state='done'))\n return True\n elif status == 'PROCESSING':\n self.write(dict(data, state='pending'))\n return True\n elif status == 'FAILED':\n self.write(dict(data, state='error'))\n return False\n elif status == 'NEW':\n self.write(dict(data, state='draft'))\n return True\n else:\n error = _('Payu: feedback error')\n self.write(dict(data, state_message=error, state='error'))\n return False\n","sub_path":"payment_payu_com/models/payu_model.py","file_name":"payu_model.py","file_ext":"py","file_size_in_byte":9843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"470235352","text":"#!/usr/bin/python3\nimport sys\nimport re\nimport os\n\n# clean session prompt command line\nos.system('clear')\n\n# prepare regular expression to allow a simple split into the word list\nreg_exp = re.compile(r'[;,:\\n]+')\n# print(list(set(reg_exp.findall('cidsa, ;sono il gioc;dsa'))))\n\nfor raw in sys.stdin:\n\t\n\t# match elements of the single raw iterated\n\ttry:\n\t\tlink, words = raw.split(';')\n\texcept Exception as e:\n\t\t# print(e)\n\t\t# import loggin --> log some error to the system\n\t\t#\n\t\tcontinue\n\n\t# execute regular expression\n\tchar_to_replace = list(set(reg_exp.findall(words)))\n\t\n\t# lambda function\n\trpl = lambda string, char: string.replace(char, '')\t\n\t\n\t# replace char into string for every char matched before\n\tfor i in range(len(char_to_replace)):\n\t\twords = rpl(words, char_to_replace[i])\t\n\n\t# prepare list of words splitted\t\n\tlist_words = words.split(' ')\n\t\n\tfor w in list_words:\n\t\tif w.lower() in link and w.lower() not in ['il', 'di', 'a', 'da', 'in', 'con', 'su', 'per', 'tra', 'fra', 'e', 'ma', 'lo', 'si', '']:\n\t\t\tprint('{};{}'.format(w.lower(), link))\n\t# sys.exit()\n\n\n","sub_path":"mr_link/link_mapper.py","file_name":"link_mapper.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"228146827","text":"# Sepehr Yazdani | CS-UY 1134 HW2\n\n\n#Question at the top, explanation on the bottom.\n\n#Q1: Create a function that finds the min and max of a sequence without loops.\ndef minmax(lis,left=0,right=None):\n if right==None:\n right=len(lis)-1\n mid= (left+right)//2\n if left==mid:\n return min(lis[left],lis[right]),max(lis[left],lis[right])\n else:\n lMin,lMax= minmax(lis,left,mid)\n rMin,rMax= minmax(lis,mid,right)\n return min(lMin,rMin),max(lMax,rMax)\n\nlis= [2,0,6,1,111111,25,-1,66]\nprint(minmax(lis))\n# The runtime would be O(N).\n# There would be O(1) runs every time the code doesn't recurse, as it would be finding the\n# min and max of a tuple containing 2 values.\n# There would be O(N) recursions.\n\n\n#Q2: Use recursion to calculate log of base two only using addition and division.\n\ndef log2int(x):\n if x<=0:\n return ('This does not work.')\n elif x//2 == 0:\n return 0\n else:\n return log2int(x//2) + 1\n\nprint (log2int(64))\n# With the exception of the recursive actions, all of the actions take a constant time.\n# There are log(n) recursive actions occuring.\n# Therefore, the runtime is O(log(n))\n\n\n#Q3: Write a recursive function that solves the element uniqueness problem in O(n^2) time.\n\ndef elemunique(lis):\n if len(lis)==1:\n return True\n else:\n elem= lis.pop()\n if elem in lis:\n return False\n else:\n return elemunique(lis)\nlis= [2,9,5,5,7,6]\nprint(elemunique(lis))\n\n# Without the recursive actions, pop takes O(1) time, and \"elem in lis\" takes O(n) time.\n# There are going to be O(n) recursions, due to the fact that it has to pop everything in the list.\n# With this, we can say that the runtime would be O(n^2).\n\n\n\n\n#Q4: Create a function that returns a list of all the subset possibilities\n\ndef subset(lis):\n result=[]\n if len(lis)>0:\n temp= lis[0]\n for i in subset(lis[1:]):\n result.append(i+[temp])\n result.append(i)\n return result\n else:\n result.append([])\n return result\n \n \nseti= [1,2,3]\nprint (subset(seti))\n\n# The slicing of the list takes O(n) time and the for loop ran O(n) time.\n# The function ran O(n) times.\n# In total, the function had a runtime of O(n^2)\n\n\n\n#Q5 Create a recursive function that checks whether a string is a palindrome\n\ndef isPalindrome(stri,i=0,j=None):\n if j==None:\n j=len(stri)-1\n if len(stri)==0:\n return False\n if i==j:\n return True\n if stri[i]==stri[j]:\n return isPalindrome(stri,i+1,j-1)\n else:\n return False\nstrong= 'paliilapp'\nprint(isPalindrome(strong))\n\n# Without recursive actions, this runs at a constant runtime.\n# The recursive actions make it run at N/2 times at worse case\n# Therefore, the runtime would be O(N)\n\n\n# Q6 Given an unsorted sequence, create a function that rearranges elements\n# in sequence so that all items less than or equal to k come before any\n# elements that are larger than k\n\ndef sortingK(lis,k):\n if 0=temp:\n return [temp]+sortingK(lis,k)\n else:\n return sortingK(lis,k)+[temp]\n else:\n return []\n\nk=5\nS= [3,6,10,2,4,10]\nprint(sortingK(S,k))\n\n# Without recursive actions, it is taking O(1) time.\n# It is doing O(n) recursions, as it is popping every item of the list\n# This program will run at O(N)\n","sub_path":"HW 2.py","file_name":"HW 2.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"416762998","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.forms.fields import IntegerField, CharField\nfrom django.forms.widgets import CheckboxSelectMultiple, HiddenInput\nfrom django.template.smartif import prefix\nfrom ch_commons.forms import ParentedForm, PrefixInsertedFormset\nfrom django.forms.models import BaseFormSet, formset_factory, ModelChoiceField, BaseModelFormSet, modelformset_factory\nfrom flag.models import Flag, SetFlag\nfrom django.core.exceptions import ValidationError\nfrom activity.models import Activity\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404, redirect\nfrom updates.models import Update\n\nfrom ch_commons.forms import FullNameField\nfrom manager.models import ManagerPersonnel\n__author__ = 'A. Mert KARA'\n__date__ = '2014-12-16'\n__company__ = 'Castle Hall Alternatives'\n__url__ = 'www.castlehallalternatives.com'\n\nclass IndividualsCoveredForm(forms.Form):\n manager_personnel = FullNameField(label=\"Name\", queryset=ManagerPersonnel.objects.all(), required=False)\n activity = forms.ModelChoiceField(queryset = Activity.objects.all(), required = False, widget=forms.HiddenInput())\n #manager_personnel_name = forms.CharField(required=False)\n #manager_personnel_id = forms.CharField(required=False, widget=forms.HiddenInput())\n\n def __init__(self, *args, **kwargs):\n act = kwargs.pop('act', None)\n manager = kwargs.pop('manager', None)\n ct_id = kwargs.pop('ct_id', None)\n versions = kwargs.pop('version', None)\n super(IndividualsCoveredForm, self).__init__(*args, **kwargs)\n\n if manager:\n mp_for_activity = SetFlag.objects.filter(bc_activity = act, content_type_id = ct_id).values_list('linked_record')\n self.fields['manager_personnel'].queryset = ManagerPersonnel.objects.filter(Q(manager_has_manager_personnel__managerindex__pk = manager) |\n Q(manager_has_manager_personnel__manager__pk__in = versions) | Q (pk__in = mp_for_activity))\n\n\nclass FlagForm(ParentedForm):\n\n class Meta:\n model = Flag\n exclude = []\n widgets = dict(content_type=CheckboxSelectMultiple)\n\n\nclass FlagFilterForm(forms.Form):\n\n rating = forms.MultipleChoiceField(\n label=\"Default Rating\",\n choices=Flag.RATING_CHOICES,\n widget=forms.CheckboxSelectMultiple,\n required=False\n )\n\n content_type = forms.ModelMultipleChoiceField(\n label=\"Links To\",\n queryset=ContentType.objects.filter(pk__in=Flag.CONTENT_TYPES),\n widget=forms.CheckboxSelectMultiple,\n required=False\n )\n\n flagNameSearch = forms.CharField(\n max_length=15,\n required=False,\n label='Flag Name'\n )\n\n def get_list_fieldnames(self, **kwargs):\n return [\n {'type': 'function', 'title': 'Flag Type', 'attr': 'type', 'function': lambda x,y: x.get_type_display()},\n {'type': 'function', 'title': 'Parent', 'attr': 'parent', 'function': lambda x,y: x.parent.name if x.parent else \"\"},\n {'type': 'field', 'title': 'Flag Name', 'attr': 'name'},\n {'type': 'function', 'title': 'Default Rating', 'attr': 'rating', 'function': lambda x,y: x.get_rating_display()},\n {'type': 'field', 'title': 'Display Order', 'attr': 'sequence'},\n {'type': 'function', 'title': 'Links to', 'attr': 'content_type', 'function': lambda x,y: \", \".join([ct.name.title() for ct in x.content_type.all()])},\n {'type': 'icon',\n 'title': '',\n 'attr': 'edit',\n 'value': 'pk',\n 'icon_type': 'edit',\n 'perm': (kwargs.get(\"user\").has_perm(\"flag.change_flag\") if kwargs.get(\"user\", False) else False)},\n {'type': 'icon',\n 'title': '',\n 'attr': 'delete',\n 'value': 'pk',\n 'icon_type': 'delete',\n 'perm': (kwargs.get(\"user\").has_perm(\"flag.delete_flag\") if kwargs.get(\"user\", False) else False)}]\n\n\nclass SetFlagForm(forms.Form):\n\n class Meta:\n model = SetFlag\n fields = ['additional_text', 'rating']\n\n\nclass GenericSetFlagForm(forms.ModelForm):\n\n prefix = \"generic_setflag_formset\"\n\n class Meta:\n model = SetFlag\n fields = [\"date_set\", \"flag\", \"rating\", \"additional_text\", \"content_type\", \"linked_record\"]\n widgets = ({\n \"content_type\": HiddenInput,\n \"linked_record\": HiddenInput\n })\n\n\nclass ManagerPersonnelWatchlistSetFlagForm(GenericSetFlagForm):\n form_name = \"Watchlist\" # It is used for texts in the UI, i.e. New Watchlist Item\n flag = ModelChoiceField(queryset=Flag.objects.filter(type=Flag.WATCHLIST, content_type__id__in=[49]))\n formclass = CharField(initial=\"ManagerPersonnelWatchlistSetFlagForm\", widget=HiddenInput)\n\n\nclass ManagerIndexWatchlistSetFlagForm(GenericSetFlagForm):\n form_name = \"Watchlist\" # It is used for texts in the UI, i.e. New Watchlist Item\n flag = ModelChoiceField(queryset=Flag.objects.filter(type=Flag.WATCHLIST, content_type__id__in=[181]))\n formclass = CharField(initial=\"ManagerIndexWatchlistSetFlagForm\", widget=HiddenInput)\n\n\nclass GenericSetFlagFormset(BaseModelFormSet, PrefixInsertedFormset):\n\n @property\n def empty_form(self):\n form = super(GenericSetFlagFormset, self).empty_form\n\n if self.initial_extra is not None:\n form.fields[\"linked_record\"].initial = self.initial_extra[0].get(\"linked_record\")\n form.fields[\"content_type\"].initial = self.initial_extra[0].get(\"content_type\")\n\n return form\n\n\nGenericSetFlagFormsetGeneric = modelformset_factory(\n SetFlag,\n formset=GenericSetFlagFormset,\n form=GenericSetFlagForm,\n can_delete=True,\n extra=0\n)\n\nGenericSetFlagFormsetManagerIndex = modelformset_factory(\n SetFlag,\n formset=GenericSetFlagFormset,\n form=ManagerIndexWatchlistSetFlagForm,\n can_delete=True,\n extra=0\n)\n\nGenericSetFlagFormsetManagerPersonnel = modelformset_factory(\n SetFlag,\n formset=GenericSetFlagFormset,\n form=ManagerPersonnelWatchlistSetFlagForm,\n can_delete=True,\n extra=0\n)\n\n\n\n#Used on the form to create new activities\nclass FakeSetFlagForm(forms.Form):\n is_selected = forms.BooleanField(widget=forms.HiddenInput(), required=False)\n additional_text = forms.CharField(widget=forms.HiddenInput(), required=False)\n rating = forms.ChoiceField(choices = Flag.RATING_CHOICES, widget=forms.HiddenInput(), required=False)\n\n linked_activity = forms.ModelChoiceField(queryset=Activity.objects.all(), widget=forms.HiddenInput(), required=False)\n flag_id = forms.ModelChoiceField(queryset=Flag.objects.all(), widget=forms.HiddenInput(), required=False)\n id = forms.CharField(widget=forms.HiddenInput(), required=False)\n\n class Meta:\n fields = ['additional_text', 'linked_activity', 'linked_record', 'rating', 'is_selected', 'flag_id', 'id']\n\n #Save settings used to determine how to render and validate input 'groups' made up of individual elements\n def __init__(self, *args, **kwargs):\n my_widget = kwargs['initial'].pop('widget', None)\n my_label = kwargs['initial'].pop('label_for_field', None)\n my_group = kwargs['initial'].pop('parent', None)\n my_rating = kwargs['initial'].pop('display_rating', None)\n flag_type = kwargs['initial'].pop('flag_type', Flag.BACKGROUND_CHECK)\n new_sf_record = kwargs['initial'].pop('new_sf_record', 1)\n linked_ct = kwargs['initial'].pop('linked_ct', ManagerPersonnel)\n\n super(FakeSetFlagForm, self).__init__(*args, **kwargs)\n\n self.fields[\"linked_record\"] = forms.ModelChoiceField(\n queryset=linked_ct.objects.all(),\n widget=forms.HiddenInput(),\n required=False\n )\n self.fields[\"linked_ct\"] = forms.IntegerField(\n initial=ContentType.objects.get_for_model(linked_ct).id,\n widget=forms.HiddenInput(),\n required=False,\n )\n self.fields[\"flag_type\"] = forms.CharField(\n initial=flag_type,\n widget=forms.HiddenInput(),\n required=False,\n )\n self.fields[\"new_sf_record\"] = forms.BooleanField(\n initial=new_sf_record,\n widget=forms.HiddenInput(),\n required=False,\n )\n\n if my_label:\n self.field_label = my_label\n\n if my_widget:\n if my_widget[:5] == 'CHECK':\n self.field_type = 'Checkbox'\n else:\n self.field_type = 'Radio'\n\n if my_widget[-3:] == 'REQ':\n self.field_required = True\n else:\n self.field_required = False\n\n\n self.group_under = my_group\n self.display_rating = my_rating\n def clean(self):\n if 'linked_record' in self.initial and self.cleaned_data['linked_record']:\n self.cleaned_data['linked_record']= self.initial['linked_record']\n return self.cleaned_data\n\n\n\n\nclass SetFlagFormSet(BaseFormSet):\n\n prefix = \"sf_formset\"\n\n def clean(self):\n if any(self.errors):\n return\n\n required_cleared = []\n required_fields = []\n lr = None\n\n #Verify an input has been selected for each group marked as \"required\"\n for form in self.forms:\n if form.field_required and form.group_under:\n #Verify all required fields have a value selected\n if form.cleaned_data['is_selected']:\n if form.group_under in required_cleared:\n required_cleared.remove(form.group_under)\n required_fields.append(form.group_under)\n else:\n required_fields.append(form.group_under)\n elif not form.group_under in required_cleared and not form.group_under in required_fields:\n required_cleared.append(form.group_under)\n\n if self.ct == 'Manager_Personnel':\n #Verify the linked record is supplied\n if 'linked_record' not in form.data:\n raise ValidationError('An error has occurred - No ManagerPersonnel associated with this record.')\n\n #Verify all records are the same for a given form\n if lr and form.data['linked_record'] != lr:\n raise ValidationError('An error has occurred - Form data has been altered.')\n\n lr = form.data['linked_record']\n\n if len(required_cleared) != 0:\n raise ValidationError('Please select a value for fields marked with a *.')\n\n return\n\n\n def __init__(self, *args, **kwargs):\n ct = kwargs.pop('ct', None)\n\n if \"prefix\" not in kwargs.keys():\n kwargs[\"prefix\"] = self.prefix\n\n super(SetFlagFormSet, self).__init__(*args, **kwargs)\n self.ct = ct\n\n\n #Because the form details are updated/created via AJAX calls, we're only interested in deleting extraneous elements\n #at this point\n def save(self):\n to_uncheck = []\n\n for form in self.forms:\n cd = form.cleaned_data\n if 'id' in cd and cd['id'] != '':\n #If this id already exists, and it's checked, update the record\n if 'is_selected' in cd and cd['is_selected'] == True:\n #If it isn't checked, this selection has been unchecked and needs to be deleted\n\n f = SetFlag.objects.get(pk = cd['id'])\n f.additional_text = cd['additional_text']\n f.rating = cd['rating']\n f.save()\n\n else:\n to_uncheck.append(cd['id'])\n else:\n #Create a new record\n if 'is_selected' in cd and cd['is_selected'] == True:\n act = cd['linked_activity']\n if self.ct == 'ManagerIndex':\n link = act.fund.manager.pk\n else:\n try:\n link = cd['linked_record'].pk\n except:\n link = cd['linked_record']\n if not link:\n link= self.initial[1]['linked_record']\n\n\n SetFlag.objects.create(\n additional_text = cd['additional_text'],\n rating = cd['rating'],\n bc_activity = act,\n content_type = ContentType.objects.get(model = self.ct),\n flag = cd['flag_id'],\n linked_record = link,\n )\n self.delete_unchecked(to_uncheck)\n\n\n #Delete any SetFlags where an id is present, but is_selected is now false or missing\n def delete_unchecked(self, arr):\n SetFlag.objects.filter(pk__in = arr).delete()\n\n\nSetFlagFormFactory = formset_factory(form = FakeSetFlagForm, formset=SetFlagFormSet, can_delete = False, extra = 0)\n","sub_path":"flag/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":13054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"429494551","text":"# n명이 줄을 서서 기다림.\n# 각 심사하는 장소마다 소요되는 시간이 다르다.\n\n# 처음에는 모든 심사대가 비어있다.\n# 1개의 심사대는 1명만 심사.\n\n# 가장 앞에서 있는 사람은 비어 있는 심사대로 받는다.\n# 하지만, 더 빨리 끝나는 심사대가 있으면 기다렸다가 그곳으로 가서 심사를 받을 수 있다.\n\n# n = 사람수\n# times = 시간이 담긴 배열\n\ndef solution(n, times):\n answer = 0\n left, right = 1, max(times) * n\n\n while left <= right:\n mid = (left+right) // 2\n people = 0\n for time in times:\n people += mid // time\n if people >= n:\n break\n\n if people >= n:\n answer = mid\n right = mid -1\n elif people < n:\n left = mid + 1\n return answer","sub_path":"프로그래머스/Level3/입국심사.py","file_name":"입국심사.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"385669988","text":"\"\"\"Create a Dash app within a Flask app.\"\"\"\nfrom pathlib import Path\nimport dash\nimport dash_table\nimport dash_html_components as html\nimport pandas as pd\nfrom .layout import html_layout\n\ndef serve_layout():\n return html.Div(\n children=get_datasets(),\n id='dash-container'\n )\n\ndef Add_Dash(server):\n \"\"\"Create a Dash app.\"\"\"\n external_stylesheets = ['/static/dist/css/styles.css',\n 'https://fonts.googleapis.com/css?family=Lato',\n 'https://use.fontawesome.com/releases/v5.8.1/css/all.css']\n external_scripts = ['/static/dist/js/includes/jquery.min.js',\n '/static/dist/js/main.js']\n dash_app = dash.Dash(server=server,\n external_stylesheets=external_stylesheets,\n external_scripts=external_scripts,\n routes_pathname_prefix='/dashapp/')\n\n # Override the underlying HTML template\n dash_app.index_string = html_layout\n\n # Create Dash Layout comprised of Data Tables\n #dash_app.layout = html.Div(\n # children=get_datasets(),\n # id='dash-container'\n # )\n dash_app.layout = serve_layout\n\n return dash_app.server\n\n\ndef get_datasets():\n \"\"\"Return previews of all CSVs saved in /data directory.\"\"\"\n p = Path('.')\n data_filepath = list(p.glob('data/*.csv'))\n arr = ['Current Outbreak of Novel Coronavirus (2019-nCoV) Globally:']\n for index, csv in enumerate(data_filepath):\n df = pd.read_csv(data_filepath[index]).head(100)\n table_preview = dash_table.DataTable(\n id='table_' + str(index),\n columns=[{\"name\": i, \"id\": i} for i in df.columns],\n data=df.to_dict(\"rows\"),\n sort_action=\"native\",\n sort_mode='single'\n )\n arr.append(table_preview)\n return arr\n","sub_path":"application/dash_application/dash_coronavirus.py","file_name":"dash_coronavirus.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"620496178","text":"from flask import Flask, render_template\nfrom flask import Response, jsonify\nimport collections\napp = Flask(__name__)\n\nimport MySQLdb\nimport json\nfrom bson import json_util\nfrom bson.json_util import dumps\n\n@app.route(\"/\")\ndef hello():\n return \"This personal Contabilidad Dashboard originated from Generic dashboard\"\n\n@app.route('/ContDashboard')\ndef ContDashboard():\n return render_template(\"ContDashboard.html\")\n\n \n@app.route(\"/queryNAS-SQL-from-Flask\")\ndef queryNAS():\n \n connection = MySQLdb.connect(host = '10.1.1.2', user='root', passwd='admin', db='Cont2016-Jan-14')\n\n cursor = connection.cursor() \n cursor.execute(\"SELECT * FROM MasterTable\")\n data = cursor.fetchall()\n #json_projects = []\n #for line in data:\n # json_projects.append(line)\n \n\n #json_projects = json.dumps(json_projects, default=json_util.default)\n connection.close()\n\n return jsonify(data)\n \n\n \nif __name__ == \"__main__\":\n app.run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"284793394","text":"# -*- coding: utf-8 -*-\n''' @author: Daniel Dreke (Fraunhofer ISI, CC X) '''\n\nCOUNTRIES = \\\n [ # http://en.wikipedia.org/wiki/ISO_3166-1\n (40, 'AT', 'Austria', 'Österreich','aut', 1)\n , (56, 'BE', 'Belgium', 'Belgien','bel', 1)\n , (100, 'BG', 'Bulgaria', 'Bulgarien','bgr', 1)\n , (191, 'HR', 'Croatia', 'Kroatien','hrv', 1)\n , (196, 'CY', 'Cyprus', 'Zypern','cyp', 1)\n , (203, 'CZ', 'Czech Republic', 'Tschechische Republik','cze', 1)\n , (208, 'DK', 'Denmark', 'Dänemark','dnk', 1)\n , (233, 'EE', 'Estonia', 'Estland','est', 1)\n , (246, 'FI', 'Finland', 'Finnland','fin', 1)\n , (250, 'FR', 'France', 'Frankreich','fra', 1)\n , (276, 'DE', 'Germany', 'Deutschland','deu', 1)\n , (300, 'GR', 'Greece', 'Griechenland','grc', 1)\n , (348, 'HU', 'Hungary', 'Ungarn','hun', 1)\n , (352, 'IS', 'Iceland', 'Island','isl', 1)\n , (372, 'IE', 'Ireland', 'Irland','irl', 1)\n , (380, 'IT', 'Italy', 'Italien','ita', 1)\n , (428, 'LV', 'Latvia', 'Lettland','lva', 1)\n , (440, 'LT', 'Lithuania', 'Litauen','ltu', 1)\n , (442, 'LU', 'Luxembourg', 'Luxemburg','lux', 1)\n , (470, 'MT', 'Malta', 'Malta','mlt', 1)\n , (528, 'NL', 'Netherlands', 'Niederlande','nld', 1)\n , (578, 'NO', 'Norway', 'Norwegen','nor', 1)\n , (616, 'PL', 'Poland', 'Polen','pol', 1)\n , (620, 'PT', 'Portugal', 'Portugal','prt', 1)\n , (642, 'RO', 'Romania', 'Rumänien','rou', 1)\n , (688, 'RS', 'Serbia', 'Serbien','srb', 1)\n , (703, 'SK', 'Slovakia', 'Slowakei','svk', 1)\n , (705, 'SI', 'Slovenia', 'Slowenien','svn', 1)\n , (724, 'ES', 'Spain', 'Spanien','esp', 1)\n , (752, 'SE', 'Sweden', 'Schweden','swe', 1)\n , (756, 'CH', 'Switzerland', 'Schweiz (Confoederatio Helvetica)', 'che', 1)\n , (826, 'GB', 'United Kingdom', 'Vereinigtes Königreich Großbritannien und Nordirland','gbr', 1)\n , (900, 'VI', 'Vienna', 'WIEN','vie', 1)\n , (4, 'AF', 'Afghanistan', 'Afghanistan','afg', 0)\n , (8, 'AL', 'Albania', 'Albanien','alb', 0)\n , (248, 'AX', 'Åland Islands', 'Åland','ala', 0)\n , (12, 'DZ', 'Algeria', 'Algerien','dza', 0)\n , (16, 'AS', 'American Samoa', 'Amerikanisch-Samoa','asm', 0)\n , (20, 'AD', 'Andorra', 'Andorra','and', 0)\n , (24, 'AO', 'Angola', 'Angola','ago', 0)\n , (660, 'AI', 'Anguilla', 'Anguilla','aia', 0)\n , (10, 'AQ', 'Antarctica', 'Antarktika','ata', 0)\n , (28, 'AG', 'Antigua and Barbuda', 'Antigua und Barbuda','atg', 0)\n , (32, 'AR', 'Argentina', 'Argentinien','arg', 0)\n , (51, 'AM', 'Armenia', 'Armenien','arm', 0)\n , (533, 'AW', 'Aruba', 'Aruba','abw', 0)\n , (36, 'AU', 'Australia', 'Australien','aus', 0)\n , (31, 'AZ', 'Azerbaijan', 'Aserbaidschan','aze', 0)\n , (44, 'BS', 'Bahamas', 'Bahamas','bhs', 0)\n , (48, 'BH', 'Bahrain', 'Bahrain','bhr', 0)\n , (50, 'BD', 'Bangladesh', 'Bangladesch','bgd', 0)\n , (52, 'BB', 'Barbados', 'Barbados','brb', 0)\n , (112, 'BY', 'Belarus', 'Belarus (Weißrussland)','blr', 0)\n , (84, 'BZ', 'Belize', 'Belize','blz', 0)\n , (204, 'BJ', 'Benin', 'Benin','ben', 0)\n , (60, 'BM', 'Bermuda', 'Bermuda','bmu', 0)\n , (64, 'BT', 'Bhutan', 'Bhutan','btn', 0)\n , (68, 'BO', 'Bolivia, Plurinational State of', 'Bolivien','bol', 0)\n , (535, 'BQ', 'Bonaire, Sint Eustatius and Saba', 'Bonaire, Sint Eustatius und Saba (Niederlande)','bes', 0)\n , (70, 'BA', 'Bosnia and Herzegovina', 'Bosnien und Herzegowina','bih', 0)\n , (72, 'BW', 'Botswana', 'Botswana','bwa', 0)\n , (74, 'BV', 'Bouvet Island', 'Bouvetinsel','bvt', 0)\n , (76, 'BR', 'Brazil', 'Brasilien','bra', 0)\n , (86, 'IO', 'British Indian Ocean Territory', 'Britisches Territorium im Indischen Ozean','iot', 0)\n , (96, 'BN', 'Brunei Darussalam', 'Brunei Darussalam','brn', 0)\n , (854, 'BF', 'Burkina Faso', 'Burkina Faso','bfa', 0)\n , (108, 'BI', 'Burundi', 'Burundi','bdi', 0)\n , (116, 'KH', 'Cambodia', 'Kambodscha','khm', 0)\n , (120, 'CM', 'Cameroon', 'Kamerun','cmr', 0)\n , (124, 'CA', 'Canada', 'Kanada','can', 0)\n , (132, 'CV', 'Cape Verde', 'Kap Verde','cpv', 0)\n , (136, 'KY', 'Cayman Islands', 'Kaimaninseln','cym', 0)\n , (140, 'CF', 'Central African Republic', 'Zentralafrikanische Republik','caf', 0)\n , (148, 'TD', 'Chad', 'Tschad','tcd', 0)\n , (152, 'CL', 'Chile', 'Chile','chl', 0)\n , (156, 'CN', 'China', 'China, Volksrepublik','chn', 0)\n , (162, 'CX', 'Christmas Island', 'Weihnachtsinsel','cxr', 0)\n , (166, 'CC', 'Cocos (Keeling)','Kokosinseln','cck', 0)\n , (170, 'CO', 'Colombia', 'Kolumbien','col', 0)\n , (174, 'KM', 'Comoros', 'Komoren','com', 0)\n , (178, 'CG', 'Congo', 'Republik Kongo','cog', 0)\n , (180, 'CD', 'Congo, the Democratic Republic of the', 'Kongo, Demokratische Republik (ehem. Zaire)','cod', 0)\n , (184, 'CK', 'Cook Islands', 'Cookinseln','cok', 0)\n , (188, 'CR', 'Costa Rica', 'Costa Rica','cri', 0)\n , (192, 'CU', 'Cuba', 'Kuba','cub', 0)\n , (531, 'CW', 'Curaçao', 'Curaçao','cuw', 0)\n , (262, 'DJ', 'Djibouti', 'Dschibuti','dji', 0)\n , (212, 'DM', 'Dominica', 'Dominica','dma', 0)\n , (214, 'DO', 'Dominican Republic', 'Dominikanische Republik','dom', 0)\n , (218, 'EC', 'Ecuador', 'Ecuador','ecu', 0)\n , (818, 'EG', 'Egypt', 'Ägypten','egy', 0)\n , (222, 'SV', 'El Salvador', 'El Salvador','slv', 0)\n , (226, 'GQ', 'Equatorial Guinea', 'Äquatorialguinea','gnq', 0)\n , (232, 'ER', 'Eritrea', 'Eritrea','eri', 0)\n , (231, 'ET', 'Ethiopia', 'Äthiopien','eth', 0)\n , (238, 'FK', 'Falkland Islands (Malvinas)', 'Falklandinseln','flk', 0)\n , (234, 'FO', 'Faroe Islands', 'Färöer','fro', 0)\n , (242, 'FJ', 'Fiji', 'Fidschi','fji', 0)\n , (254, 'GF', 'French Guiana', 'Französisch-Guayana','guf', 0)\n , (258, 'PF', 'French Polynesia', 'Französisch-Polynesien','pyf', 0)\n , (260, 'TF', 'French Southern Territories', 'Französische Süd- und Antarktisgebiete','atf', 0)\n , (266, 'GA', 'Gabon', 'Gabun','gab', 0)\n , (270, 'GM', 'Gambia', 'Gambia','gmb', 0)\n , (268, 'GE', 'Georgia', 'Georgien','geo', 0)\n , (288, 'GH', 'Ghana', 'Ghana','gha', 0)\n , (292, 'GI', 'Gibraltar', 'Gibraltar','gib', 0)\n , (304, 'GL', 'Greenland', 'Grönland','grl', 0)\n , (308, 'GD', 'Grenada', 'Grenada','grd', 0)\n , (312, 'GP', 'Guadeloupe', 'Guadeloupe','glp', 0)\n , (316, 'GU', 'Guam', 'Guam','gum', 0)\n , (320, 'GT', 'Guatemala', 'Guatemala','gtm', 0)\n , (831, 'GG', 'Guernsey', 'Guernsey (Kanalinsel)','ggy', 0)\n , (324, 'GN', 'Guinea', 'Guinea','gin', 0)\n , (624, 'GW', 'Guinea-Bissau', 'Guinea-Bissau','gnb', 0)\n , (328, 'GY', 'Guyana', 'Guyana','guy', 0)\n , (332, 'HT', 'Haiti', 'Haiti','hti', 0)\n , (334, 'HM', 'Heard Island and McDonald Islands', 'Heard und McDonaldinseln','hmd', 0)\n , (336, 'VA', 'Holy See (Vatican City State)', 'Vatikanstadt','vat', 0)\n , (340, 'HN', 'Honduras', 'Honduras','hnd', 0)\n , (344, 'HK', 'Hong Kong', 'Hongkong','hkg', 0)\n , (356, 'IN', 'India', 'Indien','ind', 0)\n , (360, 'ID', 'Indonesia', 'Indonesien','idn', 0)\n , (364, 'IR', 'Iran, Islamic Republic of', 'Iran, Islamische Republik','irn', 0)\n , (368, 'IQ', 'Iraq', 'Irak','irq', 0)\n , (833, 'IM', 'Isle of Man', 'Insel Man','imn', 0)\n , (376, 'IL', 'Israel', 'Israel','isr', 0)\n , (388, 'JM', 'Jamaica', 'Jamaika','jam', 0)\n , (392, 'JP', 'Japan', 'Japan','jpn', 0)\n , (832, 'JE', 'Jersey', 'Jersey (Kanalinsel)','jey', 0)\n , (400, 'JO', 'Jordan', 'Jordanien','jor', 0)\n , (398, 'KZ', 'Kazakhstan', 'Kasachstan','kaz', 0)\n , (404, 'KE', 'Kenya', 'Kenia','ken', 0)\n , (296, 'KI', 'Kiribati', 'Kiribati','kir', 0)\n , (410, 'KR', 'Korea, Republic of', 'Korea, Republik (Südkorea)','kor', 0)\n , (414, 'KW', 'Kuwait', 'Kuwait','kwt', 0)\n , (417, 'KG', 'Kyrgyzstan', 'Kirgisistan','kgz', 0)\n , (422, 'LB', 'Lebanon', 'Libanon','lbn', 0)\n , (426, 'LS', 'Lesotho', 'Lesotho','lso', 0)\n , (430, 'LR', 'Liberia', 'Liberia','lbr', 0)\n , (434, 'LY', 'Libya', 'Libyen','lby', 0)\n , (438, 'LI', 'Liechtenstein', 'Liechtenstein','lie', 0)\n , (446, 'MO', 'Macao', 'Macao','mac', 0)\n , (807, 'MK', 'Macedonia, The Former Yugoslav Republic of', 'Mazedonien, ehem. jugoslawische Republik [2b]','mkd', 0)\n , (450, 'MG', 'Madagascar', 'Madagaskar','mdg', 0)\n , (454, 'MW', 'Malawi', 'Malawi','mwi', 0)\n , (458, 'MY', 'Malaysia', 'Malaysia','mys', 0)\n , (462, 'MV', 'Maldives', 'Malediven','mdv', 0)\n , (466, 'ML', 'Mali', 'Mali','mli', 0)\n , (584, 'MH', 'Marshall Islands', 'Marshallinseln','mhl', 0)\n , (474, 'MQ', 'Martinique', 'Martinique','mtq', 0)\n , (478, 'MR', 'Mauritania', 'Mauretanien','mrt', 0)\n , (480, 'MU', 'Mauritius', 'Mauritius','mus', 0)\n , (175, 'YT', 'Mayotte', 'Mayotte','myt', 0)\n , (484, 'MX', 'Mexico', 'Mexiko','mex', 0)\n , (583, 'FM', 'Micronesia, Federated States of', 'Mikronesien','fsm', 0)\n , (498, 'MD', 'Moldova, Republic of', 'Moldawien (Republik Moldau)','mda', 0)\n , (492, 'MC', 'Monaco', 'Monaco','mco', 0)\n , (496, 'MN', 'Mongolia', 'Mongolei','mng', 0)\n , (499, 'ME', 'Montenegro', 'Montenegro','mne', 0)\n , (500, 'MS', 'Montserrat', 'Montserrat','msr', 0)\n , (504, 'MA', 'Morocco', 'Marokko','mar', 0)\n , (508, 'MZ', 'Mozambique', 'Mosambik','moz', 0)\n , (104, 'MM', 'Myanmar', 'Burma (jetzt Myanmar)','mmr', 0)\n , (516, 'NA', 'Namibia', 'Namibia','nam', 0)\n , (520, 'NR', 'Nauru', 'Nauru','nru', 0)\n , (524, 'NP', 'Nepal', 'Nepal','npl', 0)\n , (540, 'NC', 'New Caledonia', 'Neukaledonien','ncl', 0)\n , (554, 'NZ', 'New Zealand', 'Neuseeland','nzl', 0)\n , (558, 'NI', 'Nicaragua', 'Nicaragua','nic', 0)\n , (562, 'NE', 'Niger', 'Niger','ner', 0)\n , (566, 'NG', 'Nigeria', 'Nigeria','nga', 0)\n , (570, 'NU', 'Niue', 'Niue','niu', 0)\n , (574, 'NF', 'Norfolk Island', 'Norfolkinsel','nfk', 0)\n , (580, 'MP', 'Northern Mariana Islands', 'Nördliche Marianen','mnp', 0)\n , (512, 'OM', 'Oman', 'Oman','omn', 0)\n , (586, 'PK', 'Pakistan', 'Pakistan','pak', 0)\n , (585, 'PW', 'Palau', 'Palau','plw', 0)\n , (275, 'PS', 'Palestinian Territory, Occupied', 'Palästinensische Autonomiegebiete','pse', 0)\n , (591, 'PA', 'Panama', 'Panama','pan', 0)\n , (598, 'PG', 'Papua New Guinea', 'Papua-Neuguinea','png', 0)\n , (600, 'PY', 'Paraguay', 'Paraguay','pry', 0)\n , (604, 'PE', 'Peru', 'Peru','per', 0)\n , (608, 'PH', 'Philippines', 'Philippinen','phl', 0)\n , (612, 'PN', 'Pitcairn', 'Pitcairninseln','pcn', 0)\n , (630, 'PR', 'Puerto Rico', 'Puerto Rico','pri', 0)\n , (634, 'QA', 'Qatar', 'Katar','qat', 0)\n , (638, 'RE', 'Réunion', 'Réunion','reu', 0)\n , (643, 'RU', 'Russian Federation', 'Russische Föderation','rus', 0)\n , (646, 'RW', 'Rwanda', 'Ruanda','rwa', 0)\n , (652, 'BL', 'Saint Barthélemy', 'Saint-Barthélemy','blm', 0)\n , (654, 'SH', 'Saint Helena, Ascension and Tristan da Cunha', 'St. Helena','shn', 0)\n , (659, 'KN', 'Saint Kitts and Nevis', 'St. Kitts und Nevis','kna', 0)\n , (662, 'LC', 'Saint Lucia', 'St. Lucia','lca', 0)\n , (663, 'MF', 'Saint Martin (French part)', 'Saint-Martin (franz. Teil)','maf', 0)\n , (666, 'PM', 'Saint Pierre and Miquelon', 'Saint-Pierre und Miquelon','spm', 0)\n , (670, 'VC', 'Saint Vincent and the Grenadines', 'St. Vincent und die Grenadinen','vct', 0)\n , (882, 'WS', 'Samoa', 'Samoa','wsm', 0)\n , (674, 'SM', 'San Marino', 'San Marino','smr', 0)\n , (678, 'ST', 'Sao Tome and Principe', 'São Tomé und Príncipe','stp', 0)\n , (682, 'SA', 'Saudi Arabia', 'Saudi-Arabien','sau', 0)\n , (686, 'SN', 'Senegal', 'Senegal','sen', 0)\n , (690, 'SC', 'Seychelles', 'Seychellen','syc', 0)\n , (694, 'SL', 'Sierra Leone', 'Sierra Leone','sle', 0)\n , (702, 'SG', 'Singapore', 'Singapur','sgp', 0)\n , (534, 'SX', 'Sint Maarten (Dutch part)', 'Sint Maarten (niederl. Teil)','sxm', 0)\n , (90, 'SB', 'Solomon Islands', 'Salomonen','slb', 0)\n , (706, 'SO', 'Somalia', 'Somalia','som', 0)\n , (239, 'GS', 'South Georgia and the South Sandwich Islands', 'Südgeorgien und die Südlichen Sandwichinseln','sgs', 0)\n , (710, 'ZA', 'South Africa', 'Südafrika','zaf', 0)\n , (728, 'SS', 'South Sudan', 'Südsudan','ssd', 0)\n , (144, 'LK', 'Sri Lanka', 'Sri Lanka','lka', 0)\n , (729, 'SD', 'Sudan', 'Sudan','sdn', 0)\n , (740, 'SR', 'Suriname', 'Suriname','sur', 0)\n , (744, 'SJ', 'Svalbard and Jan Mayen', 'Svalbard und Jan Mayen','sjm', 0)\n , (748, 'SZ', 'Swaziland', 'Swasiland','swz', 0)\n , (760, 'SY', 'Syrian Arab Republic', 'Syrien, Arabische Republik','syr', 0)\n , (158, 'TW', 'Taiwan, Province of China', 'Republik China (Taiwan)','twn', 0)\n , (762, 'TJ', 'Tajikistan', 'Tadschikistan','tjk', 0)\n , (834, 'TZ', 'Tanzania, United Republic of', 'Tansania, Vereinigte Republik','tza', 0)\n , (764, 'TH', 'Thailand', 'Thailand','tha', 0)\n , (626, 'TL', 'Timor-Leste', 'Osttimor (Timor-Leste)','tls', 0)\n , (768, 'TG', 'Togo', 'Togo','tgo', 0)\n , (772, 'TK', 'Tokelau', 'Tokelau','tkl', 0)\n , (776, 'TO', 'Tonga', 'Tonga','ton', 0)\n , (780, 'TT', 'Trinidad and Tobago', 'Trinidad und Tobago','tto', 0)\n , (788, 'TN', 'Tunisia', 'Tunesien','tun', 0)\n , (792, 'TR', 'Turkey', 'Türkei','tur', 0)\n , (795, 'TM', 'Turkmenistan', 'Turkmenistan','tkm', 0)\n , (796, 'TC', 'Turks and Caicos Islands', 'Turks- und Caicosinseln','tca', 0)\n , (798, 'TV', 'Tuvalu', 'Tuvalu','tuv', 0)\n , (800, 'UG', 'Uganda', 'Uganda','uga', 0)\n , (804, 'UA', 'Ukraine', 'Ukraine','ukr', 0)\n , (581, 'UM', 'United States Minor Outlying Islands', 'United States Minor Outlying Islands','umi', 0)\n , (784, 'AE', 'United Arab Emirates', 'Vereinigte Arabische Emirate','are', 0)\n , (840, 'US', 'United States', 'Vereinigte Staaten von Amerika','usa', 0)\n , (858, 'UY', 'Uruguay', 'Uruguay','ury', 0)\n , (860, 'UZ', 'Uzbekistan', 'Usbekistan','uzb', 0)\n , (548, 'VU', 'Vanuatu', 'Vanuatu','vut', 0)\n , (862, 'VE', 'Venezuela, Bolivarian Republic of', 'Venezuela','ven', 0)\n , (704, 'VN', 'Viet Nam', 'Vietnam','vnm', 0)\n , (92, 'VG', 'Virgin Islands, British', 'Britische Jungferninseln','vgb', 0)\n , (850, 'VI', 'Virgin Islands, U.S.', 'Amerikanische Jungferninseln','vir', 0)\n , (876, 'WF', 'Wallis and Futuna', 'Wallis und Futuna','wlf', 0)\n , (732, 'EH', 'Western Sahara', 'Westsahara','esh', 0)\n , (887, 'YE', 'Yemen', 'Jemen','yem', 0)\n , (894, 'ZM', 'Zambia', 'Sambia','zmb', 0)\n , (716, 'ZW', 'Zimbabwe', 'Simbabwe','zwe', 0)\n , (384, 'CI', \"Côte d'Ivoire\", \"Côte d’Ivoire (Elfenbeinküste)\", 'civ', 0)\n , (408, 'KP', \"Korea, Democratic People's Republic of\", \"Korea, Demokratische Volksrepublik (Nordkorea)\", 'prk', 0)\n , (418, 'LA', \"Lao People's Democratic Republic\", \"Laos, Demokratische Volksrepublik\",'lao', 0)\n ]\n\n# And create dict\nCOUNTRIES_dict = {}\n\nfor ele in COUNTRIES:\n COUNTRIES_dict[ele[0]] = ele\n \n \n \n \n","sub_path":"cm/app/api_v1/my_calculation_module_directory/CM/__delete_if_tested__/common_modules/countries.py","file_name":"countries.py","file_ext":"py","file_size_in_byte":15874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"506403859","text":"from aiohttp import web\nimport socketio\n\nfrom enum import Enum, auto\nimport uuid\n\nsio = socketio.AsyncServer(async_mode='aiohttp')\napp = web.Application()\nsio.attach(app)\n\ncurrent_games = {}\n\nclass Game:\n\n class State(Enum):\n Waiting = auto()\n Running = auto()\n Aborted = auto()\n Finished = auto()\n\n def __init__(self):\n self.owner = None\n self.uuid = str(uuid.uuid4())\n self.players = []\n self.state = Game.State.Waiting\n\n\n def is_valid(self):\n return len(self.players) <= 6 and self.state == Game.State.Waiting\n\n@sio.event\nasync def connect(sid, environ):\n print(f'Client {sid} connected')\n await sio.send('Connected to CoupIO server', room=sid)\n\n\n@sio.event\nasync def create_game(sid):\n new_game = Game()\n new_game.owner = sid\n current_games[new_game.uuid] = new_game\n await sio.send(f'New game created', room=sid)\n print(f'Client {sid} create a new game {new_game.uuid}')\n return new_game.uuid\n\n\n\n@sio.event\nasync def start_game(sid, game_uuid): \n game = current_games[game_uuid]\n \n if game.owner != sid:\n await sio.send(f'Only the owner of the game can start the game', room=sid)\n return\n elif len(game.players) < 2:\n await sio.send(f'You need at least 2 players to start a game', room=sid)\n return\n\n game.state = Game.State.Running\n print(f'Client {sid} start the game {game.uuid}')\n\n\n@sio.event\nasync def find_random_game(sid): \n import random\n if current_games:\n game = random.choice(list(current_games.values()))\n return game.uuid\n else:\n await sio.send(f'No game available') \n\n@sio.event\nasync def join_game(sid, game_uuid): \n if len(sio.rooms(sid)) > 1:\n await sio.send(f'You already are in game {sio.rooms(sid)[1]}', room=sid)\n elif game_uuid not in current_games:\n await sio.send(f'Game {game_uuid} does not exists', room=sid)\n elif not current_games[game_uuid].is_valid():\n await sio.send(f'Game {game_uuid} is not available', room=sid)\n else:\n current_games[game_uuid].players.append(sid)\n sio.enter_room(sid, game_uuid)\n await sio.send(f'Game {game_uuid} joined', room=sid)\n await sio.send(f'A new player joined the game', room=game_uuid, skip_sid=sid)\n await sio.emit('player_joined_game', (game_uuid, len(current_games[game_uuid].players), False), room=game_uuid, skip_sid=current_games[game_uuid].owner)\n await sio.emit('player_joined_game', (game_uuid, len(current_games[game_uuid].players), True), room=current_games[game_uuid].owner)\n print(f'Client {sid} join the game {game_uuid}')\n\n@sio.event\nasync def leave(sid, game_uuid):\n sio.leave_room(sid, game_uuid)\n print(f'Client {sid} left game {game_uuid}')\n await sio.send(f'Left room {game_uuid}', room=sid)\n await sio.send('A player left the game', room=game_uuid)\n\n@sio.event\nasync def disconnect(sid):\n for game in sio.rooms(sid):\n if game != sid:\n await leave(sid, game)\n \n print(f'Client {sid} disconnected')\n\n\nif __name__ == '__main__':\n web.run_app(app)","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"200523426","text":"L = [i for i in range(51)]\nL.remove(0)\nsuma_parzystych = 0\nsuma_nieparzystych = 0\nfor x in L:\n if x%2 == 0:\n suma_parzystych += x\n elif x%2 != 0:\n suma_nieparzystych += x\nprint(f'Suma nieparzystych sklada: {suma_nieparzystych}, a suma parzystych: {suma_parzystych}')\n","sub_path":"02-ControlStructures/during class/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"62542429","text":"# --------------\n# Importing header files\r\nimport numpy as np\r\n\r\n# Path of the file has been stored in variable called 'path'\r\n\r\n#New record\r\nnew_record=[[50, 9, 4, 1, 0, 0, 40, 0]]\r\n\r\n#Code starts here\r\ndata=np.genfromtxt(path,delimiter=',',skip_header=1)\r\n\r\ncensus=np.concatenate((data,new_record))\n\n\n# --------------\n#Code starts here\r\nage=census[:,:1]\r\nmax_age=age.max()\r\nmin_age=age.min()\r\nage_mean=age.mean()\r\nage_std=np.std(age)\r\n\n\n\n# --------------\n#Code starts here\r\n# race_0=np.array([r for r in census[:,2:3] if r==0]).reshape(-1)\r\n# race_1=np.array([r for r in census[:,2:3] if r==1]).reshape(-1)\r\n# race_2=np.array([r for r in census[:,2:3] if r==2]).reshape(-1)\r\n# race_3=np.array([r for r in census[:,2:3] if r==3]).reshape(-1)\r\n# race_4=np.array([r for r in census[:,2:3] if r==4]).reshape(-1)\r\n\r\nrace_0=census[census[:,2]==0]\r\nrace_1=census[census[:,2]==1]\r\nrace_2=census[census[:,2]==2]\r\nrace_3=census[census[:,2]==3]\r\nrace_4=census[census[:,2]==4]\r\n\r\n\r\nlen_0=len(race_0)\r\nlen_1=len(race_1)\r\nlen_2=len(race_2)\r\nlen_3=len(race_3)\r\nlen_4=len(race_4)\r\n\r\n# race={}\r\n# race['len_0']=len_0\r\n# race['len_1']=len_1\r\n# race['len_2']=len_2\r\n# race['len_3']=len_3\r\n# race['len_4']=len_4\r\n\r\nrace_list=[len_0,len_1,len_2,len_3,len_4]\r\n\r\n# minority_race=min(race,key=race.get)[-1]\r\n\r\nminority_race=race_list.index(min(race_list))\r\n\r\nprint(race_list)\n\n\n# --------------\n#Code starts here\r\nsenior_citizens=census[census[:,0]>60]\r\nworking_hours_sum=senior_citizens.sum(axis=0)[6]\r\nsenior_citizens_len=len(senior_citizens)\r\navg_working_hours=working_hours_sum/senior_citizens_len\r\nprint(avg_working_hours)\n\n\n# --------------\n#Code starts here\r\nhigh=census[census[:,1]>10]\r\nlow=census[census[:,1]<=10]\r\nprint(high[7])\r\navg_pay_high=high[:,7].mean()\r\navg_pay_low=low[:,7].mean()\r\nprint(avg_pay_high,avg_pay_low,sep='\\n')\n\n\n","sub_path":"numpy_practice/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"409637237","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\nv = 2\na = -0.4\n\ndef gen_data(x):\n y = v*x+a*x*x+np.random.rand(len(x))*0.5\n for _ in range(int(len(y)/3)):\n y[np.random.randint(0, len(y))] += (np.random.rand()-0.3)*3\n return y\n\nx = np.arange(0, 4, 0.05)\ny = gen_data(x)\nfit = np.poly1d(np.polyfit(x, y, 2))\nstd = np.sqrt(np.mean((y-fit(x))**2))\n\nnew_x = []\nnew_y = []\nfor _x, _y in zip(x, y):\n if np.abs(_y-fit(_x)) < std:\n new_x.append(_x)\n new_y.append(_y)\nnew_fit = np.poly1d(np.polyfit(new_x, new_y, 2))\n\nplt.plot(x, y, '.k')\nplt.plot(new_x, new_y, '.r')\nplt.plot(x, fit(x), '--b', label=\"before\")\nplt.plot(x, new_fit(x), '--k', label=\"after\")\nplt.plot(x, v*x+a*x*x+0.25, 'r', label='real')\nplt.legend()\nplt.savefig(\"0512-01-Outlier.png\", bbox_inches='tight')\n","sub_path":"1W11-052-Fitting/0512-01-Outlier.py","file_name":"0512-01-Outlier.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"389354314","text":"#!/usr/bin/python\n\n##################\n# prebleach671.py\n#\n# Copyright David Baddeley, 2009\n# d.baddeley@auckland.ac.nz\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##################\n\n#import all the stuff to make this work\nfrom PYME.Acquire.protocol import *\nimport numpy\n\n#define a list of tasks, where T(when, what, *args) creates a new task\n#when is the frame number, what is a function to be called, and *args are any\n#additional arguments\ntaskList = [\nT(-1, scope.turnAllLasersOff),\n#T(-1, SetCameraShutter, False),\nT(-1, scope.joystick.Enable, False),\n#T(-1, SetEMGain,150),\n#T(20, SetCameraShutter, True),\nT(20, scope.filterWheel.SetFilterPos, \"ND4.5\"),\nT(21, scope.l671.TurnOn),\nT(58, scope.l671.TurnOff),\n#T(60, SetEMGain,0),\nT(61, scope.l671.TurnOn),\nT(61, scope.filterWheel.SetFilterPos, \"EMPTY\"),\n#T(200, SetEMGain,scope.cam.DefaultEMGain),\nT(210, MainFrame.pan_spool.OnBAnalyse, None),\nT(maxint, scope.turnAllLasersOff),\nT(maxint, scope.filterWheel.SetFilterPos, \"ND4.5\"),\nT(maxint, scope.joystick.Enable, True),\n]\n\n#optional - metadata entries\nmetaData = [\n('Protocol.DarkFrameRange', (0, 20)),\n('Protocol.DataStartsAt', 201),\n('Protocol.PrebleachFrames', (21, 58)),\n('Protocol.BleachFrames', (61,200)),\n]\n\n#optional - pre-flight check\n#a list of checks which should be performed prior to launching the protocol\n#syntax: C(expression to evaluate (quoted, should have boolean return), message to display on failure),\npreflight = [\n#C('scope.cam.GetEMGain() == scope.cam.DefaultEMGain', 'Was expecting an intial e.m. gain of %d' % scope.cam.DefaultEMGain),\n#C('scope.cam.GetROIX1() > 1', 'Looks like no ROI has been set'),\nC('scope.cam.GetIntegTime() < .06', 'Camera integration time may be too long'),\n]\n\n#must be defined for protocol to be discovered\nPROTOCOL = TaskListProtocol(taskList, metaData, preflight)\nPROTOCOL_STACK = ZStackTaskListProtocol(taskList, 101, 100, metaData, preflight, randomise = False)\n","sub_path":"PYME/Acquire/Protocols/prebleach671Neo.py","file_name":"prebleach671Neo.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"411107201","text":"from time import sleep\nfrom pyiArduinoI2Cencoder import *\nenc = pyiArduinoI2Cencoder(0x09)\n\ntxt1 = \"Поворотом ручки энкодера добейтесь требуемого\\r\\nкрайнего положения вала сервопривода.\\r\\nНажмите на ручку энкодера...\"\ntxt2 = \"Поворотом ручки энкодера добейтесь другого\\r\\nкрайнего положения вала сервопривода.\\r\\nНажмите на ручку энкодера...\"\n\n# Определяем ширину импульсов для крайних\n# положений вала сервопривода в мкс.\n\ni, j =450, 2450\n\n# Указываем выводу модуля работать с сервоприводом,\n# отведя под управление 2 полных оборота вала энкодера.\nenc.setPinOut(ENC_PIN_MODE_SER, 2)\n\n# Задаём границы поворота сервопривода, указав ширину\n# импульсов в мкс для минимального и максимального угла.\nenc.setServoLimit(i, j)\n\n# Выводим текст информирующий о действиях которые необходимо выполнить.\nprint(txt1)\n\n# Бесконечно ждём нажатия кнопки энкодера ...\nwhile enc.getButton(KEY_PUSHED) == False:\n sleep(.1)\n\n# Получаем ширину импульсов текущего положения вала сервопривода.\ni = enc.getServoWidth()\nprint(\"Ок.\" )\n\n# Бесконечно ждём отпускания кнопки энкодера ...\nwhile enc.getButton(KEY_RELEASED) == False:\n sleep(.1)\n\n# Выводим текст информирующий о действиях которые необходимо выполнить.\nprint(txt2)\n\n# Бесконечно ждём нажатия кнопки энкодера ...\nwhile enc.getButton(KEY_PUSHED) == False :\n sleep(.1)\n\n# Получаем ширину импульсов текущего положения вала сервопривода.\nj = enc.getServoWidth()\nprint(\"Ок.\" )\n\n# Бесконечно ждём отпускания кнопки энкодера ...\nwhile enc.getButton(KEY_RELEASED) == False:\n sleep(.1)\n\n# Задаём новые границы поворота сервопривода, указав ширину импульсов\n# в мкс для минимального и максимального угла.\nenc.setServoLimit(i, j)\n\nprint(\"Калибровка завершена!\")\n\n","sub_path":"pyiArduinoI2Cencoder/examples/ServoCalProc.py","file_name":"ServoCalProc.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"135981721","text":"def write_crew(dir_path):\r\n import pandas as pd\r\n import numpy as np\r\n import json\r\n data = pd.read_csv(dir_path+\"\\\\\"+'data'+\"\\\\\"+'tmdb_5000_credits.csv')\r\n\r\n # We should probably filter out empty data. I'm sure an academy award winner would have visible cast and crew anyways\r\n data = data[data.cast != '[]']\r\n data = data[data.crew != '[]']\r\n\r\n # Parsing our data that is stored as a json\r\n results = data.crew.apply(json.loads).apply(pd.io.json.json_normalize).pipe(lambda x: pd.concat(x.values))\r\n\r\n # Well, we can see that it melted the whole thing down into a few columns. We'll need a movie id to match these up with our films and other data\r\n # We can also see that each movie received its own index, which was appended by our pipe\r\n # I'm going to cheat a little here and merge our data back with a trcik matching indices\r\n # Under the assumption that every film must have at least a zero index, so we can filter on that to generate a dataframe with the same number of films as our original data with our parsed data\r\n movie_ids = results[results.index == 0]\r\n movie_ids = movie_ids.reset_index()\r\n data = data.reset_index()\r\n\r\n # Paring off some junk\r\n del movie_ids['index']\r\n del data['index']\r\n\r\n # Merging all of our data back together\r\n movie_ids = movie_ids.join(data, how='outer')\r\n movie_ids = movie_ids[['credit_id', 'movie_id']]\r\n merged = results.merge(movie_ids, on='credit_id', how='left')\r\n\r\n # Using pandas ffill to assign a movie to every entry in our merged dataframe\r\n merged['movie_id'] = merged['movie_id'].ffill()\r\n\r\n # Checking to see how many different jobs there are.\r\n # This is *without* duplicates, wow. Probably a lot more than we'll need.\r\n pd.unique(merged['job'])\r\n\r\n # Freeing up RAM as we go along\r\n del movie_ids\r\n\r\n # Pivoting all of our data so that each position is a unique column for each film\r\n positions = merged.pivot_table(values='name', index='movie_id', columns = 'job', aggfunc='first')\r\n\r\n # 418 columns is a bit outrageous to work with in this small project. Perhaps with more resources they mey come in handy, but let's try this with only a few key positions\r\n\r\n # Here's a few\r\n\r\n positions = positions.reset_index()\r\n jobs2keep = ['movie_id', 'Associate Producer', 'CG Animator', 'Casting', 'Cinematography', 'Choreographer', 'Costume Design', 'Creator', 'Director', 'Music', 'Post-Production Manager', 'Producer', 'Screenplay', 'Set Designer', 'Sound Director', 'Story']\r\n\r\n#***************************************\r\n positions = positions[jobs2keep]\r\n\r\n return positions\r\n","sub_path":"Modules/clean_crew.py","file_name":"clean_crew.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"89695029","text":"#!/usr/bin/env python3\n\n#author : Simran Kohli simran.kohli@colorado.edu\n#name : lab7main.py\n#purpose : A script to create a web server in flask that will get and display OSPF config info based on user input data\n#date : 2018.03.17\n#version : 1.1\n\n\nfrom flask import Flask, render_template, request\nimport getconfig\nimport diffconfig\nimport ospfconfig\nimport netmiko\nfrom netmiko import ConnectHandler\n\ntry: # try/except block for flask\n\n app = Flask(__name__)\n\n @app.route('/') # the route decorator tells flask which URL you should trigger our function\n def Index(): # the function is given a name which is used to gernerate URLs for that function\n return render_template('Index.html')\n\n @app.route('/GET_config', methods=['GET','POST']) # to save the configs and display the name of saved files\n def GET_config():\n data1 = getconfig.save_run()\n print(data1)\n if request.method == 'GET':\n bodyText = data1 # replace with list containing filenames of saved files\n return render_template('GET_config.html', bodyText=bodyText)\n\n\n @app.route('/OSPF_config',methods=['GET','POST']) # diplays the form for user input\n def OSPF_config():\n return render_template('OSPF_config.html')\n\n\n @app.route('/Diff_config',methods=['GET','POST']) # comapres the running and saved config files\n def Diff_config():\n data1 = diffconfig.save_run()\n #print(data1[0])\n data2 = diffconfig.get_run()\n #print(data2[0])\n data3 = diffconfig.compare(data1[0], data2[0])\n data4 = diffconfig.compare(data1[1], data2[1])\n data5 = diffconfig.compare(data1[2], data2[2])\n data6 = diffconfig.compare(data1[3], data2[3])\n if request.method == 'GET':\n bodyText = [data3,data4,data5,data6] # list containing filenames of saved files\n return render_template('Diff_config.html', bodyText=bodyText)\n\n\n @app.route('/formData1', methods=['GET','POST']) # ospf config user input for R1\n def formData1():\n\n if request.method == 'POST':\n user1 = request.form['username1']\n pass1 = request.form['password1']\n process1 = request.form['process_id1']\n area1 = request.form['area_id1']\n loop1 = request.form['loopback_IP1']\n net1_1 = request.form['network1_1']\n net1_2 = request.form['network1_2']\n\n exceptions = (netmiko.ssh_exception.NetMikoTimeoutException, netmiko.ssh_exception.NetMikoAuthenticationException)\n try: # try/except block for netmiko\n #R1\n dev1 = {\n 'device_type': 'cisco_ios',\n 'ip': loop1,\n 'username': user1,\n 'password': pass1,\n }\n\n # establishes an SSH connection by passing in the device parameters\n\n net_connect1 = ConnectHandler(**dev1)\n\n # for R1\n config_commands1 = ['router ospf ' + process1,\n 'network '+ net1_1 + ' 0.0.0.255 ' + ' area ' + area1,\n 'network '+ net1_2 + ' 0 0.0.0.255 ' + ' area ' + area1,\n 'network '+ loop1 + ' 0.0.0.0 ' + ' area ' + area1,\n ]\n output1 = net_connect1.send_config_set(config_commands1)\n print(output1)\n\n # for graceful exit from SSH session\n net_connect1.disconnect()\n\n except exceptions as b:\n print(\"Error occurred \", b)\n\n return (\"Data entered successfully.\")\n\n else:\n return(\"Please enter data to configure\")\n\n\n\n @app.route('/formData2', methods=['GET','POST']) # ospf config user input for R2\n def formData2():\n\n if request.method == 'POST':\n user2 = request.form['username2']\n pass2 = request.form['password2']\n process2 = request.form['process_id2']\n area2_1 = request.form['area_id21']\n area2_2 = request.form['area_id22']\n loop2 = request.form['loopback_IP2']\n cost1 = request.form['int_cost1']\n net2_1 = request.form['network2_1']\n net2_2 = request.form['network2_2']\n\n exceptions = (netmiko.ssh_exception.NetMikoTimeoutException, netmiko.ssh_exception.NetMikoAuthenticationException)\n try: # try/except block for netmiko\n\n #R2\n dev2 = {\n 'device_type': 'cisco_ios',\n 'ip': loop2,\n 'username': user2,\n 'password': pass2,\n }\n\n # establishes an SSH connection by passing in the device parameters\n\n net_connect2 = ConnectHandler(**dev2)\n\n #for R2\n config_commands2 = ['router ospf ' + process2,\n 'network '+ net2_1 + ' 0.0.0.255 ' + ' area ' + area2_1,\n 'network '+ net2_2 + ' 0.0.0.255 ' + ' area ' + area2_2,\n 'network '+ loop2 + ' 0.0.0.0 ' + ' area ' + area2_2,\n ]\n output2 = net_connect2.send_config_set(config_commands2)\n print(output2)\n\n config_commands3 = ['int f0/0 ',\n 'ip ospf cost ' + cost1,\n ]\n output3 = net_connect2.send_config_set(config_commands3)\n print(output3)\n\n # for graceful exit from SSH session\n net_connect2.disconnect()\n\n except exceptions as b:\n print(\"Error occurred \", b)\n\n\n return (\"Data entered successfully.\")\n\n else:\n return(\"Please enter data to configure\")\n\n\n @app.route('/formData3', methods=['GET','POST']) # ospf config user input for R3\n def formData3():\n\n if request.method == 'POST':\n user3 = request.form['username3']\n pass3 = request.form['password3']\n process3 = request.form['process_id3']\n area3 = request.form['area_id3']\n loop3 = request.form['loopback_IP3']\n net3_1 = request.form['network3_1']\n\n exceptions = (netmiko.ssh_exception.NetMikoTimeoutException, netmiko.ssh_exception.NetMikoAuthenticationException)\n try: # try/except block for netmiko\n\n #R3\n dev4 = {\n 'device_type': 'cisco_ios',\n 'ip': loop3,\n 'username': user3,\n 'password': pass3,\n }\n\n # establishes an SSH connection by passing in the device parameters\n\n net_connect4 = ConnectHandler(**dev4)\n\n # for R3\n config_commands6 = ['router ospf ' + process3,\n 'network '+ net3_1 + ' 0.0.0.255 ' + ' area ' + area3,\n 'network '+ loop3 + ' 0.0.0.0 ' + ' area ' + area3,\n ]\n output6 = net_connect4.send_config_set(config_commands6)\n print(output6)\n\n # for graceful exit from SSH session\n net_connect4.disconnect()\n\n except exceptions as b:\n print(\"Error occurred \", b)\n\n return (\"Data entered successfully.\")\n\n else:\n return(\"Please enter data to configure\")\n\n\n @app.route('/formData4', methods=['GET','POST']) # ospf config user input for R4\n def formData4():\n\n if request.method == 'POST':\n user4 = request.form['username4']\n pass4 = request.form['password4']\n process4 = request.form['process_id4']\n area4_1 = request.form['area_id41']\n area4_2 = request.form['area_id42']\n loop4 = request.form['loopback_IP4']\n cost2 = request.form['int_cost2']\n net4_1 = request.form['network4_1']\n net4_2 = request.form['network4_2']\n\n exceptions = (netmiko.ssh_exception.NetMikoTimeoutException, netmiko.ssh_exception.NetMikoAuthenticationException)\n try: # try/except block for netmiko\n #R4\n dev3 = {\n 'device_type': 'cisco_ios',\n 'ip': loop4,\n 'username': user4,\n 'password': pass4,\n }\n\n # establishes an SSH connection by passing in the device parameters\n\n net_connect3 = ConnectHandler(**dev3)\n\n #for R4\n config_commands4 = ['router ospf ' + process4,\n 'network '+ net4_1 + ' 0.0.0.255 ' + ' area ' + area4_1,\n 'network '+ net4_2 + ' 0.0.0.255 ' + ' area ' + area4_2,\n 'network '+ loop4 + ' 0.0.0.0 ' + ' area ' + area4_2,\n ]\n output4 = net_connect3.send_config_set(config_commands4)\n print(output4)\n\n config_commands5 = ['int f0/0 ',\n 'ip ospf cost ' + cost2,\n ]\n output5 = net_connect3.send_config_set(config_commands5)\n print(output5)\n\n # for graceful exit from SSH session\n net_connect3.disconnect()\n\n except exceptions as b:\n print(\"Error occurred \", b)\n\n return (\"Data entered successfully.\")\n\n else:\n return(\"Please enter data to configure\")\n\n # function calls to verify ospf was configured successfully\n ospfconfig.check_ospf()\n ospfconfig.ping_test()\n\n\n if __name__=='__main__':\n app.debug = True\n app.run(host='127.0.0.1', port =8080)\n\nexcept ImportError:\n print(\"Error: Flask module not found\")\n","sub_path":"nm7/lab7main.py","file_name":"lab7main.py","file_ext":"py","file_size_in_byte":10011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"229791880","text":"import random, sys\n\nnumber = random.randint(1,100)\ncount = 0\n\nprint(\"I'm thinking of a number between 1 and 100\")\n\nwhile True:\n print(\"\\nTake a guess\")\n guess = input()\n try:\n guess = int(guess)\n if guess < number:\n print(\"Your guess is too low\")\n count = count + 1\n continue\n elif guess > number:\n print(\"Your Guess is too high\")\n count = count + 1\n continue\n elif guess == number:\n count = str(count)\n print(\"Good job you guessed my number it took \"+ count+ \" guesses.\")\n sys.exit()\n else:\n print(\"Please enter a vaild guess\")\n except ValueError:\n print(\"Please enter a vaild guess\")","sub_path":"1-2basicsAndFlowControl/guessTheNumber.py","file_name":"guessTheNumber.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"550711223","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nPromote phi variables for stack variables.\n\nWe take the native approach by simply allocating a stack variable for each\nphi variable, and generating store (copy) instructions in predecessor basic\nblocks.\n\nThe main subtleties are:\n\n 1) phis are executed in parallel (semantically)\n\n -> generate all loads before generating any copy instruction for\n phi operands. See the 'swap' problem outlined in Briggs et al.\n\n 2) critical edges (edges from a predecessor with multiple successors, and\n a successor with multiple predecessors) are a problem, since we want to\n generate a copy for only one of the destinations in the predecessor\n\n -> split critical edges before generating copies\n\n\nNOTE: This pass *does not work together with exceptions*! If this runs before\n expanding exceptional control flow without translation back into SSA,\n the results will be incorrect.\n\n\nReferences:\n\n[1]: Practical Improvements to the Construction and Destruction of Static Single\n Assignment Form, Briggs et al\n[2]: Translating Out of Static Single Assignment Form, Sreedhar et al\n[3]: Revisiting Out-of-SSA Translation for Correctness, Code Quality, and\n Efficiency, Boissinot et al\n\"\"\"\n\nfrom __future__ import print_function, division, absolute_import\nimport collections\n\nfrom pykit import types\nfrom pykit.ir import Builder, Op, ops\nfrom pykit.analysis import cfa\n\n#===------------------------------------------------------------------===\n# Critical edges\n#===------------------------------------------------------------------===\n\ndef split_critical_edges(func, cfg, phis):\n \"\"\"\n Split critical edges to correctly handle cycles in phis. See 2) above.\n \"\"\"\n b = Builder(func)\n for block in cfg.node:\n successors = cfg.neighbors(block)\n if len(successors) > 1:\n # More than one successor, we need to split\n # (Alternatively, we could move our copies into the successor block\n # if we were the only predecessor, but this seems simpler)\n\n # Split successors with phis\n new_succs = {} # old_successor -> new_successor\n for succ in successors:\n if phis[succ]:\n label = func.temp(\"split_critical\")\n new_succ = func.new_block(label, after=block)\n new_succs[succ] = new_succ\n b.position_at_end(new_succ)\n b.jump(succ)\n\n # Patch our basic-block terminator to point to new blocks\n if new_succs:\n terminator = block.terminator\n assert terminator.opcode == 'cbranch', terminator\n test, truebb, falsebb = terminator.args\n terminator.set_args([test,\n new_succs.get(truebb, truebb),\n new_succs.get(falsebb, falsebb)])\n\n#===------------------------------------------------------------------===\n# SSA -> stack\n#===------------------------------------------------------------------===\n\ndef generate_copies(func, phis):\n \"\"\"\n Emit stores to stack variables in predecessor blocks.\n \"\"\"\n builder = Builder(func)\n vars = {}\n loads = {}\n\n # Allocate a stack variable for each phi\n builder.position_at_beginning(func.startblock)\n for block in phis:\n for phi in phis[block]:\n vars[phi] = builder.alloca(types.Pointer(phi.type))\n\n # Generate loads in blocks containing the phis\n for block in phis:\n leaders = list(block.leaders)\n last_leader = leaders[-1] if leaders else block.head\n builder.position_after(last_leader)\n for phi in phis[block]:\n loads[phi] = builder.load(vars[phi])\n\n # Generate copies (store to stack variables)\n for block in phis:\n for phi in phis[block]:\n preds, args = phi.args\n var = vars[phi]\n phi_args = [loads.get(arg, arg) for arg in args]\n for pred, arg in zip(preds, phi_args):\n builder.position_before(pred.terminator)\n builder.store(arg, var)\n\n # Replace phis\n for block in phis:\n for phi in phis[block]:\n phi.replace_uses(loads[phi])\n phi.delete()\n\n return vars, loads\n\n#===------------------------------------------------------------------===\n# Driver\n#===------------------------------------------------------------------===\n\ndef find_phis(func):\n \"\"\"Map blocks to phis found in the block\"\"\"\n phis = {}\n for block in func.blocks:\n phis[block] = []\n for op in block.leaders:\n if op.opcode == 'phi':\n phis[block].append(op)\n\n return phis\n\ndef reg2mem(func, env=None):\n cfg = cfa.cfg(func, exceptions=False) # ignore exc_setup\n split_critical_edges(func, cfg, find_phis(func))\n vars, loads = generate_copies(func, find_phis(func))\n return vars, loads\n\ndef run(func, env):\n reg2mem(func, env)","sub_path":"pykit/transform/reg2mem.py","file_name":"reg2mem.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"496409236","text":"# Count vowel\nstring = input(\"Enter your string: \")\nlower_vowel = [\"a\", \"e\", \"i\", \"o\", \"u\"]\nupper_vowel = [\"A\", \"E\", \"I\", \"O\", \"U\"]\nl_count = 0\nu_count = 0\nfor x in string:\n if x in lower_vowel:\n l_count += 1\n elif x in upper_vowel:\n u_count += 1\nprint(\"Input: \", string)\nprint(\"Lower Vowel: \", l_count)\nprint(\"Upper Vowel: \", u_count)\n\n# Sample Case:\n'''\nEnter your string: Amit Kumar\nInput: Amit Kumar\nLower Vowel: 3\nUpper Vowel: 1\n'''\n","sub_path":"submissions/sm_102_amit/week_14/day_3/evaluation/count_vowels.py","file_name":"count_vowels.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"441416356","text":"'''==========================================\n\n第一題-LeapYear_NotOOP\n\n=========================================='''\n\n# 判斷閏年函式\ndef isLeapYear(newYear):\n # 是閏年回傳true,否則回傳false\n\tif newYear % 4 == 0 and newYear % 100 != 0 or newYear % 400 == 0:\n\t\treturn True\n\telse:\n\t\treturn False\n\n# 主程式\nif __name__ == \"__main__\":\n # 迴圈執行三次\n for i in range(3):\n # 輸入\n year = int(input())\n # 呼叫函式判斷\n if isLeapYear(year):\n print(\"The %d is leap year.\" % (year))\n else:\n print(\"The %d isn't leap year.\" % (year))","sub_path":"Python 實習練習/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"211421615","text":"#ApathyWorks\n\n\n\noption = 0\nphonebook_dict = {\n \"John Doe\": \"555-555-0001\",\n \"Jane Doe\": \"555-555-0002\",\n \"Joe Schmoe\": \"555-555-0003\",\n \"Nancy Wheeler\": \"555-555-5277\",\n \"Jonathon Byers\": \"555-555-4433\",\n \"Demo\": \"555-555-4355\"\n}\n\n#Main Menu\nprint(\"Phone book\") \nprint(\"=============\")\nwhile True:\n print(\"Phone book\")\n print(\"=============\")\n print(\"1. Look up an entry\")\n print(\"2. Create or change an entry\")\n print(\"3. Delete an entry\")\n print(\"4. List all entries\")\n print(\"5. Quit\")\n\n #This While loop gets user input.\n while True:\n try:\n option = int(input(\">> \"))\n break\n except:\n print(\"Input a valid command\")\n\n #This if statement evaluates user input\n if option == 1:\n locator = input(\"Enter a name: \").lower() #Get a name to search and make it lowercase. I make it lowercase so that the user can type the search term in any case they wish.\n \n is_entry_found = False\n for key in phonebook_dict: #This for loop searches each entry for the user's input.\n if key.lower() == locator: #I also make key(name) lowercase.\n print(f\"{key}: {phonebook_dict[key]}\")\n is_entry_found = True #Tells me if anything was was found.\n if is_entry_found == False: \n print(\"No entries found.\")\n\n print(\"Search Complete\")\n elif option == 2:\n new_contact = input(\"Input a name: \")\n new_number = input(\"Input a number (555-555-5555): \")\n\n answer = input(f\"Is {new_contact}: {new_number} correct? Y/N \").lower() #Gets user input to confirm changes.\n #A potential improvement is to verify if the user is overwriting an entry.\n while True:\n if answer == \"y\":\n phonebook_dict[new_contact] = new_number\n print(\"Contact Saved.\")\n break\n elif answer == \"n\":\n print(\"Contact not saved\")\n else:\n answer = input(\"Input Y/N \")\n elif option == 3:\n marked_contact = input(\"Enter a name for deletion: \").lower() #Get user input for contact to delete.\n is_entry_found = False\n for key in phonebook_dict:\n if key.lower() == marked_contact: #If the user input is in the phone book.\n is_entry_found = True\n answer = input(f\"Would you like to delete {key}? Y/N \").lower() #Get user confirmation.\n if answer == \"y\":\n del phonebook_dict[key]\n print(\"Contact Deleted\")\n elif answer == \"n\":\n print(\"Contact not Deleted.\")\n else:\n answer = input(\"Input Y/N \")\n if is_entry_found == False:\n print(\"No entries found.\")\n elif option == 4:\n for key in phonebook_dict:\n print(f\"{key}: {phonebook_dict[key]}\")\n elif option == 5:\n exit(0)\n else:\n print(\"Input a valid command\")\n\n\n\n\n\n","sub_path":"02-week/1-tuesday/labs/henderson-ephriam/phone-book.py","file_name":"phone-book.py","file_ext":"py","file_size_in_byte":3029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"174695461","text":"#!/usr/bin/env python\n\"\"\"\nPlot VOD anomaly during Millennium drought\n\nVOD (1993_2012) data from:\n/srv/ccrc/data04/z3509830/LAI_precip_variability/Data/Vegetation_indices/VOD\n\n\"\"\"\n__author__ = \"Martin De Kauwe\"\n__version__ = \"1.0 (29.09.2019)\"\n__email__ = \"mdekauwe@gmail.com\"\n\nimport os\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import colors\nimport cartopy.crs as ccrs\nimport cartopy\nfrom cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\nimport sys\nimport matplotlib.ticker as mticker\nfrom cartopy.mpl.geoaxes import GeoAxes\nfrom mpl_toolkits.axes_grid1 import AxesGrid\n\ndef main(fname, plot_dir):\n\n ds = xr.open_dataset(fname, decode_times=False)\n bottom, top = np.min(ds.latitude).values, np.max(ds.latitude).values\n left, right =np.min(ds.longitude).values, np.max(ds.longitude).values\n\n ntime, nrows, ncols = ds.VOD.shape\n\n # Get baseline period\n # 1993-1999\n nyears = 7\n vod_pre = np.zeros((nyears,nrows,ncols))\n vals = np.zeros((3,nrows,ncols))\n yr_count = 0\n count = 0\n for year in np.arange(1993, 2000):\n for month in np.arange(1, 13):\n\n if month == 12:\n\n if year == 1993:\n\n lats = ds.latitude.values\n lons = ds.longitude.values\n lats.tofile(\"lat_vod.bin\")\n lons.tofile(\"lon_vod.bin\")\n print(lats.shape)\n print(lons.shape)\n\n vod_count = np.zeros((nrows,ncols))\n\n vals = ds.VOD[count,:,:].values\n vals = np.where(np.isnan(vals), 0.0, vals)\n vod_count = np.where(vals > 0.0, vod_count+1, vod_count)\n vod_pre[yr_count,:,:] += vals\n\n vals = ds.VOD[count+1,:,:].values\n vals = np.where(np.isnan(vals), 0.0, vals)\n vod_count = np.where(vals > 0.0, vod_count+1, vod_count)\n vod_pre[yr_count,:,:] += vals\n\n vals = ds.VOD[count+2,:,:].values\n vals = np.where(np.isnan(vals), 0.0, vals)\n vod_count = np.where(vals > 0.0, vod_count+1, vod_count)\n vod_pre[yr_count,:,:] += vals\n\n vod_pre[yr_count,:,:] /= vod_count\n\n count += 1\n yr_count += 1\n\n vod_pre = np.mean(vod_pre, axis=0)\n vod_pre = np.flipud(vod_pre)\n\n # We will have incremented the counter by one too many on the final\n # iteration, fix this as we need to start at the right point for 2000\n count = count - 1\n\n # 2000-2009\n nyears = 10\n vod_dur = np.zeros((nyears,nrows,ncols))\n yr_count = 0\n for year in np.arange(2000, 2010):\n for month in np.arange(1, 13):\n\n if month == 12:\n\n vod_count = np.zeros((nrows,ncols))\n\n vals = ds.VOD[count,:,:].values\n vals = np.where(np.isnan(vals), 0.0, vals)\n vod_count = np.where(vals > 0.0, vod_count+1, vod_count)\n vod_dur[yr_count,:,:] += vals\n\n vals = ds.VOD[count+1,:,:].values\n vals = np.where(np.isnan(vals), 0.0, vals)\n vod_count = np.where(vals > 0.0, vod_count+1, vod_count)\n vod_dur[yr_count,:,:] += vals\n\n vals = ds.VOD[count+2,:,:].values\n vals = np.where(np.isnan(vals), 0.0, vals)\n vod_count = np.where(vals > 0.0, vod_count+1, vod_count)\n vod_dur[yr_count,:,:] += vals\n\n vod_dur[yr_count,:,:] /= vod_count\n\n\n count += 1\n yr_count += 1\n\n vod_dur = np.mean(vod_dur, axis=0)\n vod_dur = np.flipud(vod_dur)\n\n chg = ((vod_dur - vod_pre) / vod_pre) * 100.0\n print(chg.shape)\n chg.tofile(\"md_change.bin\")\n\n fig = plt.figure(figsize=(9, 6))\n plt.rcParams['font.family'] = \"sans-serif\"\n plt.rcParams['font.size'] = \"14\"\n plt.rcParams['font.sans-serif'] = \"Helvetica\"\n\n cmap = plt.cm.get_cmap('BrBG', 10) # discrete colour map\n\n projection = ccrs.PlateCarree()\n axes_class = (GeoAxes, dict(map_projection=projection))\n rows = 1\n cols = 1\n\n axgr = AxesGrid(fig, 111, axes_class=axes_class,\n nrows_ncols=(rows, cols),\n axes_pad=0.2,\n cbar_location='right',\n cbar_mode='single',\n cbar_pad=0.5,\n cbar_size='5%',\n label_mode='') # note the empty label_mode\n\n\n for i, ax in enumerate(axgr):\n # add a subplot into the array of plots\n #ax = fig.add_subplot(rows, cols, i+1, projection=ccrs.PlateCarree())\n plims = plot_map(ax, chg, cmap, i, top, bottom, left, right)\n\n import cartopy.feature as cfeature\n states = cfeature.NaturalEarthFeature(category='cultural',\n name='admin_1_states_provinces_lines',\n scale='10m',facecolor='none')\n\n # plot state border\n SOURCE = 'Natural Earth'\n LICENSE = 'public domain'\n ax.add_feature(states, edgecolor='black', lw=0.5)\n\n cbar = axgr.cbar_axes[0].colorbar(plims)\n cbar.ax.set_title(\"% Difference\", fontsize=16, pad=10)\n #cbar.ax.set_yticklabels([' ', '-30', '-15', '0', '15', '<=70'])\n\n props = dict(boxstyle='round', facecolor='white', alpha=0.0, ec=\"white\")\n ax.text(0.95, 0.05, \"(a)\", transform=ax.transAxes, fontsize=12,\n verticalalignment='top', bbox=props)\n\n ofname = os.path.join(plot_dir, \"vod.png\")\n fig.savefig(ofname, dpi=300, bbox_inches='tight',\n pad_inches=0.1)\n\n\ndef plot_map(ax, var, cmap, i, top, bottom, left, right):\n print(np.nanmin(var), np.nanmax(var))\n vmin, vmax = -30., 30.\n #top, bottom = 89.8, -89.8\n #left, right = 0, 359.8\n img = ax.imshow(var, origin='lower',\n transform=ccrs.PlateCarree(),\n interpolation='nearest', cmap=cmap,\n extent=(left, right, bottom, top),\n vmin=vmin, vmax=vmax)\n ax.coastlines(resolution='10m', linewidth=1.0, color='black')\n #ax.add_feature(cartopy.feature.OCEAN)\n\n ax.set_xlim(140.7, 154)\n ax.set_ylim(-39.2, -28.1)\n\n if i == 0 or i >= 5:\n\n gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,\n linewidth=0.5, color='black', alpha=0.5,\n linestyle='--')\n else:\n gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=False,\n linewidth=0.5, color='black', alpha=0.5,\n linestyle='--')\n\n #if i < 5:\n #s gl.xlabels_bottom = False\n if i > 5:\n gl.ylabels_left = False\n\n gl.xlabels_top = False\n gl.ylabels_right = False\n gl.xlines = False\n gl.ylines = False\n gl.xformatter = LONGITUDE_FORMATTER\n gl.yformatter = LATITUDE_FORMATTER\n\n gl.xlocator = mticker.FixedLocator([141, 145, 149, 153])\n gl.ylocator = mticker.FixedLocator([-29, -32, -35, -38])\n\n return img\n\n\n\nif __name__ == \"__main__\":\n\n plot_dir = \"/Users/mdekauwe/Dropbox/Drought_risk_paper/figures/figs\"\n\n #fname = \"raw/Australia_VOD_monthly_1993_2012_masked_gapfilled.nc\"\n fname = \"Australia_VOD_monthly_1993_2012_non-masked_gapfilled_no_missing.nc\"\n main(fname, plot_dir)\n","sub_path":"VOD/plot_VOD_drought_anomaly.py","file_name":"plot_VOD_drought_anomaly.py","file_ext":"py","file_size_in_byte":7336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"548736209","text":"import math\nimport pandas\n\n\n# Defining the function with 3 parameter\ndef calculator(excel_path, price_index):\n # Loading the excel (D:\\\\testing\\\\values.xlsx) values into a Pandas Dataframe\n df = pandas.read_excel(excel_path)\n\n # The value of x\n x = float(df[\"Price\"][price_index])\n\n # The value of x\n y = float(input(\"Enter te value of y: \"))\n\n # The final result\n result = round(math.pow(x / y, 2))\n\n # Returning the result\n return result\n\n# calculator(\"D:\\\\testing\\\\values.xlsx\", 0)\n\n# End of program\n","sub_path":"super-hero-level/pytest3.py","file_name":"pytest3.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"438987544","text":"HWNM = input().split()\n\n# Image Height and Width\nimage_height = int(HWNM[0])\nimage_width = int(HWNM[1])\n\n# Kernel Height and Width\nkernel_height = int(HWNM[2])\nkernel_width = int(HWNM[3])\n\n# Matrix Height and Width\nmatrix_height = image_height - kernel_height + 1\nmatrix_width = image_width - kernel_width + 1\n\n# Image Input\nimage = []\n\nfor index in range(image_height):\n row = input().split()\n\n for col in range(len(row)):\n row[col] = int(row[col])\n\n image.append(row)\n\n# Kernel Input\nkernel = []\n\nfor index in range(kernel_height):\n row = input().split()\n\n for col in range(len(row)):\n row[col] = int(row[col])\n\n kernel.append(row)\n\nkernel.reverse()\n\nfor index in kernel:\n index.reverse()\n\n# Matrix Output\nmatrix = []\nmatrix_sum = 0\n\nfor m_height in range(matrix_height):\n matrix_row = []\n\n for m_width in range(matrix_width):\n matrix_sum = 0\n\n for k_height in range(kernel_height):\n\n for k_width in range(kernel_width):\n matrix_sum += image[m_height + k_height][m_width + k_width] * int(kernel[k_height][k_width])\n\n matrix_row.append(matrix_sum)\n matrix.append(matrix_row)\n\nfor row in matrix:\n for index in row:\n print(str(index) + \" \", end=\"\")\n print()\n","sub_path":"March 26/Image_Processing.py","file_name":"Image_Processing.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"583349079","text":"import tensorflow as tf\nimport numpy as np\nimport glob\n\n\ndef get_raw_keras_model():\n\n return tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28, 28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(10),\n tf.keras.layers.Softmax(),\n ])\n\n\ndef get_compiled_model():\n\n model = get_raw_keras_model()\n optimizer = 'adam'\n loss_fn = tf.keras.losses.SparseCategoricalCrossentropy()\n metrics = [tf.keras.metrics.SparseCategoricalAccuracy()]\n model.compile(optimizer=optimizer, loss=loss_fn, metrics=metrics)\n return model\n\n\ndef load_model_from_file(file_path):\n \n return tf.keras.models.load_model(file_path)\n\n\ndef load_dataset(batch_size):\n\n (X_train, y_train), (X_test, y_test) = tf.keras.datasets.mnist.load_data()\n train_length = len(X_train)\n test_length = len(X_test)\n X_train, X_test = X_train / 255.0, X_test / 255.0\n train_dataset = tf.data.Dataset.from_tensor_slices(\n (X_train, y_train)).batch(batch_size)\n test_dataset = tf.data.Dataset.from_tensor_slices(\n (X_test, y_test)).batch(batch_size)\n return train_dataset, test_dataset, train_length, test_length\n\n\ndef federated_avg_weights(all_client_weights, weights=None):\n \n return np.average(np.array(all_client_weights), axis=0, weights=weights)\n\n\ndef get_client_model_weights(worker_model_folder, round_num):\n \n client_weights = []\n for model_weights in glob.glob(f'{worker_model_folder}/round_{round_num}_worker_*[0-9].h5'):\n temp_model = load_model_from_file(f'{model_weights}')\n client_weights.append(temp_model.get_weights())\n return client_weights\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"148884601","text":"\"\"\"\nFile: skeet.py\nOriginal Author: Br. Burton\nCompleted By: Jaden Mounteer\nThis program implements an awesome version of skeet.\n\"\"\"\nimport arcade\nimport math\nimport random\n\n# These are Global constants to use throughout the game\nSCREEN_WIDTH = 600\nSCREEN_HEIGHT = 500\n\nRIFLE_WIDTH = 20 \nRIFLE_HEIGHT = 100 \nRIFLE_COLOR = arcade.color.DARK_RED\n\nBULLET_RADIUS = 3\nBULLET_COLOR = arcade.color.BLACK_OLIVE\nBULLET_SPEED = 10\n\nTARGET_RADIUS = 20\nTARGET_COLOR = arcade.color.CARROT_ORANGE\nTARGET_SAFE_COLOR = arcade.color.AIR_FORCE_BLUE\nTARGET_SAFE_RADIUS = 15\n\nclass Point():\n \"\"\"\n This class represents a point in the game.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Sets up the initial conditions of the point.\n :param x: float\n :param x: float\n \"\"\"\n self.x = 0\n self.y = 0\n\nclass Velocity():\n \"\"\"\n This class represents the velocity of an object.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Sets up the initial conditions of the velocity.\n :param dx: float\n :param dy: float\n \"\"\"\n self.dx = 0\n self.dy = 0\n\nclass Flying_Object():\n \"\"\"\n This class represents a flying object in the game.\n \"\"\"\n def __init__(self):\n # Creates a member variable called center and sets it to the Point class.\n self.center = Point()\n # Creates a member variable called velocity and sets it to the Velocity class.\n self.velocity = Velocity()\n # Creates a member variable for radius.\n self.radius = 0.0\n # Creates a member variable called alive and sets it to True.\n self.alive = True\n\n\n def advance(self):\n \"\"\"\n Makes the object move if it is alive.\n :return: None\n \"\"\"\n if self.alive:\n self.center.x += self.velocity.dx\n self.center.y += self.velocity.dy\n\n\n def draw(self):\n \"\"\"\n Draws the object.\n :return: None\n \"\"\"\n pass\n\n def is_off_screen(self, screen_width, screen_height):\n \"\"\"\n Checks to see if the object is off the screen.\n :param screen_width:\n :param screen_height:\n :return: Boolean\n \"\"\"\n if self.center.x < 0.0 or self.center.x > screen_width:\n return True\n if self.center.y < 0.0 or self.center.y > SCREEN_HEIGHT:\n return False\n\nclass Bullet(Flying_Object):\n \"\"\"\n A flying bullet. Child class of the Flying_object class.\n Overrides the center, velocity, and radius member variables.\n Adds a draw() method to the class.\n Adds a fire() method to the class.\n Adds an advance() method to the class.\n \"\"\"\n def __init__(self):\n \"\"\"\n Initializes the bullet.\n \"\"\"\n # Uses Super() here in order to override some attributes of the Flying_object class, while keeping others.\n super().__init__()\n\n # Overrides the radius member variable and gives it the value of BULLET_RADIUS.\n self.radius = BULLET_RADIUS\n\n # Initializes the bullets at the corner of the screen, inside the barrel.\n self.center.x = 0\n self.center.y = 0\n\n def draw(self):\n \"\"\"\n Draws a bullet to the screen.\n Renders it as a filled-in circle.\n :return: None\n \"\"\"\n arcade.draw_circle_filled(self.center.x, self.center.y, self.radius, BULLET_COLOR)\n\n def fire(self, angle: float):\n \"\"\"\n Fires the bullet.\n :param angle:\n :return:\n \"\"\"\n # --- Inverted ---\n # Angles the bullet horizontally.\n #self.velocity.dx = math.cos(math.radians(angle)) * BULLET_SPEED\n # Angles the bullet vertically.\n #self.velocity.dy = math.sin(math.radians(angle)) * BULLET_SPEED\n # Changes the alive variable to True. Is this necessary?\n #self.alive = True\n\n # --- Correct ---\n # Angles the bullet horizontally.\n self.velocity.dx = math.sin(math.radians(angle)) * BULLET_SPEED\n # Angles the bullet vertically.\n self.velocity.dy = math.cos(math.radians(angle)) * BULLET_SPEED\n # Changes the alive variable to True. Is this necessary?\n self.alive = True\n\nclass Target(Flying_Object):\n \"\"\"\n A flying standard target. Child class of the Flying_object class.\n Overrides the center, velocity, and radius attributes.\n Adds an alive member variable.\n Adds a draw() method to the class.\n Adds a hit() method to the class.\n \"\"\"\n def __init__(self):\n # Uses Super() here in order to override some attributes of the Flying_object class, while keeping others.\n super().__init__()\n\n # Makes the target spawn anywhere in the left hand corner of the screen.\n self.center.x = 0.0\n self.center.y = random.randint(SCREEN_HEIGHT // 2, SCREEN_HEIGHT - 50)\n\n # Declares a member variable for lives\n self.lives = 1\n\n # Overrides the radius member variable and gives it the value of TARGET_RADIUS.\n self.radius = TARGET_RADIUS\n\n # Overrides the velocity member variables and gives them the value of the standard target speed.\n self.velocity.dx = random.uniform(1, 5) # Gives the target a random horizontal velocity between 1 and 5 pixels/frame.\n self.velocity.dy = random.uniform(-2, 5) # Gives the target a random vertical velocity between -2 and 5 pixesl/frame.\n\n def draw(self):\n \"\"\"\n Draws a target to the screen.\n The initial position of the target is anywhere along the top\n half of the left side of the screen.\n :return:\n \"\"\"\n arcade.draw_circle_filled(self.center.x, self.center.y, self.radius, TARGET_COLOR)\n\n def hit(self):\n \"\"\"\n Represents the target getting hit.\n Kills the standard target in one hit.\n and returns an integer representing the points scored for that hit.\n :return: int\n \"\"\"\n print(\"A regular target was hit.\")\n self.alive = False\n # Returns the number of points.\n return 1\n\n\nclass Strong_target(Target):\n \"\"\"\n Represents a strong target.\n Inherits from the Target class.\n Moves more slowly than the others.\n Its horizontal velocity should be taken from the range 1 to 3.\n Its vertical velocity from the range -2 to +3.\n Takes 3 hits to destroy.\n 1 point is awarded for each of the first two hits.\n 5 points are awarded for the third hit that destroys the target.\n \"\"\"\n def __init__(self):\n # Uses Super() here in order to override some attributes of the Target class, while keeping others.\n super().__init__()\n\n # Overrides the velocity member variables\n self.velocity.dx = random.uniform(1, 3)\n self.velocity.dy = random.uniform(-2, 3)\n\n # Declares a member variable for lives\n self.lives = 3\n\n def draw(self):\n \"\"\"\n Draws a circle with a number inside of it.\n \"\"\"\n arcade.draw_circle_outline(self.center.x, self.center.y, self.radius, arcade.color.PEACH)\n text_x = self.center.x - (self.radius / 2)\n text_y = self.center.y - (self.radius / 2)\n arcade.draw_text(repr(self.lives), text_x, text_y, TARGET_COLOR, font_size=20)\n\n def hit(self):\n \"\"\"\n Represents the target getting hit.\n Kills the standard target in one hit.\n and returns an integer representing the points scored for that hit.\n :return: int\n \"\"\"\n print(\"A strong target was hit\")\n # Initiates the number of points at 0.\n points = 0\n\n # If the target has 3 lives\n if self.lives == 3:\n # Adds 1 point to points.\n points = 1\n # Decrements lives by 1\n self.lives -= 1\n\n # If the target has 2 lives.\n if self.lives == 2 and points == 0:\n # adds 1 point to points.\n points = 1\n # Decrements lives by 1\n self.lives -= 1\n\n # If the target has 1 life\n if self.lives == 1 and points == 0:\n # Adds 5 points to points\n points = 5\n # Decrements lives by 1.\n self.lives -= 1\n\n # If the target runs out of lives.\n if self.lives <= 0:\n self.alive = False\n\n # Returns the number of points.\n return points\n\n\nclass Safe_target(Target):\n \"\"\"\n This class represents a safe target in the game.\n It is rendered as a square,\n It should not be hit.\n A penaly of 10 points is incurred if this target is hit.\n \"\"\"\n def __init__(self):\n # Uses Super() here in order to override some attributes of the Target class, while keeping others.\n super().__init__()\n\n def draw(self):\n \"\"\"\n Draws the target as a square to the screen.\n \"\"\"\n arcade.draw_rectangle_filled(center_x=self.center.x, center_y=self.center.y, height=50, width=50, color=TARGET_SAFE_COLOR)\n\n def hit(self):\n \"\"\"\n Represents the target getting hit.\n Kills the standard target in one hit.\n Takes away the 10 points from the player.\n :return: int\n \"\"\"\n self.alive = False\n # Returns the number of points.\n return -10\n\n\nclass Rifle:\n \"\"\"\n The rifle is a rectangle that tracks the mouse.\n \"\"\"\n def __init__(self):\n self.center = Point() # This was originally set to (25,25)\n self.center.x = 0\n self.center.y = 0\n\n self.angle = 45\n\n def draw(self):\n arcade.draw_rectangle_filled(self.center.x, self.center.y, RIFLE_WIDTH, RIFLE_HEIGHT, RIFLE_COLOR, self.angle)\n\n\nclass Game(arcade.Window):\n \"\"\"\n This class handles all the game callbacks and interaction\n It assumes the following classes exist:\n Rifle\n Target (and it's sub-classes)\n Point\n Velocity\n Bullet\n This class will then call the appropriate functions of\n each of the above classes.\n You are welcome to modify anything in this class, but mostly\n you shouldn't have to. There are a few sections that you\n must add code to.\n \"\"\"\n\n def __init__(self, width, height, title):\n \"\"\"\n Sets up the initial conditions of the game\n :param width: Screen width\n :param height: Screen height\n \"\"\"\n super().__init__(width, height, title)\n\n self.rifle = Rifle()\n self.score = 0\n self.time = 75\n self.number_of_bullets_shot = 0\n self.number_of_targets_shot = 0\n self.number_of_points_scored = 0\n self.is_game_over = False\n self.game_started = False\n self.time_to_start_game = 30\n \n\n # Creates a list for the bullets.\n self.bullets = []\n\n # Creates a list for the targets\n self.targets = []\n\n arcade.set_background_color(arcade.color.SKY_BLUE)\n\n def on_draw(self):\n \"\"\"\n Called automatically by the arcade framework.\n Handles the responsibility of drawing all elements.\n \"\"\"\n\n # clear the screen to begin drawing\n arcade.start_render()\n\n\n # ___Draws each object___\n \n\n # Iterates through the bullets and draws them.\n for bullet in self.bullets:\n bullet.draw()\n \n # Draws the rifle after the bullets so that the bullets are only visible once they leave\n # the barrel.\n self.rifle.draw()\n\n # Iterates through the targets and draws them.\n for target in self.targets:\n target.draw()\n\n # Draws the game instructions before the game begins.\n if self.game_started == False:\n self.draw_instructions()\n\n self.draw_score()\n\n # If the game is over, displays Game over to the screen.\n if self.is_game_over == True:\n self.draw_game_over()\n\n def draw_score(self):\n \"\"\"\n Puts the current score on the screen\n \"\"\"\n score_text = \"Score: {}\".format(self.score)\n start_x = 10\n start_y = SCREEN_HEIGHT - 20\n arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=12, color=arcade.color.NAVY_BLUE)\n\n # Draws the player's time.\n formatted_time = \"{:.2f}\".format(self.time)\n score_text = \"Time Remaining: {}\".format(formatted_time)\n start_x = 100\n start_y = SCREEN_HEIGHT - 20\n arcade.draw_text(score_text, start_x=start_x, start_y=start_y, font_size=12, color=arcade.color.NAVY_BLUE)\n\n def draw_instructions(self):\n \"\"\"\n Draws the words:\n Skeet Shoot\n A game made by Jaden Mounteer using Python 3.\n Shoot targets until time runs out.\n Don't shoot the squares!\n \"\"\"\n title = \"SKEET SHOOT\"\n start_x = 10\n start_y = SCREEN_HEIGHT - 100\n arcade.draw_text(title, start_x=start_x, start_y=start_y, font_size=50, color=arcade.color.NAVY_BLUE)\n author_info = \"A game made by Jaden Mounteer\"\n start_x_2 = 10\n start_y_2 = SCREEN_HEIGHT - 130\n arcade.draw_text(author_info, start_x=start_x_2, start_y=start_y_2, font_size=25, color=arcade.color.NAVY_BLUE)\n more_author_info = \"using Python 3\"\n start_x_3 = 10\n start_y_3 = SCREEN_HEIGHT - 170\n arcade.draw_text(more_author_info, start_x=start_x_3, start_y=start_y_3, font_size=25, color=arcade.color.NAVY_BLUE)\n\n instructions1 = \"Instructions:\"\n start_x_4 = 10\n start_y_4 = SCREEN_HEIGHT / 2\n arcade.draw_text(instructions1, start_x=start_x_4, start_y=start_y_4, font_size=25,\n color=arcade.color.NAVY_BLUE)\n instructions2 = \"Left click to shoot. Use the mouse to aim.\"\n start_x_5 = 10\n start_y_5 = SCREEN_HEIGHT / 2 - 30\n arcade.draw_text(instructions2, start_x=start_x_5, start_y=start_y_5, font_size=25,\n color=arcade.color.NAVY_BLUE)\n\n instructions3 = \"Shoot as many targets as you can before\"\n start_x_6 = 10\n start_y_6 = SCREEN_HEIGHT / 2 - 60\n arcade.draw_text(instructions3, start_x=start_x_6, start_y=start_y_6, font_size=25,\n color=arcade.color.NAVY_BLUE)\n\n instructions4 = \"time runs out.\"\n start_x_7 = 10\n start_y_7 = SCREEN_HEIGHT / 2 - 90\n arcade.draw_text(instructions4, start_x=start_x_7, start_y=start_y_7, font_size=25,\n color=arcade.color.NAVY_BLUE)\n\n instructions4 = \"Don't shoot the squares!\"\n start_x_8 = 10\n start_y_8 = SCREEN_HEIGHT / 2 - 120\n arcade.draw_text(instructions4, start_x=start_x_8, start_y=start_y_8, font_size=25,\n color=arcade.color.NAVY_BLUE)\n\n\n def update(self, delta_time):\n \"\"\"\n Update each object in the game.\n :param delta_time: tells us how much time has actually elapsed\n \"\"\"\n self.check_collisions()\n self.check_off_screen()\n\n # decide if we should start a target by giving a 1 in 50 chance.\n if random.randint(1, 50) == 1:\n self.create_target()\n\n # Iterates through the bullets and tells them to advance.\n for bullet in self.bullets:\n bullet.advance()\n\n # Iterates through the targets and tells them to advance.\n for target in self.targets:\n target.advance()\n\n # Checks to see if the game has started.\n self.start_game()\n \n # Checks to see if the player has lost yet.\n self.is_game_over = self.game_over()\n\n\n def create_target(self):\n \"\"\"\n Creates a new target of a random type and adds it to the list.\n New targets are created wih 1/50 probability.\n :return:\n \"\"\"\n\n # Creates instances of the available target types.\n target = Target()\n strong_target = Strong_target()\n safe_target = Safe_target()\n\n # Decides which type of target to create.\n target_to_create = random.randint(1, 5)\n #print(target_to_create)\n if target_to_create == 1:\n self.targets.append(target)\n elif target_to_create == 2:\n self.targets.append(strong_target)\n elif target_to_create == 3:\n self.targets.append(safe_target)\n\n def check_collisions(self):\n \"\"\"\n Checks to see if bullets have hit targets.\n Updates scores and removes dead items.\n :return:\n \"\"\"\n\n for bullet in self.bullets: \n for target in self.targets:\n # Make sure they are both alive before checking for a collision\n if bullet.alive and target.alive:\n too_close = bullet.radius + target.radius\n\n if (abs(bullet.center.x - target.center.x) < too_close and\n abs(bullet.center.y - target.center.y) < too_close):\n # its a hit!\n bullet.alive = False\n self.score += target.hit()\n self.number_of_targets_shot += 1\n #self.number_of_points_scored += target.hit()\n \n\n # We will wait to remove the dead objects until after we\n # finish going through the list\n # Checks for anything that is dead, and removes it\n self.cleanup_zombies()\n\n def cleanup_zombies(self):\n \"\"\"\n Removes any dead bullets or targets from the list.\n :return:\n \"\"\"\n for bullet in self.bullets:\n if not bullet.alive:\n self.bullets.remove(bullet)\n\n for target in self.targets:\n if not target.alive:\n self.targets.remove(target)\n\n def check_off_screen(self):\n \"\"\"\n Checks to see if bullets or targets have left the screen\n and if so, removes them from their lists.\n :return:\n \"\"\"\n for bullet in self.bullets:\n if bullet.is_off_screen(SCREEN_WIDTH, SCREEN_HEIGHT):\n self.bullets.remove(bullet)\n\n for target in self.targets:\n if target.is_off_screen(SCREEN_WIDTH, SCREEN_HEIGHT):\n self.targets.remove(target)\n\n def on_mouse_motion(self, x: float, y: float, dx: float, dy: float):\n # set the rifle angle in degrees\n self.rifle.angle = self._get_angle_degrees(x, y)\n\n def on_mouse_press(self, x: float, y: float, button: int, modifiers: int):\n # Fire!\n angle = self._get_angle_degrees(x, y)\n\n bullet = Bullet()\n bullet.fire(angle)\n\n self.bullets.append(bullet)\n self.number_of_bullets_shot += 1\n\n def _get_angle_degrees(self, x, y):\n \"\"\"\n Gets the value of an angle (in degrees) defined\n by the provided x and y.\n Note: This could be a static method, but we haven't\n discussed them yet...\n \"\"\"\n # get the angle in radians\n angle_radians = math.atan2(y, x)\n\n # convert to degrees\n angle_degrees = math.degrees(angle_radians)\n\n return angle_degrees\n \n def game_over(self):\n \"\"\"\n Checks to see if the player is out of time.\n :returns: Boolean\n \"\"\"\n if self.time <= 0:\n # The game ends. Display game over to the screen.\n return True\n else:\n # Decrements the time\n self.time -= .02\n return False\n\n def start_game(self):\n \"\"\"\n Checks to see if the game has started\n \"\"\"\n if self.time <= 60:\n self.game_started = True\n \n \n def draw_game_over(self):\n \"\"\"\n Draws GAME OVER to the screen.\n \"\"\"\n game_over_text = \"GAME OVER.\".format(self.score)\n start_x = 10\n start_y = SCREEN_HEIGHT / 2\n arcade.draw_text(game_over_text, start_x=start_x, start_y=start_y, font_size=50, color=arcade.color.NAVY_BLUE)\n score_text = \"You scored: {} point(s).\".format(self.score)\n start_x_2 = 10\n start_y_2 = SCREEN_HEIGHT / 3\n arcade.draw_text(score_text, start_x=start_x_2, start_y=start_y_2, font_size=25, color=arcade.color.NAVY_BLUE)\n\n\n# Creates the game and starts it going\nwindow = Game(SCREEN_WIDTH, SCREEN_HEIGHT, \"Awesome Skeet\")\narcade.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"185977452","text":"from PyQt5.QtWidgets import QGridLayout, QSpacerItem, QSizePolicy\nimport csv\n\n''' FixtureButtonLayout arranges the buttons according to the\n layout in layout.csv. Any numeric value will be treated\n as a fixture number and any alphabetic value will be\n treated as a spacer. '''\n\nclass FixtureButtonLayout(QGridLayout):\n\n def __init__(self, buttons):\n super().__init__()\n self.buttonList = buttons\n\n # Open csv file with fixture layout\n with open('layout.csv') as layoutFile:\n layoutReader = csv.reader(layoutFile)\n rowCount = 1\n\n # Loop through each cell. If cell contains a number,\n # add the appropriate fixture button to the grid.\n # If it does not contain a number, add a spacer\n for row in layoutReader:\n colCount = 1\n for column in row:\n if column.isnumeric():\n self.addWidget(self.buttonList[int(column) - 1], rowCount, colCount)\n else:\n spacer = QSpacerItem(10, 10, QSizePolicy.Expanding)\n self.addItem(spacer, rowCount, colCount)\n colCount += 1\n rowCount += 1","sub_path":"FixtureButtonLayout.py","file_name":"FixtureButtonLayout.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"387133111","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.test import TestCase\nfrom .models import Article, Classification, Special\nfrom django.db import IntegrityError\n# Create your tests here.\n\n\nclass ClassificationMethodTest(TestCase):\n def setUp(self):\n classification1 = Classification.objects.create(content=\"Programming\")\n classification2 = Classification.objects.create(content=\"Live\")\n \n def test__str__method(self):\n classification1 = Classification.objects.get(content=\"Programming\")\n classification2 = Classification.objects.get(content=\"Live\")\n self.assertEqual(classification1.__str__(), \"Programming\")\n self.assertEqual(classification2.__str__(), \"Live\")\n\n def test_title_unique(self):\n flag = 0\n try:\n Classification.objects.create(content=\"Programming\")\n Classification.objects.create(content=\"Live\")\n except IntegrityError:\n flag = 1\n self.assertEqual(flag, 1)\n \n\nclass ArticleMethodTest(TestCase):\n def setUp(self):\n classification1 = Classification.objects.create(content=\"Programming\")\n classification2 = Classification.objects.create(content=\"Live\")\n special1 = Special.objects.create(title=\"Ruby\")\n special2 = Special.objects.create(title=\"Python\")\n Article.objects.create(title=\"Python\", subtitle=\"Django\", classification=classification1, special=special1)\n # Test Special can be null\n Article.objects.create(title=\"Ruby\", subtitle=\"Ruby On Rails\", classification=classification2)\n \n def test__str__method(self):\n article1 = Article.objects.get(title=\"Python\")\n article2 = Article.objects.get(title=\"Ruby\")\n self.assertEqual(article1.__str__(), \"Python || Django\")\n self.assertEqual(article2.__str__(), \"Ruby || Ruby On Rails\")\n\n def test_title_unique(self):\n flag = 0\n classification1 = Classification.objects.get(content=\"Programming\")\n classification2 = Classification.objects.get(content=\"Live\")\n try:\n Article.objects.create(title=\"Python\", subtitle=\"Django\", classification=classification1)\n # Test Special can be null\n Article.objects.create(title=\"Ruby\", subtitle=\"Ruby On Rails\", classification=classification2)\n except IntegrityError:\n flag = 1\n self.assertEqual(flag, 1)\n\n\n\nclass SpecialMethodTest(TestCase):\n def setUp(self):\n special1 = Special.objects.create(title=\"Ruby\")\n special2 = Special.objects.create(title=\"Python\")\n\n def test__str__method(self):\n special1 = Special.objects.get(title=\"Ruby\")\n special2 = Special.objects.get(title=\"Python\")\n self.assertEqual(special1.__str__(), \"Ruby\")\n self.assertEqual(special2.__str__(), \"Python\")\n\n def test_title_unique(self):\n flag = 0\n try:\n Special.objects.create(title=\"Ruby\")\n Special.objects.create(title=\"Python\")\n except IntegrityError:\n flag = 1\n self.assertEqual(flag, 1)\n\n","sub_path":"blog/blog/page/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"638813562","text":"def load_rentals_file(filename):\n with open(filename, 'r') as file:\n try:\n # first I read the file into a variable. Don’t care about json (yet)\n file_content = file.read()\n\n # note how I print the exception so it doesn’t fail silently\n except Exception as e:\n print(e)\n\n # now I convert a string variable to json\n data = json.loads(file_content)\n return data\n","sub_path":"students/douglas_klos/lesson02/assignment/src/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"185130543","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nimport math\nimport sys\nimport random\nimport time\n\n# run as:\n#> python Basic_KNN.py TrainingData TestData K\n\n #=========== Distance Funcs=============\ndef EculideanDistance(inputInstance,testInstance):\n Summation =0\n #for column in testInstance:\n for i in range(8):\n d=inputInstance[1][i] - testInstance[1][i]\n Summation= Summation+ math.pow(d ,2)\n Distance = [math.sqrt(Summation),inputInstance[1][9]]\n return Distance\n\n #========= Calc Nearest Neighbor option 2 ==========#\ndef Calculate_Nearest_neighbour(topMatched,K):\n #print(\"######### TopMatched ######### \\n\"+str(topMatched))\n if ( topMatched.iloc[0, 0] == 0 ):# if distance is 0\n OutputClass=topMatched.iloc[0, 1];\n FinalOutput=[OutputClass, 1.0]\n return FinalOutput\n topMatched['Count'] = topMatched.groupby('Class')['Class'].transform('count')\n tieBreakers = pd.DataFrame(columns=['tieBreaker']);\n count = 0\n while tieBreakers.shape[0] < topMatched.shape[0]:\n myNum = random.randint(0, topMatched.shape[0]*3)\n if myNum not in tieBreakers.values:\n tieBreakers.loc[len(tieBreakers)] = myNum\n count+=1\n topMatched.reset_index(drop=True, inplace=True)\n tieBreakers.reset_index(drop=True, inplace=True)\n topMatches = pd.concat([topMatched, tieBreakers], axis=1, names=['Distance', 'Class', 'Count', 'tieBreaker'])\n topCount = topMatches['Count'].max()\n Probability = float(topCount) / float(K)\n topMatch = topMatches[ (topMatches['Count'] == topCount ) ]\n topDecision = topMatch.sort_values(by=['tieBreaker'],ascending=True).head(1)\n FinalOutput = [topDecision.iloc[0,1],Probability]\n #print(FinalOutput)\n return FinalOutput\n\n #======================== \ndef ClassicalKNN(trainingdata,testingdata,K,typeofDistance):\n FinalOutput=pd.DataFrame(columns=['Class','conditional_prob']);\n for row_inTest in testingdata.iterrows():\n AllDistancePerTest=pd.DataFrame(columns=['Distance','Class'])\n for row_inTrain in trainingdata.iterrows():\n resultlist=EculideanDistance(row_inTrain, row_inTest)\n #EuclideanDistance returns [ distance.float , class.string]\n AllDistancePerTest.loc[len(AllDistancePerTest), :]=resultlist\n # print(\"Row test vs Row Train\")\n #print(row_inTest)\n #print(row_inTrain)\n BotKPerTest=AllDistancePerTest.sort_values(by=['Distance'],ascending=True).head(K)\n print(BotKPerTest)\n #input(\"Stop\")\n #TopKPerTest =\n # [ 'Distance' , 'Class' ]\n # [ 1.2 a\n # [ 2.1 b\n # [ 2.2 b\n #majority vote\n tempOutput = Calculate_Nearest_neighbour(BotKPerTest,K)\n FinalOutput.loc[len(FinalOutput), :]=tempOutput\n #print('FinalOutput')\n #print(FinalOutput)\n OutPutDate = time.strftime(\"%Y%m%d-%H%M%S\")\n print('FinalOutput')\n print(FinalOutput)\n FinalOutput.to_csv(OutPutDate+'output.csv',sep='\\t')\n\n return \"Check output file\"\n \n #================main=================\nprint (sys.argv)\n\ntrainingdata = pd.read_csv( sys.argv[1], sep='\\t', header=0) \ntestingdata= pd.read_csv( sys.argv[2], sep='\\t', header=0)\nK=int(sys.argv[3])\nprint (trainingdata)\nprint(\"### Running Classical KNN ###\")\nClassicalKNN(trainingdata,testingdata,K,1)\n\n","sub_path":"Assignments/Assignment1/old/CarlosBasic_KNN.py","file_name":"CarlosBasic_KNN.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"522524452","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\spacecomponents\\common\\components\\fitting.py\nfrom ..componentConst import FITTING_CLASS\nfrom spacecomponents.common.helper import HasFittingComponent\nfrom spacecomponents.common.helper import IsActiveComponent\nfrom spacecomponents.common.helper import IsReinforcedComponent\n\ndef IsShipWithinFittingRange(spaceComponentStaticData, shipSlimItem, componentSlimItem, ballPark):\n if shipSlimItem is None:\n return False\n elif not hasattr(componentSlimItem, 'typeID'):\n return False\n else:\n ball = ballPark.GetBall(componentSlimItem.itemID)\n itemIsDead = not ball or ball.isMoribund\n componentTypeID = componentSlimItem.typeID\n if shipSlimItem.ownerID != componentSlimItem.ownerID:\n return False\n elif itemIsDead:\n return False\n elif not HasFittingComponent(componentTypeID):\n return False\n elif not IsActiveComponent(ballPark.componentRegistry, componentTypeID, componentSlimItem.itemID):\n return False\n elif IsReinforcedComponent(ballPark.componentRegistry, componentTypeID, componentSlimItem.itemID):\n return False\n fittingRange = spaceComponentStaticData.GetAttributes(componentTypeID, FITTING_CLASS).range\n shipDistanceFromComponent = ballPark.GetSurfaceDist(shipSlimItem.itemID, componentSlimItem.itemID)\n return shipDistanceFromComponent <= fittingRange","sub_path":"client/spacecomponents/common/components/fitting.py","file_name":"fitting.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"126149701","text":"#\n# Front-end for Micropython standard console IO\n#\ntry:\n import usys as sys\nexcept:\n import sys\n\nclass IO_DEVICE:\n def __init__(self):\n try:\n from micropython import kbd_intr\n kbd_intr(-1)\n except ImportError:\n pass\n if hasattr(sys.stdin, \"buffer\"):\n self.rd_raw_fct = sys.stdin.buffer.read\n else:\n self.rd_raw_fct = sys.stdin.read\n\n def wr(self, s):\n sys.stdout.write(s)\n\n def rd(self):\n return sys.stdin.read(1)\n\n def rd_raw(self):\n return self.rd_raw_fct(1)\n\n def deinit_tty(self):\n try:\n from micropython import kbd_intr\n kbd_intr(3)\n except ImportError:\n pass\n\n def get_screen_size(self):\n self.wr('\\x1b[999;999H\\x1b[6n')\n pos = ''\n char = self.rd() ## expect ESC[yyy;xxxR\n while char != 'R':\n pos += char\n char = self.rd()\n return [int(i, 10) for i in pos.lstrip(\"\\n\\x1b[\").split(';')]\n\n## test, if the Editor class is already present\nif \"pye_edit\" not in globals().keys():\n from pye import pye_edit\n\ndef pye(*args, tab_size=4, undo=50):\n io_device = IO_DEVICE()\n ret = pye_edit(args, tab_size=tab_size, undo=undo, io_device=io_device)\n io_device.deinit_tty()\n return ret\n","sub_path":"pye_gen.py","file_name":"pye_gen.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"315964210","text":"\n\nsofar = 1\n\nright = 3\ndown = 1\n\nfor right, down in ([3,1], [1,1], [5,1], [7,1], [1,2]):\n f = open(\"d3.txt\", \"r\")\n\n for i in range(0, down):\n f.readline()\n line = f.readline()\n width = len(line.strip())\n\n offset = right\n res = 0\n\n while line and len(line) > 0:\n ind = offset % width\n c = line[ind]\n # print(c)\n if c == \"#\":\n res += 1\n \n normal = True\n for i in range(1, down):\n temp = f.readline()\n if not temp or not len(temp):\n normal = False\n break\n\n if not normal:\n break\n\n line = f.readline()\n offset += right\n\n f.close()\n\n sofar *= res\n\nprint(sofar)\n\n","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"118319107","text":"import os\nimport logging\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\nfrom core.mixins import CSVImportMixin, PrettyPrintCommandMixin\nfrom bearing.models import BearingType, BearingDesign\n\nlogger = logging.getLogger('file')\n\n\nclass Command(CSVImportMixin, PrettyPrintCommandMixin, BaseCommand):\n help = 'Import bearing designs from CSV file'\n\n @staticmethod\n def get_bearing_type(value):\n try:\n return BearingType.objects.get(value=value)\n except Exception as e:\n logger.error(e)\n return BearingType.objects.get(value='0')\n\n def handle(self, *args, **options):\n super().handle(*args, **options)\n\n count = 0\n BearingDesign.objects.all().delete()\n file_name = os.path.join(settings.BASE_DIR, '..', 'deploy', 'data', 'initial', 'bearing_designs.csv')\n for d in self.parse_csv_file(file_name):\n item = BearingDesign(**{\n 'value': d[0],\n 'name': d[1],\n 'type': self.get_bearing_type(d[2]),\n 'image': d[3],\n 'designation': d[4],\n 'standart': d[5],\n 'note': d[6],\n })\n try:\n item.save()\n count += 1\n except Exception as e:\n logger.error(e)\n self.stdout.write('Created %d bearing designs' % count)\n","sub_path":"app/bearing/management/commands/import_bearing_designs.py","file_name":"import_bearing_designs.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"37125265","text":"#!/usr/bin/python3\n\"\"\"\nconsole module\n\"\"\"\n\nimport cmd\nfrom datetime import datetime\nfrom models import storage\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"\n HBNBCommand class\n \"\"\"\n prompt = \"(hbnb) \"\n\n classes = [\"BaseModel\", \"User\", \"Amenity\",\n \"State\", \"City\", \"Place\", \"Review\"]\n\n @classmethod\n def count(self, class_name, objects_dict):\n \"\"\" count the number of instance\"\"\"\n counter = 0\n for key in objects_dict.keys():\n if class_name in key:\n counter += 1\n print(counter)\n\n def do_quit(self, args):\n \"\"\"\n exit program\n \"\"\"\n return True\n\n def do_EOF(self, args):\n \"\"\"\n Quit command to exit the program\n \"\"\"\n return True\n\n def emptyline(self):\n \"\"\"\n empty line + ENTER shouldn’t execute anything\n \"\"\"\n pass\n\n def do_help(self, args):\n \"\"\"\n help command\n \"\"\"\n cmd.Cmd.do_help(self, args)\n\n def do_create(self, args):\n \"\"\"\n creates a new instances of BaseModel\n saves it and prints the id\n \"\"\"\n args = args.split(\" \")\n if args == \"\":\n print(\"** class name missing **\")\n return\n if args[0] not in self.classes:\n print(\"** class doesn't exist **\")\n return\n else:\n new = eval(\"{}()\".format(args[0]))\n new.save()\n print(new.id)\n\n def do_show(self, args):\n \"\"\"\n Prints the string representation of an\n instance based on the class name and id\n \"\"\"\n args = args.split()\n if len(args) == 0:\n print(\"** class name missing **\")\n return\n try:\n eval(args[0])\n except Exception:\n print(\"** class doesn't exist **\")\n return\n if len(args) == 1:\n print(\"** instance id missing **\")\n else:\n storage.reload()\n container_obj = storage.all()\n key_id = args[0] + \".\" + args[1]\n if key_id in container_obj:\n value = container_obj[key_id]\n print(value)\n else:\n print(\"** no instance found **\")\n\n def do_destroy(self, args):\n \"\"\"\n Deletes an instance based on the class name and id\n \"\"\"\n if not args:\n print(\"** class name missing **\")\n return\n tokens = args.split(\" \")\n objects = storage.all()\n\n if tokens[0] in self.classes:\n if len(tokens) < 2:\n print(\"** instance id missing **\")\n return\n name = tokens[0] + \".\" + tokens[1]\n if name not in objects:\n print(\"** no instance found **\")\n else:\n obj = objects[name]\n if obj:\n objs = storage.all()\n del objs[\"{}.{}\".format(type(obj).__name__, obj.id)]\n storage.save()\n else:\n print(\"** class doesn't exist **\")\n\n def do_all(self, args):\n \"\"\"\n Prints all string representation of all instances\n based or not on the class name\n \"\"\"\n args = args.split()\n dict_obj = storage.all()\n list = []\n if len(args):\n class_name = args[0]\n if class_name not in self.classes:\n print(\"** class doesn't exist **\")\n return\n for k, v in dict_obj.items():\n if class_name in k:\n list.append((dict_obj[k].__str__()))\n else:\n for k, v in dict_obj.items():\n list.append((dict_obj[k].__str__()))\n print(list)\n\n def do_update(self, args):\n \"\"\"\n Updates an instance based on the class\n name and id by adding or updating attribute\n \"\"\"\n args = args.split()\n if not args:\n print(\"** class name missing **\")\n return\n if args[0] not in self.classes:\n print(\"** class doesn't exist **\")\n return\n try:\n args[1]\n except Exception:\n print(\"** instance id missing **\")\n return\n objects_dict = storage.all()\n my_key = args[0] + \".\" + args[1]\n if my_key not in objects_dict:\n print(\"** no instance found **\")\n return\n try:\n args[2]\n except Exception:\n print(\"** attribute name missing **\")\n return\n try:\n args[3]\n except Exception:\n print(\"** value missing **\")\n return\n if args[3]:\n setattr(objects_dict[my_key], args[2], args[3])\n my_obj = objects_dict[my_key]\n my_obj.updated_at = datetime.now()\n storage.save()\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"294241883","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\nHelpers for processing Marc XML and JSON\n'''\nimport pdb\ndef get_marc_fields(record, fields):\n '''\n Get a list of fields from a Marc record\n @args:\n record: a Fortunoff Marc record\n fields: {arr}\n number: {str} a number (as str) for a Marc field\n numbers: {arr} a list of numbers (as str) for a Marc field\n letter: {str} a letter for a Marc field\n label: {str} a human-readable label for a Marc field\n type: {list} if list, return a list of responses\n @returns:\n {obj} an object with one `label` per field as a top-level\n key, with the value of that key representing the value\n of the given field in the Marc record\n '''\n result = {}\n \n for field in fields:\n args = get_field_args(field)\n label = args['label']\n \n\n # some marc fields have list values, e.g. 655a\n if args['field_type'] == list or label=='gender':\n result[label] = get_list_field(record, args)\n # most marc fields have string values\n else:\n result[label] = get_str_field(record, args)\n\n return result\n\n\ndef get_field_args(field):\n '''\n Return the arguments to be used when parsing a Marc field\n @args:\n {obj} field: an object that defines the Marc field to parse\n number: the Marc field number to parse (if any)\n numbers: the Marc field numbers to parse (if any)\n letter: the Marc field letter to parse (if any)\n field_type: the type of object to be stored for this Marc\n field (e.g. str, list)\n @returns:\n {obj} field: an object that defines the Marc field to parse\n number: the Marc field number to parse (if any)\n numbers: the Marc field numbers to parse (if any)\n letter: the Marc field letter to parse (if any)\n field_type: the type of object to be stored for this Marc\n field (e.g. str, list)\n '''\n return {\n 'number': field.get('number', None),\n 'numbers': field.get('numbers', None),\n 'letter': field.get('letter', None),\n 'label': field.get('label', None),\n 'field_type': field.get('type', str),\n }\n\n\ndef get_list_field(record, args):\n '''\n Return the Marc field defined by `args` within `record`\n @args:\n {obj} record: an object that defines the Marc field to parse\n number: the Marc field number to parse (if any)\n numbers: the Marc field numbers to parse (if any)\n letter: the Marc field letter to parse (if any)\n field_type: the type of object to be stored for this Marc\n field (e.g. str, list)\n @returns:\n {arr} a list with the content of the requested Marc field\n '''\n l = []\n number = args['number']\n letter = args['letter']\n\n # some marc fields use an integer range, e.g. subjects = 600-699\n if args['numbers']:\n for number in args['numbers']:\n for letter in record.get(number, {}):\n for val in record.get(number, {}).get(letter, []):\n l.append(val)\n\n # marc fields with a single number field\n else:\n\n # some requests need lists for a letter\n if letter:\n for val in record.get(number, {}).get(letter, []):\n l.append(val)\n\n # others need lists for all letters in a number\n else:\n for letter in record.get(number, {}):\n for val in record.get(number, {}).get(letter, []):\n l.append(val)\n\n # dedupe list results while preserving order\n deduped = []\n for i in l:\n if i not in deduped:\n deduped.append(i)\n return deduped\n\ndef get_str_field(record, args):\n '''\n Return the Marc field defined by `args` within `record`\n @args:\n {obj} record: an object that defines the Marc field to parse\n number: the Marc field number to parse (if any)\n numbers: the Marc field numbers to parse (if any)\n letter: the Marc field letter to parse (if any)\n field_type: the type of object to be stored for this Marc\n field (e.g. str, list)\n @returns:\n {str} a string with the content of the requested Marc field\n '''\n number = args['number']\n letter = args['letter']\n return record.get(number, {}).get(letter, [''])[0]\n","sub_path":"utils/marc.py","file_name":"marc.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"502223248","text":"#!/usr/bin/env python\n\nimport fileinput\nfrom sys import argv\n\ndef strip(filename):\n filein = open(filename + \"-incl.tex\", 'w')\n ok_to_write = False\n for line in fileinput.input(filename + \".tex\"):\n if line == \"%% STRIP END\\n\":\n ok_to_write = True\n continue\n if line == \"%% STRIP BEGIN\\n\":\n ok_to_write = False\n continue\n if ok_to_write:\n filein.write(line)\n\nstrip(argv[1])","sub_path":"tex/makestrip.py","file_name":"makestrip.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"263321649","text":"# -*- coding: utf-8 -*-\n# author:lyh\n# datetime:2020/6/3 10:15\n\"\"\"\n837. 新21点\n\n爱丽丝参与一个大致基于纸牌游戏 “21点” 规则的游戏,描述如���:\n\n爱丽丝以 0 分开始,并在她的得分少于 K 分时抽取数字。 抽取时,她从 [1, W] 的范围中随机获得一个整数作为分数进行累计,其中 W 是整数。 每次抽取都是独立的,其结果具有相同的概率。\n\n当爱丽丝获得不少于 K 分时,她就停止抽取数字。 爱丽丝的分数不超过 N 的概率是多少?\n\n示例 1:\n\n输入:N = 10, K = 1, W = 10\n输出:1.00000\n说明:爱丽丝得到一张卡,然后停止。\n\n示例 2:\n\n输入:N = 6, K = 1, W = 10\n输出:0.60000\n说明:爱丽丝得到一张卡,然后停止。\n在 W = 10 的 6 种可能下,她的得分不超过 N = 6 分。\n\n示例 3:\n\n输入:N = 21, K = 17, W = 10\n输出:0.73278\n\n提示:\n\n 0 <= K <= N <= 10000\n 1 <= W <= 10000\n 如果答案与正确答案的误差不超过 10^-5,则该答案将被视为正确答案通过。\n 此问题的判断限制时间已经减少。\n\"\"\"\n\n\nclass Solution:\n def new21Game(self, N: int, K: int, W: int) -> float:\n q = [0 for i in range(N + 1)]\n q[0] = 1\n l = 0\n s = 1 if 0=K else 0\n for i in range(1, N + 1):\n if i - l > W and l < K:\n s -= q[l]\n l += 1\n q[i] = s / W\n if i < K:\n s += q[i]\n if i >=K:\n res += q[i]\n return res\n\n\nif __name__ == '__main__':\n print(\n Solution().new21Game(10, 1, 10),\n Solution().new21Game(6, 0, 10),\n Solution().new21Game(21, 17, 10),\n )\n","sub_path":"Solutions/0837.new21Game.py","file_name":"0837.new21Game.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"82590153","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 21 23:13:00 2015\n\n@author: mateusenricosrecaruso\n\"\"\"\nimport turtle\nimport random\n \ndef janela():\n global janela\n janela = turtle.Screen() \n janela.screensize()\n janela.title(\"Jogo da Forca, por Mateus Enrico Caruso\")\n janela.bgcolor(\"black\")\n \ndef escrever_janela():\n global janela\n janela.screensize()\n janela.title(\"Jogo da Forca, por Mateus Enrico Caruso\")\n janela.bgcolor(\"black\")\n desenho(-300,-120,100,0)\n \ndef desenho(x,y,dist,ang):\n global forca\n forca = turtle.Turtle()\n forca.showturtle()\n forca.penup()\n forca.speed(5)\n forca.setpos(x,y)\n forca.pendown()\n forca.color(\"white\")\n forca.left(ang)\n forca.forward(dist)\n forca.backward(50) #-250,-120\n forca.left(90)\n forca.forward(400) #-250,280\n forca.right(90)\n forca.forward(150) #-100,280\n forca.left(270)\n forca.forward(50) #-100, 230\n forca.hideturtle()\n \ndef cabeca(x,y):\n global forca\n forca.showturtle()\n forca.penup()\n forca.speed(0)\n forca.setpos(x,y)\n forca.pendown()\n forca.color(\"red\")\n forca.left(360)\n for i in range(54):\n forca.left(350) \n forca.forward(6)\n forca.hideturtle()\n\ndef corpo(x,y,parte):\n global forca\n forca.speed(5)\n forca.color(\"red\")\n if parte==\"corpo\":\n forca.showturtle()\n forca.penup()\n forca.setpos(x,y)\n forca.pendown()\n forca.left(90)\n forca.forward(169)\n forca.hideturtle()\n elif parte==\"bracoe\":\n forca.showturtle()\n forca.penup()\n forca.setpos(x,y)\n forca.pendown()\n forca.left(315)\n forca.forward(75)\n forca.hideturtle()\n elif parte==\"bracod\":\n forca.showturtle()\n forca.penup()\n forca.setpos(x,y)\n forca.pendown()\n forca.right(270)\n forca.forward(75) \n forca.hideturtle()\n elif parte==\"pernae\":\n forca.showturtle()\n forca.penup()\n forca.setpos(x,y)\n forca.pendown()\n forca.left(270)\n forca.forward(50) \n forca.hideturtle()\n elif parte==\"pernad\":\n forca.showturtle()\n forca.penup()\n forca.setpos(x,y)\n forca.pendown()\n forca.left(90)\n forca.forward(50)\n forca.hideturtle()\n elif parte=='morte':\n forca.showturtle()\n forca.penup()\n forca.color('white')\n forca.setpos(x,y)\n forca.pendown()\n forca.right(135)\n forca.backward(100)\n forca.hideturtle()\n \ndef espacos(p,palavra):\n global forca\n forca.speed(5)\n forca.color(\"white\")\n forca.left(90)\n k=0\n for i in palavra:\n n=-300+25*k\n k+=1\n forca.penup()\n forca.setpos(n,-200)\n forca.showturtle()\n forca.setpos(n,-200)\n if i==\" \":\n forca.penup()\n forca.forward(20)\n if i!=\" \":\n forca.pendown()\n forca.forward(20)\n forca.penup()\n forca.forward(5)\n forca.pendown()\n forca.hideturtle()\n\ndef perdeu():\n global lapis2\n lapis2 = turtle.Turtle()\n lapis2.color('yellow')\n lapis2.speed(5)\n lapis2.st()\n lapis2.penup()\n lapis2.setpos(50,150)\n lapis2.color(\"yellow\")\n lapis2.pendown()\n lapis2.write(\"Você Perdeu\", font=(\"Times New Roman\", 30, \"normal\"))\n lapis2.ht()\n \ndef ganhou():\n global lapis\n lapis = turtle.Turtle()\n lapis.color('yellow')\n lapis.speed(5)\n lapis.st()\n lapis.penup()\n lapis.setpos(50,150)\n lapis.color(\"yellow\")\n lapis.pendown()\n lapis.write(\"Você Ganhou\", font=(\"Times New Roman\", 30, \"normal\"))\n lapis.ht()\n\ndef escrever(entrada,palavra):\n global forca\n forca.color(\"orange\")\n i=-1\n j=0\n k=palavra.count(entrada)\n while j 0.9\n # wmmask = cropped_act_mask[:, :, :, 2]\n cropped_brain_mask = ~(cropped_brain_mask.astype(np.bool))\n final_mask = np.logical_or(cropped_brain_mask, csfmask)\n voxel_lr_mask = np.tile(np.expand_dims(final_mask, -1), (1, 1, 1, fodlr.shape[-1]))\n fodlr = np.ma.array(fodlr, mask=voxel_lr_mask, dtype=np.float32)\n fodlr = (fodlr - self.fodlr_mean) / self.fodlr_std\n fodlr = np.ma.filled(fodlr, 0.).astype(np.float32)\n\n fodlr = torch.from_numpy(fodlr)\n brain_mask = torch.from_numpy(brain_mask)\n\n self.brain_mask = brain_mask.to(self.device)\n # Load numpy to GPU\n self.fodlr_mean = torch.from_numpy(self.fodlr_mean).to(self.device)\n self.fodlr_std = torch.from_numpy(self.fodlr_std).to(self.device)\n self.fodgt_mean = torch.from_numpy(self.fodgt_mean).to(self.device)\n self.fodgt_std = torch.from_numpy(self.fodgt_std).to(self.device)\n\n if act_mask is None:\n self.fodlr_whole = fodlr.to(self.device)\n self.fodlr_whole = (self.fodlr_whole - self.fodlr_mean)/self.fodlr_std\n else:\n self.fodlr_whole = fodlr.to(self.device)\n\n\n\n\n\n def forward(self):\n \"\"\"Run forward pass; called by both functions and .\n Regarding res3dunet architecture, we regress the residual between fodgt and fodlr, and thus we need to add the\n fodlr back to recover the fodpred\n \"\"\"\n self.fodpred = self.net(self.fodlr)\n\n\n def test(self, fod_path, output_dir):\n \"\"\"Forward function used in test time.\n\n This function wraps function in no_grad() so we don't save intermediate steps for backprop\n It also calls to produce additional visualization results\n \"\"\"\n size_3d_patch = 9\n with torch.no_grad():\n try:\n os.makedirs(os.path.dirname(output_dir), exist_ok=True)\n except:\n sys.exit('we cannot create the dir')\n\n height, width, depth, channels = self.fodlr_whole.shape\n self.fodlr_whole = self.fodlr_whole.permute(3, 0, 1, 2)\n template = torch.zeros_like(self.fodlr_whole)\n final_result = torch.zeros(tuple(self.output_shape)).to(self.device)\n print('Start FOD super resolution:')\n for i in tqdm(range(height - size_3d_patch + 1)):\n for j in range(width - size_3d_patch + 1):\n for k in range(depth - size_3d_patch + 1):\n self.fodlr = self.fodlr_whole[ :, i:i + size_3d_patch,\n j:j + size_3d_patch, k:k + size_3d_patch]\n tensor_helper = self.fodlr\n self.fodlr = torch.stack([self.fodlr.float(), tensor_helper.float()])\n self.forward()\n template[ :, int((2 * i + size_3d_patch) / 2),\n int((2 * j + size_3d_patch) / 2),\n int((2 * k + size_3d_patch) / 2)] = self.fodpred[0:1, :] * self.fodgt_std + self.fodgt_mean\n\n # Fill the result into\n final_result[self.mins[0]:self.maxs[0], self.mins[1]:self.maxs[1],\n self.mins[2]:self.maxs[2], :] = template.permute(1, 2, 3, 0)\n\n final_result = final_result * self.brain_mask.unsqueeze(-1)\n\n # Dump template into a nii gz file for further evaluation using mrtrix\n final_result = final_result.detach().cpu().numpy()\n # load header from the lr data\n lr_info = nib.load(fod_path)\n nii = nib.Nifti1Image(final_result, affine=lr_info.affine,\n header=lr_info.header)\n\n nib.save(nii, output_dir)\n\n\n\n def setup(self, weights_path):\n \"\"\"Load and print networks; create schedulers\n\n Parameters:\n opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions\n \"\"\"\n self.load_networks(weights_path)\n\n\n def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):\n \"\"\"Fix InstanceNorm checkpoints incompatibility (prior to 0.4)\"\"\"\n key = keys[i]\n if i + 1 == len(keys): # at the end, pointing to a parameter/buffer\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'running_mean' or key == 'running_var'):\n if getattr(module, key) is None:\n state_dict.pop('.'.join(keys))\n if module.__class__.__name__.startswith('InstanceNorm') and \\\n (key == 'num_batches_tracked'):\n state_dict.pop('.'.join(keys))\n else:\n self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)\n\n def load_networks(self, load_path):\n \"\"\"Load all the networks from the disk.\n\n Parameters:\n epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)\n \"\"\"\n print('loading the model from %s' % load_path)\n # if you are using PyTorch newer than 0.4 (e.g., built from\n # GitHub source), you can remove str() on self.device\n state_dict = torch.load(load_path, map_location=str(self.device))\n if hasattr(state_dict, '_metadata'):\n del state_dict._metadata\n\n # patch InstanceNorm checkpoints prior to 0.4\n for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop\n self.__patch_instance_norm_state_dict(state_dict, self.net, key.split('.'))\n self.net.load_state_dict(state_dict)\n\n def suffering(self, phase, fodlr, fodmt):\n\n self.optimizer.zero_grad()\n with torch.set_grad_enabled(phase == 'train'):\n \n fodpred = self.net(fodlr)\n pred = fodpred * self.fodmt_std + self.fodmt_mean\n ground_truth = fodmt[:, :, self.size_3d_patch // 2, self.size_3d_patch // 2, self.size_3d_patch // 2]\n\n loss = self.criterion(pred, ground_truth)\n if phase == 'train':\n loss.backward()\n self.optimizer.step()\n \n return loss.item()\n","sub_path":"models/fodnet_model.py","file_name":"fodnet_model.py","file_ext":"py","file_size_in_byte":9674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"613417753","text":"from django.shortcuts import render\r\nfrom.models import Producto\r\nfrom .forms import ContactoForm\r\n\r\n# Create your views here.\r\ndef home(request):\r\n productos = Producto.objects.all()\r\n data = {\r\n 'productos': productos\r\n }\r\n return render(request, 'app/home.html', data)\r\n\r\ndef contacto(request):\r\n data = {\r\n 'form': ContactoForm()\r\n }\r\n\r\n if request.method == 'POST':\r\n formulario = ContactoForm(data=request.POST)\r\n if formulario.is_valid():\r\n formulario.save()\r\n data[\"mensaje\"] = \"Conctacto guardado\"\r\n else:\r\n data[\"form\"] = formulario\r\n\r\n return render(request, 'app/contacto.html', data)\r\n\r\ndef galeria(request):\r\n return render(request, 'app/galeria.html')","sub_path":"tienda_zapatos/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"71865749","text":"# Programming often involves examining a set of conditions and deciding which action to take based on those conditions.\n# Python’s if statement allows you to examine the current state of a program and respond appropriately to that state\n# If statement’s clause (that is, the block following the if statement) will execute if the statement’s condition is True.\n# The clause is skipped if the condition is False.\n\ndef is_even(n):\n remainder=n%2\n if remainder==0:\n print('{} is even.'.format(n))\n else:\n print('{} is not even'.format(n))\n\nprint(is_even(2))\nprint(is_even(3))\n\n\nbanned_users = ['andrew', 'carolina', 'david']\nuser = 'marie'\nif user not in banned_users:\n print(user.title() + \", you can post a response if you wish.\")\n\nage=12\nif age < 4:\n price=0\nelif age < 18:\n price=5\nelif age < 65:\n price = 10\nelse:\n price = 5\nprint(\"Your admission cost is $\"+str(price)+\".\")\n\n\nrequested_toppings = ['mushrooms', 'green peppers', 'extra cheese']\nif requested_toppings:\n for requested_topping in requested_toppings:\n if requested_topping=='green peppers':\n print(\"Sorry, we are out of green peppers right now\")\n else:\n print(\"Adding \"+requested_topping+\".\")\nelse:\n print(\"Are you sure you want a plain pizza?\")\nprint(\"\\nFinished making your pizza!\")\n\navailable_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']\nrequested_toppings = ['mushrooms', 'french fries', 'extra cheese']\nfor requested_topping in requested_toppings:\n if requested_topping in available_toppings:\n print(\"Adding \"+ requested_topping+\".\")\n else:\n print(\"Sorry, we don't have \"+requested_topping+\".\")\nprint(\"\\nFinished making your pizza!\")\n\n\n","sub_path":"src/basicKB/dev/basics/If Statements.py","file_name":"If Statements.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"65459897","text":"import numpy as np\n\nfrom code.args import get_args\nfrom copy import deepcopy\n\n\nclass GlobalAligner():\n def __init__(self, args):\n self.query = args.query\n self.ref = args.reference\n\n # scores\n self.match = args.match\n self.mismatch = args.mismatch\n self.gap = args.gap\n\n # Initialize similarity matrix\n self.sim = np.zeros((len(self.query)+1, len(self.ref)+1), dtype = np.int16)\n self.sim[0, :] = np.array([self.gap*i for i in range(len(self.ref)+1)]) # initialize row 0\n self.sim[:, 0] = np.array([self.gap * i for i in range(len(self.query)+1)]) # initialize column one\n\n # Initialize best moves matrix\n self.best_moves = np.zeros((len(self.query)+1, len(self.ref)+1), dtype = np.int16)\n self.best_moves[0, 1:] += 1 # on the edge last step is always horizontal\n self.best_moves[1:, 0] += 2 # on the edge last step is always vertical\n self.best_moves = self.best_moves[:, :, None].tolist() # unsqueeze\n\n\n def step(self, i, j):\n \"\"\"\n horizontal: insertion on the query\n vertical: insertion on the reference\n \"\"\"\n s_ij = (lambda i,j: self.match if self.query[i-1] == self.ref[j-1] else self.mismatch)\n\n # scores associated to each move\n move_1 = self.sim[i-1,j-1] + s_ij(i,j) # diagonal\n move_2 = self.sim[i, j-1] + self.gap # horizontal move, -->\n move_3 = self.sim[i-1, j] + self.gap # vertical move\n moves = np.array([move_1, move_2, move_3])\n\n max_move = np.max(moves)\n best_moves = np.argwhere(moves == max_move) # return more than one element in case of more than one max\n best_moves = np.squeeze(best_moves, -1).tolist()\n\n self.best_moves[i][j] = best_moves\n self.sim[i, j] = max_move\n\n\n def generate_sim_mat(self):\n # generate similarity matrix, breadth first\n print(self.best_moves[0])\n for i in range(1, len(self.query)+1):\n for j in range(1, len(self.ref)+1):\n self.step(i, j)\n print(self.best_moves[i])\n\n\n return(self.sim[-1, -1])\n\n def merge_alignments(self, alignment:list, subpaths:list):\n \"\"\"\n :param alignment:\n :param subpaths:\n :return:\n \"\"\"\n alignments_paths = []\n for s_path in subpaths:\n copy_alignment = deepcopy(alignment)\n current_path = s_path + copy_alignment # equivalent to extend but inth eorder I need\n alignments_paths.append(current_path)\n\n return alignments_paths\n\n\n def align(self, query: str, ref: str, best_moves: list):\n \"\"\"\n Build alignment at this level of the tree\n :return: level_q_alig:list , level_r_alig:list.\n Each element of the list contains alignment from a single node\n \"\"\"\n\n def horizontal(q_alignment, r_alignment, col):\n col -= 1\n q_alignment = '_' + q_alignment\n r_alignment = ref[col] + r_alignment\n return q_alignment, r_alignment, col\n\n def vertical(q_alignment, r_alignment, row):\n row -= 1\n q_alignment = query[row] + q_alignment\n r_alignment = '_' + r_alignment\n return q_alignment, r_alignment, row\n\n def diagonal(q_alignment, r_alignment, pos):\n pos = [el - 1 for el in pos]\n q_alignment = query[pos[0]] + q_alignment\n r_alignment = ref[pos[1]] + r_alignment\n return q_alignment, r_alignment, pos\n\n # find the final alignments\n pos = [len(query), len(ref)] # rows\n q_alignment = r_alignment = \"\"\n level_q_alig = level_r_alig = []\n\n while pos != [0, 0]:\n if len(best_moves[pos[0]][pos[1]]) == 1: # if only one optimal path: base case\n\n if best_moves[pos[0]][pos[1]][0] == 0: # if diagonal\n q_alignment, r_alignment, pos = diagonal(q_alignment, r_alignment, pos)\n\n elif best_moves[pos[0]][pos[1]][0] == 1: # if horizontal\n q_alignment, r_alignment, pos[1] = horizontal(q_alignment, r_alignment, pos[1])\n\n else: # else vertical\n q_alignment, r_alignment, pos[0] = vertical(q_alignment, r_alignment, pos[0])\n\n else: # if more than one optimal path, recursion\n q_alignment = [q_alignment]\n r_alignment = [r_alignment]\n available_moves = best_moves[pos[0]][pos[1]]\n for move in available_moves:\n best_moves[pos[0]][pos[1]] = [move]\n q_subpaths, r_subpaths = self.align(query[0: pos[0]], ref[0:pos[1]], best_moves)\n q_alignment.append(q_subpaths)\n r_alignment.append(r_subpaths)\n\n return q_alignment, r_alignment\n\n return [q_alignment], [r_alignment] # base case\n\n\n\ndef main(args):\n global_aligner = GlobalAligner(args)\n optimal_score = global_aligner.generate_sim_mat()\n print(f\"Optimal alignment score: {optimal_score}\")\n print(global_aligner.align(global_aligner.query, global_aligner.ref, global_aligner.best_moves))\n\n\n\nif __name__ == \"__main__\":\n args = get_args()\n main(args)\n\n\n","sub_path":"Lab2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"602428307","text":"import socket\r\nimport os\r\nimport time\r\nimport threading\r\n\r\n\r\ndef set_socket_server(ip, port):\r\n sock = socket.socket()\r\n\r\n sock.bind((ip, port))\r\n\r\n sock.listen()\r\n return sock\r\n\r\n\r\ndef sock_listen(sock):\r\n client, addr = sock.accept()\r\n return client\r\n\r\n\r\ndef set_transfer_location():\r\n desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')\r\n share_folder = os.path.join(desktop, \"Share folder\")\r\n return share_folder\r\n\r\n\r\ndef create_folder(share_folder):\r\n if os.path.exists(share_folder):\r\n return False\r\n else:\r\n os.mkdir(share_folder)\r\n os.chdir(share_folder)\r\n\r\n\r\ndef list_all_files(share_folder):\r\n all_folders = []\r\n all_files = []\r\n for root, folders, files in os.walk(share_folder):\r\n\r\n for eachfold in folders:\r\n all_folders.append(root.replace(\"\\\\\", \"/\") +\r\n \"/\"+eachfold.replace(\"\\\\\", \"/\"))\r\n\r\n for eachfile in files:\r\n all_files.append(os.path.join(root, eachfile))\r\n\r\n return all_folders, all_files\r\n\r\n\r\ndef send_files(client, share_folder):\r\n print(client)\r\n files = os.listdir(share_folder)\r\n for file in files:\r\n client.send(bytes(file, \"utf-8\"))\r\n response = client.recv(4).decode(\"utf-8\")\r\n print(file)\r\n print(response)\r\n if response == \"yes\":\r\n client.send(bytes(\"ok\", \"utf-8\"))\r\n else:\r\n client.send(bytes(\"ok\", \"utf-8\"))\r\n print(file)\r\n upload(client, share_folder, file)\r\n\r\n\r\ndef upload(s, share_folder, filename):\r\n buffer = 1024\r\n s.send(bytes(filename, \"utf-8\"))\r\n s.recv(4)\r\n filename = os.path.join(share_folder, filename)\r\n file_type = os.path.isfile(filename)\r\n print(file_type)\r\n if file_type:\r\n\r\n with open(filename, \"rb\") as f:\r\n s.send(bytes(\"file //\" + str(os.path.getsize(filename)), \"utf-8\"))\r\n\r\n print(s.recv(4).decode(\"utf-8\"))\r\n l = f.read(1024)\r\n s.send(l)\r\n while l != b'':\r\n l = f.read(1024)\r\n s.send(l)\r\n\r\n f.close()\r\n\r\n print(s.recv(buffer).decode(\"utf-8\"))\r\n else:\r\n s.send(bytes(\"folder //\", \"utf-8\"))\r\n s.recv(4)\r\n all_folders, all_files = list_all_files(share_folder)\r\n s.send(bytes(str(len(all_folders)), \"utf-8\"))\r\n s.recv(4)\r\n for a in all_folders:\r\n print(a)\r\n a = \"\\\"\" + a + \"\\\"\"\r\n s.send(bytes(a, \"utf-8\"))\r\n s.recv(4)\r\n\r\n s.send(bytes(str(len(all_files)), \"utf-8\"))\r\n s.recv(4)\r\n\r\n for a in all_files:\r\n print(\"went to for loop\")\r\n s.send(bytes(a.replace(\"\\\\\", \"/\"), \"utf-8\"))\r\n print(\"sent filename\" + a)\r\n\r\n print(\"recieved \" + s.recv(4).decode(\"utf-8\"))\r\n\r\n with open(a, \"rb\") as f:\r\n s.send(bytes(str(os.path.getsize(a)), \"utf-8\"))\r\n print(\"sent file size\")\r\n\r\n print(\"recieved \" + s.recv(4).decode(\"utf-8\"))\r\n\r\n l = f.read(1024)\r\n s.send(l)\r\n print(\"sending data\")\r\n print(\"recieved \" + s.recv(4).decode(\"utf-8\"))\r\n print(\"going inside while loop\")\r\n while l != b'':\r\n print(l)\r\n print(\"went inside while loop\")\r\n l = f.read(1024)\r\n print(\"sending data\")\r\n s.send(l)\r\n print(\"sent data\")\r\n s.recv(4)\r\n\r\n f.close()\r\n s.recv(1024)\r\n\r\n\r\ndef start_server(ip, port):\r\n sock = set_socket_server(ip, port)\r\n client = sock_listen(sock)\r\n\r\n client.send(bytes(\"working\", \"utf-8\"))\r\n\r\n share_folder = set_transfer_location()\r\n create_folder(share_folder)\r\n while True:\r\n send_files(client, share_folder)\r\n time.sleep(1 / 100)\r\n\r\n\r\ndef sock_connect(ip, port):\r\n sock = socket.socket()\r\n sock.connect((ip, port))\r\n return sock\r\n\r\n\r\ndef text_send(s, text):\r\n s.send(bytes(str(text), \"utf-8\"))\r\n\r\n\r\ndef get_files(sock, share_folder):\r\n print(sock)\r\n files = os.listdir(share_folder)\r\n filename = sock.recv(1024).decode(\"utf-8\")\r\n print(filename)\r\n if filename in files:\r\n sock.send(bytes(\"yes\", \"utf-8\"))\r\n sock.recv(4)\r\n print(filename + \"exists and will not be transfered\")\r\n else:\r\n sock.send(bytes(\"no\", \"utf-8\"))\r\n sock.recv(4)\r\n\r\n print(filename + \"does not exist and will be transfered\")\r\n download(sock, share_folder)\r\n\r\n\r\ndef download(s, share_folder):\r\n name = s.recv(1024).decode(\"utf-8\")\r\n name = os.path.join(share_folder, name)\r\n s.send(bytes(\"ok\", \"utf-8\"))\r\n d_typa_file = s.recv(32).decode(\"utf-8\")\r\n print(d_typa_file)\r\n\r\n if d_typa_file.startswith(\"file //\"):\r\n s.send(bytes(\"ok\", \"utf-8\"))\r\n filesize = int(d_typa_file.replace(\"file //\", \"\"))\r\n with open(name, \"wb\") as f:\r\n\r\n data = s.recv(4096)\r\n totalr = len(data)\r\n f.write(data)\r\n while totalr < filesize:\r\n data = s.recv(4096)\r\n totalr += len(data)\r\n f.write(data)\r\n print(\"downloading\")\r\n\r\n f.close()\r\n\r\n s.send(bytes(\"File downloaded: \" +\r\n name, \"utf-8\"))\r\n\r\n elif d_typa_file.startswith(\"folder //\"):\r\n print(\"---- Starting to create folders ----- \")\r\n text_send(s, \"ok\")\r\n\r\n length_of_fold = s.recv(1024)\r\n\r\n text_send(s, \"ok\")\r\n os.system(\"mkdir \" + name.replace(\" \", \"\\ \"))\r\n print(\"mkdir \" + name)\r\n for a in range(0, int(length_of_fold)):\r\n\r\n foldername = s.recv(1024).decode(\"utf-8\")\r\n print(os.system(\"mkdir \" + foldername))\r\n os.system(\"mkdir \" + foldername.replace(\" \", \"\\ \"))\r\n text_send(s, \"ok\")\r\n\r\n print(\"---- Starting to recieve files -----\")\r\n length_of_files = s.recv(1024).decode(\"utf-8\")\r\n print(\"recieved number of files\" + str(length_of_files))\r\n\r\n text_send(s, \"ok\")\r\n print(\"Sent ok\")\r\n for a in range(0, int(length_of_files)):\r\n\r\n filename = s.recv(1024).decode(\"utf-8\")\r\n print(\"Recieved filename as \" + str(filename))\r\n text_send(s, \"ok\")\r\n print(\"Sent ok\")\r\n\r\n filesize = s.recv(1024)\r\n filesize = filesize.decode(\"utf-8\")\r\n print(\"recieved file size\" + filesize)\r\n\r\n text_send(s, \"ok\")\r\n print(\"Sent ok\")\r\n\r\n filesize = int(filesize)\r\n\r\n with open(filename, \"wb\") as f:\r\n\r\n data = s.recv(4096)\r\n\r\n text_send(s, \"ok\")\r\n\r\n totalr = len(data)\r\n f.write(data)\r\n\r\n while totalr < filesize:\r\n\r\n data = s.recv(4096)\r\n\r\n text_send(s, \"ok\")\r\n\r\n totalr += len(data)\r\n f.write(data)\r\n\r\n f.close()\r\n s.send(bytes(\"File downloaded: \" +\r\n name, \"utf-8\"))\r\n\r\n\r\ndef start_client(ip, port):\r\n\r\n sock = sock_connect(ip, port)\r\n print(sock.recv(1024).decode(\"utf-8\"))\r\n\r\n share_folder = set_transfer_location()\r\n\r\n create_folder(share_folder)\r\n\r\n while True:\r\n get_files(sock, share_folder)\r\n time.sleep(1 / 100)\r\n\r\n# the the port of the server (port of client on another computer)\r\nthreading.Thread(target=start_server, args=[\"0.0.0.0\", 55664]).start()\r\n\r\n# the ip of the other computer and port of client (port of server on another computer)\r\nthreading.Thread(target=start_client, args=[\"3.1.5.105\", 55665]).start()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"262052707","text":"# -*- coding: utf-8 -*-\n\"\"\"\nhandles things considered by the iPDA, or multi bernoulli filters\nIn this case,\n object existence - bernoulli probability\n object genuity - whether existing object is from long-term false positive\n object detectability - whether real object is temporarily undetectable\n object previous position x - for determining long-term false positives\n object previous position y - \" \"\n current number of detections\n average score of detections, used to determine, genuity\n label integer, (probably) unique for each originating msmt\n probability of being in detected tile (temporary for this timestep)\n object previous orientation cos\n object previous orientation sin\n stationaryness, used to determine genuity\n\"\"\"\nimport numpy as np\nfrom singleTracker import prepSample as soPrepObject\nfrom singleTracker import prepMeasurement as soPrepMeasurement\nfrom singleTracker import likelihood as soLikelihood\nfrom singleTracker import update as soUpdate\nfrom singleTracker import likelihoodNewObject as soLikelihoodNewObject\nfrom singleTracker import mlSample as soNewObject\nfrom singleTracker import validSample as soValidSample\nfrom singleTracker import predict as soPredict\nfrom singleTracker import reOrient as soReOrient\nfrom singleTracker import positionDistribution as soPositionDistribution\nfrom singleTracker import report as soReport\nfrom singleTracker import nft as sonft\n\nnft = sonft + 12\nsurvival_probability = .997\ndetectability_steadystate = .99 # average probability of object being detected\ndetectability_timestep_ratio = .75 # amount it changes in one second\nexist_object_ratio = .65\nmatch_nll_offset = -2.\n\n\ndetectability_pos2pos = 1 - (1 - detectability_steadystate) * detectability_timestep_ratio\ndetectability_neg2pos = detectability_steadystate * detectability_timestep_ratio\ndetectability_multiplier = detectability_pos2pos - detectability_neg2pos\ndetectability_constant = detectability_neg2pos\ndef predict(sample):\n soPredict(sample[:sonft])\n pexist, preal, pdetect, origcenterx, origcentery = sample[sonft:sonft+5]\n newpexist = pexist*survival_probability\n # remove stuff outside of kitti visible zone\n if sample[0] < 0 or sample[0] > 55 or abs(sample[1]) > sample[0]*.87+1.87:\n newpexist *= .5\n if sample[0] < -5 or sample[0] > 63 or abs(sample[1]) > sample[0]*.87+6:\n newpexist = 0.\n # change reality based on absolute and relative motion\n currdist = np.hypot(sample[0],sample[1])\n prevdist = np.hypot(origcenterx, origcentery)\n assert min(currdist, prevdist) > 1e-8\n distanceratio = min(currdist, prevdist) / max(currdist, prevdist)\n distanceratio = min(distanceratio + .05, 1)\n sindist = abs(sample[sonft+10]*sample[0] - sample[sonft+9]*sample[1]) / currdist\n sindist = max(sindist - .05, 0)\n newstationaryness = distanceratio**2 * (1-sindist)**3\n newstationaryness *= 3.5 / max(abs(sample[5]), 3.5)\n newstationaryness = max(min(sample[sonft+11], newstationaryness), .3)\n sample[sonft+11] = newstationaryness\n newpreal = sample[sonft+6] /(sample[sonft+6]+\n (1-sample[sonft+6])*newstationaryness)\n existworks = preal / newpreal\n newpexist *= existworks / (1-newpexist+newpexist*existworks)\n newpdetect = pdetect*detectability_multiplier+detectability_constant\n sample[sonft:sonft+3] = (newpexist, newpreal, newpdetect)\n \ndef _nlOdds(p):\n if p < 1e-11: return 25.\n if 1-p < 1e-11: return -25.\n return -np.log(p / (1-p))\n \n\"\"\"\nreturns:\n prepped object from single tracker\n negative log-odds of match (for adding to NLL of match matrix)\n\"\"\"\ndef prepObject(sample, pindetectregion):\n sample[sonft+8] = pindetectregion # easy way to keep this around\n soprep = soPrepObject(sample[:sonft])\n pexist, preal, pdetect = sample[sonft:sonft+3]\n pmatches = pexist * pindetectregion\n return soprep + (_nlOdds(pmatches),)\n\n\"\"\"\nweights are for determining which objects to prune or report\nonly their relative values matter, but these are from 0 to 1\n\"\"\"\ndef postMatchWeight(sample, msmt):\n preal = sample[sonft+1]\n realscore = msmt[2]\n preal = preal*realscore / (preal*realscore + (1-preal)*(1-realscore))\n return preal # pexist = 1\n\n\"\"\"\nprepObject must have been called at least once this timestep\n so that pindetectregion is updated\n\"\"\"\ndef postObjMissWeight(sample):\n pexist, preal, pdetect, pindetectregion = sample[[sonft,sonft+1,sonft+2,sonft+8]]\n eer = pindetectregion\n existdetect = pdetect * eer\n pexist = pexist*(1-existdetect) / (pexist*(1-existdetect) + 1-pexist)\n return pexist * preal\n\n\"\"\"\nreturns:\n prepped measurement from single tracker\n negative log-odds of msmt match (for adding to NLL of match matrix)\n\"\"\"\ndef prepMeasurement(msmt):\n somsmt, newobjectrate, score = msmt\n soprep = soPrepMeasurement(somsmt)\n newmsmtlik = soLikelihoodNewObject(soprep)\n llexist = newobjectrate * exist_object_ratio\n llnotexist = (1-exist_object_ratio)\n logodds = np.log(llexist + llnotexist)\n return soprep + (logodds - newmsmtlik + match_nll_offset,)\n\ndef postMsmtMissWeight(msmt):\n somsmt, newobjectrate, score = msmt\n llexist = newobjectrate * exist_object_ratio\n llnotexist = (1-exist_object_ratio)\n pexist = llexist/ (llexist + llnotexist)\n return pexist*score\n\n\"\"\"\nactually negative log likelihood\nthis already accounts for false positive and negative probabilities\n\"\"\"\ndef likelihood(preppedsample, preppedmsmt):\n solik = soLikelihood(preppedsample[:-1], preppedmsmt[:-1])\n return solik + preppedsample[-1] + preppedmsmt[-1]\n\ndef updateMatch(sample, msmt):\n preppedsample = soPrepObject(sample[:sonft])\n preppedmsmt = soPrepMeasurement(msmt[0])\n newsample = sample.copy()\n newsample[:sonft] = soUpdate(sample[:sonft], preppedsample, preppedmsmt)\n pexist, preal, pdetect, oldposx, oldposy = sample[sonft:sonft+5]\n newsample[sonft] = 1.\n # do correct update for reality score\n npreviousdetections = sample[sonft+5]\n meanscore = sample[sonft+6]\n realscore = msmt[2]\n if npreviousdetections < 10:\n newmeanscore = ((meanscore**2 *npreviousdetections + realscore**2)/(\n npreviousdetections+1))**.5\n else:\n newmeanscore = (meanscore**2 * .9 + realscore**2 * .1)**.5\n newsample[sonft+1] = newmeanscore / (newmeanscore+\n (1-newmeanscore)*newsample[sonft+11])\n newsample[sonft+5] = npreviousdetections + 1\n newsample[sonft+6] = newmeanscore\n newsample[sonft+2] = 1.\n # update old positions for reality checks\n currdist = np.hypot(newsample[0], newsample[1])\n newsample[sonft+3] = (oldposx*4 + newsample[0])/5.\n newsample[sonft+4] = (oldposy*4 + newsample[1])/5.\n newsample[sonft+9] = (sample[sonft+9]*4 + newsample[0]/currdist)/5.\n newsample[sonft+10] = (sample[sonft+10]*4 + newsample[1]/currdist)/5.\n newsample[sonft+9:sonft+11] /= np.hypot(newsample[sonft+9],newsample[sonft+10])\n return newsample\n \ndef updateMiss(sample):\n newsample = sample.copy()\n pexist, preal, pdetect= sample[sonft:sonft+3]\n pindetectregion = sample[sonft+8]\n eer = pindetectregion\n existdetect = pdetect * eer\n newsample[sonft] = pexist*(1-existdetect) / (pexist*(1-existdetect) + 1-pexist)\n newsample[sonft+2] = pdetect*(1 - eer) / (pdetect*(1 - eer) + 1 - pdetect)\n return newsample\n\ndef updateNew(msmt):\n newsample = np.zeros(nft)\n newsample[:sonft] = soNewObject(soPrepMeasurement(msmt[0]))\n llexist = msmt[1] * exist_object_ratio\n llnotexist = 1 - exist_object_ratio\n newsample[sonft] = llexist/ (llexist + llnotexist)\n newsample[sonft+1] = msmt[2]\n newsample[sonft+2] = 1.\n newsample[sonft+3:sonft+5] = newsample[:2]\n newsample[sonft+5] = 1\n newsample[sonft+6] = newsample[sonft+1]\n newsample[sonft+7] = np.random.randint(int(1e9))#hash(newsample.data.tobytes()) % 1e9\n currdist = np.hypot(newsample[0], newsample[1])\n newsample[sonft+9] = newsample[0]/currdist\n newsample[sonft+10] = newsample[1]/currdist\n newsample[sonft+11] = 1.\n return newsample\n\ndef validSample(sample):\n valid = True\n if sample[sonft] > 1e-2:\n valid &= soValidSample(sample[:sonft])\n elif sample[sonft] > 1e-5 and not soValidSample(sample[:sonft]):\n print(\"invalid (but very unlikely) sample\")\n valid &= sample[sonft] >= 0 and sample[sonft] <= 1\n valid &= sample[sonft+1] >= 0 and sample[sonft+1] <= 1\n valid &= sample[sonft+2] >= 0 and sample[sonft+2] <= 1\n valid &= sample[sonft+6] >= 0 and sample[sonft+6] <= 1\n return valid\n\ndef reOrient(sample, newpose):\n soReOrient(sample, newpose)\n sample[sonft+9:sonft+11] = np.dot(newpose[:2,:2], sample[sonft+9:sonft+11])\n \npositionDistribution = soPositionDistribution\n\n\n\"\"\" returns a float that is the prune weight, and the object in report format \"\"\"\ndef report(sample):\n return sample[sonft]*sample[sonft+1], soReport(sample[:sonft])\n\n\"\"\" if sample has 0 pexist, no reason to perform calculations (might be empty) \"\"\"\ndef shouldUseObject(sample): return sample[sonft]*sample[sonft+1] > 0","sub_path":"singleIntegrator.py","file_name":"singleIntegrator.py","file_ext":"py","file_size_in_byte":9191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"8889688","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/marc/Git/common-framework/common/migrations/0008_auto_20180302.py\n# Compiled at: 2018-03-02 06:56:09\n# Size of source mod 2**32: 520 bytes\nfrom django.db import migrations\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('contenttypes', '0002_remove_content_type_name'),\n ('common', '0007_auto_20180210')]\n operations = [\n migrations.AlterIndexTogether(name='metadata',\n index_together={\n ('content_type', 'object_id', 'deletion_date', 'key'), ('content_type', 'object_id'), ('content_type', 'object_id', 'deletion_date')})]","sub_path":"pycfiles/common_framework-2019.11.25-py3-none-any/0008_auto_20180302.cpython-37.py","file_name":"0008_auto_20180302.cpython-37.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"545134474","text":"__author__ = 'yinyanhe'\n\"\"\"\nduplicates are allowed\n\"\"\"\ndef search(nums, target):\n \"\"\"\n :param nums: List[int]\n :param target: int\n :return:bool\n \"\"\"\n idx=0\n for i in range(1, len(nums)):\n if nums[i]>1\n if nums[mid]==target:\n return True\n elif nums[mid] 60:\n comment = balance_comment_high\n else:\n comment = balance_comment_medium\n\n await bot.send_message(\n chat_id=cid,\n text=balance_phrase.format(balance, comment),\n reply_to_message_id=get_mid(message),\n parse_mode=\"html\",\n )\n\n\nmy_tacos_handler = MessageHandler(\n callback=my_tacos_callback,\n filters=Filters.group & Filters.command([\"mytacos\", \"mytacos@HeyTacoBot\"]),\n)\n\n\nasync def taco_top_callback(bot, message):\n \"\"\" shows top-5(or less) taco-users in chat \"\"\"\n\n cid = get_cid(message)\n mid = get_mid(message)\n store_name(message)\n\n tacos = Tacos.get(Tacos.chat == cid)\n\n balances = json.loads(tacos.taco_balance)\n\n if len(balances) == 0: # in case tacos-table is empty\n bot.send_message(\n text=empty_top_phrase,\n chat_id=cid,\n reply_to_message_id=mid,\n parse_mode=\"html\",\n )\n return\n\n top = list()\n\n while len(balances) > 0 and len(top) < 5:\n top_uid = max(balances, key=balances.get)\n username = resolve_name(top_uid)\n top.append([username, balances.get(top_uid)])\n del balances[top_uid]\n\n formatted_top = \"\"\n for user in top:\n formatted_top += \"{}. {} - {} tacos!\\n\".format(\n top.index(user) + 1, user[0], user[1]\n )\n\n await bot.send_message(\n text=taco_top_phrase.format(len(top), formatted_top),\n chat_id=cid,\n reply_to_message_id=mid,\n parse_mode=\"html\",\n )\n\n\ntaco_top_handler = MessageHandler(\n callback=taco_top_callback,\n filters=Filters.group & Filters.command([\"tacotop\", \"tacotop@HeyTacoBot\"]),\n)\n","sub_path":"handlers/leaderboards.py","file_name":"leaderboards.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"336785585","text":"import click\n\nfrom . import config\nfrom . import env as tutor_env\nfrom . import fmt\nfrom . import opts\nfrom . import utils\n\n\nDOCKER_IMAGE = \"regis/openedx-android:hawthorn\"\n\n@click.group(\n help=\"Build an Android app for your Open edX platform [BETA FEATURE]\"\n)\ndef android():\n pass\n\n@click.command(\n help=\"Generate the environment required for building the application\"\n)\n@opts.root\ndef env(root):\n tutor_env.render_target(root, config.load(root), \"android\")\n\n@click.group(\n help=\"Build the application\"\n)\ndef build():\n pass\n\n@click.command(\n help=\"Build the application in debug mode\"\n)\n@opts.root\ndef debug(root):\n docker_run(\n root, \"./gradlew\", \"assembleProdDebuggable\", \"&&\",\n \"cp\", \"OpenEdXMobile/build/outputs/apk/prod/debuggable/*.apk\", \"/openedx/data/\"\n )\n click.echo(fmt.info(\"The debuggable APK file is available in {}\".format(tutor_env.data_path(root, \"android\"))))\n\n@click.command(\n help=\"Build the application in release mode\"\n)\n@opts.root\ndef release(root):\n docker_run(root, \"./gradlew\", \"assembleProdRelease\")\n click.echo(fmt.info(\"The production APK file is available in {}\".format(tutor_env.data_path(root, \"android\"))))\n\n@click.command(\n help=\"Pull the docker image\"\n)\n@opts.root\ndef pullimage():\n utils.execute(\"docker\", \"pull\", DOCKER_IMAGE)\n\ndef docker_run(root, *command):\n utils.docker_run(\n \"--volume={}/:/openedx/config/\".format(tutor_env.pathjoin(root, \"android\")),\n \"--volume={}:/openedx/data\".format(tutor_env.data_path(root, \"android\")),\n DOCKER_IMAGE,\n *command\n )\n\nbuild.add_command(debug)\nbuild.add_command(release)\nandroid.add_command(build)\nandroid.add_command(env)\nandroid.add_command(pullimage)\n","sub_path":"tutor/android.py","file_name":"android.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"188267696","text":"#!/usr/bin/env python\n\nimport requests\nimport json\nimport sys\n\n\n# get the domain to scan for subdomains\n\n# search for command line arguments, reset to \"annashut.com\" if not found\nargs = sys.argv[1:]\ndomain = args[0] if len(args) > 0 else \"annashut.com\"\n\n# read all subdomains\nfile = open(\"subdomains.txt\")\n# read all content\ncontent = file.read()\n# split by new lines\nsubdomains = content.splitlines()\nfile.close()\n\nfor subdomain in subdomains:\n # construct the url\n url = f\"https://{subdomain}.{domain}\"\n try:\n # if this raises an ERROR, that means the subdomain does not exist\n requests.get(url)\n except requests.ConnectionError:\n # if the subdomain does not exist, just pass, print nothing\n pass\n else:\n print(\"=> Discovered subdomain:\", url)\n subdomain_name = url.split(\"//\")[1].split(\".\")[0]\n dict = {'subdomain name': subdomain_name, 'domain name': url}\n #Convert the dictionary gotten to json\n dict = json.dumps(dict)\n print(dict)\n","sub_path":"subdomain_scrape_finished.py","file_name":"subdomain_scrape_finished.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"299052709","text":"from flask import Flask, jsonify, request\nfrom flask_restful import Api, Resource\nfrom selenium import webdriver\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport requests\nfrom bs4 import BeautifulSoup\nimport pickle\nimport re\nimport time\nimport pandas as pd\n\n\ndef clean_url(coulum):\n clean = []\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item))\n\n return clean\n\n\ndef clean_list(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.text))\n\n return clean\n\n\ndef clean_list1(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.a.text))\n\n return clean\n\n\ndef clean_discount(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.text))\n\n return clean\n\n\ndef clean_prix(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.text))\n\n return clean\n\n\ndef clean_car(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.text))\n\n return clean\n\n\ndef clean_des(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.text))\n\n return clean\n\n\ndef clean_numcom(coulum):\n clean = []\n\n for x in range(len(coulum)):\n for item in coulum[x]:\n clean.append((item.text))\n\n return clean\n\n\ndef url_to_transcript1(clean_link):\n response = requests.get(clean_link)\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n name = soup.find_all('div', attrs={'class': '-fs0 -pls -prl'})\n details = soup.find_all('div', attrs={'class': 'markup -pam'})\n marque = soup.find_all('div', attrs={'class': '-fs14 -pvxs'})\n price = soup.find_all('span', attrs={'class': '-b -ltr -tal -fs24'})\n discount = soup.find_all('span', attrs={'class': 'tag _dsct _dyn -mls'})\n car = soup.find_all('div', attrs={'class': 'markup -pam'})\n descrptivetechnique = soup.find_all('div', attrs={'class': 'card-b -fh'})\n avis = soup.find_all('div', attrs={'class': 'stars _m -mvs'})\n numcomments = soup.find_all('div', attrs={'class': 'cola -phm -df -d-co'})\n comments = soup.find_all('p', attrs={'class': '-pvs'})\n\n Name = []\n Deatils = []\n Marque = []\n Prix = []\n Discount = []\n Car = []\n Des = []\n Avis = []\n Numcmts = []\n Cmts = []\n for x in range(len(marque)):\n Name.append(name[x])\n Deatils.append(details[x])\n Marque.append(marque[x])\n Prix.append(price[x])\n Discount.append(discount[x])\n Car.append(car[x])\n Des.append(descrptivetechnique[x])\n # Avis.append(avis[x])\n Numcmts.append(numcomments[x])\n # Cmts.append(comments[x])\n\n return Name, Deatils, Marque, Prix, Discount, Car, Des, Avis, Numcmts, Cmts\n\n\nclass Moteur(Resource):\n def post(self):\n postedData = request.get_json()\n\n product = postedData['product']\n value = str(product)+\" jumia\"\n value = value.replace(' ', '+')\n executable_path =r'C:\\Users\\Amani\\Desktop\\chromedriver.exe'\n browser = webdriver.Chrome(executable_path=executable_path)\n\n #browser = webdriver.Chrome(ChromeDriverManager().install())\n\n for i in range(1, 20):\n browser.get(\"https://www.google.com/search?q=\" +\n value + \"&start=\" + str(i))\n matched_elements = browser.find_elements_by_xpath(\n '//a[starts-with(@href, \"https://www.jumia.\")]')\n if matched_elements:\n matched_elements[0].click()\n print(matched_elements[0])\n break\n\n time.sleep(5)\n links = []\n while True:\n spans_to_iterate = browser.find_elements_by_xpath(\n \"//a[contains(@class,'core')]\")\n print(spans_to_iterate)\n link_list = []\n\n # iterate span elements to save the href attribute of a element\n for span in spans_to_iterate:\n link_text = span.get_attribute(\"href\")\n link_list.append(link_text)\n links.append(link_list)\n\n try:\n if browser.find_element_by_xpath('.//a[@title=\"Suivant\"]'):\n browser.find_element_by_xpath(\n './/a[@title=\"Suivant\"]').click()\n time.sleep(5)\n\n except:\n break\n\n clean_link = clean_url(links)\n print(\"clean liiiiiiink\",len(clean_link))\n jumia = [url_to_transcript1(u) for u in clean_link[:1]]\n\n Name = []\n Deatils = []\n Marque = []\n Prix = []\n Discount = []\n Car = []\n Des = []\n Avis = []\n Numcmts = []\n Cmts = []\n for item in jumia:\n Name.append(item[0])\n Deatils = [].append(item[1])\n Marque.append(item[2])\n Prix.append(item[3])\n Discount.append(item[4])\n Car.append(item[5])\n Des.append(item[6])\n Avis.append(item[7])\n Numcmts.append(item[8])\n Cmts.append(item[9])\n\n clean_marque = clean_list1(Marque)\n clean_name = clean_list(Name)\n clean_disc = clean_discount(Discount)\n clean_carac = clean_car(Car)\n clean_price = clean_prix(Prix)\n clean_description = clean_des(Des)\n clean_numcommentaire = clean_numcom(Numcmts)\n df = pd.DataFrame(clean_marque, columns=['marque'])\n df[\"name\"] = clean_name\n df[\"marque\"] = clean_marque\n df[\"Prix\"] = clean_price\n df[\"discount\"] = clean_disc\n df[\"Avis\"] = clean_numcommentaire\n df[\"caracterstique\"] = clean_carac\n df[\"deescriptive\"] = clean_description\n df.to_csv(\"testmoteur.csv\", index=False, header=True)\n\n retJson = {\n \"status\": 200,\n \"message\": \"Succesfuly signed up for this api\",\n \"response\": {\n \"message\": \"terminer\",\n \"product\": product,\n\n\n\n }\n }\n\n return jsonify(retJson, 200)\n","sub_path":"product_similarity/resource/moteur.py","file_name":"moteur.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"4013013","text":"\"\"\"\nTaken heavily from https://github.com/singer-io/tap-dynamodb/blob/master/tap_dynamodb/sync_strategies/full_table.py\n\"\"\"\n\nimport re\n\nimport botocore.exceptions\nimport singer\nfrom tap_dynamodb import dynamodb\n\nLOGGER = singer.get_logger()\n\n\ndef scan_table(table_name, projection, last_evaluated_key, config, schema_inf=False):\n scan_params = {\n 'TableName': table_name,\n 'Limit': config['num_inference_records'] if schema_inf else 1000\n }\n\n if projection is not None and projection != '':\n scan_params['ProjectionExpression'] = projection\n if last_evaluated_key is not None:\n scan_params['ExclusiveStartKey'] = last_evaluated_key\n\n client = dynamodb.get_client(config)\n has_more = True\n\n while has_more:\n LOGGER.info(f'Scanning table {table_name} with params:')\n for key, value in scan_params.items():\n LOGGER.info(f'\\t{key} = {value}')\n\n result = scan_r(client, scan_params)\n\n yield result\n\n if result.get('LastEvaluatedKey'):\n scan_params['ExclusiveStartKey'] = result['LastEvaluatedKey']\n\n has_more = result.get('LastEvaluatedKey', False)\n\n\ndef scan_r(client, scan_params):\n try:\n result = client.scan(**scan_params)\n except botocore.exceptions.ClientError as e:\n kw = str(e).split(\" \")[-1]\n LOGGER.info(f\"Modifying projection expression: error with reserved keyword: {kw}\")\n attr_nm = f\"#{kw[0:2]}\"\n scan_params['ProjectionExpression'] = re.sub(f\"(?<=,){kw}(?=$|,)|(?<=^){kw}(?=$|,)\",\n f\"{attr_nm}\",\n scan_params['ProjectionExpression'])\n if scan_params.get('ExpressionAttributeNames'):\n scan_params['ExpressionAttributeNames'][attr_nm] = kw\n else:\n scan_params['ExpressionAttributeNames'] = {attr_nm: kw}\n result = scan_r(client, scan_params)\n\n return result","sub_path":"tap_dynamodb/sync_strategies/full_table.py","file_name":"full_table.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"607565625","text":"# -*- coding: utf-8 -*-\r\n\r\n\r\nclass Listener(object):\r\n\t'''监听器\r\n\t'''\r\n\teventTypeList = [] # 监听的事件类型\r\n\tconditionList = () # 触发条件\r\n\tconditionScope = \"\" # 条件范围\r\n\teventList = () # 达成条件后触发的事件\r\n\t\r\n\tdef __init__(self, _id):\r\n\t\tself.id = _id\r\n\t\t\r\n\tdef checkCondition(self, who, **kwargs):\r\n\t\t'''检查条件\r\n\t\t'''\r\n\t\tif self.conditionScope: # 根据范围检查条件\r\n\t\t\treturn self.checkConditionByScope(who, **kwargs)\r\n\t\t\r\n\t\tfor idx, conditionStr in self.conditionList:\r\n\t\t\tif conditionStr.startswith(\"$\"): # 自定义的条件\r\n\t\t\t\tconditionName = conditionStr[1:]\r\n\t\t\t\tresult = self.checkCustomCondition(who, conditionName, **kwargs)\r\n\t\t\telse:\r\n\t\t\t\tresult = listener.defines.checkCondition(who, conditionStr, **kwargs)\r\n\t\t\tif not result: # 只要有条件不成立,直接返回\r\n\t\t\t\treturn 0\r\n\t\t\t\r\n\t\treturn 1\r\n\t\r\n\tdef checkConditionByScope(self, who, **kwargs):\r\n\t\t'''根据范围检查条件\r\n\t\t'''\r\n\t\tresultList = {}\r\n\t\tconditionScope = self.conditionScope \r\n\t\tfor idx, conditionStr in self.conditionList:\r\n\t\t\tif conditionStr.startswith(\"$\"): # 自定义的条件\r\n\t\t\t\tconditionName = conditionStr[1:]\r\n\t\t\t\tresult = self.checkCustomCondition(who, conditionName, **kwargs)\r\n\t\t\telse:\r\n\t\t\t\tresult = listener.defines.checkCondition(who, conditionStr, **kwargs)\r\n\t\t\tresultList[idx] = result\r\n\t\t\tconditionScope = conditionScope.replace(str(idx), str(result))\r\n\t\treturn eval(conditionScope)\r\n\t\r\n\tdef checkCustomCondition(self, who, conditionName, **kwargs):\r\n\t\t'''检查自定义条件\r\n\t\t'''\r\n\t\treturn 0\r\n\t\r\n\tdef triggerEvent(self, who, **kwargs):\r\n\t\t'''触发事件\r\n\t\t'''\r\n\t\tkwargs[\"eventId\"] = self.id\r\n\t\tfor eventStr in self.eventList:\r\n\t\t\tif eventStr.startswith(\"$\"): # 自定义的事件\r\n\t\t\t\teventName = eventStr[1:]\r\n\t\t\t\tself.triggerCustomEvent(who, eventName, **kwargs)\r\n\t\t\telse:\r\n\t\t\t\tlistener.defines.triggerEvent(who, eventStr, **kwargs)\r\n\t\t\r\n\tdef triggerCustomEvent(self, who, eventName, **kwargs):\r\n\t\t'''触发自定义事件\r\n\t\t'''\r\n\t\tpass\r\n\r\n\r\nimport listener.defines","sub_path":"logic/listener/object.py","file_name":"object.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"486064064","text":"from RecommenderSystem.Classification import Features\r\nfrom RecommenderSystem.Classification.Classifiers import classifiers\r\nimport psycopg2\r\nimport pickle\r\n\r\ndef main():\r\n\r\n\r\n try:\r\n conn = psycopg2.connect(dbname='trajectory_simulator', user='bhavesh', host='geoserver.sb.dfki.de',password='LrVYI%TMT%d3')\r\n except:\r\n print(\"I am unable to connect to the database\")\r\n\r\n cur = conn.cursor()\r\n\r\n\r\n # read cluster center, receipt_list(mapping.matching), trace_list(mapping.matching)\r\n with open('./ClusterCenters.p', 'rb') as fp:\r\n cluster_centers = pickle.load(fp)\r\n\r\n with open('./receipts_list.p', 'rb') as fp:\r\n receipt_list = pickle.load(fp)\r\n\r\n with open('./trace_list.p', 'rb') as fp:\r\n trace_list = pickle.load(fp)\r\n\r\n\r\n # Assignment of cluster labels to traces\r\n classifier_label_matrix=Features.trace_feature_labels(conn,cluster_centers,receipt_list,trace_list)\r\n\r\n with open('classifier_label_matrix.p', 'wb') as fp:\r\n pickle.dump(classifier_label_matrix, fp)\r\n\r\n\r\n # Index 1=shelfmeter_id, 2=shelf_name, 3=department_name\r\n Features.labelEncoder(conn,cur,1)\r\n\r\n\r\n # features\r\n classifier_feature_matrix=Features.trace_features(conn,trace_list)\r\n\r\n\r\n # Classification Modeling\r\n classifiers().cross_validation(classifier_feature_matrix,classifier_label_matrix,50)\r\n\r\n\r\n # K Nearest Neighbour\r\n\r\n # Random Forest\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"RecommenderSystem/Classification/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"34854779","text":"# -------------------------------------------------------\n\n# Vertical and horizontal checks [DONE]\n# Diagonal checks from left and right side [DONE]\n# Actions when no condition is met [DONE]\n# User input feature [DONE]\n# Game over along with making the computer wanna win [DONE]\n# Improvement in the random function and\n# for the computer to make more strategic moves [DONE]\n# Create a GUI\n\n# --------------------------------------------------------\n\n\nimport random\n\n\nclass GameFunctions:\n\n @staticmethod\n def view_grid(lst):\n for item in range(len(lst)):\n print(lst[item])\n print(\"------------\")\n\n @staticmethod\n def count(lst, item):\n count = 0\n for items in lst:\n if item == items:\n count += 1\n return count\n\n @staticmethod\n def box_count(lst):\n count = 0\n for num in range(len(lst)):\n for num_inner in range(len(lst)):\n if lst[num][num_inner] != 0:\n count += 1\n return count\n\n @staticmethod\n def random_move(lst):\n for index in range(len(lst)):\n for inner_index in range(len(lst[0])):\n if lst[index][inner_index] != 1 and lst[index][inner_index] != 2:\n lst[index][inner_index] = 2\n return\n\n @staticmethod\n def horizontal_check(lst, player, computer, player_count, computer_count):\n for item in range(len(lst)):\n if GameFunctions.count(lst[item], player) == player_count \\\n and GameFunctions.count(lst[item], computer) == computer_count:\n for num in range(len(lst[item])):\n if lst[item][num] != 1 and lst[item][num] == 0:\n lst[item][num] = 2\n break # stops the function once it finds a line that meets the condition\n\n @staticmethod\n def vertical_check(lst, player, computer, player_count, computer_count):\n for i in range(len(lst[0])):\n vertical_lst = []\n for num in range(len(lst)):\n vertical_lst.append(lst[num][i])\n if GameFunctions.count(vertical_lst, player) == player_count \\\n and GameFunctions.count(vertical_lst, computer) == computer_count:\n for n in range(len(lst)):\n if lst[n][i] != 1 and lst[n][i] == 0:\n lst[n][i] = 2\n break\n\n @staticmethod\n def diagonal_check_left(lst, player, computer, player_count, computer_count):\n for i in range(len(lst[0])):\n diagonal_lst_left = []\n for num in range(len(lst)):\n diagonal_lst_left.append(lst[num][num])\n if GameFunctions.count(diagonal_lst_left, player) == player_count \\\n and GameFunctions.count(diagonal_lst_left, computer) == computer_count:\n for n in range(len(lst)):\n if lst[n][n] != 1 and lst[n][n] == 0:\n lst[n][n] = 2\n return\n\n @staticmethod\n def diagonal_check_right(lst, player, computer, player_count, computer_count):\n diagonal_lst_right = []\n count = len(lst) - 1\n while count >= 0:\n for num in range(len(lst[0])):\n diagonal_lst_right.append(lst[count][num])\n count -= 1\n if GameFunctions.count(diagonal_lst_right, player) == player_count \\\n and GameFunctions.count(diagonal_lst_right, computer) == computer_count:\n new_count = len(lst) - 1\n while new_count >= 0:\n for n in range(len(lst[0])):\n if lst[new_count][n] != 1 and lst[new_count][n] == 0:\n lst[new_count][n] = 2\n return\n new_count -= 1\n\n @staticmethod\n def win_check(lst, player):\n for item in range(len(lst)):\n if GameFunctions.count(lst[item], player) == 3:\n return True\n\n for i in range(len(lst[0])):\n vertical_lst = []\n for num in range(len(lst)):\n vertical_lst.append(lst[num][i])\n if GameFunctions.count(vertical_lst, player) == 3:\n return True\n\n diagonal_lst_left = []\n for num in range(len(lst)):\n diagonal_lst_left.append(lst[num][num])\n if GameFunctions.count(diagonal_lst_left, player) == 3:\n return True\n\n diagonal_lst_right = []\n count = len(lst) - 1\n while count >= 0:\n for num in range(len(lst[0])):\n diagonal_lst_right.append(lst[count][num])\n count -= 1\n if GameFunctions.count(diagonal_lst_right, player) == 3:\n return True\n\n\ngrid = [\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]\n]\nprint(\"(1) is the player AND (2) is the computer\")\nGameFunctions.view_grid(grid)\n\nwhile True:\n u_grid = int(input(\"Grid?? PRESS(0 OR 1 OR 2)\"))\n u_index = int(input(\"Index?? PRESS(0 OR 1 OR 2)\"))\n if grid[u_grid][u_index] == 0:\n grid[u_grid][u_index] = 1\n else:\n print(\"Not Valid\")\n count = GameFunctions.box_count(grid)\n\n if GameFunctions.box_count(grid) == count:\n GameFunctions.horizontal_check(grid, 1, 2, 0, 2)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.vertical_check(grid, 1, 2, 0, 2)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.diagonal_check_left(grid, 1, 2, 0, 2)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.diagonal_check_right(grid, 1, 2, 0, 2)\n\n if GameFunctions.box_count(grid) == count:\n GameFunctions.horizontal_check(grid, 1, 2, 2, 0)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.vertical_check(grid, 1, 2, 2, 0)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.diagonal_check_left(grid, 1, 2, 2, 0)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.diagonal_check_right(grid, 1, 2, 2, 0)\n\n if GameFunctions.box_count(grid) == count:\n GameFunctions.horizontal_check(grid, 1, 2, 0, 1)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.vertical_check(grid, 1, 2, 0, 1)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.diagonal_check_left(grid, 1, 2, 0, 1)\n if GameFunctions.box_count(grid) == count:\n GameFunctions.diagonal_check_right(grid, 1, 2, 0, 1)\n\n if GameFunctions.box_count(grid) == count:\n GameFunctions.random_move(grid)\n\n if GameFunctions.win_check(grid, 2):\n GameFunctions.view_grid(grid)\n print(\"Player Lost!!!!\")\n break\n if GameFunctions.win_check(grid, 1):\n GameFunctions.view_grid(grid)\n print(\"Player Wins!!!!!\")\n break\n\n if GameFunctions.box_count(grid) == 9:\n GameFunctions.view_grid(grid)\n print(\"Game Tied!!!!!\")\n break\n\n GameFunctions.view_grid(grid)\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":6970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"358340319","text":"import torch\nfrom torch.utils.data import Dataset, DataLoader\n\nimport cv2\n\nclass MRIDataset(Dataset):\n def __init__(self, df, transform=None):\n \"\"\"\n Initializes dataset class\n :param df: DataFrame containing MRI and segmentation mask paths\n :param transform: Image transforms\n \"\"\"\n self.df = df\n self.transform = transform\n\n def __getitem__(self, idx):\n mri = cv2.imread(self.df.iloc[idx]['MRI'])\n mask = cv2.imread(self.df.iloc[idx]['Mask'], 0)\n\n if self.transform is not None:\n mri = self.transform(mri)\n mask = self.transform(mask)\n\n return {\n 'MRI': mri,\n 'Mask': mask\n }\n\n def __len__(self):\n return len(self.df)\n","sub_path":"MRI Model/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"162081813","text":"from os import getcwd\nfrom yaml import load\nimport logging\n\n\n# getting path\ndef _get_scriptpath():\n\treturn getcwd()\t\n\n# reading config from yaml file\ndef _get_config(cfgpath):\n\tcfgfile = '%s/config.yaml' % cfgpath\n\tcfgdata = load(open(cfgfile, 'r'))\n\treturn cfgdata\n\n# logging config\ndef _set_logger(logfile, loglevel):\n\tif loglevel == \"DEBUG\":\n\t\tlevel = logging.DEBUG\n\telif loglevel == \"INFO\":\n\t\tlevel = logging.INFO\n\telse:\n\t\tlevel = logging.WARNING\n\n\tif logfile.startswith(\"./\"):\n\t\tlogfile = \"%s/%s\" % (SCRIPTPATH, logfile)\n\t\n\tlogging.basicConfig(\\\n\t\tlevel=level,\\\n\t\tfilename=\"{0}.log\".format(logfile),\\\n\t\tformat=\"%(asctime)s [%(levelname)-5.5s] %(message)s\"\\\n\t\t)\n\tlogger = logging.getLogger()\n\tlogger.debug(\"Logger initialised.\")\t\n\treturn logger\n\n\nSCRIPTPATH = _get_scriptpath()\n_cfgdata = _get_config(SCRIPTPATH)\n\nMEMFREE =\t_cfgdata[\"Basic\"][\"memfree\"]\nSPACEFREE =\t_cfgdata[\"Basic\"][\"spacefree\"]\n\nDATA_DIR = \t_cfgdata[\"Basic\"][\"data_dir\"]\nOBSERVATORY=_cfgdata[\"Observatory\"]\n\nINSTR_DEV = _cfgdata[\"Instru\"][\"device\"]\nINSTR_TAG = _cfgdata[\"Instru\"][\"usbtag\"]\nINSTR_ID = \t_cfgdata[\"Instru\"][\"id\"]\nEXP_MAX =\t_cfgdata[\"Instru\"][\"expo_max\"]\nEXP_MIN = \t_cfgdata[\"Instru\"][\"expo_min\"]\nSUNDT = \t_cfgdata[\"Instru\"][\"sundt\"]\n\nlogger = _set_logger( \\\n\t_cfgdata[\"Basic\"][\"logfile\"], _cfgdata[\"Basic\"][\"loglevel\"])\n\nSHMOD = \t_cfgdata[\"SenseHat\"][\"enable\"]\nSHORI = \t_cfgdata[\"SenseHat\"][\"ori\"]\n\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"454913089","text":"from __future__ import print_function\nimport os\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\nclass Net(nn.Module):\n def __init__(self, input_dim=28, output_dim=10):\n super(Net, self).__init__()\n # Build the model\n self.in_dense = nn.Sequential(\n nn.Linear(input_dim, 32),\n nn.LeakyReLU())\n self.recurrent = nn.RNN(32, 128, batch_first=True)\n self.out_dense = nn.Sequential(\n nn.Linear(128, 32),\n nn.LeakyReLU(),\n nn.Linear(32, output_dim),\n nn.Softmax(dim=1))\n\n def forward(self, x):\n embedded = self.in_dense(x)\n # embedded = [batch_size, 28, 32]\n\n rnn_out, h = self.recurrent(embedded)\n h = torch.squeeze(h, 0)\n # h = [batch_size, 128]\n\n dense_out = self.out_dense(h)\n # dense_out = [batch_size, output_dim]\n\n return dense_out # Get last pred from seq\n\n\ndef train(args, model, device, train_loader, optimizer, epoch):\n model.train()\n correct = 0\n current_samples = 0\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n data = data.view((-1, 28, 28))\n optimizer.zero_grad()\n output = model(data)\n loss = F.cross_entropy(output, target)\n loss.backward()\n pred = output.argmax(dim=1, keepdim=True)\n correct += pred.eq(target.view_as(pred)).sum().item()\n current_samples += data.size(0)\n optimizer.step()\n if batch_idx % 10 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}\\tAcc: {:.2f}%'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item(),\n 100. * correct / current_samples))\n\n\ndef test(model, device, test_loader):\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n data = data.view((-1, 28, 28))\n output = model(data)\n test_loss += F.cross_entropy(output, target, reduction='sum').item()\n pred = output.argmax(dim=1, keepdim=True)\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n test_acc = correct / len(test_loader.dataset)\n\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset), 100. * test_acc))\n\n return test_loss, test_acc\n\n\ndef main():\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch RNN MNIST Example')\n parser.add_argument('--batch-size', type=int, default=100, metavar='N',\n help='input batch size for training (default: 100)')\n parser.add_argument('--epochs', type=int, default=5, metavar='N',\n help='number of epochs to train (default: 5)')\n parser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--output-path', type=str, default=\"onnx_models/rnn_mnist.onnx\",\n help='Output path to store the onnx file')\n parser.add_argument('--output-metric', type=str, default=\"\",\n help='Output file path to store the metric value obtained in test set')\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'batch_size': args.batch_size}\n if use_cuda:\n kwargs.update({'num_workers': 2,\n 'pin_memory': True,\n 'shuffle': True})\n\n # Prepare data generators\n transform=transforms.Compose([transforms.ToTensor()])\n dataset1 = datasets.MNIST('../data', train=True, download=True,\n transform=transform)\n dataset2 = datasets.MNIST('../data', train=False,\n transform=transform)\n train_loader = torch.utils.data.DataLoader(dataset1, **kwargs)\n test_loader = torch.utils.data.DataLoader(dataset2, **kwargs)\n\n model = Net().to(device)\n optimizer = optim.Adam(model.parameters(), lr=args.lr)\n\n # Train\n test_acc = -1.0\n for epoch in range(1, args.epochs + 1):\n train(args, model, device, train_loader, optimizer, epoch)\n _, test_acc = test(model, device, test_loader)\n\n # In case of providing output metric file, store the test accuracy value\n if args.output_metric != \"\":\n with open(args.output_metric, 'w') as ofile:\n ofile.write(str(test_acc))\n\n # Save to ONNX file\n dummy_input = torch.randn(args.batch_size, 28, 28, device=device)\n torch.onnx._export(model, dummy_input, args.output_path, keep_initializers_as_inputs=True)\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/tests/py_onnx/pytorch/export_scripts/rnn_mnist_pytorch_export.py","file_name":"rnn_mnist_pytorch_export.py","file_ext":"py","file_size_in_byte":5350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"379864734","text":"# © 2016 Therp BV \n# © 2018 TKOpen \n# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).\n\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nimport threading\nimport time\n\nimport odoo\nfrom odoo.tests import common\n\nADMIN_USER_ID = common.ADMIN_USER_ID\n\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import UserError\n\n_logger = logging.getLogger(__name__)\n_MARKER_PHRASE = '[[waiting for OCR]]'\n_PDF_OCR_DOCUMENTS_THREADS = []\nOCR_LANGUAGE = [('afr', 'Afrikaans'),\n ('amh', 'Amharic'),\n ('ara', 'Arabic'),\n ('asm', 'Assamese'),\n ('aze', 'Azerbaijani'),\n ('aze_cyrl', 'Azerbaijani - Cyrilic'),\n ('bel', 'Belarusian'),\n ('ben', 'Bengali'),\n ('bod', 'Tibetan'),\n ('bos', 'Bosnian'),\n ('bul', 'Bulgarian'),\n ('cat', 'Catalan; Valencian'),\n ('ceb', 'Cebuano'),\n ('ces', 'Czech'),\n ('chi_sim', 'Chinese - Simplified'),\n ('chi_tra', 'Chinese - Traditional'),\n ('chr', 'Cherokee'),\n ('cym', 'Welsh'),\n ('dan', 'Danish'),\n ('dan_frak', 'Danish - Fraktur'),\n ('deu', 'German'),\n ('deu_frak', 'German - Fraktur'),\n ('dzo', 'Dzongkha'),\n ('ell', 'Greek, Modern (1453-)'),\n ('eng', 'English'),\n ('enm', 'English, Middle (1100-1500)'),\n ('epo', 'Esperanto'),\n ('equ', 'Math / equation detection module'),\n ('est', 'Estonian'),\n ('eus', 'Basque'),\n ('fas', 'Persian'),\n ('fin', 'Finnish'),\n ('fra', 'French'),\n ('frk', 'Frankish'),\n ('frm', 'French, Middle (ca.1400-1600)'),\n ('gle', 'Irish'),\n ('glg', 'Galician'),\n ('grc', 'Greek, Ancient (to 1453)'),\n ('guj', 'Gujarati'),\n ('hat', 'Haitian; Haitian Creole'),\n ('heb', 'Hebrew'),\n ('hin', 'Hindi'),\n ('hrv', 'Croatian'),\n ('hun', 'Hungarian'),\n ('iku', 'Inuktitut'),\n ('ind', 'Indonesian'),\n ('isl', 'Icelandic'),\n ('ita', 'Italian'),\n ('ita_old', 'Italian - Old'),\n ('jav', 'Javanese'),\n ('jpn', 'Japanese'),\n ('kan', 'Kannada'),\n ('kat', 'Georgian'),\n ('kat_old', 'Georgian - Old'),\n ('kaz', 'Kazakh'),\n ('khm', 'Central Khmer'),\n ('kir', 'Kirghiz; Kyrgyz'),\n ('kor', 'Korean'),\n ('kur', 'Kurdish'),\n ('lao', 'Lao'),\n ('lat', 'Latin'),\n ('lav', 'Latvian'),\n ('lit', 'Lithuanian'),\n ('mal', 'Malayalam'),\n ('mar', 'Marathi'),\n ('mkd', 'Macedonian'),\n ('mlt', 'Maltese'),\n ('msa', 'Malay'),\n ('mya', 'Burmese'),\n ('nep', 'Nepali'),\n ('nld', 'Dutch; Flemish'),\n ('nor', 'Norwegian'),\n ('ori', 'Oriya'),\n ('osd', 'Orientation and script detection module'),\n ('pan', 'Panjabi; Punjabi'),\n ('pol', 'Polish'),\n ('por', 'Portuguese'),\n ('pus', 'Pushto; Pashto'),\n ('ron', 'Romanian; Moldavian; Moldovan'),\n ('rus', 'Russian'),\n ('san', 'Sanskrit'),\n ('sin', 'Sinhala; Sinhalese'),\n ('slk', 'Slovak'),\n ('slk_frak', 'Slovak - Fraktur'),\n ('slv', 'Slovenian'),\n ('spa', 'Spanish; Castilian'),\n ('spa_old', 'Spanish; Castilian - Old'),\n ('sqi', 'Albanian'),\n ('srp', 'Serbian'),\n ('srp_latn', 'Serbian - Latin'),\n ('swa', 'Swahili'),\n ('swe', 'Swedish'),\n ('syr', 'Syriac'),\n ('tam', 'Tamil'),\n ('tel', 'Telugu'),\n ('tgk', 'Tajik'),\n ('tgl', 'Tagalog'),\n ('tha', 'Thai'),\n ('tir', 'Tigrinya'),\n ('tur', 'Turkish'),\n ('uig', 'Uighur; Uyghur'),\n ('ukr', 'Ukrainian'),\n ('urd', 'Urdu'),\n ('uzb', 'Uzbek'),\n ('uzb_cyrl', 'Uzbek - Cyrilic'),\n ('vie', 'Vietnamese'),\n ('yid', 'Yiddish'), ]\n\n\ndef ncpus():\n # for Linux, Unix and MacOS\n if hasattr(os, 'sysconf'):\n if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:\n # Linux and Unix\n ncpus = os.sysconf('SC_NPROCESSORS_ONLN')\n if isinstance(ncpus, int) and ncpus > 0:\n return ncpus\n else:\n # MacOS X\n return int(os.popen2('sysctl -n hw.ncpu')[1].read())\n # for Windows\n if 'NUMBER_OF_PROCESSORS' in os.environ:\n ncpus = int(os.environ['NUMBER_OF_PROCESSORS'])\n if ncpus > 0:\n return ncpus\n # return the default value\n return 1\n\n\n_SEMAPHORES_POOL = threading.BoundedSemaphore(ncpus())\n\n\nclass IrAttachment(models.Model):\n _inherit = 'ir.attachment'\n\n language = fields.Selection(OCR_LANGUAGE, 'Language',\n default=lambda self:\n self.env['ir.config_parameter'].get_param(\n 'document_ocr.language', 'eng'))\n # We need to redefine index_content field to be able to update it\n # on the onchange_language() in form\n index_content = fields.Text('Indexed Content',\n readonly=False,\n prefetch=False)\n index_content_rel = fields.Text(related='index_content',\n string='Indexed Content Rel')\n processing_time = fields.Char('Processing Time',\n readonly=True,\n copy=False,\n help='Processing time.\\n'\n '(00:00:00 means less than one second)')\n\n @api.onchange('language')\n def onchange_language(self):\n process = subprocess.Popen(['tesseract', '--list-langs'],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdout, stderr = process.communicate()\n #if self.language not in stderr.decode().split('\\n')[1:-1]:\n # raise UserError(_(\n # \"Language not installed.\"\n # \" Please ask your system administrator to\"\n # \" install tesseract '%s' language.\" %\n # self.language))\n if self.store_fname:\n bin_data = self._file_read(self.store_fname)\n else:\n bin_data = self.db_datas\n if bin_data:\n index_content = self._index(\n bin_data.decode('base64'), self.datas_fname, self.mimetype)\n return {'value': {\n 'index_content': index_content}}\n return {'value': {}}\n\n @api.model\n def _index(self, bin_data, datas_fname, mimetype):\n content = super(IrAttachment, self)._index(\n bin_data, datas_fname, mimetype)\n if not content or content == 'image':\n has_synchr_param = self.env['ir.config_parameter'].get_param(\n 'document_ocr.synchronous', 'False') == 'True'\n has_force_flag = self.env.context.get('document_ocr_force')\n synchr = has_synchr_param or has_force_flag\n if synchr:\n content = self._index_ocr(bin_data)\n else:\n content = _MARKER_PHRASE\n return content\n\n def _index_ocr(self, bin_data):\n if self.datas_fname:\n process = subprocess.Popen(\n ['tesseract', 'stdin', 'stdout', '-l', self.language],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n stdout, stderr = process.communicate(bin_data)\n if stderr:\n _logger.warning('Error during OCR: %s', stderr.decode())\n return stdout.decode()\n else:\n _logger.warning('OCR IMAGE \"%s\", no image to process...',\n self.name)\n return False\n\n def _ocr_image_thread(self, i, t, image):\n global ocr_images_text\n with _SEMAPHORES_POOL:\n with threading.Lock():\n _logger.info('OCR PDF INFO \"%s\" image %d/%d to text...',\n self.name, i, t)\n ocr_images_text[self.id][i] = self._index_ocr(image)\n\n def _index_doc_pdf_thread(self, bin_data):\n global ocr_images_text\n ocr_images_text[self.id] = {}\n buf = _MARKER_PHRASE\n tmpdir = tempfile.mkdtemp()\n _logger.info('OCR PDF INFO \"%s\"...', self.name)\n time_start = time.time()\n stdout, stderr = subprocess.Popen(\n ['pdftotext', '-layout', '-nopgbrk', '-', '-'],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE).communicate(bin_data)\n if stderr:\n _logger.warning('OCR PDF ERROR to text: %s',\n stderr.decode())\n buf = stdout\n # OCR PDF Images\n stdout, stderr = subprocess.Popen(\n ['pdfimages', '-p', '-', tmpdir + '/ocr'],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE).communicate(bin_data)\n if stderr:\n _logger.warning('OCR PDF WARNING Images: %s',\n stderr.decode())\n # OCR every image greater than 50Kb\n filelist = sorted([(file) for file\n in os.listdir(tmpdir)\n if os.path.getsize(\n os.path.join(tmpdir, file)) > 50000])\n filelist_size = len(filelist)\n count = 1\n workers = []\n for pdf in filelist:\n img_file = os.path.join(tmpdir, pdf)\n image = open(img_file, 'rb').read()\n t = threading.Thread(target=self._ocr_image_thread,\n name=u'ocr_image_' + str(count),\n args=(count,\n filelist_size,\n image))\n t.start()\n count += 1\n workers.append(t)\n for t in workers:\n t.join()\n index_content = buf\n for text in sorted(ocr_images_text[self.id]):\n try:\n index_content = \\\n u'%s\\n%s' % (\n index_content,\n ocr_images_text[self.id][text])\n except:\n try:\n index_content = \\\n u'%s\\n%s' % (\n index_content,\n ocr_images_text[self.id][text].decode(\n 'utf8'))\n except:\n try:\n index_content = \\\n u'%s\\n%s' % (\n index_content.decode('utf8'),\n ocr_images_text[self.id][text])\n except:\n try:\n index_content = \\\n u'%s\\n%s' % (\n index_content.decode('utf8'),\n ocr_images_text[self.id][text].decode('utf8'))\n except:\n shutil.rmtree(tmpdir)\n ocr_images_text.pop(self.id) # release memory\n m, s = divmod((time.time() - time_start), 60)\n h, m = divmod(m, 60)\n self.index_content = index_content\n self.processing_time = \"%02d:%02d:%02d\" % (h, m, s)\n shutil.rmtree(tmpdir)\n return self.index_content\n\n def _index_pdf(self, bin_data):\n global ocr_images_text\n buf = _MARKER_PHRASE\n has_synchr_param = self.env['ir.config_parameter'].get_param(\n 'document_ocr.synchronous', 'False') == 'True'\n has_force_flag = self.env.context.get('document_ocr_force')\n synchr = has_synchr_param or has_force_flag\n try:\n if ocr_images_text:\n pass\n except:\n ocr_images_text = {}\n if synchr:\n buf = self._index_doc_pdf_thread(bin_data)\n else:\n buf = _MARKER_PHRASE\n return buf\n\n @api.model\n def _ocr_cron(self):\n for this in self.with_context(document_ocr_force=True).search(\n [('index_content', '=', _MARKER_PHRASE)]):\n if not this.datas:\n continue\n index_content = this._index(\n this.datas, this.datas_fname, this.mimetype)\n this.write({\n 'index_content': index_content,\n })","sub_path":"tko_document_ocr-11.0.1.0.0/tko_document_ocr/models/ir_attachment.py","file_name":"ir_attachment.py","file_ext":"py","file_size_in_byte":13345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"579821712","text":"#! python3\r\n# Inspired by https://youtu.be/ufaOgM9QYk0\r\n\r\nimport time\r\nimport datetime\r\nimport threading\r\nimport copy\r\n\r\n\r\nclass PostgresStorage:\r\n\r\n def __init__(self, databaseurl=None, conn=None):\r\n self.fields = (\"username\", \"firstContact\", \"language\")\r\n self.userdata = {}\r\n # TODO Sorry, Postgres queries are not open source :(\r\n print(\"Skipping Postgres connection\")\r\n\r\n def storeField(self, uid, fields, values):\r\n # Store data in a specific field\r\n\r\n if not isinstance(fields, tuple) and not isinstance(fields, list):\r\n fields = (fields, )\r\n if not isinstance(values, tuple) and not isinstance(values, list):\r\n values = (values, )\r\n\r\n if len(fields) != len(values):\r\n raise ValueError(\r\n \"Length of fields (%d) and values (%d) needs to be the same\" %\r\n (len(fields), len(values)))\r\n\r\n for field in fields:\r\n if field not in self.fields:\r\n raise ValueError(\r\n \"'field' must be one of %r. Found %r\" %\r\n (self.fields, field))\r\n\r\n # TODO Sorry, Postgres queries are not open source :(\r\n\r\n if uid not in self.userdata:\r\n self.userdata[uid] = {}\r\n\r\n for field, value in zip(fields, values):\r\n self.userdata[uid][field] = value\r\n\r\n def storeData(self, uid, data):\r\n # Store data in the arbitrary 'data' field as json data\r\n\r\n # TODO Sorry, Postgres queries are not open source :(\r\n if uid not in self.userdata:\r\n self.userdata[uid] = {}\r\n self.userdata[uid][\"data\"] = data\r\n\r\n def retrieveUser(self, uid):\r\n # TODO Sorry, Postgres queries are not open source :(\r\n if uid not in self.userdata:\r\n self.userdata[uid] = {}\r\n return self.userdata[uid]\r\n\r\n def deleteUser(self, uid):\r\n # TODO Sorry, Postgres queries are not open source :(\r\n if uid in self.userdata:\r\n self.userdata.pop(uid)\r\n\r\n\r\n# SQL version\r\nclass Users:\r\n def __init__(\r\n self,\r\n nowTime=datetime.datetime.now().time(),\r\n databaseurl=None):\r\n self._lastPushFetchTime = nowTime\r\n self.__threadLockDB = threading.RLock()\r\n\r\n self._db = PostgresStorage(databaseurl=databaseurl)\r\n\r\n def _set(self, uid, key, value):\r\n with self.__threadLockDB:\r\n if key in self._db.fields:\r\n # Additionaly store firstContact if no record exists\r\n if uid not in self._db.userdata and key != \"firstContact\":\r\n self._db.storeField(\r\n uid, (key, \"firstContact\"), (value, time.time()))\r\n elif uid not in self._db.userdata:\r\n self._db.storeField(uid, (key, ), (value, ))\r\n elif uid in self._db.userdata and (key not in self._db.userdata[uid] or self._db.userdata[uid][key] != value):\r\n # Only store if value has changed or does not exist\r\n print(\"Cannot store permanently\")\r\n self._db.storeField(uid, (key, ), (value, ))\r\n else:\r\n data = self._db.userdata[uid][\"data\"] if uid in self._db.userdata and \"data\" in self._db.userdata[uid] else {\r\n }\r\n # Only store if value has changed\r\n if key not in data or data[key] != value:\r\n data[key] = value\r\n self._db.storeData(uid, data)\r\n print(\"Cannot store permanently\")\r\n\r\n def _delete(self, uid, key):\r\n with self.__threadLockDB:\r\n if uid not in self._db.userdata:\r\n return\r\n\r\n if key in self._db.fields:\r\n if key not in self._db.userdata[uid]:\r\n return\r\n self._db.storeField(uid, (key, ), (None, ))\r\n else:\r\n if key not in self._db.userdata[uid][\"data\"]:\r\n return\r\n data = self._db.userdata[uid][\"data\"] if uid in self._db.userdata and \"data\" in self._db.userdata[uid] else {\r\n }\r\n data.pop(key, None)\r\n self._db.storeData(uid, data)\r\n\r\n def _get(\r\n self,\r\n uid,\r\n key,\r\n fallback=\"This is a unique fallback value\"):\r\n if key in self._db.fields and key in self._db.userdata[uid]:\r\n return self._db.userdata[uid][key]\r\n if \"data\" in self._db.userdata[uid] and key in self._db.userdata[uid][\"data\"]:\r\n return self._db.userdata[uid][\"data\"][key]\r\n if fallback == \"This is a unique fallback value\":\r\n raise KeyError(\"No key %r in userdata for uid=%r\" % (key, uid))\r\n else:\r\n return fallback\r\n\r\n def _append(self, uid, key, value):\r\n # This only works on data fields\r\n if not self._appendIfNotExists(uid, key, value):\r\n with self.__threadLockDB:\r\n self._db.userdata[uid][\"data\"][key].append(value)\r\n self._db.storeData(uid, self._db.userdata[uid][\"data\"])\r\n\r\n def _appendIfNotExists(self, uid, key, value):\r\n # This only works on data fields\r\n with self.__threadLockDB:\r\n data = self._db.userdata[uid][\"data\"] if uid in self._db.userdata and \"data\" in self._db.userdata[uid] else {\r\n }\r\n\r\n if key not in data:\r\n data[key] = []\r\n\r\n if value in data[key]:\r\n return False # Already there\r\n\r\n data[key].append(value)\r\n self._db.storeData(uid, data)\r\n return True # Saved\r\n\r\n def _remove(self, uid, key, value):\r\n # This only works on data fields\r\n with self.__threadLockDB:\r\n data = self._db.userdata[uid][\"data\"] if uid in self._db.userdata and \"data\" in self._db.userdata[uid] else {\r\n }\r\n if key not in data:\r\n return\r\n\r\n if value not in data[key]:\r\n return\r\n\r\n data[key].remove(value)\r\n self._db.storeData(uid, data)\r\n\r\n def getDatabaseCopy(self):\r\n # Integrate \"data\" field\r\n data = {}\r\n for uid in self._db.userdata:\r\n data[uid] = {}\r\n for field in self._db.userdata[uid]:\r\n if field != \"data\":\r\n data[uid][field] = copy.deepcopy(\r\n self._db.userdata[uid][field])\r\n else:\r\n for key in self._db.userdata[uid][\"data\"]:\r\n data[uid][key] = copy.deepcopy(\r\n self._db.userdata[uid][\"data\"][key])\r\n\r\n return data\r\n\r\n def isUser(self, uid):\r\n return uid in self._db.userdata\r\n\r\n def addUser(self, uid, name=None):\r\n if uid not in self._db.userdata:\r\n self._set(uid, \"firstContact\", time.time())\r\n if \"username\" not in self._db.userdata[uid] and name is not None:\r\n self._set(uid, \"username\", name)\r\n\r\n def deleteUser(self, uid):\r\n self._db.deleteUser(uid)\r\n\r\n def getUsers(self):\r\n return self._db.userdata.keys()\r\n\r\n def getStats(self):\r\n # [(uid, username, timestamp, feedback, askedforfeedback), ...]\r\n tmp = []\r\n for uid in self._db.userdata:\r\n if \"username\" in self._db.userdata[uid] and \"firstContact\" in self._db.userdata[uid]:\r\n tmp.append(\r\n (uid,\r\n self._db.userdata[uid][\"username\"],\r\n self._db.userdata[uid][\"firstContact\"],\r\n self.getFeedback(uid),\r\n self.askedForFeedback(uid)))\r\n elif \"firstContact\" in self._db.userdata[uid]:\r\n tmp.append(\r\n (uid,\r\n \"\",\r\n self._db.userdata[uid][\"firstContact\"],\r\n self.getFeedback(uid),\r\n self.askedForFeedback(uid)))\r\n else:\r\n tmp.append(\r\n (uid,\r\n \"\",\r\n 0,\r\n self.getFeedback(uid),\r\n self.askedForFeedback(uid)))\r\n\r\n tmp.sort(key=lambda item: item[2])\r\n\r\n return tmp\r\n\r\n def getUsername(self, uid):\r\n return self._get(uid, \"username\", None)\r\n\r\n def saveFavorite(self, uid, canteenid):\r\n self._appendIfNotExists(uid, \"favorites\", canteenid)\r\n\r\n def getFavorites(self, uid):\r\n return self._get(uid, \"favorites\", [])\r\n\r\n def isFavorite(self, uid, canteenid):\r\n return canteenid in self._get(uid, \"favorites\", [])\r\n\r\n def removeFavorite(self, uid, canteenid):\r\n self._remove(uid, \"favorites\", canteenid)\r\n\r\n def enablePush(self, uid, at_time):\r\n if not isinstance(at_time, datetime.time):\r\n raise TypeError(\r\n \"at_time expected datetime.time. Given type was %s\" % str(\r\n type(at_time)))\r\n self._set(uid, \"push\", [at_time.hour, at_time.minute, at_time.second])\r\n\r\n def disablePush(self, uid):\r\n self._delete(uid, \"push\")\r\n\r\n def getPush(self, uid):\r\n arr = self._get(uid, \"push\", None)\r\n if not arr:\r\n return None\r\n\r\n return datetime.time(arr[0], arr[1], arr[2])\r\n\r\n def enablePushSilent(self, uid):\r\n self._set(uid, \"pushsilent\", True)\r\n\r\n def disablePushSilent(self, uid):\r\n self._set(uid, \"pushsilent\", False)\r\n\r\n def isPushSilent(self, uid):\r\n return self._get(uid, \"pushsilent\", True)\r\n\r\n def getPendingPushObjects(self, now_time):\r\n # Return all push objects between _lastPushFetchTime and now_time\r\n # Set _lastPushFetchTime to now_time\r\n result = []\r\n for uid in self._db.userdata:\r\n if \"data\" in self._db.userdata[uid] and \"push\" in self._db.userdata[uid][\"data\"] and self.getFavorites(\r\n uid):\r\n at_time = self.getPush(uid)\r\n if at_time > self._lastPushFetchTime and at_time <= now_time:\r\n result.append((uid, self.getFavorites(uid)))\r\n\r\n self._lastPushFetchTime = now_time\r\n return result\r\n\r\n def setLastCanteen(self, uid, canteenid):\r\n self._set(uid, \"last_canteen\", canteenid)\r\n\r\n def getLastCanteen(self, uid):\r\n return self._get(uid, \"last_canteen\", None)\r\n\r\n def enableEmojis(self, uid):\r\n self._set(uid, \"emojis\", True)\r\n\r\n def disableEmojis(self, uid):\r\n self._set(uid, \"emojis\", False)\r\n\r\n def showEmojis(self, uid):\r\n return self._get(uid, \"emojis\", True)\r\n\r\n def getLanguage(self, uid, fallback):\r\n return self._get(uid, \"language\", fallback)\r\n\r\n def setLanguage(self, uid, lang):\r\n self._set(uid, \"language\", lang)\r\n\r\n def saveFeedback(self, uid, text):\r\n self._append(uid, \"feedback\", text)\r\n\r\n def getFeedback(self, uid):\r\n return self._get(uid, \"feedback\", [])\r\n\r\n def askedForFeedback(self, uid):\r\n return self._get(uid, \"askedforfeedback\", False)\r\n\r\n def setAskedForFeedback(self, uid):\r\n self._set(uid, \"askedforfeedback\", True)\r\n\r\n def enableShowNotes(self, uid):\r\n self._set(uid, \"shownotes\", True)\r\n\r\n def disableShowNotes(self, uid):\r\n self._set(uid, \"shownotes\", False)\r\n\r\n def showNotes(self, uid):\r\n return self._get(uid, \"shownotes\", False)\r\n\r\n def setShowPrices(self, uid, role=\"all\"):\r\n if role not in (\r\n False,\r\n \"all\",\r\n \"students\",\r\n \"employees\",\r\n \"pupils\",\r\n \"others\"):\r\n raise ValueError(\r\n \"Argument 'role' must be one of (False, 'all', 'students', 'employees', 'pupils', 'others') in setShowPrices(uid=%s, role='%s')\" %\r\n (str(uid), str(role)))\r\n self._set(uid, \"showprices\", role)\r\n\r\n def disableShowPrices(self, uid):\r\n self._set(uid, \"showprices\", False)\r\n\r\n def getShowPrices(self, uid):\r\n return self._get(uid, \"showprices\", False)\r\n","sub_path":"mensabot/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":12143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"233765394","text":"# Recursive Python function to solve tower of hanoi\n\n# Step 1: move n-1 desks from source to tmp\n# Step 2: move nth desk from source to destination\n# Step 3: move n-1 desks from tmp to destination\n\n\ndef TowerOfHanoi(h, from_rod, to_rod, tmp_rod):\n if h == 1:\n print(\"Move disk 1 from %s to %s\" %(from_rod, to_rod))\n return\n TowerOfHanoi(h-1, from_rod, tmp_rod, to_rod)\n print(\"Move disk %d from %s to %s\" %(h, from_rod, to_rod))\n TowerOfHanoi(h-1, tmp_rod, to_rod, from_rod)\n\n\nh=4\nTowerOfHanoi(h, 'A', 'C', 'B')\n\n","sub_path":"python_algo/HanoiTower.py","file_name":"HanoiTower.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"385204605","text":"\n\"\"\"\nMain URL mapping configuration file.\n\nInclude other URLConfs from external apps using method `include()`.\n\nIt is also a good practice to keep a single URL to the root index page.\n\nThis examples uses Django's default media\nfiles serving technique in development.\n\"\"\"\n\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom django.views.generic import TemplateView\n\nfrom server.apps.places.views import home\n\nurlpatterns = [\n path('', home, name='home'),\n path(\n 'about/', TemplateView.as_view(template_name='pages/about.html'), name='about',\n ),\n path(settings.ADMIN_URL, admin.site.urls),\n\n # users management\n path('users/', include('server.apps.users.urls', namespace='users')),\n path('accounts/', include('allauth.urls')), # noqa: DJ05\n # we don't have an api, but since we have one view and it serves json for frontend\n # let's call it so\n path('api/v1/', include('server.apps.places.urls', namespace='places')),\n\n path('tinymce/', include('tinymce.urls')), # noqa: DJ05\n]\n\nif settings.DEBUG: # pragma: no cover\n import debug_toolbar # noqa: WPS433\n from django.conf.urls.static import static # noqa: WPS433\n\n urlpatterns = [\n # URLs specific only to django-debug-toolbar:\n path('__debug__/', include(debug_toolbar.urls)), # noqa: DJ05\n ] + urlpatterns + static(\n # Serving media files in development only:\n settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT,\n )\n","sub_path":"server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"237620708","text":"def country_code(output,file_name):\n '''\n ***help***\n output : 現状csvのみ\n file_name : 任意のファイルネームを取得\n 今回使用しているpandas.read_htmlは、lxml、html5lib、\n beautifulsoup4が必要なので、pipでインストールしておく\n '''\n import pandas as pd\n url = \"https://www-yousei.jsps.go.jp/yousei1/kuniList.do\"\n dfs = pd.read_html(url,header = 0)\n if output == \"csv\":\n dfs[0].to_csv(file_name + \".csv\")\n return dfs[0]\n","sub_path":"country_code/country_code.py","file_name":"country_code.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"112985229","text":"from django.shortcuts import render\nfrom django.db.models import Sum\nfrom django.contrib.auth.decorators import login_required\n\nfrom guests.models import Guest\nfrom bookings.models import Booking\n\n\n\n# Create your views here.\n@login_required\ndef dashboard(request):\n\n guests = Guest.objects.filter(deleted=False, user=request.user)\n bookings = Booking.objects.filter(deleted=False, user=request.user)\n\n total_guests = 0\n total_bookings = 0\n total_sales = 0\n no_show_percentage = 0\n completed_percentage = 0\n avg_booking_value = 0\n\n if guests:\n total_guests = guests.count()\n\n if bookings:\n total_bookings = bookings.count()\n\n if bookings.filter(status='COM'):\n total_sales = bookings.filter(status='COM').aggregate(Sum('booking_value'))['booking_value__sum']\n completed_percentage = (bookings.filter(status='COM').count() / bookings.count()) * 100\n avg_booking_value = bookings.filter(status='COM').aggregate(Sum('booking_value'))['booking_value__sum'] / bookings.filter(status='COM').count()\n \n if bookings.filter(status='NOS'):\n no_show_percentage = (bookings.filter(status='NOS').count() / bookings.count()) * 100\n\n stats = {\n 'total_guests': total_guests,\n 'total_bookings': total_bookings,\n 'total_sales': total_sales,\n 'no_show_percentage': no_show_percentage,\n 'completed_percentage': completed_percentage,\n 'avg_booking_value': avg_booking_value,\n }\n\n context = {\n 'stats': stats,\n 'page': 'dashboard',\n }\n return render(request, 'reports/dashboard.html', context)","sub_path":"reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"472845741","text":"'''\n素数の定義: 1とその数字のみで割り切れるもの (1, 2, 3, 5, 7...)\nまたその最大値は√nになる。n = 100ならば10 * 11 < nとなり対象の値を超えてしまうため。\nこのことから与えられた数値から素数を求めることはO(logn)で求められる\n'''\nimport math\n\ndef prime_number(n) -> bool:\n i = 2\n while i <= math.sqrt(n):\n if n % i == 0:\n return False\n i += 1\n \n return True\n\nprint(prime_number(10)) # False\nprint(prime_number(13)) # True\n\n\n'''\n素因数分解: 与えられた数字を素数で分解すること。例えば 60 = 2^2 + 3^1 + 5^1 といったこと。\nなぜ素数かというと、例えば2, 4であれば2, 2^2で分解できる。つまり2で累乗を計算する際に、その倍数は計算として含まれるため。\nこのことから素因数分解はO(logn)で求められる。基数は素数によって厳密に異なるが、その数値で割られていくためO(logn)と考えられる\n\n仮に60で計算すると[(2, 2), (3, 1), (5, 1)]という結果になる。\nこのことから60は2, 3, 5を組み合わせた約数を持っていると言えるが、\n素数という1と自分の値だけという性質を考えると素数は 2, 3, 5という結果に 1 を追加した、[1, 2, 3, 5]が素数の数となる。\n\nまたこの時に注意しなければいけないのは、素数である。素数はそれ自体が素数であるため素因数分���はできない。\nよって、次の関数では最後に n != 1 つまり、分解できなかった場合は素数であるため、それをアペンドして返す。\n'''\n\nimport math\ndef prime_factorization(n) -> list:\n p = 2\n pf_list = []\n last = n\n\n while p <= math.sqrt(last):\n cnt = 0\n\n if n % p != 0: pass\n else:\n while n % p == 0:\n n //= p\n cnt += 1\n\n pf_list.append((p, cnt))\n p += 1\n\n if n != 1: pf_list.append((n, 1))\n\n return pf_list\n\nprint(prime_factorization(6)) # [(2, 1), (3, 1)]\nprint(prime_factorization(60)) # [(2, 2), (3, 1), (5, 1)]\nprint(prime_factorization(51)) # [(3, 1), (17, 1)]\nprint(prime_factorization(13)) # [(13, 1)]\n","sub_path":"Algorithem/素因数分解.py","file_name":"素因数分解.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"511435740","text":"import asyncio\nimport random\n\nfrom ew.static import poi as poi_static\nfrom ew.utils import dungeons as dungeon_utils\nfrom ew.utils import frontend as fe_utils\nfrom ew.utils import rolemgr as ewrolemgr\nfrom ew.utils.combat import EwUser\nfrom . import dungeonutils\n\n\nasync def tutorial_cmd(cmd):\n user_data = EwUser(member=cmd.message.author)\n client = cmd.client\n\n if user_data.poi not in poi_static.tutorial_pois:\n return\n\n if user_data.id_user not in dungeonutils.user_to_tutorial_state:\n return await dungeon_utils.begin_tutorial(cmd.message.author)\n\n tutorial_state = dungeonutils.user_to_tutorial_state.get(user_data.id_user)\n\n tutorial_scene = poi_static.dungeon_tutorial[tutorial_state]\n\n cmd_content = cmd.message.content[1:].lower()\n\n # Administrators can skip the tutorial\n if cmd_content == \"skiptutorial\" and cmd.message.author.guild_permissions.administrator:\n new_state = 20\n dungeonutils.user_to_tutorial_state[user_data.id_user] = new_state\n\n scene = poi_static.dungeon_tutorial[new_state]\n\n if scene.poi != None:\n user_data.poi = scene.poi\n\n if scene.life_state != None:\n user_data.life_state = scene.life_state\n\n user_data.persist()\n\n await ewrolemgr.updateRoles(client=cmd.client, member=cmd.message.author)\n\n response = dungeon_utils.format_tutorial_response(scene)\n\n poi_def = poi_static.id_to_poi.get(user_data.poi)\n channels = [poi_def.channel]\n return await fe_utils.post_in_channels(cmd.guild.id, fe_utils.formatMessage(cmd.message.author, response), channels)\n\n if cmd_content in tutorial_scene.options:\n new_state = tutorial_scene.options.get(cmd_content)\n dungeonutils.user_to_tutorial_state[user_data.id_user] = new_state\n\n scene = poi_static.dungeon_tutorial[new_state]\n\n if scene.poi != None:\n user_data.poi = scene.poi\n\n if scene.life_state != None:\n user_data.life_state = scene.life_state\n\n user_data.persist()\n\n await ewrolemgr.updateRoles(client=cmd.client, member=cmd.message.author)\n\n response = dungeon_utils.format_tutorial_response(scene)\n\n poi_def = poi_static.id_to_poi.get(user_data.poi)\n channels = [poi_def.channel]\n return await fe_utils.post_in_channels(cmd.guild.id, fe_utils.formatMessage(cmd.message.author, response), channels)\n\n\n else:\n \"\"\" couldn't process the command. bail out!! \"\"\"\n \"\"\" bot rule 0: be cute \"\"\"\n randint = random.randint(1, 3)\n msg_mistake = \"ENDLESS WAR is growing frustrated.\"\n if randint == 2:\n msg_mistake = \"ENDLESS WAR denies you his favor.\"\n elif randint == 3:\n msg_mistake = \"ENDLESS WAR pays you no mind.\"\n\n msg = await fe_utils.send_message(client, cmd.message.channel, msg_mistake)\n await asyncio.sleep(2)\n try:\n await msg.delete()\n pass\n except:\n pass\n\n # response = dungeon_utils.format_tutorial_response(tutorial_scene)\n # return await fe_utils.send_message(client, cmd.message.channel, fe_utils.formatMessage(cmd.message.author, response))\n return\n","sub_path":"ew/cmd/dungeons/dungeoncmds.py","file_name":"dungeoncmds.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"74266033","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.dispatch.dispatcher import receiver\nfrom django.db.models.signals import post_save\nfrom django.urls import reverse\nfrom django.utils.encoding import python_2_unicode_compatible\n\n\n@python_2_unicode_compatible\nclass UserProfile(models.Model):\n LANDING_CHOICES = (\n ('network', 'Network'),\n ('services', 'Services'),\n ('community', 'Community'),\n )\n\n user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)\n email = models.CharField(max_length=255, blank=True, null=True)\n display_name = models.CharField(max_length=255, blank=True, null=True)\n avatar = models.ImageField(null=True)\n created = models.DateTimeField(auto_now_add=True, blank=True, null=True)\n modified = models.DateTimeField(auto_now=True, blank=True, null=True)\n\n landing_page = models.CharField(max_length=255,\n choices=LANDING_CHOICES,\n default='community')\n view_network = models.BooleanField(default=True)\n view_services = models.BooleanField(default=True)\n view_community = models.BooleanField(default=True)\n\n def __str__(self):\n return \"%s [%s]\" % (self.user.username, self.display_name)\n\n def get_absolute_url(self):\n return self.url()\n\n def url(self):\n return reverse('userprofile_detail', args=[self.pk])\n\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, **kwargs):\n user = kwargs['instance']\n user_profile, created = UserProfile.objects.get_or_create(user=user)\n if(created):\n user_profile.display_name = \"%s %s\" % (user.first_name, user.last_name)\n user.email = user_profile.email\n user.save()\n\n@receiver(post_save, sender=UserProfile)\ndef create_user_profile(sender, **kwargs):\n profile = kwargs['instance']\n profile.user.email = profile.email\n profile.user.save()\n","sub_path":"src/niweb/apps/userprofile/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"166622144","text":"\r\nimport drawer\r\nimport traceback\r\nimport colorsys\r\nfrom blinkt import set_pixel, set_brightness, show, clear\r\nimport numpy as np\r\nimport random\r\nimport math\r\nrunning = True\r\n\r\n\r\n\r\n\r\ndef framer(N):\r\n scale=(170-40.0/3.0)/N\r\n dx = 2.5\r\n dy = 5.0\r\n Ny = N\r\n Nx = int(N*1.5)\r\n dl = 1\r\n xSquare =[]\r\n frame = np.zeros((Nx,Ny))\r\n count = 1\r\n while (frame == 0).any():\r\n x = np.random.randint(0,Nx)\r\n y = np.random.randint(0,Ny)\r\n Rx = np.random.randint(-x,Nx-x)\r\n Ry = np.random.randint(-y,Ny-y)\r\n print('x : '+str(np.min((x,x+Rx)))+\" y : \"+str(np.min((y,y+Ry)))+' Rx : '+str(np.max((x,x+Rx)))+' Ry : '+str(np.max((y,y+Ry))))\r\n \r\n #if x+Rx None:\n self.cpu_info.update(\n {\n \"riscv32\": {\"endian\": \"little\", \"bits\": 32},\n \"riscv64\": {\"endian\": \"little\", \"bits\": 64},\n }\n )\n\n self.os_info.update(\n {\n \"none\": {\n \"is_bareboard\": True,\n \"version\": \"unknown\",\n \"exeext\": \"\",\n \"dllext\": \"\",\n },\n }\n )\n\n self.host_guess.pop(\"x86-windows\")\n self.host_guess.update(\n {\n \"x86_64-windows64\": {\n \"os\": \"Windows\",\n \"cpu\": \"AMD64\",\n },\n }\n )\n\n self.platform_info.update(\n {\n \"riscv32-elf\": {\"cpu\": \"riscv32\", \"os\": \"none\", \"is_hie\": True},\n \"riscv64-elf\": {\"cpu\": \"riscv64\", \"os\": \"none\", \"is_hie\": True},\n \"riscv32-unknown-elf\": {\"cpu\": \"riscv32\", \"os\": \"none\", \"is_hie\": True},\n \"riscv64-unknown-elf\": {\"cpu\": \"riscv64\", \"os\": \"none\", \"is_hie\": True},\n }\n )\n\n self.build_targets.update(\n {\n \"riscv32-elf\": {\"name\": \"riscv32-elf\"},\n \"riscv64-elf\": {\"name\": \"riscv64-elf\"},\n \"riscv32-unknown-elf\": {\"name\": \"riscv32-unknown-elf\"},\n \"riscv64-unknown-elf\": {\"name\": \"riscv64-unknown-elf\"},\n\n }\n )\n","sub_path":"lib/platform_db.py","file_name":"platform_db.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"88436861","text":"from tkinter import *\nimport tkinter.messagebox as tm\n\n\nusername = ''\ncheck = 0\n# ------------Class for the login here. -\n\n\nclass LoginFrame(Frame):\n def __init__(self, master):\n super().__init__(master)\n self.label_1 = Label(self, text= \"Enter your name : \")\n self.entry_1 = Entry(self)\n self.label_1.grid(row = 3 , sticky=E)\n self.entry_1.grid(row=3, column=1)\n self.checkbox = Checkbutton(self, text=\"I am human\", variable = var)\n self.checkbox.grid(columnspan=2)\n self.logbtn = Button(self, text=\"Login\", command = self._login_btn_clicked)\n self.logbtn.grid(columnspan=2)\n self.pack()\n\n def _login_btn_clicked(self):\n global username, check\n username = self.entry_1.get()\n username = username.rstrip(' ')\n if(var.get() and len(username) >= 3):\n check = 1\n root.destroy()\n else:\n if(len(username) < 3 and not var.get()):\n tm._show('Nope', 'can\\'t let u in sry')\n elif(len(username) < 3):\n tm._show('Error', 'len(name) should be > 3')\n else:\n tm._show('Error', 'prove to us u r human. pls')\n\nroot = Tk()\nroot.title('Login - PowerPuff Chat : Where life happens')\nvar = IntVar()\nroot.geometry(\"400x500\")\nroot.resizable(width=FALSE, height=FALSE)\nlf = LoginFrame(root)\nroot.mainloop()\n\n# -------After login checked, the chat box starts from here.\nusername = username.title()\nimport socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect(('localhost',5555))\ns.sendall(str.encode('initSecName:'+ username))\n\ndef sendData(param):\n if param == '\\n\\n':\n EntryBox.delete(1.0,END)\n return\n if len(param) > 1:\n if '\\n\\n' in param:\n #strip both the carriage return and appened with only one.\n param = param.rstrip('\\n')\n param = param + '\\n'\n EntryBox.delete(1.0, END)\n insertText(1, '>>' + param)\n s.sendall(str.encode(param))\n data = s.recv(4500)\n insertText(2, '>>' + data.decode('utf-8'))\n ChatLog.see(END) #this shows the END of the chatlog; auto scroll down\n\ndef insertText(num, param):\n ChatLog.config(state = NORMAL)\n if num == 1:\n ChatLog.insert(END, param, 'BLK')\n else:\n ChatLog.insert(END, param,'BLUE')\n ChatLog.config(state = DISABLED)\n\nif check == 1:\n base = Tk()\n base.title('PowerPuff Chat Girls')\n base.geometry(\"400x500\")\n base.resizable(width=FALSE, height=FALSE)\n\n #Create a Chat window\n ChatLog = Text(base, bd=0, bg=\"light grey\", height=\"13\", width=\"55\", font=\"Arial\",)\n ChatLog.insert(END, 'Welcome to the PowerPuff Chat, ' + username + '\\n', 'INIT') # THIS IS HERE <-----------------\n ChatLog.config(state = DISABLED)\n ChatLog.tag_config('INIT', foreground = 'red', justify = CENTER)\n ChatLog.tag_config('BLUE', foreground = 'blue', justify = LEFT)\n ChatLog.tag_config('BLK', foreground = 'black', justify = RIGHT)\n\n #Bind a scrollbar to the Chat window\n scrollbar = Scrollbar(base, command=ChatLog.yview, cursor=\"heart\")\n ChatLog['yscrollcommand'] = scrollbar.set\n\n #Create the box to enter message\n EntryBox = Text(base, bg=\"white\",width=\"29\", height=\"5\", font=\"Arial\")\n EntryBox.bind(\"\", lambda event: sendData(EntryBox.get(1.0, END)))\n\n #Create the Button to send message\n SendButton = Button(base, font=30, text=\"Send\", width=\"11\", height= 1,\n bg=\"white\", fg = 'navy blue', activebackground=\"#FACC2E\", command=lambda: sendData(EntryBox.get(1.0, END)))\n\n #Place all components on the screen\n scrollbar.place(x=380,y=6, height=386)\n ChatLog.place(x=8, y=6, height=405, width=370)\n EntryBox.place(x=128, y=425, height=60, width=248)\n SendButton.place(x=6, y=425, height=60)\n\n base.mainloop()\n","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"309272557","text":"# -*- coding: utf-8 -*-\n\nfrom li_common.padroes import cadastro\n\n\nclass DescontoValidador(cadastro.ValidadorBase):\n @property\n def eh_valido(self):\n try:\n valor = float(self.valor)\n if valor > 100.0 or valor < 0.0:\n self.erros = u'Porcentagem inválida. Insira um valor entre 0% e 100%.'\n except (TypeError, ValueError):\n self.erros = u'Porcentagem inválida. Insira um valor entre 0% e 100%.'\n return not self.erros\n\n\nclass FormularioPayPalTransparente(cadastro.Formulario):\n _PARCELAS = [(x, x) for x in range(1, 12)]\n _PARCELAS.insert(0, (12, 'Todas'))\n ativo = cadastro.CampoFormulario('ativo', 'Pagamento ativo?', tipo=cadastro.TipoDeCampo.boleano, ordem=1)\n usuario = cadastro.CampoFormulario('usuario', u'Email cadastrado no PayPal Plus', requerido=True, tamanho_max=128, ordem=2)\n valor_minimo_aceitado = cadastro.CampoFormulario('valor_minimo_aceitado', u'Valor mínimo', requerido=False, decimais=2, ordem=3, tipo=cadastro.TipoDeCampo.decimal, texto_ajuda=u'Informe o valor mínimo para exibir esta forma de pagamento.')\n valor_minimo_parcela = cadastro.CampoFormulario('valor_minimo_parcela', u'Valor mínimo da parcela', requerido=False, decimais=2, ordem=4, tipo=cadastro.TipoDeCampo.decimal)\n mostrar_parcelamento = cadastro.CampoFormulario('mostrar_parcelamento', u'Marque para mostrar o parcelamento na listagem e na página do produto.', tipo=cadastro.TipoDeCampo.boleano, requerido=False, ordem=5)\n parcelas_sem_juros = cadastro.CampoFormulario('parcelas_sem_juros', 'Parcelas sem juros', tipo=cadastro.TipoDeCampo.escolha, requerido=False, ordem=6, texto_ajuda=u'Número de parcelas sem juros para esta forma de pagamento.', opcoes=_PARCELAS)\n tem_desconto = cadastro.CampoFormulario('desconto', u'Usar desconto?', requerido=False, ordem=3, tipo=cadastro.TipoDeCampo.boleano, texto_ajuda=u'Marque esse campo caso você queira aplicar o desconto no pagamento.')\n desconto_valor = cadastro.CampoFormulario('desconto_valor', u'Desconto aplicado', requerido=False, ordem=4, decimais=2, tipo=cadastro.TipoDeCampo.decimal, validador=DescontoValidador)\n aplicar_no_total = cadastro.CampoFormulario('aplicar_no_total', u'Aplicar no total?', requerido=False, ordem=5, tipo=cadastro.TipoDeCampo.boleano, texto_ajuda=u'Aplicar desconto no total da compra (incluir por exemplo o frete).')\n","sub_path":"src/pagador_paypal_transparente/cadastro.py","file_name":"cadastro.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"615185948","text":"\n#\n# image dimensions\n#\n\nimg_width = 64\nimg_height = 64\nimg_channels = 4\n\n#\n# training params\n#\n\nnb_steps = 10000\nbatch_size = 256\nk_d = 1 # number of discriminator updates per step\nk_g = 2 # number of generative network updates per step\nlog_interval = 100","sub_path":"scripts/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"208109261","text":"#!/usr/bin/ python3\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask\nimport getlogdata\nimport secrets\n\napp = Flask(__name__)\napp.config[\"JSON_AS_ASCII\"] = False\n\nsecret = secrets.token_urlsafe(32)\napp.secret_key = secret\n\n\n@app.route(\"/getlogdata\", methods=[\"GET\", \"POST\"])\ndef get():\n return getlogdata.getlogdata()\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"py/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"180177447","text":"from typing import Callable\n\n\nclass Monkey:\n def __init__(self, name) -> None:\n self.name = name\n self.items: list[int] = []\n self.friends: dict[int, Monkey] = {}\n self.operation: Callable[[int], int] = None\n self.test_div: int = None\n self.test_pass: int = None\n self.test_fail: int = None\n self.total_inspections: int = 0\n\n def inspect(self):\n self.total_inspections += len(self.items)\n self.items = [int(self.operation(item) / 3) for item in self.items]\n self.throw()\n\n def throw(self):\n for item in self.items:\n if item % self.test_div:\n self.friends[self.test_fail].items.append(item)\n else:\n self.friends[self.test_pass].items.append(item)\n self.items.clear()\n\n\ndef create_monkey(monkeys: list[Monkey], name: str):\n name = int(name.strip(\":\"))\n new_monkey = Monkey(name)\n for monkey in monkeys:\n monkey.friends[name] = new_monkey\n new_monkey.friends[monkey.name] = monkey\n monkeys.append(new_monkey)\n return monkeys\n\n\ndef assign_items(monkey: Monkey, items: list[str]):\n for i in range(2, len(items)):\n monkey.items.append(int(items[i].strip(\",\")))\n\n\ndef assign_operation(monkey: Monkey, line: list[str]):\n # Operation: new = old + 8\n if line[4] == \"+\":\n if line[-1] == \"old\":\n monkey.operation = lambda x: int(x + x)\n else:\n monkey.operation = lambda x: int(x + int(line[-1]))\n else:\n if line[-1] == \"old\":\n monkey.operation = lambda x: int(x * x)\n else:\n monkey.operation = lambda x: int(x * int(line[-1]))\n\n\ndef parse(inp):\n monkeys = []\n with open(inp) as f:\n for l in f:\n l = l.strip().split()\n if not l:\n continue\n if l[0] == \"Monkey\":\n monkeys = create_monkey(monkeys, l[1])\n elif l[0] == \"Starting\":\n assign_items(monkeys[-1], l)\n elif l[0] == \"Operation:\":\n assign_operation(monkeys[-1], l)\n elif l[0] == \"Test:\":\n monkeys[-1].test_div = int(l[-1])\n elif l[1] == \"true:\":\n monkeys[-1].test_pass = int(l[-1])\n elif l[1] == \"false:\":\n monkeys[-1].test_fail = int(l[-1])\n return monkeys\n\n\ndef play(monkeys: list[Monkey], rounds: int):\n for round in range(rounds):\n for monkey in monkeys:\n monkey.inspect()\n interactions = [monkey.total_inspections for monkey in monkeys]\n interactions.sort()\n print(interactions[-1] * interactions[-2])\n\n\nif __name__ == \"__main__\":\n in_file = \"/home/adam/projects/adventofcode/2022/11/input.txt\"\n monkeys = parse(in_file)\n play(monkeys, 20)\n","sub_path":"2022/11/11-1.py","file_name":"11-1.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"107379494","text":"import json\nimport socket\n\n\ndef get_stats(ipaddr, port):\n '''Retrieves uWSGI server stats\n\n To activate statistics socket in uWSGI server, use cli param\n --stats 127.0.0.1:7000\n\n or put in configuration file\n [uwsgi]\n stats = 127.0.0.1:7000\n '''\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((ipaddr, port))\n\n data = ''\n while True:\n res = s.recv(1024)\n if res:\n data += res\n else:\n break\n\n s.close()\n return json.loads(data)\n\n\ndef get_stats2(ip_addr, port):\n uwsgi_stats = get_stats(ip_addr, port)\n times = [w['avg_rt'] for w in uwsgi_stats['workers'] if w['avg_rt'] > 0]\n avg_rt = sum(times) / float(len(times))\n req_count = sum([w['requests'] for w in uwsgi_stats['workers']])\n return {'avg_rt': int(avg_rt / 1000), 'req_count': req_count}\n","sub_path":"monz/uwsgi.py","file_name":"uwsgi.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"230507744","text":"import json\nfrom codecs import BOM_UTF8\nfrom http import HTTPStatus\nfrom tornado.web import RequestHandler\n\nfrom jassrealtime.webapi.handlers.parameter_names import MESSAGE\nfrom jassrealtime.webapi.handlers.utils import add_cors\n\n\nclass BaseHandler(RequestHandler):\n \"\"\"\n Base handler offering some utility methods.\n Should be sub classed by all handlers withing JASS\n\n \"\"\"\n\n def write_and_set_status(self, message: dict, status: HTTPStatus):\n \"\"\"\n Writes message and set status. Adds coors headers if applies\n :param message:\n :param status:\n :return:\n \"\"\"\n if message is not None:\n self.write(message)\n add_cors(self)\n self.set_status(status)\n\n def strip_body_bom(self, bom=BOM_UTF8):\n body = self.request.body\n if body.startswith(bom):\n body = body[len(bom):]\n\n return json.loads(body.decode(\"utf-8\"))\n\n def send_zip_file_with_get(self, localFilePath: str, downloadFileName: str = 'default.zip'):\n \"\"\"\n Sends a local zip file, via get request\n :param localFilePath:\n :param downloadFileName:\n :return:\n \"\"\"\n buf_size = 4096\n self.set_header('Content-Type', 'application/zip')\n self.set_header('Content-Disposition', 'attachment; filename=' + downloadFileName)\n with open(localFilePath, 'rb') as f:\n while True:\n data = f.read(buf_size)\n if not data:\n break\n self.write(data)\n self.finish()\n\n def missing_required_field(self, required_field):\n self.write_and_set_status({MESSAGE: \"Missing required parameters. {0}\".format(required_field)},\n HTTPStatus.UNPROCESSABLE_ENTITY)\n","sub_path":"jassrealtime/webapi/handlers/base_handler.py","file_name":"base_handler.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"377659201","text":"from .exceptions import *\n\nfrom typing import Callable, Any, List\n\n\nclass Parameter:\n\n ALL_LOCATION = ['url', 'query', 'form', 'header', 'cookie']\n\n def __init__(self,\n name: str,\n type: Callable[[str], Any],\n location: (str, List[str]) = 'query',\n optional: bool =False,\n default: Any =None,\n action: str = None,\n append: bool = False,\n description: str = None,\n warning: str = None):\n\n self.name = name\n self.type = type # type or [type, type]\n self.location = location # cookies, query, form, headers\n self.optional = optional # true, false\n self.default = default # if optional is true\n self.action = action # rename\n self.append = append # list or not\n self.description = description # description\n self.warning = warning\n if self.optional and self.default is None:\n raise ParamNeedDefaultValueIfItsOptional()\n\n # location iterable\n if not isinstance(self.location, list):\n self.location = [self.location]\n unexpected_location = list(set(self.location) - set(Parameter.ALL_LOCATION))\n if unexpected_location:\n raise ParamComingFromUnknownLocation(self.name, unexpected_location)\n\n\nclass ParameterGroup:\n pass","sub_path":"nougat_router/param.py","file_name":"param.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"456197898","text":"from pygame.transform import scale\nfrom pygame import BLEND_ADD\nfrom functools import partial\nimport random\n\nTREE_TOP = 33\nTREE_LEFT = 80\nTREE_RIGHT = 400\nTREE_BOTTOM = 250\nTREE_TRUNK = 250\n\n# alien = Actor('alien')\ntree = Actor('tree')\n# alien.topright = 0, 10\n\nWIDTH = tree.width\nHEIGHT = tree.height\n\nleaves = []\nb = 0\n\ndef draw():\n tree.draw()\n for leaf in leaves:\n leaf.draw()\n\n\ndef create_leaf(coords):\n leaf = Actor('leaf')\n leaf._surf = scale(leaf._surf, (20,20))\n leaf.topleft = coords\n return leaf\n\n\ndef autumn():\n clock.schedule_interval(brown, 0.1)\n\ndef brown():\n global b\n for leaf in leaves:\n leaf._surf.fill((b, 0, 0, 100), special_flags=BLEND_ADD)\n b += 10\n if b == 100:\n clock.unschedule(brown)\n leaves_fall(leaves)\n\n\ndef leaves_fall(leaves):\n for leaf in leaves:\n leaf_fall(leaf)\n\n\ndef leaf_fall(leaf):\n animate(leaf, pos=(leaf.center[0], 550), tween='accelerate')\n\n\nfor i in range(100):\n x = random.randint(TREE_LEFT, TREE_RIGHT)\n y = random.randint(TREE_TOP, TREE_BOTTOM)\n coords = (x, y)\n # print(coords)\n leaves.append(create_leaf(coords))\n\nautumn()\n","sub_path":"team10/intro.py","file_name":"intro.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"369004144","text":"import os\nfrom ....kernel import (vars, map)\nfrom . import room_objects\n\n###############################################################################\n\ndef inst_calc(self):\n\n\t'''sets self.instance based upon relavant variables'''\n\t\n\tself.instance = [0,0,0,(0,0,0),(0,0,0,0,0,0)]\n\t\t\n###############################################################################\n\ndef connections(self):\n\n\t'''returns a dict of the current room connections the room has'''\n\t\n\treturn {'graveyard' : map.a1_graveyard,\n\t\t\t'hut' : map.a1_hut_path,\n\t\t\t'cliff' : map.a1_cliff_path,\n\t\t\t'inn' : map.a1_inn_f1,\n\t\t\t'window' : map.a1_inn_f2,\n\t\t\t'shed' : map.a1_inn_shed,\n\t\t\t}\n\n###############################################################################\n\ndef npcs(self):\n\n\t'''returns a dict of the npcs currently in the room'''\n\t\n\treturn {}\n\n###############################################################################\n\ndef objects(self):\n\n\t'''returns a dict of the objects currently in the room'''\n\t\n\treturn {}\n\t\n###############################################################################\n\t\t\ndef description(self):\n\n\t'''sets vars.crnt_text to a description of the room'''\n\t\n\tvars.crnt_text = '''\nThere is the inn, a shed, a path to a cliff, a path to a graveyard, and of\ncourse the path back to the hut.\n'''\n\n###############################################################################\n\ndef transition(self, next_room):\n\n\t'''sets vars.crnt_text to a description of going to another room'''\n\t\n\tif next_room == map.a1_graveyard:\n\t\tvars.crnt_text = '''\nYou walk to the graveyard.\n'''\n\telif next_room == map.a1_hut_path:\n\t\tvars.crnt_text = '''\nYou walk to the hut.\n'''\n\telif next_room == map.a1_inn_f1:\n\t\tvars.crnt_text = '''\nYou open the sturdy door and walk inside. You wait for your eyes to adjust to\nthe dim light.\n'''\n\telif next_room == map.a1_inn_f2:\n\t\tvars.crnt_text = '''\nYou scale the inn and climb in one of the upper floor windows.\n'''\n\telif next_room == map.a1_inn_shed:\n\t\tvars.crnt_text = '''\nYou open the shed door. It's trash. You enter and throw an iron bolt behind you\nto lock the door.\n'''\n\telif next_room == map.a1_cliff_path:\n\t\tvars.crnt_text = '''\nYou walk towards the cliff.\n'''\n\n###############################################################################\n\ndef enter(self):\n\n\t'''sets vars.crnt_text to a description of entering the room'''\n\t\n\tvars.crnt_text = '''\nYou wake up in front of the in. You lazy piece of shit.\n'''\n\n###############################################################################\n\ndef image(self):\n\n\t'''sets vars.crnt_image to an image of the room'''\n\t\n\timage_dir = os.getcwd() + '/program_files/world/rooms/a1_inn_surr/room_images/'\n\tvars.crnt_image = image_dir + 'blank.gif'\n","sub_path":"Python/Dao Story Game/v0.1/program_files/world/rooms/a1_inn_surr/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"89105959","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# 3x + 2y = 12\n\n# titik potong 1 dg sumbu-x => y = 0 => 3x = 12\n# | 3 | | x | = | 12 |\nx1 = np.linalg.solve([[3]], [12])[0]\ny1 = 0\nprint(x1, y1)\n\n# titik potong 2 dg sumbu-y => x = 0 => 2y = 12\n# | 2 | | y | = | 12 |\ny2 = np.linalg.solve([[2]], [12])[0]\nx2 = 0\nprint(x2, y2)\n\nx = np.array([x1, x2]) # 4,0\ny = np.array([y1, y2]) # 0,6\n\nplt.plot(x, y)\nplt.grid(True)\nplt.show()","sub_path":"6a Matplotlib/45.soal_draw_linearEq.py","file_name":"45.soal_draw_linearEq.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"73659295","text":"# Imports\nfrom socket import *\nfrom _thread import *\nimport time\nimport sys\n\nsys.path.append('..')\nsys.path.append('../Biblioteca')\nfrom Mensaje import Mensaje\nfrom IntermediarioServidor import IntermediarioServidor\n\n\"\"\"\nClase de Capa de Comunicaciones.\n\nEnvía al Cliente lo que devuelve el IntermediarioServidor.\nPasa a IntermediarioServidor lo que recibe del Cliente.\n\"\"\"\nclass Servidor:\n def __init__(self):\n \"\"\"\n Método que inicializa el Servidor.\n Se inicializan las variables.\n Se crea el socket.\n Se establecen el host y el puerto.\n Se crea la lista con los clientes.\n \"\"\"\n self.s = socket(AF_INET, SOCK_STREAM)\n self.host = \"0.0.0.0\"\n self.port = 9797\n\n # El servidor le asigna un número a los clientes según esta lista\n self.lista_de_clientes = [\"2\", \"1\"]\n self.client = \"\" # Número del cliente\n self.exit = False\n\n def __del__(self):\n \"\"\"\n Se destruyen los socket que no son nulos al final de la ejecución.\n \"\"\"\n if self.s == None:\n self.s = None\n\n def ligarSocket(self):\n \"\"\"\n Se relaciona un socket con el puerto y el host.\n \"\"\"\n while True:\n try:\n self.s.bind((self.host, self.port))\n break\n except error as e:\n print(\"\\nERROR: \", e, \"\\n\")\n\n def conexiones(self):\n \"\"\"\n Se espera a la conexión de clientes.\n\n Return:\n cliente -- Cliente\n direccion -- Dirección del cliente\n \"\"\"\n cliente, direccion = self.s.accept()\n print(\"| Conexión establecida.\\t\\t|\")\n print(\"| El cliente es:\\t\\t|\\n|\\t\", direccion[0] + \":\" + str(direccion[1])+\"\\t|\")\n return cliente, direccion\n\n def recibir(self, _cliente):\n \"\"\"\n Se gestionan los mensajes recibidos de los clientes.\n\n Parámetros:\n cliente -- Cliente que ha enviado el mensaje\n\n Return:\n reply.decode(\"UTF-8\") -- Mensaje recibido \n \"\"\"\n while True:\n try:\n reply = _cliente.recv(2048)\n return reply.decode(\"UTF-8\")\n break\n except:\n print(\"\\nRecv: No responde.\\n\")\n print(\"Se intentará de nuevo en 5 segundos.\\n\")\n time.sleep(5)\n\n def enviarId(self, _cliente):\n \"\"\"\n Se asigna un número al cliente pasado y se le envía.\n\n Parámetros:\n _cliente -- Cliente al que enviar el id\n \"\"\"\n self.client = self.lista_de_clientes.pop()\n # Envia al cliente su número de cliente (1 o 2)\n _cliente.send(self.client.encode(\"UTF-8\"))\n\n def enviar_Mensaje(self, msg, _cliente):\n \"\"\"\n Se realiza el envio de mensajes de Cliente a Servidor.\n\n Parámetros:\n msg -- Mensaje a enviar\n _cliente -- Cliente al que se le quiere enviar el mensaje\n \"\"\"\n while True:\n try:\n _cliente.send(msg.encode(\"UTF-8\"))\n break\n except:\n print(\"\\nSend: No responde.\\n\")\n print(\"Se intentará de nuevo en 5 segundos.\\n\")\n time.sleep(5)\n\n def enviar_Mensaje_Codificado(self, cod, obj, _cliente):\n \"\"\"\n Se crea un objeto Mensaje con el código de mensaje y el objeto\n y se lo envía al Cliente.\n\n Parámetros:\n cod -- Código del mensaje\n obj -- Objeto del mensaje\n \"\"\"\n while True:\n try:\n mensaje = Mensaje(cod, obj)\n cadena = mensaje.convertirEnCadena()\n _cliente.send(cadena.encode(\"UTF-8\"))\n break\n except:\n print(cod, obj, _cliente)\n print(\"\\nSend_esp: No responde.\\n\")\n print(\"Se intentará de nuevo en 5 segundos.\\n\")\n time.sleep(5)\n\n def interpretarMensaje(self, msg):\n \"\"\"\n Se interpreta el mensaje pasado por parámetro, convirtiéndolo\n en un objeto Mensaje.\n\n Parámetros:\n msg -- Mensaje que se tiene que interpretar\n\n Return:\n mensaje -- Mensaje interpretado\n \"\"\"\n mensaje = Mensaje.convertirEnObjeto(msg) \n return mensaje\n\n def inicializarJugador(self, _cliente, id):\n \"\"\"\n Se inicializa un jugador, para lo que se requiere de un cliente y su id, \n enviándole el id que se le ha asignado.\n\n Parámetros:\n _cliente -- Cliente en el que se encuentra el jugador\n id -- Id del jugador \n \"\"\"\n \n self.enviar_Mensaje(\"\\n¿Desea empezar el juego?\", _cliente)\n respuesta = self.recibir(_cliente)\n mensaje = self.interpretarMensaje(respuesta)\n\n if (mensaje.getCode() == \"102\"): \n if mensaje.getObj() == \"1\":\n print(\"| El jugador \" + str(id) +\n \" quiere jugar.\\t|\\n| Se le envía el id de jugador.\\t|\")\n self.enviar_Mensaje_Codificado(\"201\", str(id), _cliente)\n else:\n print(\"| El jugador \" + str(id) +\n \" no quiere jugar.|\\n| Finalizar conexión.\\t\\t|\")\n\n def seleccionJuego(self,_cliente):\n \"\"\"\n Se pregunta al cliente 1 qué juego desea jugar ya sea el Tres en Raya o el Conecta 4.\n\n Parámetros:\n _cliente -- Cliente en el que se encuentra el jugador\n \"\"\"\n self.enviar_Mensaje(\"________________________________________________\\n|\\tSeleccione el juego deseado\\t\\t|\\n|Primera opción----->Tres en Raya\\t\\t|\\n|Segunda Opcion----->Conecta 4\\t\\t\\t|\\n|_______________________________________________|\\n\", _cliente)\n respuesta = self.recibir(_cliente)\n mensaje = self.interpretarMensaje(respuesta)\n return mensaje.getObj()\n\n def main(self):\n \"\"\"\n Main de la clase Cliente en que se realizan las llamadas\n a las funciones de la misma.\n \"\"\"\n self.ligarSocket()\n self.s.listen(2) # 2 clientes\n\n print(\"\\n\\n_________________________________\\n| Esperando a los clientes\\t|\")\n\n # Inicialización de los clientes\n cliente1, direccion1 = self.conexiones()\n self.enviarId(cliente1) # Espera conexión del 1 cliente\n\n cliente2, direccion2 = self.conexiones()\n self.enviarId(cliente2) # Espera conexión del 2 cliente\n\n # PROBANDO LA CONEXION\n # Se le da el identificador a cada Cliente\n self.inicializarJugador(cliente1, 1)\n print(\"|-------------------------------|\")\n self.inicializarJugador(cliente2, 2)\n print(\"|_______________________________|\\n\\n\")\n\n #Ahora se pedirá escoger el juego que se desea jugar al primer jugador.\n seleccion=self.seleccionJuego(cliente1)\n\n #En función de la respuesta se llamará al arbitro de un juego o de otro(En el intermediarioServidor)\n intermediario=IntermediarioServidor(seleccion) #Inicializamos el IntermediarioServidor y a su vez, el arbitro.\n\n # INICIA EL JUEGO\n cliente = cliente1 # Empieza jugando el jugador1\n mens, obj,dest = intermediario.arbitrar(\"103\") # Le muestra el tablero\n\n self.enviar_Mensaje_Codificado(mens, obj, cliente) # Le envía un mensaje 202 y el tablero\n\n # Para que los hilos no mueran\n while not self.exit: \n \"\"\"\n Comunicación con el jugador\n \"\"\"\n mensaje = self.interpretarMensaje(self.recibir(cliente))\n mens, obj, dest = intermediario.arbitrar(mensaje.getCode(), mensaje.getObj()) \n\n if (mens == \"200\"):\n self.enviar_Mensaje_Codificado(mens, obj, cliente1)\n self.enviar_Mensaje_Codificado(mens, obj, cliente2)\n self.exit = True\n elif dest == 1:\n cliente = cliente1\n self.enviar_Mensaje_Codificado(mens, obj, cliente)\n else:\n cliente = cliente2\n self.enviar_Mensaje_Codificado(mens, obj, cliente)\n\n print(\"\\nLos jugadores han terminado de jugar.\\n\")\n time.sleep(5)\n self.s.close()\n self.s = None\n\n# Creación del Servidor\nservidor = Servidor()\n# Llamada al main\nservidor.main()\n","sub_path":"src/Servidor/Servidor.py","file_name":"Servidor.py","file_ext":"py","file_size_in_byte":8357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"580593411","text":"# Copyright 2013 – present by the SalishSeaCast Project contributors\n# and The University of British Columbia\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# https://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# SPDX-License-Identifier: Apache-2.0\n\n\n\"\"\"Unit tests for SalishSeaCast collect_weather worker.\n\"\"\"\nimport grp\nimport logging\nimport os\nimport textwrap\nfrom pathlib import Path\nfrom types import SimpleNamespace\n\nimport arrow\nimport attr\nimport nemo_nowcast\nimport pytest\n\nfrom nowcast.workers import collect_weather\n\n\n@pytest.fixture()\ndef config(base_config):\n \"\"\":py:class:`nemo_nowcast.Config` instance from YAML fragment to use as config for unit tests.\"\"\"\n config_file = Path(base_config.file)\n with config_file.open(\"at\") as f:\n f.write(\n textwrap.dedent(\n \"\"\"\\\n file group: allen\n\n weather:\n download:\n 2.5 km:\n datamart dir: datamart/hrdps-continental/\n GRIB dir: forcing/atmospheric/continental2.5/GRIB/\n forecast duration: 48\n ECCC file template: \"{date}T{forecast}Z_MSC_HRDPS_{variable}_RLatLon0.0225_PT{hour}H.grib2\"\n variables:\n - [UGRD_AGL-10m, u10, u_wind] # u component of wind velocity at 10m elevation\n - [VGRD_AGL-10m, v10, v_wind] # v component of wind velocity at 10m elevation\n - [DSWRF_Sfc, ssrd, solar] # accumulated downward shortwave (solar) radiation at ground level\n - [DLWRF_Sfc, strd, therm_rad] # accumulated downward longwave (thermal) radiation at ground level\n - [LHTFL_Sfc, lhtfl, LHTFL_surface] # upward surface latent heat flux (for VHFR FVCOM)\n - [TMP_AGL-2m, t2m, tair] # air temperature at 2m elevation\n - [SPFH_AGL-2m, sh2, qair] # specific humidity at 2m elevation\n - [RH_AGL-2m, r2, RH_2maboveground] # relative humidity at 2m elevation (for VHFR FVCOM)\n - [APCP_Sfc, unknown, precip] # accumulated precipitation at ground level\n - [PRATE_Sfc, prate, PRATE_surface] # precipitation rate at ground level (for VHFR FVCOM)\n - [PRMSL_MSL, prmsl, atmpres] # atmospheric pressure at mean sea level\n 1 km:\n datamart dir: datamart/hrdps-west/1km\n GRIB dir: forcing/atmospheric/GEM1.0/GRIB/\n forecast duration: 36\n ECCC file template: 'CMC_hrdps_west_{variable}_rotated_latlon0.009x0.009_{date}T{forecast}Z_P{hour}-00.grib2'\n variables:\n - UGRD_TGL_10 # u component of wind velocity at 10m elevation\n - VGRD_TGL_10 # v component of wind velocity at 10m elevation\n - DSWRF_SFC_0 # accumulated downward shortwave (solar) radiation at ground level\n - DLWRF_SFC_0 # accumulated downward longwave (thermal) radiation at ground level\n - LHTFL_SFC_0 # upward surface latent heat flux (for VHFR FVCOM)\n - TMP_TGL_2 # air temperature at 2m elevation\n - SPFH_TGL_2 # specific humidity at 2m elevation\n - RH_TGL_2 # relative humidity at 2m elevation (for VHFR FVCOM)\n - APCP_SFC_0 # accumulated precipitation at ground level\n - PRATE_SFC_0 # precipitation rate at ground level (for VHFR FVCOM)\n - PRMSL_MSL_0 # atmospheric pressure at mean sea level\n \"\"\"\n )\n )\n config_ = nemo_nowcast.Config()\n config_.load(config_file)\n return config_\n\n\n@pytest.fixture\ndef mock_worker(mock_nowcast_worker, monkeypatch):\n monkeypatch.setattr(collect_weather, \"NowcastWorker\", mock_nowcast_worker)\n\n\nclass TestMain:\n \"\"\"Unit tests for main() function.\"\"\"\n\n def test_instantiate_worker(self, mock_worker):\n worker = collect_weather.main()\n assert worker.name == \"collect_weather\"\n assert worker.description.startswith(\n \"SalishSeaCast worker that monitors a mirror of HRDPS files from the ECCC MSC datamart\"\n )\n\n def test_add_forecast_arg(self, mock_worker):\n worker = collect_weather.main()\n assert worker.cli.parser._actions[3].dest == \"forecast\"\n assert worker.cli.parser._actions[3].choices == {\"00\", \"06\", \"12\", \"18\"}\n assert worker.cli.parser._actions[3].help\n\n def test_add_resolution_arg(self, mock_worker):\n worker = collect_weather.main()\n assert worker.cli.parser._actions[4].dest == \"resolution\"\n assert worker.cli.parser._actions[4].choices == {\"1km\", \"2.5km\"}\n assert worker.cli.parser._actions[4].default == \"2.5km\"\n assert worker.cli.parser._actions[4].help\n\n def test_add_backfill_option(self, mock_worker):\n worker = collect_weather.main()\n assert worker.cli.parser._actions[5].dest == \"backfill\"\n assert worker.cli.parser._actions[5].default is False\n assert worker.cli.parser._actions[5].help\n\n def test_add_backfill_date_option(self, mock_worker):\n worker = collect_weather.main()\n assert worker.cli.parser._actions[6].dest == \"backfill_date\"\n expected = nemo_nowcast.cli.CommandLineInterface.arrow_date\n assert worker.cli.parser._actions[6].type == expected\n assert worker.cli.parser._actions[6].default == arrow.now().floor(\"day\").shift(\n days=-1\n )\n assert worker.cli.parser._actions[6].help\n\n\nclass TestConfig:\n \"\"\"Unit tests for production YAML config file elements related to worker.\"\"\"\n\n def test_message_registry(self, prod_config):\n assert \"collect_weather\" in prod_config[\"message registry\"][\"workers\"]\n msg_registry = prod_config[\"message registry\"][\"workers\"][\"collect_weather\"]\n assert msg_registry[\"checklist key\"] == \"weather forecast\"\n\n def test_message_registry_keys(self, prod_config):\n msg_registry = prod_config[\"message registry\"][\"workers\"][\"collect_weather\"]\n assert list(msg_registry.keys()) == [\n \"checklist key\",\n \"success 2.5km 00\",\n \"failure 2.5km 00\",\n \"success 2.5km 06\",\n \"failure 2.5km 06\",\n \"success 2.5km 12\",\n \"failure 2.5km 12\",\n \"success 2.5km 18\",\n \"failure 2.5km 18\",\n \"success 1km 00\",\n \"failure 1km 00\",\n \"success 1km 12\",\n \"failure 1km 12\",\n \"crash\",\n ]\n\n def test_file_group(self, prod_config):\n assert \"file group\" in prod_config\n assert prod_config[\"file group\"] == \"sallen\"\n\n def test_weather_download_2_5_km_section(self, prod_config):\n weather_download = prod_config[\"weather\"][\"download\"][\"2.5 km\"]\n assert (\n weather_download[\"datamart dir\"]\n == \"/SalishSeaCast/datamart/hrdps-continental/\"\n )\n assert (\n weather_download[\"GRIB dir\"]\n == \"/results/forcing/atmospheric/continental2.5/GRIB/\"\n )\n assert weather_download[\"forecast duration\"] == 48\n assert (\n weather_download[\"ECCC file template\"]\n == \"{date}T{forecast}Z_MSC_HRDPS_{variable}_RLatLon0.0225_PT{hour}H.grib2\"\n )\n assert weather_download[\"variables\"] == [\n [\"UGRD_AGL-10m\", \"u10\", \"u_wind\"],\n [\"VGRD_AGL-10m\", \"v10\", \"v_wind\"],\n [\"DSWRF_Sfc\", \"ssrd\", \"solar\"],\n [\"DLWRF_Sfc\", \"strd\", \"therm_rad\"],\n [\"LHTFL_Sfc\", \"lhtfl\", \"LHTFL_surface\"],\n [\"TMP_AGL-2m\", \"t2m\", \"tair\"],\n [\"SPFH_AGL-2m\", \"sh2\", \"qair\"],\n [\"RH_AGL-2m\", \"r2\", \"RH_2maboveground\"],\n [\"APCP_Sfc\", \"unknown\", \"precip\"],\n [\"PRATE_Sfc\", \"prate\", \"PRATE_surface\"],\n [\"PRMSL_MSL\", \"prmsl\", \"atmpres\"],\n ]\n\n def test_weather_download_1_km_section(self, prod_config):\n weather_download = prod_config[\"weather\"][\"download\"][\"1 km\"]\n assert (\n weather_download[\"datamart dir\"]\n == \"/SalishSeaCast/datamart/hrdps-west/1km/\"\n )\n assert (\n weather_download[\"GRIB dir\"] == \"/results/forcing/atmospheric/GEM1.0/GRIB/\"\n )\n assert weather_download[\"forecast duration\"] == 36\n assert (\n weather_download[\"ECCC file template\"]\n == \"CMC_hrdps_west_{variable}_rotated_latlon0.009x0.009_{date}T{forecast}Z_P{hour}-00.grib2\"\n )\n assert weather_download[\"variables\"] == [\n \"UGRD_TGL_10\",\n \"VGRD_TGL_10\",\n \"DSWRF_SFC_0\",\n \"DLWRF_SFC_0\",\n \"LHTFL_SFC_0\",\n \"TMP_TGL_2\",\n \"SPFH_TGL_2\",\n \"RH_TGL_2\",\n \"APCP_SFC_0\",\n \"PRATE_SFC_0\",\n \"PRMSL_MSL_0\",\n ]\n\n def test_logging_section(self, prod_config):\n loggers = prod_config[\"logging\"][\"publisher\"][\"loggers\"]\n assert loggers[\"watchdog\"][\"qualname\"] == \"watchdog\"\n assert loggers[\"watchdog\"][\"level\"] == \"WARNING\"\n assert loggers[\"watchdog\"][\"formatter\"] == \"simple\"\n\n\n@pytest.mark.parametrize(\n \"forecast, resolution, utcnow, forecast_date\",\n (\n (\"00\", \"2.5km\", \"2018-12-29 03:58:43\", \"2018-12-29\"),\n (\"06\", \"2.5km\", \"2018-12-28 09:59:43\", \"2018-12-28\"),\n (\"12\", \"2.5km\", \"2018-12-28 15:56:43\", \"2018-12-28\"),\n (\"18\", \"2.5km\", \"2018-12-28 21:54:43\", \"2018-12-28\"),\n (\"00\", \"1km\", \"2020-02-20 03:58:43\", \"2020-02-20\"),\n (\"12\", \"1km\", \"2020-02-20 15:56:43\", \"2020-02-20\"),\n ),\n)\nclass TestSuccess:\n \"\"\"Unit tests for success() function.\"\"\"\n\n def test_success(\n self, forecast, resolution, utcnow, forecast_date, caplog, monkeypatch\n ):\n def mock_utcnow():\n return arrow.get(utcnow)\n\n monkeypatch.setattr(collect_weather.arrow, \"utcnow\", mock_utcnow)\n parsed_args = SimpleNamespace(forecast=forecast, resolution=resolution)\n caplog.set_level(logging.DEBUG)\n\n msg_type = collect_weather.success(parsed_args)\n\n assert caplog.records[0].levelname == \"INFO\"\n expected = f\"{forecast_date} {resolution} weather forecast {forecast} collection complete\"\n assert caplog.messages[0] == expected\n assert msg_type == f\"success {resolution} {forecast}\"\n\n\n@pytest.mark.parametrize(\n \"forecast, resolution, utcnow, forecast_date\",\n (\n (\"00\", \"2.5km\", \"2018-12-29 03:58:43\", \"2018-12-29\"),\n (\"06\", \"2.5km\", \"2018-12-28 09:59:43\", \"2018-12-28\"),\n (\"12\", \"2.5km\", \"2018-12-28 15:56:43\", \"2018-12-28\"),\n (\"18\", \"2.5km\", \"2018-12-28 21:54:43\", \"2018-12-28\"),\n (\"00\", \"1km\", \"2020-02-10 03:58:43\", \"2020-02-10\"),\n (\"12\", \"1km\", \"2020-02-10 15:56:43\", \"2020-02-10\"),\n ),\n)\nclass TestFailure:\n \"\"\"Unit tests for failure() function.\"\"\"\n\n def test_failure(\n self, forecast, resolution, utcnow, forecast_date, caplog, monkeypatch\n ):\n def mock_utcnow():\n return arrow.get(utcnow)\n\n monkeypatch.setattr(collect_weather.arrow, \"utcnow\", mock_utcnow)\n parsed_args = SimpleNamespace(forecast=forecast, resolution=resolution)\n caplog.set_level(logging.DEBUG)\n\n msg_type = collect_weather.failure(parsed_args)\n\n assert caplog.records[0].levelname == \"CRITICAL\"\n expected = f\"{forecast_date} {resolution} weather forecast {forecast} collection failed\"\n assert caplog.messages[0] == expected\n assert msg_type == f\"failure {resolution} {forecast}\"\n\n\nclass TestCollectWeather:\n \"\"\"Unit tests for collect_weather() function.\"\"\"\n\n @staticmethod\n @pytest.fixture\n def mock_calc_expected_files(monkeypatch):\n def mock_calc_expected_files(*args):\n return set()\n\n monkeypatch.setattr(\n collect_weather, \"_calc_expected_files\", mock_calc_expected_files\n )\n\n @pytest.mark.parametrize(\n \"forecast, resolution\",\n (\n (\"00\", \"2.5km\"),\n (\"06\", \"2.5km\"),\n (\"12\", \"2.5km\"),\n (\"18\", \"2.5km\"),\n (\"00\", \"1km\"),\n (\"12\", \"1km\"),\n ),\n )\n def test_checklist_backfill(\n self,\n forecast,\n resolution,\n mock_calc_expected_files,\n config,\n caplog,\n tmp_path,\n monkeypatch,\n ):\n resolution_key = resolution.replace(\"km\", \" km\")\n grib_dir = tmp_path / config[\"weather\"][\"download\"][resolution_key][\"GRIB dir\"]\n grib_dir.mkdir(parents=True)\n monkeypatch.setitem(\n config[\"weather\"][\"download\"][resolution_key], \"GRIB dir\", grib_dir\n )\n grp_name = grp.getgrgid(os.getgid()).gr_name\n monkeypatch.setitem(config, \"file group\", grp_name)\n parsed_args = SimpleNamespace(\n forecast=forecast,\n resolution=resolution,\n backfill=True,\n backfill_date=arrow.get(\"2020-05-04\"),\n )\n caplog.set_level(logging.DEBUG)\n\n checklist = collect_weather.collect_weather(parsed_args, config)\n\n assert caplog.records[0].levelname == \"DEBUG\"\n assert caplog.messages[0] == f\"created {grib_dir/'20200504'}/\"\n assert caplog.records[1].levelname == \"DEBUG\"\n assert caplog.messages[1] == f\"created {grib_dir/'20200504'}/{forecast}/\"\n assert caplog.records[2].levelname == \"INFO\"\n datamart_dir = Path(\n config[\"weather\"][\"download\"][resolution_key][\"datamart dir\"]\n )\n expected = f\"starting to move 2020-05-04 files from {datamart_dir/forecast}/\"\n assert caplog.messages[2] == expected\n assert caplog.records[3].levelname == \"INFO\"\n expected = f\"finished collecting files from {datamart_dir/forecast}/ to {grib_dir}/20200504/{forecast}/\"\n assert caplog.messages[3] == expected\n expected = {f\"{forecast} {resolution}\": f\"{grib_dir}/20200504/{forecast}\"}\n assert checklist == expected\n\n @pytest.mark.parametrize(\n \"forecast, resolution, utcnow, forecast_date\",\n (\n (\"00\", \"2.5km\", \"2018-12-29 03:58:43\", \"20181229\"),\n (\"06\", \"2.5km\", \"2018-12-28 09:59:43\", \"20181228\"),\n (\"12\", \"2.5km\", \"2018-12-28 15:56:43\", \"20181228\"),\n (\"18\", \"2.5km\", \"2018-12-28 21:54:43\", \"20181228\"),\n (\"00\", \"1km\", \"2020-02-10 03:58:43\", \"20200210\"),\n (\"12\", \"1km\", \"2020-02-10 15:56:43\", \"20200210\"),\n ),\n )\n def test_checklist_observer(\n self,\n forecast,\n resolution,\n utcnow,\n forecast_date,\n mock_calc_expected_files,\n config,\n caplog,\n tmp_path,\n monkeypatch,\n ):\n def mock_utcnow():\n return arrow.get(utcnow)\n\n monkeypatch.setattr(collect_weather.arrow, \"utcnow\", mock_utcnow)\n\n class MockObserver:\n def schedule(self, event_handler, path, recursive):\n pass\n\n def join(self):\n pass\n\n def start(self):\n pass\n\n def stop(self):\n pass\n\n monkeypatch.setattr(\n collect_weather.watchdog.observers, \"Observer\", MockObserver\n )\n\n resolution_key = resolution.replace(\"km\", \" km\")\n grib_dir = tmp_path / config[\"weather\"][\"download\"][resolution_key][\"GRIB dir\"]\n grib_dir.mkdir(parents=True)\n monkeypatch.setitem(\n config[\"weather\"][\"download\"][resolution_key], \"GRIB dir\", grib_dir\n )\n grp_name = grp.getgrgid(os.getgid()).gr_name\n monkeypatch.setitem(config, \"file group\", grp_name)\n parsed_args = SimpleNamespace(\n forecast=forecast, resolution=resolution, backfill=False\n )\n caplog.set_level(logging.DEBUG)\n\n checklist = collect_weather.collect_weather(parsed_args, config)\n\n assert caplog.records[2].levelname == \"INFO\"\n datamart_dir = Path(\n config[\"weather\"][\"download\"][resolution_key][\"datamart dir\"]\n )\n expected = f\"starting to watch for files in {datamart_dir/forecast}/\"\n assert caplog.messages[2] == expected\n expected = {\n f\"{forecast} {resolution}\": f\"{grib_dir}/{forecast_date}/{forecast}\"\n }\n assert checklist == expected\n\n\n@pytest.mark.parametrize(\n \"forecast, resolution, utcnow\",\n (\n (\"00\", \"2.5 km\", arrow.get(\"2018-12-29 03:58:43\")),\n (\"06\", \"2.5 km\", arrow.get(\"2018-12-28 09:59:43\")),\n (\"12\", \"2.5 km\", arrow.get(\"2018-12-28 15:56:43\")),\n (\"18\", \"2.5 km\", arrow.get(\"2018-12-28 21:54:43\")),\n (\"00\", \"1 km\", arrow.get(\"2020-02-10 03:58:43\")),\n (\"12\", \"1 km\", arrow.get(\"2020-02-10 15:56:43\")),\n ),\n)\nclass TestCalcExpectedFiles:\n \"\"\"Unit tests for _calc_expected_files() function.\"\"\"\n\n def test_expected_files(\n self, forecast, resolution, utcnow, config, prod_config, caplog, monkeypatch\n ):\n def mock_utcnow():\n return arrow.get(utcnow)\n\n monkeypatch.setattr(collect_weather.arrow, \"utcnow\", mock_utcnow)\n datamart_dir = Path(config[\"weather\"][\"download\"][resolution][\"datamart dir\"])\n forecast_date = utcnow.shift(hours=-int(forecast)).format(\"YYYYMMDD\")\n caplog.set_level(logging.DEBUG)\n\n expected_files = collect_weather._calc_expected_files(\n datamart_dir, forecast, forecast_date, resolution, config\n )\n\n assert caplog.records[0].levelname == \"DEBUG\"\n expected = f\"calculated set of expected file paths for {resolution} {forecast_date}/{forecast}\"\n assert caplog.messages[0] == expected\n forecast_duration = config[\"weather\"][\"download\"][resolution][\n \"forecast duration\"\n ]\n var_names = config[\"weather\"][\"download\"][resolution][\"variables\"]\n msc_var_names = [\n var_name[0] if resolution == \"2.5 km\" else var_name\n for var_name in var_names\n ]\n file_template = config[\"weather\"][\"download\"][resolution][\"ECCC file template\"]\n expected = set()\n for hour in range(forecast_duration):\n forecast_hour = f\"{hour + 1:03d}\"\n var_files = {\n file_template.format(\n variable=var,\n date=forecast_date,\n forecast=forecast,\n hour=forecast_hour,\n )\n for var in msc_var_names\n }\n expected.update(\n {\n datamart_dir / forecast / f\"{forecast_hour}\" / var_file\n for var_file in var_files\n }\n )\n assert expected_files == expected\n assert len(expected_files) == forecast_duration * len(var_names)\n\n\n@pytest.mark.parametrize(\n \"forecast, resolution\",\n (\n (\"00\", \"2.5 km\"),\n (\"06\", \"2.5 km\"),\n (\"12\", \"2.5 km\"),\n (\"18\", \"2.5 km\"),\n (\"00\", \"1 km\"),\n (\"12\", \"1 km\"),\n ),\n)\nclass TestMoveFile:\n \"\"\"Unit test for _move_file() function.\"\"\"\n\n def test_move_file(\n self, forecast, resolution, config, caplog, tmp_path, monkeypatch\n ):\n grib_dir = tmp_path / config[\"weather\"][\"download\"][resolution][\"GRIB dir\"]\n grib_dir.mkdir(parents=True)\n monkeypatch.setitem(\n config[\"weather\"][\"download\"][resolution], \"GRIB dir\", grib_dir\n )\n grp_name = grp.getgrgid(os.getgid()).gr_name\n monkeypatch.setitem(config, \"file group\", grp_name)\n datamart_dir = (\n tmp_path / config[\"weather\"][\"download\"][resolution][\"datamart dir\"]\n )\n caplog.set_level(logging.DEBUG)\n\n file_template = config[\"weather\"][\"download\"][resolution][\"ECCC file template\"]\n var_file = file_template.format(\n variable=\"UGRD_TGL_10\", date=\"20200505\", forecast=forecast, hour=\"043\"\n )\n (datamart_dir / forecast / \"043\").mkdir(parents=True)\n expected_file = datamart_dir / forecast / \"043\" / var_file\n expected_file.write_bytes(b\"\")\n grib_forecast_dir = grib_dir / \"20200505\" / forecast\n grib_forecast_dir.mkdir(parents=True)\n\n collect_weather._move_file(expected_file, grib_forecast_dir, grp_name)\n\n assert (grib_forecast_dir / \"043\" / var_file).exists()\n assert not expected_file.exists()\n assert caplog.records[0].levelname == \"DEBUG\"\n assert (\n caplog.messages[0] == f\"moved {expected_file} to {grib_forecast_dir/'043'}/\"\n )\n\n\n@pytest.mark.parametrize(\"resolution\", (\"2.5 km\", \"1 km\"))\nclass TestGribFileEventHandler:\n \"\"\"Unit tests for _GribFileEventHandler class.\"\"\"\n\n def test_constructor(self, resolution, config):\n handler = collect_weather._GribFileEventHandler(\n expected_files=set(),\n grib_forecast_dir=Path(),\n grp_name=config[\"file group\"],\n )\n assert handler.expected_files == set()\n assert handler.grib_forecast_dir == Path()\n assert handler.grp_name == config[\"file group\"]\n\n def test_move_expected_file(\n self, resolution, config, caplog, tmp_path, monkeypatch\n ):\n @attr.s\n class MockEvent:\n dest_path = attr.ib()\n\n grib_dir = tmp_path / config[\"weather\"][\"download\"][resolution][\"GRIB dir\"]\n grib_dir.mkdir(parents=True)\n monkeypatch.setitem(\n config[\"weather\"][\"download\"][resolution], \"GRIB dir\", grib_dir\n )\n grp_name = grp.getgrgid(os.getgid()).gr_name\n monkeypatch.setitem(config, \"file group\", grp_name)\n datamart_dir = (\n tmp_path / config[\"weather\"][\"download\"][resolution][\"datamart dir\"]\n )\n (datamart_dir / \"18\" / \"043\").mkdir(parents=True)\n expected_file = (\n datamart_dir\n / \"18\"\n / \"043\"\n / \"CMC_hrdps_west_TCDC_SFC_0_ps2.5km_2018123018_P043-00.grib2\"\n )\n expected_file.write_bytes(b\"\")\n expected_files = {expected_file}\n grib_forecast_dir = grib_dir / \"20181230\" / \"18\"\n grib_forecast_dir.mkdir(parents=True)\n grib_hour_dir = grib_forecast_dir / \"043\"\n caplog.set_level(logging.DEBUG)\n\n handler = collect_weather._GribFileEventHandler(\n expected_files, grib_forecast_dir, grp_name=config[\"file group\"]\n )\n handler.on_moved(MockEvent(dest_path=expected_file))\n\n assert (\n grib_forecast_dir\n / \"043\"\n / \"CMC_hrdps_west_TCDC_SFC_0_ps2.5km_2018123018_P043-00.grib2\"\n ).exists()\n assert not expected_file.exists()\n assert caplog.records[0].levelname == \"DEBUG\"\n assert caplog.messages[0] == f\"moved {expected_file} to {grib_hour_dir}/\"\n assert expected_file not in expected_files\n\n def test_ignore_unexpected_file(\n self, resolution, config, caplog, tmp_path, monkeypatch\n ):\n @attr.s\n class MockEvent:\n dest_path = attr.ib()\n\n grib_dir = tmp_path / config[\"weather\"][\"download\"][resolution][\"GRIB dir\"]\n grib_dir.mkdir(parents=True)\n monkeypatch.setitem(\n config[\"weather\"][\"download\"][resolution], \"GRIB dir\", grib_dir\n )\n grp_name = grp.getgrgid(os.getgid()).gr_name\n monkeypatch.setitem(config, \"file group\", grp_name)\n datamart_dir = (\n tmp_path / config[\"weather\"][\"download\"][resolution][\"datamart dir\"]\n )\n (datamart_dir / \"18\" / \"043\").mkdir(parents=True)\n expected_file = (\n datamart_dir\n / \"18\"\n / \"043\"\n / \"CMC_hrdps_west_TCDC_SFC_0_ps2.5km_2018123018_P043-00.grib2\"\n )\n expected_file.write_bytes(b\"\")\n expected_files = {expected_file}\n grib_forecast_dir = grib_dir / \"20181230\" / \"18\"\n grib_forecast_dir.mkdir(parents=True)\n grib_hour_dir = grib_forecast_dir / \"043\"\n caplog.set_level(logging.DEBUG)\n\n handler = collect_weather._GribFileEventHandler(\n expected_files, grib_forecast_dir, grp_name=config[\"file group\"]\n )\n handler.on_moved(MockEvent(dest_path=\"foo\"))\n\n assert not caplog.records\n assert expected_file in expected_files\n","sub_path":"tests/workers/test_collect_weather.py","file_name":"test_collect_weather.py","file_ext":"py","file_size_in_byte":25066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"565319271","text":"from math import *\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nstep = 0.003\nwith open('euler.txt') as e:\n euler = [float(x.strip()) for x in e.readlines()]\nwith open('lfrog.txt') as l:\n lfrog = [float(x.strip()) for x in l.readlines()]\nwith open('symp.txt') as s:\n symp = [float(x.strip()) for x in s.readlines()]\nwith open('midpoint.txt') as m:\n midpoint = [float(x.strip()) for x in m.readlines()]\n\nanalyticSolution = np.vectorize(lambda t: 0.000327029 * np.exp(-0.266667 * t) * sin(19.9982 * t)\n + 0.024545 * np.exp(-0.266667 * t) * cos(19.9982 * t) - 0.024545)\n\n# limit them to the same length\nmin_len = min(len(euler), len(lfrog), len(symp), len(midpoint))\neuler = euler[:min_len]\nlfrog = lfrog[:min_len]\nsymp = symp[:min_len]\nmidpoint = midpoint[:min_len]\n\ntimeSteps = np.arange(min_len) * step\nanalytic = analyticSolution(timeSteps)\n\nplt.figure(figsize=(20, 10))\nplt.subplot(211)\nplt.title('Different solvers for masspoint hanging from spring')\nplt.plot(timeSteps, euler, label='euler')\nplt.plot(timeSteps, lfrog, label='leapfrog')\nplt.plot(timeSteps, symp, label='symplectic')\nplt.plot(timeSteps, midpoint, label='midpoint')\nplt.plot(timeSteps, analytic, label='analytic solution')\nplt.xlabel('Time in seconds')\nplt.ylabel('Y coordinate')\nplt.legend()\n\nplt.subplot(212)\nplt.title('Error for the different solvers')\nplt.plot(timeSteps, analytic - euler, label='euler')\nplt.plot(timeSteps, analytic - lfrog, label='leapfrog')\nplt.plot(timeSteps, analytic - symp, label='symplectic')\nplt.plot(timeSteps, analytic - midpoint, label='midpoint')\nplt.xlabel('Time in seconds')\nplt.ylabel('Y coordinate')\nplt.legend()\n\nplt.show()\n","sub_path":"MassSpring/report/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"163374764","text":"from katherine import d1\nfrom utils import find_one\nfrom dict import Dict as dict, List as list\n\n\nproviders = list(d1.piper.provider.find({}, {'_id': False}))\n\nmap_type_collection = {\n 'bethesda/invoice': d1.bethesda.invoice,\n 'bethesda/ticket': d1.bethesda.ticket,\n 'bethesda/remission': d1.bethesda.remission,\n 'bethesda/sale_note': d1.bethesda.sale_note\n}\n\n\ndef populate_purchases_for_provider(provider):\n if isinstance(provider, str):\n provider_id = provider\n elif isinstance(provider, dict):\n provider_id = provider.id\n else:\n raise Exception('proovider should be a id or a dict with id key')\n\n provider = find_one(lambda x: x.id == provider_id, providers)\n provider.purchases = list(d1.bethesda.purchase.find({'provider.id': provider_id}, {'_id': False},\n sort=[('datetime', 1)]))\n\n\ndef populate_items_for_provider(provider):\n if isinstance(provider, str):\n provider_id = provider\n elif isinstance(provider, dict):\n provider_id = provider.id\n else:\n raise Exception('proovider should be a id or a dict with id key')\n\n provider = find_one(lambda x: x.id == provider_id, providers)\n provider['items'] = list()\n provider.concepts = list()\n\n items_sku = list()\n concepts_number_id = list()\n\n if 'purchases' not in provider:\n populate_purchases_for_provider(provider_id)\n\n for p in reversed(provider.purchases):\n items = p['items']\n concepts = list()\n\n def doit(document):\n if document.type in map_type_collection.keys():\n document = map_type_collection[document.type].find_one({'id': document.id}, {'_id': False})\n if document is not None:\n # items.extend(document['items'])\n if 'cfdi' in document:\n cfdi = d1.haley.cfdi.find_one({'uuid': document.cfdi.uuid}, {'_id': False})\n concepts.extend(cfdi.concepts)\n\n if 'document' in p:\n doit(p.document)\n elif 'documents' in p:\n for doc in p.documents:\n doit(doc)\n items = list(filter(lambda x: 'provider_item' in x and 'sku' in x.provider_item, items))\n concepts = list(filter(lambda x: 'number_id' in x, concepts))\n for concept in concepts:\n for k in list(concept.keys()):\n if k not in ['number_id', 'description', 'ClaveProdServ']:\n del concept[k]\n if concept.number_id not in concepts_number_id:\n concepts_number_id.append(concept.number_id)\n provider.concepts.append(concept)\n\n for item in items:\n item.local_sku = item.sku\n item.sku = item.provider_item.sku\n if 'description' in item.provider_item:\n item.description = item.provider_item.description\n else:\n del item.description\n for k in list(item.keys()):\n if k not in ['sku', 'description', 'local_sku']:\n del item[k]\n concept = find_one(lambda x: x.number_id == item.sku, provider.concepts)\n if concept is not None:\n if 'ClaveProdServ' in concept:\n item.ClaveProdServ = concept.ClaveProdServ\n\n if item.sku not in items_sku:\n items_sku.append(item.sku)\n provider['items'].append(item)\n\n\nif __name__ == '__main__':\n provider = find_one(lambda x: x.id == '61-10', providers)\n populate_items_for_provider(provider)\n print(len(provider['items']))\n","sub_path":"share/piper/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"412792083","text":"import cv2\nimport os\n\n\nCAPTURE = cv2.VideoCapture(1)\nface_knowns_folder = os.path.join(os.getcwd(),'known_faces')\nprint(face_knowns_folder)\n\nname = input('Please enter name: ')\nperson_folder = os.path.join(face_knowns_folder,name)\nif not os.path.exists(person_folder):\n os.mkdir(person_folder)\nfor i in range(250):\n _,frame = CAPTURE.read()\n show_frame = frame.copy()\n cv2.putText(show_frame,'Face no {}'.format(i+1),(50,50),cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,0),1,cv2.LINE_AA)\n cv2.imshow('Face',show_frame)\n cv2.waitKey(1)\n cv2.imwrite(os.path.join(person_folder,'{}_face_{}.jpg'.format(name,i+1)),frame)\n \ncv2.destroyAllWindows()\nCAPTURE.release()","sub_path":"grabface.py","file_name":"grabface.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"99521205","text":"import socket\nimport time\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((\"127.0.0.1\", 1234))\ns.listen(5)\n\nwhile True:\n connection, address = s.accept()\n print(\"Connected address\", address)\n m_file = open(\"text.txt\", \"w+\")\n m_time = time.asctime(time.localtime())\n m_file.write(str(m_time) + \"\\n\" + \"connected -> \" + str(address))\n m_file.close()\n","sub_path":"Week8/1server.py","file_name":"1server.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"278812583","text":"import traceback\nimport asyncio\nimport logging\n\nfrom discord.ext import commands\n\nfrom .common import Cog\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Admin(Cog):\n @commands.command(hidden=True)\n @commands.is_owner()\n async def shutdown(self, ctx):\n log.info('Logging out! %s', ctx.author)\n await ctx.send(\"dude rip\")\n #await self.bot.session.close() \n await self.bot.logout()\n\n @commands.command(hidden=True)\n @commands.is_owner()\n async def load(self, ctx, extension_name : str):\n \"\"\"Loads an extension.\"\"\"\n try:\n self.bot.load_extension(\"ext.\" + extension_name)\n except Exception as e: \n await ctx.send(f'```py\\n{traceback.format_exc()}\\n```')\n return\n log.info(f'Loaded {extension_name}')\n await ctx.send(f':ok_hand: `{extension_name}` loaded.')\n\n @commands.command(hidden=True)\n @commands.is_owner()\n async def unload(self, ctx, extension_name : str):\n \"\"\"Unloads an extension.\"\"\"\n self.bot.unload_extension('ext.' + extension_name)\n log.info(f'Unloaded {extension_name}')\n await ctx.send(f':ok_hand: `{extension_name}` unloaded.')\n\n @commands.command(hidden=True)\n @commands.is_owner()\n async def reload(self, ctx, extension_name : str):\n \"\"\"Reloads an extension\"\"\"\n try:\n self.bot.unload_extension('ext.' + extension_name)\n self.bot.load_extension('ext.' + extension_name)\n except Exception as err:\n await ctx.send(f'```{traceback.format_exc()}```')\n return\n log.info(f'Reloaded {extension_name}')\n await ctx.send(f':ok_hand: Reloaded `{extension_name}`')\n\n @commands.command()\n @commands.is_owner()\n async def shell(self, ctx, *, command: str):\n \"\"\"Execute shell commands.\"\"\"\n with ctx.typing():\n p = await asyncio.create_subprocess_shell(command,\n stderr=asyncio.subprocess.PIPE,\n stdout=asyncio.subprocess.PIPE,\n )\n\n out, err = map(lambda s: s.decode('utf-8'), await p.communicate())\n\n result = f'{out}{err}' \n await ctx.send(f\"`{command}`: ```{result}```\\n\")\n\n @commands.command()\n @commands.is_owner()\n async def update(self, ctx):\n \"\"\"im lazy\"\"\"\n await ctx.invoke(self.bot.get_command('shell'), command='git pull')\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","sub_path":"ext/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"213391454","text":"import numpy as np\nfrom vtk import *\nfrom read_vtk import *\nimport glob\nfrom natsort import natsorted\nimport plotly.graph_objects as go\nimport plotly.express as px\n\ndef slice_extract(polydata,X0,N):\n\tplane=vtkPlane()\n\tplane.SetOrigin(X0)\n\tplane.SetNormal(N[0],N[1],N[2])\n\n\t# Create a cutter\n\tcutter=vtkCutter()\n\tcutter.SetCutFunction(plane)\n\tcutter.SetInputData(polydata)\n\tcutter.Update()\n\n\t# Convert to PolyData\n\tstripper=vtkStripper()\n\tstripper.SetInputConnection(cutter.GetOutputPort())\n\tstripper.Update()\n\n\t# Extract points\n\tcontour=vtkPolyData()\n\tcontour=stripper.GetOutput()\n\n\tdisp = contour.GetPointData().GetArray('NRRDImage')\t\n\tcontour_points = contour.GetPoints()\n\t\n\treturn disp, contour_points, cutter\n\ndef main():\n\tfiles = glob.glob('../Patient_Data/4DCT_109/Attempt3/displacement_surfaces/*.vtk')\n\tfiles=natsorted(files)\n\tprint(files)\n\n\tNfiles = len(files)\n\n\tcolors=px.colors.cyclical.IceFire\n\t# colors=np.append(colors,colors)\n\tprint(len(colors))\n\n\t# Extract slice from every time step\n\tfig=go.Figure()\n\tfor i in range(8):\n\t\treader=vtkDataSetReader()\n\t\treader.SetFileName(files[i])\n\t\treader.ReadAllVectorsOn()\n\t\treader.ReadAllScalarsOn()\n\t\treader.Update()\n\n\t\t# Load the data\n\t\tdata = reader.GetOutput()\n\n\t\t# Get the number of points\n\t\tplane_center=(-2.251,-288.365,-165.872)\n\t\tplane_normal=(.04,-0.8,0.5)\n\n\t\tcontour_disp,contour_points,cutter = slice_extract(data,plane_center,plane_normal)\n\t\tNpoints = contour_points.GetNumberOfPoints()\n\t\t\n\t\tX=np.zeros((3,Npoints))\n\t\tfor j in range(Npoints):\n\t\t\tp=contour_points.GetPoint(j)\n\t\t\tX[0,j] = p[0]+contour_disp.GetComponent(j,0)\n\t\t\tX[1,j] = p[1]+contour_disp.GetComponent(j,1)\n\t\t\tX[2,j] = p[2]+contour_disp.GetComponent(j,2)\n\n\n\t\tfig.add_trace(go.Scatter3d(x=X[0,:],y=X[1,:],z=X[2,:],mode=\"markers\",marker_color=colors[i]))\n\n\tfig.update_layout(scene=dict(aspectmode='data',aspectratio=dict(x=1,y=1,z=1)))\n\tfig.show()\n\n\n\t# Visualize Slice\n\n\tcutterMapper=vtk.vtkPolyDataMapper()\n\tcutterMapper.SetInputConnection(cutter.GetOutputPort())\n\n\t#create plane actor\n\tplaneActor=vtk.vtkActor()\n\tplaneActor.GetProperty().SetColor(255,255,255)\n\tplaneActor.GetProperty().SetLineWidth(20)\n\tplaneActor.SetMapper(cutterMapper)\n\n\tmapper = vtk.vtkPolyDataMapper()\n\tmapper.SetInputData(data)\n\n\tactor = vtk.vtkActor()\n\tactor.SetMapper(mapper)\n\tactor.GetProperty().SetPointSize(2)\n\n\trenderer = vtk.vtkRenderer()\n\trenderWindow = vtk.vtkRenderWindow()\n\trenderWindow.AddRenderer(renderer)\n\trenderWindowInteractor = vtk.vtkRenderWindowInteractor()\n\trenderWindowInteractor.SetRenderWindow(renderWindow)\n\n\trenderer.AddActor(actor)\n\trenderer.AddActor(planeActor)\n\n\trenderWindow.Render()\n\trenderWindowInteractor.Start()\n\n\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n\n","sub_path":"surf_slice.py","file_name":"surf_slice.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"527853392","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom .models import URLInfo\nfrom .forms import URLForm\nimport re\nimport requests\nimport html\n\n# Create your views here.\ndef url_list(request):\n urls = URLInfo.objects.all()\n return render(request, 'url_list.html', {'urls' : urls})\n\n@login_required\ndef url_detail(request, pk):\n url = get_object_or_404(URLInfo, pk=pk)\n if url.status_code[0] == '2':\n ok = True\n else:\n ok = False\n return render(request, 'url_detail.html', {'url' : url, 'ok' : ok})\n\n@login_required\ndef url_new(request):\n if request.method == \"POST\":\n form = URLForm(request.POST)\n if form.is_valid():\n url = form.save(commit=False)\n req = requests.get(form.cleaned_data['short_url'])\n url.expanded_url = req.url\n url.status_code = req.status_code\n try:\n url.page_title = html.unescape(re.compile('(.*)').search(req.text).group(1))\n except AttributeError:\n url.page_title = 'No title available'\n url.save()\n return redirect('app.views.url_detail', pk=url.pk)\n else:\n form = URLForm()\n return render(request, 'url_new.html', {'form' : form})\n\n@login_required\ndef url_remove(request, pk):\n url = get_object_or_404(URLInfo, pk=pk)\n url.delete()\n return redirect('app.views.url_list')\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"204266903","text":"#-*- coding:utf-8 -*-\nimport os\nimport argparse\nimport numpy as np\nimport time\nimport sys\nimport argparse\nimport paddle\nimport paddle.fluid as fluid\nimport cv2\nfrom collections import Counter\n\nfrom model.alexnet import AlexNet\n\nos.environ['FLAGS_fraction_of_gpu_memory_to_use'] = '0.99'\n\npath = os.getcwd()\n\n\n# 绘制关键点\ndef draw_landmark_point(image, points):\n \"\"\"\n Draw landmark point on image.\n \"\"\"\n for point in points:\n cv2.circle(image, (int(point[0]), int(\n point[1])), 1, (0, 255, 0), -1, cv2.LINE_AA)\n\ndef create_model(model='',image_shape=[224,224],class_num=9):\n\n train_image = fluid.layers.data(name='img', shape=[3] + image_shape, dtype='float32')\n \n predict = AlexNet().net(train_image)\n print('train_image.shape = ',train_image.shape)\n return predict\n\ndef load_model(exe,program,model=''):\n if model == 'ResNet':\n fluid.io.load_params(executor=exe, dirname=\"\", filename=path+'/params/ResNet.params', main_program=program)\n\n\ndef infer(model):\n\n predict = create_model(model='ResNet')\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n\n exe.run(fluid.default_startup_program())\n fluid.memory_optimize(fluid.default_main_program())\n load_model(exe,fluid.default_main_program(),model=model)\n print(\"load model succeed\")\n\n imgs = []\n\n image = cv2.imread(\"/home/airobot/Face-Localization/dataset/300w_224x224/indoor_012.png\")\n image_224 = cv2.resize(image, (224,224), interpolation=cv2.INTER_CUBIC)\n image_224 = image_224.transpose((2,0,1))\n imgs.append(image_224)\n imgs = np.array(imgs)\n imgs = imgs.astype(np.float32)\n imgs /= 255.0\n result = exe.run(fluid.default_main_program(),\n feed={'img': imgs},\n fetch_list=[predict])\n \n points = result[0]\n points = points.reshape(-1,2)\n\n draw_landmark_point(image,points)\n cv2.imshow(\"image!\",image)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n\nif __name__ == \"__main__\":\n parse = argparse.ArgumentParser(description='')\n parse.add_argument('--model', help='model name', nargs='?')\n args = parse.parse_args()\n model = \"ResNet\"\n #DataSet = create_reader()\n infer(model)","sub_path":"infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"58875669","text":"import millyn_nester #调用之前写的函数\nman = []\nother = []\ntry :\n date = open('sketch.txt') #date打开sketch.txt文本数据\n for each_item in date: #进行date每一行的循环判断\n try:\n (role,line_spoken) = each_item.split(':',1) #使用split方式 分割 :号前后的对话\n line_spoken = line_spoken.strip() #去除空格\n if role == 'Man': # 冒号前的对话赋值到role对象里 如果 role 等于Man,即为Man的对话\n man.append(line_spoken) #插入冒号后的对话内容至man[]这个列表\n elif role == 'Other Man': #向上同理如role 等于other man 即为 other man的对话\n other.append(line_spoken) #插入冒号后的对话内容至other[]这个列表\n except ValueError:\n pass\n\n date.close()\nexcept IOError:\n print ('the datefile is missing!')\n\ntry:\n with open('man_date.txt','w') as man_file:\n millyn_nester.print_lol (man,edit=man_file) #调用函数并写入参数 edit在函数里代表的是插入位置\n #那么 man,edit=man_file意思就是 把man的内容插入到man_date.txt内\n with open('other_date.txt','w') as other_file:\n millyn_nester.print_lol (other,edit=other_file)\nexcept IOError as err:\n print ('file error'+ str(err))","sub_path":"Chapter4/1.6.py","file_name":"1.6.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"9160786","text":"\"\"\"参数管理\"\"\"\nfrom schema import Schema, Optional\nfrom src.commons.model_resource import ModelSchemaResource\nfrom src.models.args_mgr import CommonCode, IndustryPosition\n\n\nclass CommonCodeAPI(ModelSchemaResource):\n \"\"\"通用参数字典\"\"\"\n\n model = CommonCode\n allow_query_all = True\n filter_fields = [\n [\"type\", \"==\", \"type\", str],\n [\"code\", \"==\", \"code\", str],\n [\"name\", \"==\", \"name\", str],\n [\"desc\", \"==\", \"desc\", str],\n [\"operator\", \"==\", \"operator\", str],\n [\"operator_id\", \"==\", \"operator_id\", str]\n ]\n validate_schemas = {\n \"post\": Schema(\n {\"type\": str,\n \"code\": str,\n \"name\": str,\n \"desc\": str,\n \"operator_id\": str,\n \"operator\": str}\n ),\n \"put\": Schema(\n {\"id\": str,\n Optional(\"code\"): str,\n Optional(\"type\"): str,\n Optional(\"name\"): str,\n Optional(\"desc\"): str,\n \"operator_id\": str,\n \"operator\": str\n }\n ),\n \"delete\": Schema(\n {\"id\": str}\n )\n }\n\n\nclass IndustryPositionAPI(ModelSchemaResource):\n \"\"\"行业信息表\"\"\"\n model = IndustryPosition\n allow_query_all = True\n filter_fields = [\n [\"industry_code\", \"==\", \"industry_code\", str],\n [\"industry_name\", \"==\", \"industry_name\", str],\n [\"position_name\", \"==\", \"position_name\", str],\n [\"position_code\", \"==\", \"position_code\", str],\n [\"rank\", \"==\", \"rank\", str],\n [\"operator\", \"==\", \"operator\", str],\n [\"operator_id\", \"==\", \"operator_id\", str]\n ]\n validate_schemas = {\n \"post\": Schema(\n {\"industry_code\": str,\n \"industry_name\": str,\n \"position_code\": str,\n \"position_name\": str,\n Optional(\"rank\"): str,\n \"operator_id\": str,\n \"operator\": str,\n }\n ),\n \"put\": Schema(\n {\"id\": str,\n Optional(\"industry_name\"): str,\n Optional(\"position_name\"): str,\n Optional(\"rank\"): str,\n \"operator_id\": str,\n \"operator\": str,\n }\n ),\n \"delete\": Schema(\n {\"id\": str}\n )\n }\n\n\nclass IndustryCodeAPI(ModelSchemaResource):\n \"\"\"行业代码表\"\"\"\n model = IndustryPosition\n\n def get(self):\n pipline = [\n {\"$group\": {\"_id\": {\"industry_code\": \"$industry_code\", \"industry_name\": \"$industry_name\"}}\n\n }\n ]\n queryset = IndustryPosition.objects().only(\"industry_code\", \"industry_name\").aggregate(*pipline)\n return {\"results\": [_[\"_id\"] for _ in queryset]}\n","sub_path":"xxw/support/src/modules/args_mgr.py","file_name":"args_mgr.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"477918178","text":"import networkx as nx\nimport numpy as np\nimport pandas as pd\nimport csv\nimport matplotlib.pyplot as plt\n\ndef load_country(country):\n\n attr_list = []\n edge_list = []\n init_list = []\n data_frame_list = (pd.read_excel(f\"World Bank Data {country}.xlsx\"),\n pd.read_excel(f\"CIRI {country}.xlsx\"),\n pd.read_excel(f\"DPI {country}.xlsx\"))\n df = pd.concat(data_frame_list)\n header_list = df.columns.values.tolist()\n country_dict = df.to_dict(orient='index')\n y = len(country_dict)\n # iterate through data set and assign PMESII points to weighted edge lists\n for val in range(0, y):\n edge_list.append((country_dict[val]['Variable Code'], country_dict[val]['Domain']))\n edge_list.append((country_dict[val]['Domain'], 'PMESII Resources'))\n for y in range(1975, 1979):\n if country_dict[val][y] != str(country_dict[val][y]):\n init_list.append(country_dict[val][y])\n attr_list.append((country_dict[val]['Variable Code'],\n country_dict[val]['Domain'],\n np.mean(init_list)))\n init_list = []\n pmesii_graph = nx.Graph()\n pmesii_graph.add_weighted_edges_from(attr_list, 'W')\n print(nx.info(pmesii_graph))\n return pmesii_graph\n\n","sub_path":"gat/core/sna/loadResources.py","file_name":"loadResources.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"303078676","text":"# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding field 'FlatBlock.lang_code'\n db.add_column('flatblocks_flatblock', 'lang_code',\n self.gf('django.db.models.fields.CharField')(default='en-us', max_length=5, blank=True),\n keep_default=False)\n\n # Adding field 'FlatBlock.site'\n db.add_column('flatblocks_flatblock', 'site',\n self.gf('django.db.models.fields.related.ForeignKey')(to=orm['sites.Site'], null=True, blank=True),\n keep_default=False)\n\n # Adding unique constraint on 'FlatBlock', fields ['lang_code', 'slug', 'site']\n db.create_unique('flatblocks_flatblock', ['lang_code', 'slug', 'site_id'])\n\n def backwards(self, orm):\n # Removing unique constraint on 'FlatBlock', fields ['lang_code', 'slug', 'site']\n db.delete_unique('flatblocks_flatblock', ['lang_code', 'slug', 'site_id'])\n\n # Deleting field 'FlatBlock.lang_code'\n db.delete_column('flatblocks_flatblock', 'lang_code')\n\n # Deleting field 'FlatBlock.site'\n db.delete_column('flatblocks_flatblock', 'site_id')\n\n models = {\n 'flatblocks.flatblock': {\n 'Meta': {'unique_together': \"(('slug', 'lang_code', 'site'),)\", 'object_name': 'FlatBlock'},\n 'content': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n 'header': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'lang_code': ('django.db.models.fields.CharField', [], {'default': \"'en-us'\", 'max_length': '5', 'blank': 'True'}),\n 'site': ('django.db.models.fields.related.ForeignKey', [], {'to': \"orm['sites.Site']\", 'null': 'True', 'blank': 'True'}),\n 'slug': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})\n },\n 'sites.site': {\n 'Meta': {'ordering': \"('domain',)\", 'object_name': 'Site', 'db_table': \"'django_site'\"},\n 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n }\n }\n\n complete_apps = ['flatblocks']","sub_path":"flatblocks/migrations/0002_auto__add_field_flatblock_lang_code__add_field_flatblock_site__add_uni.py","file_name":"0002_auto__add_field_flatblock_lang_code__add_field_flatblock_site__add_uni.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"198861062","text":"# -*- coding: utf-8 -*-\nfrom odoo.http import request, route, Controller, redirect_with_hash\nfrom datetime import date, timedelta\nimport base64\n\n\nclass Admission(Controller):\n @route('/admission', auth='public', website=True)\n def index(self, **kw):\n return request.render('uni_admission.index')\n\n @route('/personal/info', auth='user', website=True, methods=['GET'])\n def form_pers_info(self, **kw):\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n if not student:\n return request.render('website.403')\n\n \n return request.render('uni_admission.personal_info', {\n 'student': student,\n 'has_errors': kw.get('has_errors', False)\n })\n\n @route('/personal/info', auth='user', website=True, methods=['POST'])\n def personal_info_post(self, **kw):\n try:\n request.session['admission_step'] = 2\n return redirect_with_hash('/registration/form')\n except Exception as e:\n return redirect_with_hash('/registration/form?has_errors=True')\n \n\n # GET|POST /admission/form\n @route('/admission/form', auth='user', website=True, methods=['GET'])\n def form(self, **kw):\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n if not student:\n return request.render('website.403')\n\n admission = request.env['uni.admission'].sudo().search([\n ('student_id', '=', student.id),\n ('state', '=', 'form')\n ])\n\n admission_reg = request.env['uni.admission'].sudo().search([\n ('student_id', '=', student.id),\n ('state', '=', 'reg_form')\n ])\n\n try:\n admission.ensure_one()\n except Exception:\n return request.render('uni_admission.form_done',{'admission_reg':admission_reg})\n\n\n country_id = request.env['res.country']\n\n country_ids = country_id.sudo().search([])\n\n sudan_id = country_id.sudo().search([('code','=','SD')]).id\n\n state_ids = request.env['res.country.state'].sudo().search(\n [('country_id', '=', sudan_id)]\n )\n\n # A hack to retrieve translated terms\n gender_list = request.env['uni.student']._fields['gender']._description_selection(\n request.env\n )\n martial_status = request.env['uni.student']._fields['martial_status']._description_selection(\n request.env\n )\n religion = request.env['uni.student']._fields['religion']._description_selection(\n request.env\n )\n\n return request.render('uni_admission.form', {\n 'countries': country_ids,\n 'states': state_ids,\n 'student': student,\n 'max_date': date.today() - timedelta(days=15*365),\n 'gender_list': gender_list,\n 'martial_status': martial_status,\n 'religion': religion,\n 'has_errors': kw.get('has_errors', False)\n })\n\n @route('/admission/form', auth='user', website=True, methods=['POST'])\n def form_post(self, **kw):\n try:\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n image = kw['student_id_img']\n\n # Check allowed extensions\n if image.content_type not in ['image/jpeg', 'image/png']:\n raise Exception('We only accept JPG/JPEG/PNG formats')\n image_data = image.read()\n if len(image_data) / (1024.0 * 1024.0) > 8.0:\n raise Exception('Maximum image size exceeded')\n\n student.sudo().write({\n 'student_national_id_img': base64.encodestring(image_data)\n })\n # TODO: Validate data first, This is risky!\n\n student.write({\n 'first_name_en': kw['first_name_en'].strip().title(),\n 'middle_name_en': kw['middle_name_en'].strip().title(),\n 'last_name_en': kw['last_name_en'].strip().title(),\n 'fourth_name_en': kw['fourth_name_en'].strip().title(),\n 'birth_date': kw['birth_date'].strip(),\n 'place_of_birth': kw['place_of_birth'].strip(),\n 'nationality_id': kw['nationality_id'].strip(),\n 'gender': kw['gender'].strip(),\n 'address': kw['address'].strip(),\n 'email': kw['email'].strip(),\n 'city': kw['city'].strip(),\n 'state_id': kw['state_id'].strip(),\n 'phone': kw['phone'].strip(),\n 'mobile': kw['mobile'].strip(),\n 'religion': kw['religion'].strip(),\n 'national_id': kw['national_id'].strip(),\n 'martial_status': kw['martial_status'].strip(),\n })\n\n # Advance to next step\n request.session['admission_step'] = 1\n return redirect_with_hash('/school/certificate')\n except Exception:\n return redirect_with_hash('/admission/form?has_errors=True')\n\n\n #GET|POST /school/certificate\n\n @route('/school/certificate', auth='user', website=True, methods=['GET'])\n def school_form(self, **kw):\n\n step = request.session.get('admission_step', 0)\n\n if step < 1:\n return redirect_with_hash('/admission/form')\n\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n if not student:\n return request.render('website.403')\n\n return request.render('uni_admission.school_certificate', {\n 'student': student,\n 'has_errors': kw.get('has_errors', False)\n })\n\n @route('/school/certificate', auth='user', website=True, methods=['POST'])\n def school_form_post(self, **kw):\n try:\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n admission_id = request.env['uni.admission'].sudo().search(\n [('student_id', '=',student.id)],\n limit=1\n )\n admission_id.student_id.write({\n 'secondary_school': kw['secondary_school'].strip(),\n 'examination_date': kw['examination_date'].strip(),\n 'certificate_date': kw['certificate_date'].strip(),\n })\n\n print('----------- admission_id',admission_id.sec_subject)\n\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['first_sub'].strip(),\n 'degree': kw['first_deg'].strip(),\n })\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['sec_sub'].strip(),\n 'degree': kw['sec_deg'].strip(),\n })\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['third_sub'].strip(),\n 'degree': kw['third_deg'].strip(),\n })\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['for_sub'].strip(),\n 'degree': kw['for_deg'].strip(),\n })\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['fif_sub'].strip(),\n 'degree': kw['fif_deg'].strip(),\n })\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['six_sub'].strip(),\n 'degree': kw['six_deg'].strip(),\n })\n admission_id.sec_subject.create({\n 'admission_id': admission_id.id,\n 'name': kw['sev_sub'].strip(),\n 'degree': kw['sev_deg'].strip(),\n }) \n\n # Advance to next step\n request.session['admission_step'] = 2\n return redirect_with_hash('/admission/form/family')\n except Exception:\n return redirect_with_hash('/school/certificate?has_errors=True')\n\n @route('/admission/form/family', auth='user', website=True, methods=['GET'])\n def family(self, **kw):\n step = request.session.get('admission_step', 0)\n\n if step < 2:\n return redirect_with_hash('/admission/form')\n\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n guardian_education_level = request.env['uni.student']._fields['guardian_education_level']._description_selection(\n request.env\n )\n\n mother_education_level = request.env['uni.student']._fields['mother_education_level']._description_selection(\n request.env\n )\n if not student:\n return request.render('website.403')\n\n admission = request.env['uni.admission'].sudo().search([\n ('student_id', '=', student.id),\n ('state', '=', 'form')\n ])\n\n try:\n admission.ensure_one()\n except Exception:\n return request.render('uni_admission.form_done')\n\n return request.render('uni_admission.form_family', {\n 'student': student,\n 'guardian_education_level': guardian_education_level,\n 'mother_education_level': mother_education_level,\n 'has_errors': kw.get('has_errors', False)\n })\n\n @route('/admission/form/family', auth='user', website=True, methods=['POST'])\n def family_post(self, **kw):\n try:\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n image = kw['nationality_id_photo']\n\n if image:\n if image.content_type not in ['image/jpeg', 'image/png']:\n raise Exception('We only accept JPG/JPEG/PNG formats')\n\n image_data = image.read()\n\n if len(image_data) / (1024.0 * 1024.0) > 8.0:\n raise Exception('Maximum image size exceeded')\n\n student.sudo().write({\n 'guardian_national_id_img': base64.encodestring(image_data)\n })\n # TODO: Validate data first, This is risky!\n student.sudo().write({\n 'guardian_name': kw['guardian_name'].strip(),\n 'guardian_relation': kw['guardian_relation'].strip(),\n 'guardian_job': kw['guardian_job'].strip(),\n 'guardian_nationality_id': kw['guardian_nationality_id'].strip(),\n 'guardian_phone': kw['guardian_phone'].strip(),\n 'guardian_address': kw['guardian_address'].strip(),\n 'guardian_email': kw['guardian_email'].strip(),\n # 'relative_name': kw['relative_name'].strip(),\n # 'relative_phone': kw['relative_phone'].strip(),\n # 'relative_address': kw['relative_address'].strip(),\n 'guardian_education_level': kw['guardian_education_level'].strip(),\n 'kin_emergency': kw['kin_emergency'].strip(),\n 'kin_ph_emergency': kw['kin_ph_emergency'].strip(),\n 'mother_name': kw['mother_name'].strip(),\n 'mother_education_level': kw['mother_education_level'].strip(),\n 'mother_job': kw['mother_job'].strip(),\n })\n\n ##############\n # Advance to next step\n request.session['admission_step'] = 3\n return redirect_with_hash('/admission/form/photo')\n except Exception as e:\n return redirect_with_hash('/admission/form/family?has_errors=True')\n\n @route('/admission/form/photo', auth='user', website=True, methods=['GET'])\n def photo(self, **kw):\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n if not student:\n return request.render('website.403')\n\n admission = request.env['uni.admission'].sudo().search([\n ('student_id', '=', student.id),\n ('state', '=', 'form')\n ])\n\n try:\n admission.ensure_one()\n except Exception:\n return request.render('uni_admission.form_done')\n\n step = request.session.get('admission_step', 0)\n\n if step < 3:\n return redirect_with_hash('/admission/form')\n\n return request.render('uni_admission.form_photo', {\n 'student': student,\n 'has_errors': kw.get('has_errors', False)\n })\n\n @route('/admission/form/photo', auth='user', website=True, methods=['POST'])\n def photo_post(self, **kw):\n try:\n image = kw['image']\n\n # Check allowed extensions\n if image.content_type not in ['image/jpeg', 'image/png']:\n raise Exception('We only accept JPG/JPEG/PNG formats')\n\n # Check size limit\n image_data = image.read()\n if len(image_data) / (1024.0 * 1024.0) > 8.0:\n raise Exception('Maximum image size exceeded')\n\n request.env.user.sudo().write({\n 'image': base64.encodestring(image_data)\n })\n # TODO: Make image appear in student view\n request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1).write({\n 'std_img': base64.encodestring(image_data)\n }) \n\n # Advance to next step\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n request.env['uni.admission'].sudo().search([\n ('student_id', '=', student.id),\n ('state', '=', 'form'),\n ], limit=1).write({\n 'state': 'committee',\n })\n\n request.session['admission_step'] = 4\n return redirect_with_hash('/admission/form/success')\n except Exception:\n\n return redirect_with_hash('/admission/form/photo?has_errors=True')\n\n @route('/admission/form/success', auth='user', website=True )\n def submit(self, **kw):\n\n step = request.session.get('admission_step', 0)\n\n if step < 4:\n return redirect_with_hash('/admission/form')\n\n return request.render('uni_admission.form_success')\n\n\n\n @route('/registration/form' , auth='user', website=True ,methods=['GET'])\n def submit_(self, **kw):\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n admission_list = request.env['uni.student']._fields['type_admission']._description_selection(\n request.env\n )\n\n is_previouse_admitt = request.env['uni.student']._fields['is_previouse_admitt']._description_selection(\n request.env\n )\n\n reasons = request.env['uni.student']._fields['reasons']._description_selection(\n request.env\n )\n\n blood_group = request.env['uni.student']._fields['blood_group']._description_selection(\n request.env\n )\n\n return request.render('uni_admission.registration_form', {\n 'student': student,\n 'admission_list':admission_list,\n 'is_previouse_admitt':is_previouse_admitt,\n 'reasons':reasons,\n 'blood_group':blood_group,\n 'has_errors': kw.get('has_errors', False)\n })\n\n @route('/registration/form', auth='user', website=True, methods=['POST'])\n def form_(self, **kw):\n\n try:\n student = request.env['uni.student'].sudo().search(\n [('user_id', '=', request.env.user.id)],\n limit=1\n )\n\n image = kw['blood_image']\n\n if image:\n if image.content_type not in ['image/jpeg', 'image/png']:\n raise Exception('We only accept JPG/JPEG/PNG formats')\n\n image_data = image.read()\n\n if len(image_data) / (1024.0 * 1024.0) > 8.0:\n raise Exception('Maximum image size exceeded')\n\n student.sudo().write({\n 'blood_image': base64.encodestring(image_data)\n })\n\n # TODO: Validate data first, This is risky!\n student.sudo().write({\n 'relative_name': kw['relative_name'].strip(),\n 'relative_phone': kw['relative_phone'].strip(),\n 'relative_address': kw['relative_address'].strip(),\n 'blood_group': kw['blood_group'].strip(),\n 'allergies_disea': kw['allergies_disea'].strip(),\n 'chronic_dsease': kw['chronic_dsease'].strip(),\n 'other_dsease': kw['other_dsease'].strip(),\n 'secondary_school': kw['secondary_school'].strip(),\n 'certificate_date': kw['certificate_date'].strip(),\n 'examination_date': kw['examination_date'].strip(),\n 'type_admission': kw['type_admission'].strip(),\n 'is_previouse_admitt': kw['is_previouse_admitt'].strip(),\n 'reasons': kw['reasons'].strip(),\n 'other': kw['other'].strip(),\n #'sibling_in_nile': kw['sibling_in_nile'].strip(),\n \n })\n\n request.env['uni.admission'].sudo().search([\n ('student_id', '=', student.id),\n ('state', '=', 'reg_form'),\n ], limit=1).write({\n 'state': 'clinic',\n })\n\n request.session['registration_step'] = 1\n return request.render('uni_admission.reg_form_success')\n except Exception:\n return redirect_with_hash('/registration/form?has_errors=True')\n\n","sub_path":"uni_admission/controllers/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":18278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"158490454","text":"from peewee import *\nfrom datetime import date\nimport time\nimport os\n#import FaceAlgo\n\ndb = SqliteDatabase('baza/people.db')\n\n\nclass Profiler(object):\n def __enter__(self):\n self._startTime = time.time()\n\n def __exit__(self, type, value, traceback):\n print(\"Elapsed time: {:.3f} sec\".format(time.time() - self._startTime))\n\n\nclass Person(Model):\n name = CharField()\n second_name = CharField()\n birthday = DateField()\n is_relative = BooleanField()\n\n class Meta:\n database = db # модель будет использовать базу данных 'people.db\n\n\nclass Face(Model):\n owner = ForeignKeyField(Person, related_name='face')\n image_path = CharField()\n\n class Meta:\n database = db # модель будет использовать базу данных 'people.db'\n\n\nclass Data(Model):\n owner = ForeignKeyField(Face, related_name='data')\n code = CharField()\n\n class Meta:\n database = db # модель будет использовать базу данных 'people.db'\n\n\ndef create_tables():\n # Создание таблиц в базе\n try:\n Person.create_table()\n print(\"создали Person\")\n Person.create(name='noname', second_name='для сбора всех подряд фотографий', birthday=date(2007, 1, 10), is_relative=True)\n Person.create(name='bufer', second_name='Для обмена фотографиями', birthday=date(2007, 1, 10), is_relative=True)\n except:\n print(\"таблица Person уже создана\")\n\n try:\n Face.create_table()\n print(\"создали Face\")\n except:\n print(\"таблица Face уже создана\")\n\n try:\n Data.create_table()\n print(\"создали Data\")\n except:\n print(\"таблица Data уже создана\")\n\n\n\n\ndef add_person(name=\"test\", second_name=\"\", birthday=date(2018, 1, 10)):\n # добавляем в базу нового человека\n person = Person.create(name=name, second_name=second_name, birthday=birthday, is_relative=True)\n print(\"добавили в базу: \", name, second_name, birthday)\n return person\n\n\ndef search_person(name):\n # поиск человека в базе\n try:\n #print(\"поиск\", name)\n person = Person.get(Person.name == name)\n #print(\"найден человек:\", person.name, person.id)\n return True, person\n except:\n print(\"Ничего не найдено\")\n return False, 0\n\ndef search_person_id(id):\n # поиск человека в базе\n try:\n #print(\"поиск по id\", id)\n person = Person.get(Person.id == id)\n #print(\"найден человек:\", person.name, person.id)\n return True, person\n except:\n print(\"Ничего не найдено\")\n return False, 0\n\ndef add_face(person, face_file, face_descriptor):\n # добавляем персоне новое лицо и метрику по нему\n image_p = face_file # 'c:/faces/1.jpg'\n #with Profiler() as p:\n face = Face.create(owner=person, image_path=image_p)\n #print(\"добавляем новое лицо персоне\")\n\n # face_descriptor = [0.3,0.7,-0.9]\n lists = [{'owner': face, 'code': x} for x in face_descriptor]\n # print(lists)\n with Profiler() as p:\n Data.insert_many(lists).execute()\n # for code in face_descriptor:\n # Data.create(owner=face, code=code)\n return face\n\n\ndef search_faces(person):\n # ищем все лица персоны\n faces = []\n data = []\n try:\n for p in person.face:\n # print(p.image_path)\n faces.append(p)\n data_f = []\n # перебираем все признаки в лице, создаем отдельный лист с ними\n for d in p.data:\n data_f.append(float(d.code))\n\n data.append(data_f)\n # print(data_f)\n\n return faces, data\n except:\n print(\"ошибка поиска лиц в персоне\")\n return faces, data\n\n# create_tables()\ndef select_all_person():\n persons =[]\n for person in Person.select():\n persons.append(person)\n return persons\n\ndef set_face( person, face):\n #Назначаем лицо персоне\n print(\"перенос лица\", person.name, face.image_path)\n\n face.owner = person.id\n face.save()\n\ndef del_face(face):\n # уничтожаем с базы данных все записи, и файл с директории\n # list_del=[]\n # for data in face.data:\n # #print(data.code)\n # list_del.append(data)\n #\n # for d in list_del:\n # d.delete()\n #\n with Profiler() as p:\n Data.delete().where(Data.owner == face).execute()\n\n #print(\"удаляем файл\", face.image_path)\n try:\n os.remove(face.image_path)\n except:\n print (\"нету скриншота\")\n face.delete_instance()\n\ndef change_persone(persone, name, second_name, birthday):\n # изменяем персону\n persone.name = name\n persone.second_name = second_name\n persone.birthday = birthday\n persone.save()\n\n #person_new = Person.get(Person.get_id == )\n return\n\ndef del_persone(persone):\n print(\"удаляем персону \", persone.name)\n\n for f in persone.face:\n del_face(f)\n persone.delete_instance()\n\ndef del_face_in_persone(persone):\n\n print(\"удаляем все лица с персоны \", persone.name)\n\n for f in persone.face:\n del_face(f)\n persone.save()\n\ndef reset_base():\n # все лица переносим в noname и уничтожаем всех персон\n\n all = select_all_person()\n print(\"выбираем всех персон \", len(all))\n res,noname =search_person(\"noname\")\n print(noname.name, noname.id)\n\n print(\"перебираем их всех\")\n for p in all:\n if p.name!=\"noname\" and p.name!=\"bufer\":\n # переписываем все лица на нонэйм и удаляем персону\n for f in p.face:\n f.owner = noname.id\n f.save()\n p.delete_instance()\n\n return\n\n\n\n","sub_path":"baza/db_fases.py","file_name":"db_fases.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"557726872","text":"# problem1\n\nfrom typing import Dict, List, Union\nimport time\n\n\ndef get_number_of_vowels(text: str) -> int:\n \"\"\"\n calculate the number of vowels in text\n Args:\n text: the text\n\n Returns:\n the number of vowels\n \"\"\"\n vowels = frozenset(['a', 'e', 'i', 'o', 'u'])\n # num = 0\n # for x in text:\n # if x in vowels:\n # num += 1\n #\n num = sum(1 for x in text if x in vowels)\n print(f'Number of vowels: {num}')\n return num\n\n\nstart = time.time()\nget_number_of_vowels('annabarseghyan'*100)\nprint(time.time() - start)\n\n#\n# # problem2\n# def characters_2 ( s ):\n# num = 0\n# for i in range(len(s) - 2):\n# if s[i:(i + 3)] == 'bob':\n# num += 1\n# print('Number of vowels: ' + str(num))\n#\n#\n# characters_2('azcbobobegghaklbob')\n#\n#\n# # problem3\n# def longest_substring ( s ):\n# import string\n# alphabet_string = list(string.ascii_lowercase)\n# options = []\n# seq = s[0]\n# for i in range(len(s) - 1):\n# if alphabet_string.index(s[i + 1]) >= alphabet_string.index(s[i]):\n# seq = seq + s[i + 1]\n# else:\n# seq = s[i + 1]\n# options.append(seq)\n# print('Longest substring in alphabetical order is: ' + str(max(options, key=len)))\n#\n#\n# longest_substring('azcbobobegghakl')\n# longest_substring('abcbcd')\n","sub_path":"unit1_problems.py","file_name":"unit1_problems.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"9995163","text":"import graphics as gr\nwindow=gr.GraphWin(\"project\", 500, 500)\ndef draw_sky():\n sky=gr.Rectangle(gr.Point(0, 400), gr.Point(500, 0))\n sky.setFill('skyblue')\n sky.draw(window)\n\ndef draw_sea():\n sea=gr.Rectangle(gr.Point(0, 400), gr.Point(500, 500))\n sea.setFill('blue')\n sea.draw(window)\n\ndef draw_sun():\n sun=gr.Circle(gr.Point(500, 0), 60)\n sun.setFill('yellow')\n sun.draw(window)\n\ndef draw_cloud1_1():\n cloud1=gr.Circle(gr.Point(50, 70), 20)\n cloud1.setFill('white')\n cloud1.draw(window)\n\n cloud2=gr.Circle(gr.Point(70, 65), 30)\n cloud2.setFill('white')\n cloud2.draw(window)\n\n cloud3=gr.Circle(gr.Point(100, 70), 20)\n cloud3.setFill('white')\n cloud3.draw(window)\n\n cloud4=gr.Circle(gr.Point(60, 85), 20)\n cloud4.setFill('white')\n cloud4.draw(window)\n\n cloud5=gr.Circle(gr.Point(90, 90), 20)\n cloud5.setFill('white')\n cloud5.draw(window)\n\n cloud6=gr.Circle(gr.Point(100, 80), 15)\n cloud6.setFill('white')\n cloud6.draw(window)\n\ndef draw_cloud1_2():\n cloud1=gr.Circle(gr.Point(400, 40), 20)\n cloud1.setFill('white')\n cloud1.draw(window)\n\n cloud2=gr.Circle(gr.Point(420, 35), 30)\n cloud2.setFill('white')\n cloud2.draw(window)\n\n cloud3=gr.Circle(gr.Point(450, 40), 20)\n cloud3.setFill('white')\n cloud3.draw(window)\n\n cloud4=gr.Circle(gr.Point(410, 55), 20)\n cloud4.setFill('white')\n cloud4.draw(window)\n\n cloud5=gr.Circle(gr.Point(440, 60), 20)\n cloud5.setFill('white')\n cloud5.draw(window)\n\n cloud6=gr.Circle(gr.Point(450, 50), 15)\n cloud6.setFill('white')\n cloud6.draw(window)\n\ndef draw_cloud1_3():\n cloud1=gr.Circle(gr.Point(320, 100), 20)\n cloud1.setFill('white')\n cloud1.draw(window)\n\n cloud2=gr.Circle(gr.Point(340, 95), 30)\n cloud2.setFill('white')\n cloud2.draw(window)\n\n cloud3=gr.Circle(gr.Point(370, 100), 20)\n cloud3.setFill('white')\n cloud3.draw(window)\n\n cloud4=gr.Circle(gr.Point(330, 115), 20)\n cloud4.setFill('white')\n cloud4.draw(window)\n\n cloud5=gr.Circle(gr.Point(360, 120), 20)\n cloud5.setFill('white')\n cloud5.draw(window)\n\n cloud6=gr.Circle(gr.Point(370, 110), 15)\n cloud6.setFill('white')\n cloud6.draw(window)\n\ndef draw_bird():\n bird1_1=gr.Line(gr.Point(200, 75), gr.Point(215, 70))\n bird1_2=gr.Line(gr.Point(215, 70), gr.Point(210, 85))\n bird1_1.draw(window)\n bird1_2.draw(window)\n\n bird2_1=gr.Line(gr.Point(230, 90), gr.Point(245, 85))\n bird2_2=gr.Line(gr.Point(245, 85), gr.Point(240, 100))\n bird2_1.draw(window)\n bird2_2.draw(window)\n\n bird3_1=gr.Line(gr.Point(225, 65), gr.Point(240, 60))\n bird3_2=gr.Line(gr.Point(240, 60), gr.Point(235, 75))\n bird3_1.draw(window)\n bird3_2.draw(window)\n\ndef draw_ship():\n ship_side=gr.Polygon(gr.Point(80, 420), gr.Point(180, 420), gr.Point(250, 370), gr.Point(50, 370))\n ship_side.setFill('grey')\n ship_side.draw(window)\n\n ship_deck=gr.Rectangle(gr.Point(80, 370), gr.Point(140, 320))\n ship_deck.setFill('white')\n ship_deck.draw(window)\n\n ship_window1=gr.Circle(gr.Point(95, 345), 5)\n ship_window1.setFill('black')\n ship_window1.draw(window)\n\n ship_window2=gr.Circle(gr.Point(125, 345), 5)\n ship_window2.setFill('black')\n ship_window2.draw(window)\n\n ship_flag=gr.Rectangle(gr.Point(125, 305), gr.Point(135, 315))\n ship_flag.setFill('red')\n ship_flag.draw(window)\n\n ship_flagline=gr.Line(gr.Point(125, 320), gr.Point(125, 315))\n ship_flagline.draw(window)\n\ndef draw_palm():\n palm_ground=gr.Polygon(gr.Point(260, 460), gr.Point(460, 460), gr.Point(360, 420))\n palm_ground.setFill('brown')\n palm_ground.draw(window)\n\n palm1=gr.Polygon(gr.Point(360, 420), gr.Point(345, 395), gr.Point(375, 395))\n palm1.setFill('brown')\n palm1.draw(window)\n\n palm2=gr.Polygon(gr.Point(360, 395), gr.Point(345, 370), gr.Point(375, 370))\n palm2.setFill('brown')\n palm2.draw(window)\n\n palm3=gr.Polygon(gr.Point(360, 370), gr.Point(345, 345), gr.Point(375, 345))\n palm3.setFill('brown')\n palm3.draw(window)\n\n palm4=gr.Polygon(gr.Point(360, 345), gr.Point(345, 320), gr.Point(375, 320))\n palm4.setFill('brown')\n palm4.draw(window)\n\n palm5=gr.Polygon(gr.Point(360, 320), gr.Point(345, 295), gr.Point(375, 295))\n palm5.setFill('brown')\n palm5.draw(window)\n\n palm6=gr.Polygon(gr.Point(360, 295), gr.Point(345, 270), gr.Point(375, 270))\n palm6.setFill('brown')\n palm6.draw(window)\n\n palm7=gr.Polygon(gr.Point(360, 270), gr.Point(345, 245), gr.Point(375, 245))\n palm7.setFill('brown')\n palm7.draw(window)\n\n palm_list1=gr.Polygon(gr.Point(360, 245), gr.Point(270, 235), gr.Point(330, 290))\n palm_list1.setFill('green')\n palm_list1.draw(window)\n\n palm_list2=gr.Polygon(gr.Point(360, 245), gr.Point(275, 205), gr.Point(280, 170))\n palm_list2.setFill('green')\n palm_list2.draw(window)\n\n palm_list3=gr.Polygon(gr.Point(360, 245), gr.Point(350, 180), gr.Point(370, 180))\n palm_list3.setFill('green')\n palm_list3.draw(window)\n\n palm_list4=gr.Polygon(gr.Point(360, 245), gr.Point(420, 205), gr.Point(400, 165))\n palm_list4.setFill('green')\n palm_list4.draw(window)\n\n palm_list5=gr.Polygon(gr.Point(360, 245), gr.Point(440, 235), gr.Point(370, 290))\n palm_list5.setFill('green')\n palm_list5.draw(window)\n\ndef draw_picture():\n draw_sky()\n draw_sea()\n draw_sun()\n draw_cloud1_1()\n draw_cloud1_2()\n draw_cloud1_3()\n draw_ship()\n draw_bird()\n draw_palm()\n\ndraw_picture()\n\nwindow.getMouse()\nwindow.close()\n","sub_path":"graphics/picture2.py","file_name":"picture2.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"212859984","text":"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy\n\nmatplotlib.rc_file(\"ubuntu_matplotlibrc\")\n\nparams = {'backend': 'pdf',\n 'figure.figsize': [3.38, 3.38],\n 'font.family':'serif',\n 'font.size':10,\n# 'font.serif': 'Times Roman',\n 'axes.titlesize': 'medium',\n 'axes.labelsize': 'medium',\n 'legend.fontsize': 8,\n 'legend.frameon' : False,\n# 'text.usetex': True,\n# 'figure.dpi': 600,\n 'lines.markersize': 4,\n 'lines.linewidth': 1,\n 'lines.antialiased': False,\n 'path.simplify': False,\n # townsley below here\n 'legend.numpoints': 1}\n\nmatplotlib.rcParams.update(params)\n\nORANGE = (0.90,0.60,0.00)\nSKY_BLUE = (0.35,0.70,0.90)\nBLUE_GREEN = (0.00,0.60,0.50)\nYELLOW = (0.95,0.90,0.25)\nBLUE = (0.00,0.45,0.70)\nVERMILLION = (0.80,0.40,0.00)\nRED_PURPLE = (0.80,0.60,0.70)\n\nax = plt.subplot(111)\n\ndata21 = numpy.genfromtxt( '/dmt/townsley/mixed_hybrid_wd_snia/finish_runs/snia_21_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata22 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_22_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata23 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_23_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata24 = numpy.genfromtxt( '/dmt/townsley/mixed_hybrid_wd_snia/finish_runs/snia_24_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata25 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_25_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata26 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_26_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata27 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_27_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata28 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_28_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata29 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_29_hybrid2/profile21_flash_h201.dat', unpack=True )\ndata30 = numpy.genfromtxt( '/dmt/caugustine/Hybrid_Research/flash_runs/snia_30_hybrid2/profile21_flash_h201.dat', unpack=True )\n\nplt.plot( data21[0], data21[15]/1.99e33, label = '21', color=ORANGE )\nplt.plot( data22[0], data22[15]/1.99e33, label = '22', color=SKY_BLUE )\nplt.plot( data23[0], data23[15]/1.99e33, label = '23', color=BLUE_GREEN )\nplt.plot( data24[0], data24[15]/1.99e33, label = '24', color=YELLOW )\nplt.plot( data25[0], data25[15]/1.99e33, label = '25', color=BLUE )\nplt.plot( data26[0], data26[15]/1.99e33, label = '26', color=VERMILLION )\nplt.plot( data27[0], data27[15]/1.99e33, label = '27', color=RED_PURPLE )\nplt.plot( data28[0], data28[15]/1.99e33, label = '28', color='black' )\nplt.plot( data29[0], data29[15]/1.99e33, '--', label = '29', color=ORANGE )\nplt.plot( data30[0], data30[15]/1.99e33, '--', label = '30', color=SKY_BLUE )\n\n\nplt.xlabel('Time (s)')\nplt.ylabel('Expected $^{56}$Ni Yield (M$_\\\\odot$)')\nplt.legend(loc = 'best')\n\nplt.xlim([0,4])\n\nax.yaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\nax.xaxis.set_minor_locator(matplotlib.ticker.AutoMinorLocator())\n\nplt.annotate(\"CONe Hybrid\", (2.0,0.2))\n\nplt.tight_layout()\nplt.savefig('Hybrid_Ni56mass_v_time_plot.pdf')\n#plt.show()\n","sub_path":"plotscripts/21_30_plot_Hybrid.py","file_name":"21_30_plot_Hybrid.py","file_ext":"py","file_size_in_byte":3340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"405796135","text":"import cv2, os\nimport numpy as np\n\n\nPATH_DATA = '/Users/amanrana/Desktop/predicted_images'\nPATH_COLOR_CODED = '/Users/amanrana/Desktop/color_coded_images'\n\nfor i in range(1, 68):\n\t# Reading images\n\ttry:\n\t\tx = np.array(cv2.imread(os.path.join(PATH_DATA, '{}_perio.png'.format(i))))\n\t\ty = np.array(cv2.imread(os.path.join(PATH_DATA, '{}_gnd_color.png'.format(i))))\n\t\tpred = np.array(cv2.imread(os.path.join(PATH_DATA, '{}_pred_color.png'.format(i))))\n\t\tcolor_coded = np.array(cv2.imread(os.path.join(PATH_DATA, '{}_color_coded.png'.format(i))))\n\texcept:\n\t\t# print('error')\n\t\tcontinue\n\n\tgrid = np.zeros([960, 1280, 3])\n\tgrid[:480, :640, :] = x\n\tgrid[:480, 640:, :] = y\n\tgrid[480:, :640, :] = pred\n\tgrid[480:, 640:, :] = color_coded\n\tcv2.imwrite(os.path.join(PATH_COLOR_CODED, '{}._grid.png'.format(i)), grid)\n","sub_path":"Postprocessing/generate_results_grid.py","file_name":"generate_results_grid.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"360756111","text":"import matplotlib.pyplot as plt\nimport math\nfrom collections import OrderedDict\n# plt.ylabel('some label')\n\"\"\"\nto automate data:-\n------------------\n\n$cat > answers.txt \n1\n5\nx\n(press ctrl+d)\n\n$ cat < answers.txt|python3 graph_plot.py \nChoice from below \n\t1. create graph\n\t2. add edges\n\t3. plot graph\n\tx. exit\n\t:enter number of vertices : \n\n created graph with vertices as:-\na, b, c, d, e, \n\n\nChoice from below \n\t1. create graph\n\t2. add edges\n\t3. plot graph\n\tx. exit\n\t:$\n\n\"\"\"\ndef plotgraph(graph):\n\n\t#set range of axis - hardcoded\n\tplt.axis([-6, 6, -6, 6])\n\tplt.axis('off')\n\n\t# plot verticess\n\tfor i in graph:\n\t\ty = graph[i]['y']\n\t\tx = graph[i]['x']\n\n\t\tplt.plot([x],[y], 'ro')\n\t\tplt.annotate(i, xy=(x, y), xytext=(x, y))\n\n\t# plot edges\n\tfor j in graph:\n\t\tfor k in graph[j]['data']:\n\t\t\t# print(j,k)\n\t\t\tplt.plot([graph[j]['x'],graph[k]['x']],[graph[j]['y'],graph[k]['y']], 'k-')\n\t\n\tprint('\\n\\n')\n\tplt.show()\n##printed x y axis\n# xa=[]\n# ya=[]\n# for i in range(-6,7,1):\n# \txa.append(0)\n# \tya.append(i)\n# plt.plot(xa,ya,'k-')\n# plt.plot(ya,xa,'k-')\n\n##working on printing vertices\ndef creategraph():\n\tn = int(input('enter number of vertices : '))\n\n\tgraph = OrderedDict()\n\tfor k in range(n):\n\t\tgraph[chr(ord('a') + k)] = {\n\t\t'data':[],\n\t\t'x':'',\n\t\t'y':''\n\t\t}\n\n\t# hypotenues - hardcoded\n\tfixed_length = 5\n\n\ttry:\n\t d = 360/len(graph)\n\texcept:\n\t\t# basically except ZeroDivisionError here\n\t d = 0\n\n\tm=0\n\t# plot verticess\n\tfor i in graph:\n\n\t\tgraph[i]['y'] = fixed_length * math.sin(math.radians(m))\n\t\tgraph[i]['x'] = fixed_length * math.cos(math.radians(m))\n\n\t\tm=m+d\n\n\tprint('\\n\\n created graph with vertices as:-')\n\tfor i in graph:\n\t\tprint(i,end=', ')\n\n\tprint('\\n\\n')\n\n\treturn graph\n\n\ndef addedges(graph):\n\tm=int(input('enter no. of edges : '))\n\n\ttemp=[]\n\tfor i in range(m):\n\t\ttemp=input('enter edges as a,b and press enter : ').split(',')\n\t\t\n\t\tgraph[temp[0]]['data'].append(temp[1])\n\t\tgraph[temp[1]]['data'].append(temp[0])\n\n\tprint('\\n\\n edges added \\n\\n')\n\n\n\n\n\n\n\t\nwhile(True):\n\tc=input('Choice from below \\n\\\n\t1. create graph\\n\\\n\t2. add edges\\n\\\n\t3. plot graph\\n\\\n\tx. exit\\n\\\n\t:')\n\n\tif c=='1':\n\t\tgraph = creategraph()\n\telif c=='2':\n\t\t\"\"\"alternative for below is to assign \n\t\t\t\tgraph=None \n\n\t\t\t\tand check \n\t\t\t\t\n\t\t\t\tif graph is not None: \n\t\t\"\"\"\n\t\ttry:\n\t\t graph\n\t\texcept:\n\t\t\t# basically except NameError here\n\t\t graph = creategraph()\n\n\t\taddedges(graph)\n\telif c=='3':\n\t\ttry:\n\t\t graph\n\t\texcept:\n\t\t graph = creategraph()\n\t\tplotgraph(graph)\n\telif c=='x':\n\t\tbreak\n\telse:\n\t\tprint('try again \\n\\n')\n# print(math.radians(d))\n# print(d*math.pi/180)\n# print(math.degrees(math.radians(d)))","sub_path":"graph_plot.py","file_name":"graph_plot.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"559026603","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\n\nif __name__ == '__main__':\n\n # create SparkSession\n spark = (SparkSession\n .builder\n .appName('CreateRawDataFrameWithSchema')\n .getOrCreate())\n\n # Raw data\n raw_data = [\n ('Stephan Smith', 26, 3.5, ['Python', 'Spark']),\n ('Jules Morgan', 23, 2.2, ['Java', 'Hive']),\n ('Ketty Lopez', 39, 4.0, ['Scala', 'Hive'])\n ]\n\n # programatic schema declaration\n programaticSchema = StructType([StructField('Name', StringType(), False),\n StructField('Age', IntegerType(), False),\n StructField('Rating', FloatType(), False),\n StructField('Skills', ArrayType(StringType(), False), False)])\n\n # Create DataFrame using programatic schema\n programatic_df = spark.createDataFrame(raw_data, programaticSchema)\n\n # DDL schema declaration\n DDLSchema = \"Name STRING, Age INT, Rating FLOAT, Skills ARRAY\"\n\n # Create DataFrame using DDL schema\n DDL_df = spark.createDataFrame(raw_data, DDLSchema)\n\n # Show created dataframe\n programatic_df.show(n=20, truncate=False)\n DDL_df.show(n=20, truncate=False)\n\n # Print schema\n print(programatic_df.printSchema())\n print(DDL_df.printSchema())\n","sub_path":"CreateDataFrameWithSchema/src/create_raw_dataframe_with_schema.py","file_name":"create_raw_dataframe_with_schema.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"187275837","text":"'''\nDisplay, summarize, and compare meta-learned plasticity rules.\nCreated by Basile Van Hoorick, December 2020.\n'''\n\n# Library imports.\nimport argparse\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pickle\nimport shutil\nimport sys\n\n# Repository imports.\nfrom eval_util import *\n\n_DEFAULT_RESULTS_DIR = r'D:\\Development\\CVR Data\\Plasticity Rules\\inspect_results'\n_DEFAULT_RULES_DIR = r'D:\\Development\\CVR Data\\Plasticity Rules\\rules'\n_DEFAULT_PLOTS_DIR = 'inspect_plots/'\n\ntable_models = ['table_prepost', 'table_prepostcount', 'table_prepostpercent']\nann_models = ['reg_oneprepost', 'reg_oneprepostall', 'reg_allpostall']\nall_models = ['ff', 'rnn', *table_models, *ann_models]\n\nmodel_legends = {\n 'ff': 'GD',\n 'rnn': 'RNN',\n 'table_prepost': 'PrePost',\n 'table_prepostcount': 'PrePostCount',\n 'table_prepostpercent': 'PrePostPercent',\n 'reg_oneprepost': 'ANNPrePost',\n 'reg_oneprepostall': 'ANNPrePostAll',\n 'reg_allpostall': 'ANNAllPostAll'\n}\n\n\n# Process arguments.\nparser = argparse.ArgumentParser()\n\n# General network architecture.\nparser.add_argument('--results_dir', default=_DEFAULT_RESULTS_DIR, type=str,\n help='Path to input directory containing pickle files with generated stats.')\nparser.add_argument('--rules_dir', default=_DEFAULT_RULES_DIR, type=str,\n help='Path to input directory containing pickle files with plasticity rules.')\nparser.add_argument('--plots_dir', default=_DEFAULT_PLOTS_DIR, type=str,\n help='Path to output directory for storing figures.')\n\n\ndef _get_property_from_tag(exp_tag, name):\n if name == 'model':\n # Exists in beginning of tag.\n for model_name in all_models:\n if exp_tag.startswith(model_name + '_'):\n return model_name\n\n raise ValueError('Model not found in ' + exp_tag)\n\n else:\n # Parse assuming '..._nameval_...' or '..._nameval'\n if '_' + name in exp_tag:\n start = exp_tag.index('_' + name) + len('_' + name)\n else:\n # Probably absent (= false) boolean flag.\n # raise ValueError('Parameter ' + name + ' not found in ' + exp_tag)\n return '0'\n\n if '_' in exp_tag[start:]:\n end = exp_tag[start:].index('_') + start\n else: # End of string.\n end = len(exp_tag)\n\n if start == end:\n # Probably present (= true) boolean flag.\n result = '1'\n else:\n result = exp_tag[start:end]\n\n return result\n\n\ndef _load_data_from_files(args, must_contain='', must_not_contain='', summarize=True):\n '''\n Args:\n must_contain: Experiment tag (i.e. file name) must contain all non-empty strings of this list.\n must_not_contain: Exclude experiment tags that contain at least one non-empty string of this list.\n summarize: If True, aggregate multiple runs into one mean and stddev.\n Returns:\n [(tag1, stats1, rules1), (tag2, stats2, rules2), ...].\n '''\n\n if not(isinstance(must_contain, list)):\n must_contain = [must_contain]\n if not(isinstance(must_not_contain, list)):\n must_not_contain = [must_not_contain]\n\n all_files = os.listdir(args.rules_dir)\n all_files = [fn for fn in all_files if fn.endswith('.p')]\n for mc in must_contain:\n if len(mc) != 0:\n all_files = [fn for fn in all_files if mc in fn]\n for mnc in must_not_contain:\n if len(mnc) != 0:\n all_files = [fn for fn in all_files if mnc not in fn]\n results = []\n\n for fn in all_files:\n exp_tag = fn[:-8]\n stats_fp = os.path.join(args.results_dir, exp_tag + '.p')\n rules_fp = os.path.join(args.rules_dir, exp_tag + '_rules.p')\n if not(os.path.isfile(stats_fp)) or not(os.path.isfile(rules_fp)):\n continue\n\n with open(stats_fp, 'rb') as f:\n (stats_up, _) = pickle.load(f)\n with open(rules_fp, 'rb') as f:\n all_rules = pickle.load(f) # [(hidden1, output1), (hidden2, output2), ...]\n \n if summarize:\n # Typically, stats_up = length 5 list.\n stats_up = convert_multi_stats_uncertainty(stats_up)\n\n results.append((exp_tag, stats_up, all_rules))\n\n return results\n\n\ndef _print_rule(rule, desc):\n print(desc)\n print(np.array(rule))\n print()\n\n\ndef _print_rules(args):\n '''\n Simply prints rules for prepost.\n '''\n results = _load_data_from_files(args, must_contain='table_prepost_')\n \n # Loop over all experiments and all runs.\n for (exp_tag, stats, rules) in results:\n \n print(exp_tag)\n if '_gr' in exp_tag:\n print('=> Has hidden layer rule')\n if '_or' in exp_tag:\n print('=> Has output layer rule')\n \n # for rule_set in rules:\n # (hidden_rule, output_rule) = rule_set\n # if hidden_rule is not None:\n # _print_rule(hidden_rule, 'Hidden:')\n # if output_rule is not None:\n # _print_rule(output_rule, 'Output:')\n\n if rules[0][0] is not None:\n all_hidden = [np.array(rs[0]) for rs in rules]\n hidden_mean = np.mean(all_hidden, axis=0)\n hidden_std = np.std(all_hidden, axis=0)\n _print_rule(hidden_mean, 'Mean hidden:')\n _print_rule(hidden_std, 'Stddev hidden:')\n if rules[0][1] is not None:\n all_output = [np.array(rs[1]) for rs in rules]\n output_mean = np.mean(all_output, axis=0)\n output_std = np.std(all_output, axis=0)\n _print_rule(output_mean, 'Mean output:')\n _print_rule(output_std, 'Stddev output:')\n\n print()\n\n\ndef _plot_rules(args):\n '''\n Plots rules for prepostcount or prepostpercent as they vary over layer firing count.\n '''\n must_contains = ['table_prepostcount_', 'table_prepostpercent_']\n for must_contain in must_contains:\n results = _load_data_from_files(args, must_contain=must_contain)\n \n # Loop over all experiments and all runs.\n for (exp_tag, stats, rules) in results:\n \n print(exp_tag)\n if '_gr' in exp_tag:\n print('=> Has hidden layer rule')\n if '_or' in exp_tag:\n print('=> Has output layer rule')\n \n # for rule_set in rules:\n # (hidden_rule, output_rule) = rule_set\n # if hidden_rule is not None:\n # _print_rule(hidden_rule, 'Hidden:')\n # if output_rule is not None:\n # _print_rule(output_rule, 'Output:')\n\n fig = plt.figure(figsize=(6, 4))\n\n if rules[0][0] is not None:\n all_hidden = [np.array(rs[0]) for rs in rules]\n hidden_mean = np.mean(all_hidden, axis=0)\n hidden_std = np.std(all_hidden, axis=0)\n _print_rule(hidden_mean, 'Mean hidden:')\n _print_rule(hidden_std, 'Stddev hidden:')\n\n if 'percent' in must_contain:\n xs = np.linspace(0, 100, len(hidden_mean[0, 0]))\n else:\n xs = np.arange(len(hidden_mean[0, 0]))\n for i in range(2):\n for j in range(2):\n label = 'Hidden $(' + str(i) + ', ' + str(j) + ')$'\n plt.plot(xs, hidden_mean[i, j], label=label)\n\n if rules[0][1] is not None:\n all_output = [np.array(rs[1]) for rs in rules]\n output_mean = np.mean(all_output, axis=0)\n output_std = np.std(all_output, axis=0)\n _print_rule(output_mean, 'Mean output:')\n _print_rule(output_std, 'Stddev output:')\n\n if 'percent' in must_contain:\n xs = np.linspace(0, 100, len(output_mean[0, 0]))\n else:\n xs = np.arange(len(output_mean[0, 0]))\n for i in range(2):\n for j in range(2):\n label = 'Output $(' + str(i) + ', ' + str(j) + ')$'\n plt.plot(xs, output_mean[i, j], label=label)\n \n model_name = _get_property_from_tag(exp_tag, 'model')\n dataset = _get_property_from_tag(exp_tag, 'dup')\n if 'percent' in must_contain:\n plt.xlabel('Fraction of incoming firing nodes [%]')\n else:\n plt.xlabel('Number of incoming firing nodes')\n plt.ylabel(r'$\\beta$')\n title = f'Plasticity rules for {model_legends[model_name]} on {dataset}'\n plt.title(title)\n plt.legend()\n fig.tight_layout()\n \n save_path = os.path.join(args.plots_dir, exp_tag)\n print('Saving figure to:', save_path)\n plt.savefig(save_path + '.pdf', dpi=192)\n plt.savefig(save_path + '.png', dpi=192)\n # plt.show()\n\n print()\n\n\ndef main(args):\n\n # Set plotting style\n use_seaborn = True\n if use_seaborn:\n plt.style.use('seaborn')\n # We need to add some colors to seaborn's default cycler (which only hax 6)\n default_colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n default_colors += ['#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\n plt.rcParams['axes.prop_cycle'] = plt.cycler(color=default_colors)\n\n # Add a semi-transparent backgroud to the legend for legibility\n plt.rcParams['legend.frameon'] = 'True'\n \n _print_rules(args)\n _plot_rules(args)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n main(args)\n\n\n","sub_path":"BrainNet/inspect_rules.py","file_name":"inspect_rules.py","file_ext":"py","file_size_in_byte":9699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"74427130","text":"class Solution(object):\n def mergeTwoLists(self, l1, l2):\n pos1 = 0\n pos2 = 0\n merged = []\n while pos1 < len(l1) and pos2 < len(l2):\n if l1[pos1] < l2[pos2]:\n merged.append(l1[pos1])\n pos1 += 1\n else:\n merged.append(l2[pos2])\n pos2 += 1\n merged += l1[pos1:]\n merged += l2[pos2:]","sub_path":"src/1709/170908/21_MergeTwoSortedLists.py","file_name":"21_MergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"174551113","text":"#!/usr/bin/python\n#\n# Copyright 2018-2021 Polyaxon, 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\nfrom marshmallow import EXCLUDE, fields\n\nfrom polyaxon.deploy.schemas.celery import CelerySchema\nfrom polyaxon.k8s import k8s_schemas\nfrom polyaxon.schemas.base import BaseCamelSchema, BaseConfig\nfrom polyaxon.schemas.fields.swagger import SwaggerField\n\n\nclass ServiceSchema(BaseCamelSchema):\n enabled = fields.Bool(allow_none=True)\n image = fields.Str(allow_none=True)\n image_tag = fields.Str(allow_none=True)\n image_pull_policy = fields.Str(allow_none=True)\n replicas = fields.Int(allow_none=True)\n concurrency = fields.Int(allow_none=True)\n resources = SwaggerField(cls=k8s_schemas.V1ResourceRequirements, allow_none=True)\n\n class Meta:\n unknown = EXCLUDE\n\n @staticmethod\n def schema_config():\n return Service\n\n\nclass Service(BaseConfig):\n SCHEMA = ServiceSchema\n REDUCED_ATTRIBUTES = [\n \"enabled\",\n \"image\",\n \"imageTag\",\n \"imagePullPolicy\",\n \"replicas\",\n \"concurrency\",\n \"resources\",\n ]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n ):\n self.enabled = enabled\n self.image = image\n self.image_tag = image_tag\n self.image_pull_policy = image_pull_policy\n self.replicas = replicas\n self.concurrency = concurrency\n self.resources = resources\n\n\nclass WorkerServiceSchema(ServiceSchema):\n celery = fields.Nested(CelerySchema, allow_none=True)\n\n @staticmethod\n def schema_config():\n return WorkerServiceConfig\n\n\nclass WorkerServiceConfig(Service):\n SCHEMA = WorkerServiceSchema\n REDUCED_ATTRIBUTES = Service.REDUCED_ATTRIBUTES + [\"celery\"]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n celery=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n concurrency=concurrency,\n resources=resources,\n )\n self.celery = celery\n\n\nclass HelperServiceSchema(ServiceSchema):\n sleep_interval = fields.Int(allow_none=True)\n sync_interval = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return HelperServiceConfig\n\n\nclass HelperServiceConfig(Service):\n SCHEMA = HelperServiceSchema\n REDUCED_ATTRIBUTES = Service.REDUCED_ATTRIBUTES + [\n \"sleepInterval\",\n \"syncInterval\",\n ]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n sleep_interval=None,\n sync_interval=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n concurrency=concurrency,\n resources=resources,\n )\n self.sleep_interval = sleep_interval\n self.sync_interval = sync_interval\n\n\nclass AgentServiceSchema(ServiceSchema):\n instance = fields.String(allow_none=True)\n token = fields.String(allow_none=True)\n is_replica = fields.Bool(allow_none=True)\n compressed_logs = fields.Bool(allow_none=True)\n\n @staticmethod\n def schema_config():\n return AgentServiceConfig\n\n\nclass AgentServiceConfig(Service):\n SCHEMA = AgentServiceSchema\n REDUCED_ATTRIBUTES = Service.REDUCED_ATTRIBUTES + [\n \"instance\",\n \"token\",\n \"isReplica\",\n \"compressedLogs\",\n ]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n instance=None,\n token=None,\n is_replica=None,\n compressed_logs=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n concurrency=concurrency,\n resources=resources,\n )\n self.instance = instance\n self.token = token\n self.is_replica = is_replica\n self.compressed_logs = compressed_logs\n\n\nclass OperatorServiceSchema(ServiceSchema):\n skip_crd = fields.Bool(allow_none=True, data_key=\"skipCRD\")\n\n @staticmethod\n def schema_config():\n return OperatorServiceConfig\n\n\nclass OperatorServiceConfig(Service):\n SCHEMA = OperatorServiceSchema\n REDUCED_ATTRIBUTES = Service.REDUCED_ATTRIBUTES + [\"skipCRD\"]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n skip_crd=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n concurrency=concurrency,\n resources=resources,\n )\n self.skip_crd = skip_crd\n\n\nclass ApiServiceSchema(ServiceSchema):\n service = fields.Dict(allow_none=True)\n\n @staticmethod\n def schema_config():\n return ApiServiceConfig\n\n\nclass ApiServiceConfig(Service):\n SCHEMA = ApiServiceSchema\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n service=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n concurrency=concurrency,\n resources=resources,\n )\n self.service = service\n\n\nclass HooksSchema(ServiceSchema):\n load_fixtures = fields.Bool(allow_none=True)\n\n @staticmethod\n def schema_config():\n return HooksConfig\n\n\nclass HooksConfig(Service):\n SCHEMA = HooksSchema\n REDUCED_ATTRIBUTES = Service.REDUCED_ATTRIBUTES + [\"loadFixtures\"]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n concurrency=None,\n resources=None,\n load_fixtures=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n concurrency=concurrency,\n resources=resources,\n )\n self.load_fixtures = load_fixtures\n\n\nclass ThirdPartyServiceSchema(ServiceSchema):\n enabled = fields.Bool(allow_none=True)\n persistence = fields.Dict(allow_none=True)\n node_selector = fields.Dict(allow_none=True)\n affinity = fields.Dict(allow_none=True)\n tolerations = fields.List(fields.Dict(allow_none=True), allow_none=True)\n\n @staticmethod\n def schema_config():\n return ThirdPartyService\n\n\nclass ThirdPartyService(Service):\n SCHEMA = ThirdPartyServiceSchema\n REDUCED_ATTRIBUTES = [\n \"enabled\",\n \"image\",\n \"imageTag\",\n \"imagePullPolicy\",\n \"replicas\",\n \"concurrency\",\n \"resources\",\n \"persistence\",\n \"nodeSelector\",\n \"affinity\",\n \"tolerations\",\n ]\n\n def __init__(\n self,\n enabled=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n resources=None,\n persistence=None,\n node_selector=None,\n affinity=None,\n tolerations=None,\n ):\n super().__init__(\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n resources=resources,\n )\n self.enabled = enabled\n self.persistence = persistence\n self.node_selector = node_selector\n self.affinity = affinity\n self.tolerations = tolerations\n\n\nclass PostgresqlSchema(ThirdPartyServiceSchema):\n postgres_user = fields.Str(allow_none=True)\n postgres_password = fields.Str(allow_none=True)\n postgres_database = fields.Str(allow_none=True)\n conn_max_age = fields.Int(allow_none=True)\n\n @staticmethod\n def schema_config():\n return PostgresqlConfig\n\n\nclass PostgresqlConfig(ThirdPartyService):\n SCHEMA = PostgresqlSchema\n REDUCED_ATTRIBUTES = ThirdPartyService.REDUCED_ATTRIBUTES + [\n \"postgresUser\",\n \"postgresPassword\",\n \"postgresDatabase\",\n \"connMaxAge\",\n ]\n\n def __init__(\n self,\n enabled=None,\n postgres_user=None,\n postgres_password=None,\n postgres_database=None,\n conn_max_age=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n resources=None,\n persistence=None,\n node_selector=None,\n affinity=None,\n tolerations=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n resources=resources,\n persistence=persistence,\n node_selector=node_selector,\n affinity=affinity,\n tolerations=tolerations,\n )\n self.postgres_user = postgres_user\n self.postgres_password = postgres_password\n self.postgres_database = postgres_database\n self.conn_max_age = conn_max_age\n\n\nclass RedisSchema(ThirdPartyServiceSchema):\n image = fields.Raw(allow_none=True)\n non_broker = fields.Bool(allow_none=True)\n use_password = fields.Bool(allow_none=True)\n password = fields.Str(allow_none=True)\n\n @staticmethod\n def schema_config():\n return RedisConfig\n\n\nclass RedisConfig(ThirdPartyService):\n SCHEMA = RedisSchema\n REDUCED_ATTRIBUTES = ThirdPartyService.REDUCED_ATTRIBUTES + [\n \"nonBroker\",\n \"usePassword\",\n \"password\",\n ]\n\n def __init__(\n self,\n enabled=None,\n non_broker=None,\n use_password=None,\n password=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n resources=None,\n persistence=None,\n node_selector=None,\n affinity=None,\n tolerations=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n resources=resources,\n persistence=persistence,\n node_selector=node_selector,\n affinity=affinity,\n tolerations=tolerations,\n )\n self.non_broker = non_broker\n self.use_password = use_password\n self.password = password\n\n\nclass RabbitmqSchema(ThirdPartyServiceSchema):\n rabbitmq_username = fields.Str(allow_none=True)\n rabbitmq_password = fields.Str(allow_none=True)\n\n @staticmethod\n def schema_config():\n return RabbitmqConfig\n\n\nclass RabbitmqConfig(ThirdPartyService):\n SCHEMA = RabbitmqSchema\n REDUCED_ATTRIBUTES = ThirdPartyService.REDUCED_ATTRIBUTES + [\n \"rabbitmqUsername\",\n \"rabbitmqPassword\",\n ]\n\n def __init__(\n self,\n enabled=None,\n rabbitmq_username=None,\n rabbitmq_password=None,\n image=None,\n image_tag=None,\n image_pull_policy=None,\n replicas=None,\n resources=None,\n persistence=None,\n node_selector=None,\n affinity=None,\n tolerations=None,\n ):\n super().__init__(\n enabled=enabled,\n image=image,\n image_tag=image_tag,\n image_pull_policy=image_pull_policy,\n replicas=replicas,\n resources=resources,\n persistence=persistence,\n node_selector=node_selector,\n affinity=affinity,\n tolerations=tolerations,\n )\n self.rabbitmq_username = rabbitmq_username\n self.rabbitmq_password = rabbitmq_password\n\n\nclass ExternalServiceSchema(BaseCamelSchema):\n user = fields.Str(allow_none=True)\n password = fields.Str(allow_none=True)\n host = fields.Str(allow_none=True)\n port = fields.Int(allow_none=True)\n database = fields.Str(allow_none=True)\n use_password = fields.Bool(allow_none=True)\n conn_max_age = fields.Int(allow_none=True)\n pgbouncer = fields.Dict(allow_none=True)\n options = fields.Dict(allow_none=True)\n\n @staticmethod\n def schema_config():\n return ExternalService\n\n\nclass ExternalService(BaseConfig):\n SCHEMA = ExternalServiceSchema\n REDUCED_ATTRIBUTES = [\n \"user\",\n \"password\",\n \"host\",\n \"port\",\n \"database\",\n \"usePassword\",\n \"connMaxAge\",\n \"pgbouncer\",\n \"options\",\n ]\n\n def __init__(\n self,\n user=None,\n password=None,\n host=None,\n port=None,\n database=None,\n use_password=None,\n conn_max_age=None,\n pgbouncer=None,\n options=None,\n ):\n self.user = user\n self.password = password\n self.host = host\n self.port = port\n self.database = database\n self.use_password = use_password\n self.conn_max_age = conn_max_age\n self.pgbouncer = pgbouncer\n self.options = options\n\n\nclass ExternalBackendSchema(BaseCamelSchema):\n enabled = fields.Bool(allow_none=True)\n backend = fields.Str(allow_none=True)\n options = fields.Dict(allow_none=True)\n\n @staticmethod\n def schema_config():\n return ExternalBackend\n\n\nclass ExternalBackend(BaseConfig):\n SCHEMA = ExternalBackendSchema\n REDUCED_ATTRIBUTES = [\n \"enabled\",\n \"backend\",\n \"options\",\n ]\n\n def __init__(\n self,\n enabled=None,\n backend=None,\n options=None,\n ):\n self.enabled = enabled\n self.backend = backend\n self.options = options\n\n\nclass AuthServicesSchema(BaseCamelSchema):\n github = fields.Nested(ExternalBackendSchema, allow_none=True)\n gitlab = fields.Nested(ExternalBackendSchema, allow_none=True)\n bitbucket = fields.Nested(ExternalBackendSchema, allow_none=True)\n google = fields.Nested(ExternalBackendSchema, allow_none=True)\n saml = fields.Nested(ExternalBackendSchema, allow_none=True)\n\n @staticmethod\n def schema_config():\n return AuthServicesConfig\n\n\nclass AuthServicesConfig(BaseConfig):\n SCHEMA = AuthServicesSchema\n REDUCED_ATTRIBUTES = [\n \"github\",\n \"gitlab\",\n \"bitbucket\",\n \"google\",\n \"saml\",\n ]\n\n def __init__(\n self,\n github=None,\n gitlab=None,\n bitbucket=None,\n google=None,\n saml=None,\n ):\n self.github = github\n self.gitlab = gitlab\n self.bitbucket = bitbucket\n self.google = google\n self.saml = saml\n\n\nclass ExternalServicesSchema(BaseCamelSchema):\n redis = fields.Nested(ExternalServiceSchema, allow_none=True)\n rabbitmq = fields.Nested(ExternalServiceSchema, allow_none=True)\n postgresql = fields.Nested(ExternalServiceSchema, allow_none=True)\n gateway = fields.Nested(ExternalServiceSchema, allow_none=True)\n api = fields.Nested(ExternalServiceSchema, allow_none=True)\n transactions = fields.Nested(ExternalBackendSchema, allow_none=True)\n analytics = fields.Nested(ExternalBackendSchema, allow_none=True)\n metrics = fields.Nested(ExternalBackendSchema, allow_none=True)\n errors = fields.Nested(ExternalBackendSchema, allow_none=True)\n auth = fields.Nested(AuthServicesSchema, allow_none=True)\n allowed_versions = fields.List(fields.Str(), allow_none=True)\n\n @staticmethod\n def schema_config():\n return ExternalServicesConfig\n\n\nclass ExternalServicesConfig(BaseConfig):\n SCHEMA = ExternalServicesSchema\n REDUCED_ATTRIBUTES = [\n \"redis\",\n \"rabbitmq\",\n \"postgresql\",\n \"gateway\",\n \"api\",\n \"transactions\",\n \"analytics\",\n \"metrics\",\n \"errors\",\n \"auth\",\n \"allowedVersions\",\n ]\n\n def __init__(\n self,\n redis=None,\n rabbitmq=None,\n postgresql=None,\n gateway=None,\n api=None,\n transactions=None,\n analytics=None,\n metrics=None,\n errors=None,\n auth=None,\n allowed_versions=None,\n ):\n self.redis = redis\n self.rabbitmq = rabbitmq\n self.postgresql = postgresql\n self.gateway = gateway\n self.api = api\n self.transactions = transactions\n self.analytics = analytics\n self.metrics = metrics\n self.errors = errors\n self.auth = auth\n self.allowed_versions = allowed_versions\n","sub_path":"src/polyaxon/deploy/schemas/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":17970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"317511927","text":"import logging\nimport sys\n\nimport telepot\nfrom telepot.aio.helper import ChatHandler\n\nfrom actions import *\nfrom statemachine import DudoStateMachine\n\nBOT_NAME = \"@du2bot\"\n\n\nclass DudoHandler(ChatHandler):\n def __init__(self, *args, **kwargs):\n super(DudoHandler, self).__init__(*args, **kwargs)\n\n self.logger = logging.getLogger(\"dudo.handler\")\n self.logger.setLevel(logging.DEBUG)\n self.handler = logging.StreamHandler(sys.stdout)\n self.handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n self.handler.setFormatter(formatter)\n self.logger.addHandler(self.handler)\n\n self.context = None\n\n logger = self.logger\n\n async def on_close(e):\n logger.debug(\"Dying...\")\n if self.context is not None and not self.context.dead:\n self.context.destroy()\n self.logger.removeHandler(self.handler)\n await self.sender.sendMessage(\"You've been silent for too long. See ya next time!\")\n\n self.on_close = on_close\n\n async def on_chat_message(self, msg):\n content_type, chat_type, chat_id = telepot.glance(msg)\n\n if self.context is not None and self.context.dead:\n self.context = None\n\n if content_type != \"text\":\n return\n\n text = msg[\"text\"]\n tokens = text.split()\n\n if len(tokens) == 0:\n return\n\n command = tokens[0].lower()\n if command.endswith(BOT_NAME):\n command = command[:-len(BOT_NAME)]\n\n player = msg[\"from\"][\"id\"]\n player_name = msg[\"from\"][\"first_name\"]\n\n if self.context is None:\n await self.no_game_command(command, text, player, player_name)\n else:\n with await self.context.timeout_lock:\n await self.handle_command(command, text, player, player_name)\n\n if self.context is not None and self.context.dead:\n self.context = None\n\n async def no_game_command(self, command, text, player, player_name):\n\n if command == \"/startgame\" and self.context is None:\n self.context = DudoStateMachine(self.sender)\n with await self.context.timeout_lock:\n self.context.announce_start(player_name)\n self.context.start()\n self.context.on_input(Join(player, player_name))\n await self.context.force_announce()\n elif command == \"/help\":\n await self.sender.sendMessage(\n \"Available commands are:\\n\"\n \"\\t /startgame\\n\"\n \"\\t /endgame\\n\"\n \"\\t /join\\n\"\n \"\\t /flee\\n\"\n \"\\t /ask question ## n (n being the initial bet)\\n\"\n \"\\t /raise n (raise the bet to an integer n > 0)\\n\"\n \"\\t /calzo\\n\"\n \"\\t /dudo\\n\"\n \"\\t /help\"\n )\n\n async def handle_command(self, command, text, player, player_name):\n\n current_input = None\n if command == \"/join\":\n current_input = Join(player, player_name)\n elif command == \"/flee\":\n current_input = Flee(player)\n elif command == \"/ask\":\n\n question, initial_bet = self.parse_question(text)\n current_input = MakeQuestion(player, question, initial_bet)\n\n elif command == \"/raise\":\n\n bet = self.parse_bet(text)\n if bet is not None:\n current_input = MakeBet(player, bet)\n else:\n self.context.get_angery()\n\n elif command == \"/dudo\":\n current_input = Doubt(player)\n elif command == \"/calzo\":\n current_input = Fit(player)\n elif command == \"/endgame\" and self.context is not None:\n if self.context.game_owner == player:\n self.context.announce_cancel(player_name)\n await self.context.force_announce()\n self.context.destroy()\n self.context = None\n return\n else:\n return\n\n if self.context is not None and current_input is not None:\n self.context.on_input(current_input)\n\n if self.context is not None:\n await self.context.force_announce()\n\n async def on_callback_query(self, msg):\n query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')\n\n if self.context is not None:\n val_to_add = 1 if query_data == \"yes\" else 0\n\n with await self.context.timeout_lock:\n self.context.on_input(Answer(from_id, val_to_add))\n await self.context.force_announce()\n\n @staticmethod\n def parse_question(text):\n if len(text.split(\" \", 1)) <= 1:\n return None, None\n\n text = text.split(\" \", 1)[1]\n\n tokens = text.split(\"##\", 1)\n\n if len(tokens) < 2:\n return None, None\n\n try:\n question = tokens[0]\n initial_bet = int(tokens[1])\n\n return question, initial_bet\n\n except ValueError:\n return None, None\n\n @staticmethod\n def parse_bet(text):\n try:\n text = text.split(\" \", 1)[1]\n return int(text)\n except ValueError:\n return None\n except IndexError:\n return None\n","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"194598607","text":"#!/usr/bin/python\nimport sys\nimport nwb\nimport test_utils as ut\n\n# creates time series without 'data' field\n# TESTS softlink of TimeSeries.data\n\ndef test_softlink():\n if __file__.startswith(\"./\"):\n fname1 = \"x\" + __file__[3:-3] + \"1\" + \".nwb\"\n fname2 = \"x\" + __file__[3:-3] + \"2\" + \".nwb\"\n else:\n fname1 = \"x\" + __file__[1:-3] + \"1\" + \".nwb\"\n fname2 = \"x\" + __file__[1:-3] + \"2\" + \".nwb\"\n name1 = \"softlink_source\"\n name2 = \"softlink_reader\"\n create_softlink_source(fname1, name1, \"acquisition\")\n create_softlink_reader(fname2, name2, fname1, name1, \"acquisition\")\n #\n ut.verify_timeseries(fname1, name1, \"acquisition/timeseries\", \"TimeSeries\")\n ut.verify_timeseries(fname2, name2, \"acquisition/timeseries\", \"TimeSeries\")\n ##\n val = ut.verify_present(fname2, \"acquisition/timeseries/\"+name2, \"data\")\n\ndef create_softlink_reader(fname, name, src_fname, src_name, target):\n settings = {}\n settings[\"filename\"] = fname\n settings[\"identifier\"] = nwb.create_identifier(\"softlink reader\")\n settings[\"overwrite\"] = True\n settings[\"description\"] = \"softlink test\"\n neurodata = nwb.NWB(**settings)\n source = neurodata.create_timeseries(\"TimeSeries\", name, target)\n source.set_data_as_remote_link(src_fname, \"acquisition/timeseries/\"+src_name+\"/data\")\n source.set_time([345])\n source.finalize()\n neurodata.close()\n\ndef create_softlink_source(fname, name, target):\n settings = {}\n settings[\"filename\"] = fname\n settings[\"identifier\"] = nwb.create_identifier(\"softlink source\")\n settings[\"overwrite\"] = True\n settings[\"description\"] = \"time series no data test\"\n settings[\"start_time\"] = \"Sat Jul 04 2015 3:14:16\"\n neurodata = nwb.NWB(**settings)\n source = neurodata.create_timeseries(\"TimeSeries\", name, target)\n source.set_data([234], unit=\"parsec\", conversion=1, resolution=1e-3)\n source.set_time([123])\n source.finalize()\n neurodata.close()\n\ntest_softlink()\nprint(\"%s PASSED\" % __file__)\n\n","sub_path":"ainwb/unittest/y_softlink.py","file_name":"y_softlink.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"580131040","text":"\"\"\"code for dealing with aligned fasta\nnumpy (unsigned 8bit) representation is used:\n\nrow = seq.rec\ncol = aligned pos (with gaps starting from 0\n\n-=0\nA=1\nC=2\nG=4\nT=8\n\n\"\"\"\nimport fasta as F\nimport numpy as N\n\nimport operator\n\nbase = {0: '-',\n 1: 'A',\n 2: 'C',\n 3: 'M',\n 4: 'G',\n 5: 'R',\n 6: 'S',\n 7: 'V',\n 8: 'T',\n 9: 'W',\n 10: 'Y',\n 11: 'H',\n 12: 'K',\n 13: 'D',\n 14: 'B',\n 15: 'N',\n '-': 0,\n 'A': 1,\n 'B': 14,\n 'C': 2,\n 'D': 13,\n 'G': 4,\n 'H': 11,\n 'I': 11,\n 'K': 12,\n 'M': 3,\n 'N': 15,\n 'R': 5,\n 'S': 6,\n 'T': 8,\n 'V': 7,\n 'W': 9,\n 'Y': 10}\n\n\ndef rowsOr(mat):\n \"\"\"or the rows of a matrix\n \"\"\"\n return reduce(operator.__or__,[mat[i,:] for i in range(mat.shape[0])])\n\ndef rowVec2Str(row):\n \"\"\"\n \"\"\"\n t=[]\n for n in row:\n t.append(base[n])\n return ''.join(t)\n\ndef oneIfFound(row,n):\n \"\"\"\n \"\"\"\n return (row & n >0).astype('B')\n\n\n\nclass Alignment (dict):\n \"\"\"Holds aligned sequences\n \"\"\"\n\n\n def __init__ (self,inFasta):\n self.order=[]\n for s in F.FastaIterator(inFasta):\n self.order.append(s.title)\n self[s.title]=s\n \n self.alnLength = max([len(s) for s in self.values()])\n self.seqMat=N.zeros((len(self),self.alnLength),\n dtype='B')\n for i,k in enumerate(self.order):\n for j,b in enumerate(self[k]):\n self.seqMat[i,j]=base[b]\n\n self.seqOr=rowsOr(self.seqMat)\n\n\n def posDiversity(self):\n return reduce(operator.__add__, [oneIfFound(self.seqOr,base[c])\n for c in 'ACGT'])\n \n \n def orAllSeq(self,keys=None):\n pass\n\n def baseComp(self,start=None,end=None):\n rv={}\n \n \n \n","sub_path":"msa.py","file_name":"msa.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"137676524","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/11/26 9:36\n# @Author : llc\n# @File : standalone.py\n \nimport os, sys\nfrom qgis.core import QgsProject, QgsApplication, QgsVectorLayer\nfrom qgis.gui import QgsMapCanvas, QgsMapToolPan, QgsMapToolZoom, QgsMapToolIdentify\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QFileDialog\nfrom ui.main_ui import Ui_MainWindow\n \nos.environ['GDAL_DATA'] = r'C:\\OSGeo4W\\share\\gdal'\nos.environ['PROJ_LIB'] = r'C:\\OSGeo4W\\share\\proj'\n\nclass MapExplorer(QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(MapExplorer, self).__init__()\n self.setupUi(self)\n \n self.init_mapcanvas()\n self.slot_connect()\n \n def slot_connect(self):\n self.action_open.triggered.connect(self.action_open_triggered)\n self.action_basemap.triggered.connect(self.action_basemap_triggered)\n self.action_mark.triggered.connect(self.action_mark_triggered)\n self.action_zoomin.triggered.connect(self.action_zoomin_triggered)\n self.action_zoomout.triggered.connect(self.action_zoomout_triggered)\n self.action_pan.triggered.connect(self.action_pan_triggered)\n self.action_identify.triggered.connect(self.action_identify_triggered)\n \n def init_mapcanvas(self):\n self.mapCanvas = QgsMapCanvas()\n self.mapCanvas.xyCoordinates.connect(self.show_lonlat)\n self.mapCanvas.setCanvasColor(Qt.white)\n # self.mapCanvas.show()\n layout = QVBoxLayout(self.centralwidget)\n layout.setContentsMargins(0, 0, 0, 0)\n layout.addWidget(self.mapCanvas)\n \n def loadMap(self, fullpath):\n print(fullpath)\n self.layer = QgsVectorLayer(fullpath, \"shp\", \"ogr\")\n QgsProject.instance().addMapLayer(self.layer)\n self.mapCanvas.setLayers([self.layer])\n self.mapCanvas.setExtent(self.layer.extent())\n self.mapCanvas.refresh()\n \n def action_open_triggered(self):\n fullpath, format = QFileDialog.getOpenFileName(self, '打开数据', '', '*.shp')\n if os.path.exists(fullpath):\n self.loadMap(fullpath)\n \n def action_basemap_triggered(self):\n pass\n \n def action_mark_triggered(self):\n pass\n \n def action_zoomin_triggered(self):\n self.maptool = QgsMapToolZoom(self.mapCanvas, False)\n self.mapCanvas.setMapTool(self.maptool)\n \n def action_zoomout_triggered(self):\n self.maptool = QgsMapToolZoom(self.mapCanvas, True)\n self.mapCanvas.setMapTool(self.maptool)\n \n def action_pan_triggered(self):\n self.maptool = QgsMapToolPan(self.mapCanvas)\n self.mapCanvas.setMapTool(self.maptool)\n \n def action_identify_triggered(self):\n self.maptool = QgsMapToolIdentify(self.mapCanvas)\n self.mapCanvas.setMapTool(self.maptool)\n \n def show_lonlat(self, point):\n x = point.x()\n y = point.y()\n self.statusbar.showMessage(f'经度:{x},纬度:{y}')\n \n \ndef main():\n qgs = QgsApplication([], True)\n qgs.setPrefixPath('qgis', True)\n qgs.initQgis()\n \n window = MapExplorer()\n window.show()\n \n exit_code = qgs.exec_()\n qgs.exitQgis()\n sys.exit(exit_code)\n \n \nif __name__ == '__main__':\n main()","sub_path":"standalone_app.py","file_name":"standalone_app.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"270588749","text":"\"\"\"\nA PyCUDA program, to make the most of available resources, should respect the rules\ndictated by the structure and the internal organization of the SM that imposes constraints on\nthe performance of the thread. In particular, the knowledge and correct use of the various\ntypes of memory that the GPU makes available is fundamental in order to achieve maximum\neffciency in the programs. In the CUDA-capable GPU card, there are four types of memories,\nwhich are defned, as follows:\n\nf Registers: In this, a register is allocated for each thread. This can only access its\nregister but not the registers of other threads, even if they belong to the same block.\n\nf The shared memory: Here, each block has its own shared memory between the\nthreads that belong to it. Even this memory is extremely fast.\n\nf The constant memory: All threads in a grid have constant access to the memory,\nbut can be accessed only while reading. The data present in it persists for the entire\nduration of the application.\n\nf The global memory: All threads of all the grids (so all kernels) have access to the\nglobal memory. The constant memory data present in it persists for the entire\nduration of the application.\n\n\nOne of the key points to understand how to make the PyCUDA programs with satisfactory\nperformance is that not all memory is the same, but you have to try to make the best of each\ntype of memory. The basic idea is to minimize the global memory access via the use of the\nshared memory. The technique is usually used to divide the domain/codomain of the problem\nin such a way so that we enable a block of threads to perform its elaborations in a closed\nsubset of data. In this way, the threads adhering to the concerned block will work together to\nload the shared global memory area that is to be processed in the memory, to then proceed to\nexploiting the higher speed of this memory zone.\n\n\nThe basic steps to be performed for each thread will then be as follows:\n1. Load data from the global memory to the shared memory.\n\n2. Synchronize all the threads of the block so that everyone can read safety positions\nshared memory flled by other threads.\n\n3. Process the data of the shared memory.\n\n4. Make a new synchronization as necessary to ensure that the shared memory has\nbeen updated with the results.\n\n5. Write the results in the global memory.\n\"\"\"\n\nimport numpy as np\nfrom pycuda import driver, compiler, gpuarray\n\n# -- initialize the device\nimport pycuda.autoinit\n\n# note: thread (x, y) == np (1, 0)\nkernel_code_template = \"\"\"\n__global__ void MatrixMulKernel(float *a, float *b, float *c)\n{\n int tx = threadIdx.x;\n int ty = threadIdx.y;\n float Pvalue = 0;\n for (int k=0; k<%(MATRIX_SIZE)s; ++k){\n float Aelement = a[ty*%(MATRIX_SIZE)s+k];\n float Belement = b[k*%(MATRIX_SIZE)s+tx];\n Pvalue += Aelement*Belement;\n }\n c[ty*%(MATRIX_SIZE)s+tx] = Pvalue;\n}\n\"\"\"\nMATRIX_SIZE = 5\n\na_cpu = np.random.randn(MATRIX_SIZE, MATRIX_SIZE).astype(np.float32)\nb_cpu = np.random.randn(MATRIX_SIZE, MATRIX_SIZE).astype(np.float32)\nc_cpu = np.dot(a_cpu, b_cpu)\na_gpu = gpuarray.to_gpu(a_cpu)\nb_gpu = gpuarray.to_gpu(b_cpu)\n\nc_gpu = gpuarray.empty((MATRIX_SIZE, MATRIX_SIZE), np.float32)\nkernel_code = kernel_code_template%{\n 'MATRIX_SIZE': MATRIX_SIZE\n }\n\nmod = compiler.SourceModule(kernel_code)\n\nmatrixmul = mod.get_function('MatrixMulKernel')\n\nmatrixmul(\n a_gpu, b_gpu,\n c_gpu,\n block = (MATRIX_SIZE, MATRIX_SIZE, 1)\n )\n\n# print the results\nprint('-'*80)\nprint('Matrix A (GPU):')\nprint(a_gpu.get())\n\nprint('-'*80)\nprint('Matrix B (GPU):')\nprint(b_gpu.get())\n\nprint('-'*80)\nprint('Matrix C (GPU):')\nprint(c_gpu.get())\n\nprint('-'*80)\nprint('Matrix A (CPU):')\nprint(a_cpu)\n\nprint('-'*80)\nprint('Matrix B (CPU):')\nprint(b_cpu)\n\nprint('-'*80)\nprint('Matrix C (CPU):')\nprint(c_cpu)\n\nprint('-'*80)\nprint('CPU-GPU difference:')\nprint(c_cpu-c_gpu.get())\n\nprint('all close?', np.allclose(c_cpu, c_gpu.get()))\n","sub_path":"ParallelProgramming/GPUProgramming/matrixmanipulation_pycuda.py","file_name":"matrixmanipulation_pycuda.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"63765517","text":"#coding=utf-8\n\n\"\"\"\nCreated on 2020/11/18\n@author: lianxiujuan\n@desc: 物料管理\n\"\"\"\n\nimport pytest\nimport sys\nimport random,string\nfrom DataApp.MaterialData import *\nfrom src.public.common.Login import *\nfrom src.pageobjectAPP.pageMaterial import *\nfrom src.public.common.Select_Item import *\nfrom src.public.common.Search_Item import *\n# from src.public.common.Close_current_tab import *\n\n\naddcodedata = ''.join(random.sample(string.ascii_letters + string.digits, 4))\naddnamedata = ''.join(random.sample(string.ascii_letters + string.digits, 4))\neditnamedata = ''.join(random.sample(string.ascii_letters + string.digits, 4))\ncopycodedata = ''.join(random.sample(string.ascii_letters + string.digits, 4))\n\n\nclass Test_Material:\n def setup_class(self):\n app_login(username, password)\n login_material()\n\n # def teardown_class(self):\n # Close_current_tab()\n # app_logout()\n\n # 新增物料\n def test_add_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n material_add(addcodedata, addnamedata, adddescdata)\n time.sleep(2)\n assert new_page_source(addcodedata)\n\n # 搜索物料\n def test_search_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n search_item(\"编码\", addcodedata)\n time.sleep(2)\n text = new_get_text(firstdata_app)\n time.sleep(2)\n assert addcodedata in text\n search_item(\"编码\", ' ')\n time.sleep(2)\n\n # 编辑物料\n def test_edit_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addcodedata)\n material_edit(editnamedata)\n time.sleep(2)\n assert new_page_source(editnamedata)\n\n # 复制物料\n def test_copy_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n material_copy(copycodedata)\n time.sleep(2)\n assert new_page_source(copycodedata)\n\n # 验证物料\n def test_verify_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addcodedata)\n material_verify()\n search_item('编码', addcodedata)\n time.sleep(2)\n assert new_page_source(\"已验证\")\n search_item(\"编码\", ' ')\n\n # 取消验证物料\n def test_cancelverify_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addcodedata)\n material_cancelverify()\n search_item('编码', addcodedata)\n time.sleep(2)\n assert new_page_source(\"可编辑\")\n search_item(\"编码\", ' ')\n\n # 失效物料\n def test_noeffect_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addcodedata)\n material_noeffect()\n search_item('编码', addcodedata)\n time.sleep(2)\n assert new_page_source(\"失效的\")\n search_item(\"编码\", ' ')\n\n # 生效物料\n def test_effect_material(self):\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n select_item(addcodedata)\n material_effect()\n search_item('编码', addcodedata)\n time.sleep(2)\n assert new_page_source(\"可编辑\")\n search_item(\"编码\", ' ')\n\n\n\n\nif __name__ == '__main__':\n pytest.main(['-s','test_material.py'])\n","sub_path":"TestcaseApp/Material/test_Material.py","file_name":"test_Material.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"191863634","text":"from collections import deque\n\n\nn, k = map(int, input().split())\nq = deque(range(1, n + 1))\n\norder = []\nwhile q:\n for _ in range(k - 1):\n q.append(q.popleft())\n order.append(str(q.popleft()))\n\nanswer = '<'\nanswer += ', '.join(order)\nanswer += '>'\nprint(answer)\n","sub_path":"BJ/Queue&deque/11866_Josephus.py","file_name":"11866_Josephus.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"146207211","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nfrom command_3.validator_3 import command3\nfrom utils import temporary_file\n\n\nCONTENT = [\n u'ทางไปรษณีย์เป็นต้น [overlap] [overlap]\\n', # 0\n u'อีกทั้งพลังงานภาคการผลิตต่าง [overlap] ๆ [overlap]\\n', # 1\n u'[music]\\n', # 2\n u'We have the order up here [lipsmack] and we believe\\n', # 3\n u'#uh [cough] sorry, school counselor candidate too [cough]\\n', # 4\n u'#uh [cough] sorry, school counselor candidate too [coughy]\\n', # 5\n u'[sta] Velkommen til [sta] Troldespejlet Podcast nummer tolv,\\n', # 6\n u'[sta] [stay] Velkommen til Troldespejlet Podcast nummer tolv,\\n', # 7\n u'[breath]Et ega sul ju seal [breath] Otepää majal ma ei tea, kui tugev katus on.\\n', # 8\n u'[breath] Et ega sul ju seal[breath] Otepää majal ma ei tea, kui tugev katus on.\\n', # 9\n u'[breath] Et ega sul ju seal[breath]Otepää majal ma ei tea, kui tugev katus on.\\n', # 10\n]\nEXCLUDES = [1, 2, 3, 4, 6]\nCATCHES = [0, 5, 7, 8, 9, 10]\n\n\ndef test_command_3(tmpdir):\n file_ = temporary_file(tmpdir, CONTENT)\n found = command3(file_)\n\n for key in sorted(found.keys()):\n print(key, found[key])\n\n for item in EXCLUDES:\n assert item not in found\n\n for item in CATCHES:\n assert item in found\n\n #assert 0\n","sub_path":"src/tests/test_command_3.py","file_name":"test_command_3.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"227409464","text":"import os\nimport tensorflow as tf\nimport shutil\n\n# https://www.kaggle.com/competitions/dogs-vs-cats-redux-kernels-edition\nprint(len(os.listdir(\"/data/dogs-vs-cats-redux-kernels-edition/train\")))\n\n# for i in os.listdir(\"/data/dogs-vs-cats-redux-kernels-edition/train/\"):\n# if 'cat' in i:\n# # shutil.copyfile(어떤파일을, 어떤경로로)\n# shutil.copyfile(\"/data/dogs-vs-cats-redux-kernels-edition/train/\" + i, \"/data/dogs-vs-cats-redux-kernels-edition/dataset/cat/\" + i)\n# if 'dog' in i:\n# shutil.copyfile(\"/data/dogs-vs-cats-redux-kernels-edition/train/\" + i, \"/data/dogs-vs-cats-redux-kernels-edition/dataset/dog/\" + i)\n \n\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\n '/data/dogs-vs-cats-redux-kernels-edition/dataset',\n image_size=(64, 64),\n batch_size=64,\n subset='training',\n validation_split=0.2,\n seed=1234\n)\n\nval_ds = tf.keras.preprocessing.image_dataset_from_directory(\n '/data/dogs-vs-cats-redux-kernels-edition/dataset',\n image_size=(64, 64),\n batch_size=64,\n subset='validation',\n validation_split=0.2,\n seed=1234\n)\n\nprint(train_ds)\n# def 전처리함수(이미지, 정답):\n# 이미지 = tf.cast(이미지, tf.float32) / 255.0\n# return 이미지, 정답\ndef 전처리함수(i, 정답):\n i = tf.cast(i / 255.0, tf.float32)\n return i, 정답\n\ntrain_ds = train_ds.map(전처리함수)\nval_ds = train_ds.map(전처리함수)\n\n# import matplotlib.pyplot as plt\n\nfor i, 정답 in train_ds.take(1):\n print(i)\n print(정답)\n # print(i.shape)\n# print(정답.shape)\n# plt.imshow(i[0].numpy().astype('uint8'))\n# plt.show()\n# exit()\n\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Conv2D(32, (3, 3), padding='same', activation='relu', input_shape=(64, 64, 3) ),\n tf.keras.layers.MaxPooling2D( (2, 2) ),\n tf.keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'),\n tf.keras.layers.MaxPooling2D( (2, 2) ),\n tf.keras.layers.Conv2D(128, (3, 3), padding='same', activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.MaxPooling2D( (2, 2) ),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(1, activation='sigmoid'),\n])\n\nmodel.summary()\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(train_ds, validation_data=val_ds, epochs=5)","sub_path":"codingapple/dogs_vs_cats.py","file_name":"dogs_vs_cats.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"352584046","text":"import numpy as np\n\nedge_length = (1 << 16) + 1\nmax_hue = 6 * edge_length\nmax_sat = 0xFFFF\nmax_val = 0xFF\n\n\ndef rgb_to_hsv(arr):\n \"\"\"\n This is an implementation of the algorithm by Chernow, Alander & Bochko (2015):\n \"Integer-based accurate conversion between RGB and HSV color spaces\"\n\n It takes a numpy array of 8-bit unsigned integer RGB 3-element arrays and returns\n integer triples for HSV values. These have the range:\n\n - H: 0 - 393222\n - S: 0 - 65535 (0xFFFF)\n - V: 0 - 255 (0xFF\n\n It has been confirmed to be accurate to within 1e-05 of the values returned\n by colorsys.rgb_to_hsv for the entire input domain.\n \"\"\"\n\n # broaden the array straight away to ensure we don't encounter overflows\n arr32 = arr.astype(\"uint32\")\n arr_max = arr32.max(-1)\n arr_min = arr32.min(-1)\n delta = arr_max - arr_min\n\n # handle divide-by-zero errors gracefully\n with np.errstate(divide=\"ignore\", invalid=\"ignore\"):\n s = ((delta << 16) - 1) // arr_max\n s[delta == 0] = 0\n out = np.zeros_like(arr32)\n\n diff_0_1 = np.abs(arr32[..., 0] - arr32[..., 1])\n diff_0_2 = np.abs(arr32[..., 0] - arr32[..., 2])\n diff_1_2 = np.abs(arr32[..., 1] - arr32[..., 2])\n\n # red is max, blue is min\n idx = (arr32[..., 0] == arr_max) & (arr32[..., 2] == arr_min)\n out[idx, 0] = 1 + ((diff_1_2[idx] << 16) // delta[idx])\n\n # green is max, blue is min\n idx = (arr32[..., 1] == arr_max) & (arr32[..., 2] == arr_min)\n out[idx, 0] = (2 * edge_length) - (1 + ((diff_0_2[idx] << 16) // delta[idx]))\n\n # green is max, red is min\n idx = (arr32[..., 1] == arr_max) & (arr32[..., 0] == arr_min)\n out[idx, 0] = (2 * edge_length) + (1 + (((-diff_0_2[idx]) << 16) // delta[idx]))\n\n # blue is max, red is min\n idx = (arr32[..., 2] == arr_max) & (arr32[..., 0] == arr_min)\n out[idx, 0] = (4 * edge_length) - (1 + (((-diff_0_1[idx]) << 16) // delta[idx]))\n\n # blue is max, green is min\n idx = (arr32[..., 2] == arr_max) & (arr32[..., 1] == arr_min)\n out[idx, 0] = (4 * edge_length) + (1 + ((diff_0_1[idx] << 16) // delta[idx]))\n\n # red is max, green is min\n idx = (arr32[..., 0] == arr_max) & (arr32[..., 1] == arr_min)\n out[idx, 0] = (6 * edge_length) - (1 + (((-diff_1_2[idx]) << 16) // delta[idx]))\n\n out[..., 1] = s\n out[..., 2] = arr_max\n\n return out / [max_hue, max_sat, max_val]\n\n\ndef rgb_to_hex(r, g, b):\n return \"%02x%02x%02x\" % (r, g, b)\n","sub_path":"pipeline/inferrer/palette_inferrer/app/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"256383905","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/8/6 23:21\n# @Author : pankui\n# @Site : https://github.com/pankui\n# @File : pillow_demo.py\n# @Software: PyCharm\n\nfrom PIL import Image\n\n# 打开一个jpg图像文件,注意是当前路径:\nim = Image.open('test.jpg')\n# 获得图像尺寸:\nw, h = im.size\nprint('Original image size: %sx%s' % (w, h))\n# 缩放到50%:\nim.thumbnail((w//2, h//2))\nprint('Resize image to: %sx%s' % (w//2, h//2))\n# 把缩放后的图像用jpeg格式保存:\nim.save('thumbnail.jpg', 'jpeg')\n\n\n\nfrom PIL import Image, ImageFilter\n\n# 打开一个jpg图像文件,注意是当前路径:\nim = Image.open('test.jpg')\n# 应用模糊滤镜:\nim2 = im.filter(ImageFilter.BLUR)\nim2.save('blur.jpg', 'jpeg')","sub_path":"python-learn/basis/third_party_modules/pillow_demo.py","file_name":"pillow_demo.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"3422477","text":"import logging\nfrom collections import Counter\n\nimport numpy as np\nfrom typing import Mapping, Sequence\n\nimport torch\nimport torch.utils.data\nfrom torch import Tensor\nfrom tqdm import tqdm\n\nfrom nmtg.data.dictionary import Dictionary\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_embedding(embed_path):\n \"\"\"Parse embedding text file into a dictionary of word and embedding tensors.\n\n The first line can have vocabulary size and dimension. The following lines\n should contain word and embedding separated by spaces.\n\n Example:\n 2 5\n the -0.0230 -0.0264 0.0287 0.0171 0.1403\n at -0.0395 -0.1286 0.0275 0.0254 -0.0932\n \"\"\"\n embed_dict = {}\n with open(embed_path) as f_embed:\n next(f_embed) # skip header\n for line in f_embed:\n pieces = line.rstrip().split(\" \")\n embed_dict[pieces[0]] = torch.tensor([float(weight) for weight in pieces[1:]])\n return embed_dict\n\n\ndef load_embedding(embed_dict, vocab: Dictionary, embedding):\n for idx in range(len(vocab)):\n token = vocab.symbol(idx)\n if token in embed_dict:\n embedding.weight.data[idx] = embed_dict[token]\n return embedding\n\n\ndef get_indices_and_vocabulary(filenames, split_words=True, lower=False, progress_bar=True, report_every=100000):\n offsets = [[0] for _ in filenames]\n lengths = [[] for _ in filenames]\n counters = [Counter() for _ in filenames]\n\n file_handles = [open(filename) for filename in filenames]\n\n try:\n with tqdm(unit='lines', disable=not progress_bar) as pbar:\n i = 0\n lines = [f.readline() for f in file_handles]\n while all(line != '' for line in lines):\n proc_lines = [line.rstrip() for line in lines]\n\n if lower:\n proc_lines = [line.lower() for line in lines]\n if split_words:\n proc_lines = [line.split() for line in lines]\n\n for offset, f in zip(offsets, file_handles):\n offset.append(f.tell())\n\n for length, counter, line in zip(lengths, counters, proc_lines):\n length.append(len(line))\n counter.update(line)\n\n i += 1\n\n if i % report_every == 0:\n logger.info('{:,} lines processed'.format(i))\n\n lines = [f.readline() for f in file_handles]\n pbar.update()\n\n if any(line != '' for line in lines):\n logger.warning('Files are not the same length')\n finally:\n for f in file_handles:\n f.close()\n\n return list(zip(offsets, lengths, counters))\n\n\ndef generate_length_based_batches_from_samples(samples, length_per_batch, max_examples_per_batch=128,\n batch_size_align=1, count_padding=True, key_fn=None,\n len_fn=None, filter_fn=None):\n \"\"\"\n Generate batches of indices such that the total length of each batch does not exceed length_per_batch.\n :param samples: An iterable of samples\n :param length_per_batch: Maximum total length per batch\n :param max_examples_per_batch: Maximum number of samples per batch\n :param batch_size_align: Make sure batch size is a multiple of this number,\n unless it would be smaller than this number\n :param count_padding: Count padding against the total length of the batch\n :param key_fn: Optional function to get a sort key from a sample\n :param len_fn: Optional function to get the length of a sample\n :param filter_fn: Optional function that takes a sample and returns a boolean.\n Use only those examples where the function returns True\n :return: A list of batches. Each batch is a list of integer indices\n \"\"\"\n if len_fn is None:\n len_fn = len\n if key_fn is None:\n key_fn = len\n if filter_fn is None:\n filter_fn = lambda x: True\n\n lengths = np.empty(len(samples), np.long)\n keys = []\n filtered = []\n for i, sample in enumerate(samples):\n lengths[i] = len_fn(sample)\n filtered.append(filter_fn(sample))\n keys.append(key_fn(sample))\n indices = sorted(filter(lambda x: filtered[x], range(len(lengths))), key=keys.__getitem__)\n\n return _generate_length_based_batches(lengths, indices, length_per_batch, max_examples_per_batch,\n batch_size_align, count_padding)\n\n\ndef generate_length_based_batches_from_lengths(lengths, length_per_batch, max_examples_per_batch=128,\n batch_size_align=1, count_padding=True, key_fn=None, filter_fn=None):\n \"\"\"\n Generate batches of indices such that the total length of each batch does not exceed length_per_batch.\n :param lengths: A list of lengths for all samples\n :param length_per_batch: Maximum total length per batch\n :param max_examples_per_batch: Maximum number of samples per batch\n :param batch_size_align: Make sure batch size is a multiple of this number,\n unless it would be smaller than this number\n :param count_padding: Count padding against the total length of the batch\n :param key_fn: Optional function to get a sort key from a sample index\n :param filter_fn: Optional function that takes an index and returns a boolean.\n Use only indices where the function returns True\n :return: A list of batches. Each batch is a list of integer indices\n \"\"\"\n if key_fn is None:\n key_fn = lengths.__getitem__\n if filter_fn is None:\n filter_fn = lambda x: True\n\n indices = sorted(filter(filter_fn, range(len(lengths))), key=key_fn)\n\n return _generate_length_based_batches(lengths, indices, length_per_batch, max_examples_per_batch,\n batch_size_align, count_padding)\n\n\ndef _generate_length_based_batches(lengths, indices, length_per_batch, max_examples_per_batch=128,\n batch_size_align=1, count_padding=True):\n # indices are the indices of samples, sorted by length and filtered\n\n batches = []\n cur_batch = []\n cur_batch_size = 0\n cur_batch_sizes = []\n sample_length = -1\n\n def batch_is_full():\n \"\"\"Returns True if the batch would exceed the maximum size if we added the current example\"\"\"\n\n if len(cur_batch) == max_examples_per_batch:\n return True\n\n if count_padding:\n # because data is sorted by length, the current length is the longest one so far\n longest_length = sample_length\n\n if len(cur_batch_sizes) > 0:\n longest_length = max(max(cur_batch_sizes), sample_length)\n\n return longest_length * (len(cur_batch) + 1) > length_per_batch\n else:\n return cur_batch_size + sample_length > length_per_batch\n\n for i in indices:\n sample_length = lengths[i]\n\n if batch_is_full():\n current_size = len(cur_batch)\n\n scaled_size = current_size\n # cut down batch size to a multiple of batch_size_align\n if current_size > batch_size_align:\n scaled_size = batch_size_align * (current_size // batch_size_align)\n\n trunc_batch = cur_batch[:scaled_size]\n if batch_size_align > 1:\n assert (len(trunc_batch) < batch_size_align or len(trunc_batch) % batch_size_align == 0), \\\n 'Batch size is not a multiple of {}, current batch_size is {}' \\\n .format(batch_size_align, len(trunc_batch))\n batches.append(trunc_batch) # add this batch into the batch list\n\n cur_batch = cur_batch[scaled_size:] # reset the current batch\n cur_batch_sizes = cur_batch_sizes[scaled_size:]\n cur_batch_size = sum(cur_batch_sizes)\n\n cur_batch.append(i)\n cur_batch_size += sample_length\n cur_batch_sizes.append(sample_length)\n\n if len(cur_batch) > 0:\n batches.append(cur_batch)\n\n return batches\n\n\ndef collate_tensor_structures(samples):\n \"\"\"Collates structures of tensors of the same shape. Keeps the structure\"\"\"\n assert len(samples) > 0\n test = samples[0]\n\n if isinstance(test, Tensor):\n return torch.stack(samples)\n elif isinstance(test, Mapping):\n return {k: collate_tensor_structures([item[k] for item in samples]) for k in test.keys()}\n elif isinstance(test, Sequence):\n return [collate_tensor_structures([item[i] for item in samples]) for i in range(len(test))]\n else:\n raise NotImplementedError\n\n\ndef collate_sequences(samples, pad, align_right=False):\n \"\"\"Collates 1D tensors of different length with padding.\"\"\"\n lengths = [x.size(0) for x in samples]\n max_length = max(lengths)\n # initialize with batch_size * length first\n tensor = samples[0].new(len(samples), max_length).fill_(pad)\n\n def copy_tensor(src, dst):\n dst.copy_(src)\n\n for i, sample in enumerate(samples):\n copy_tensor(sample, tensor[i][max_length - lengths[i]:] if align_right else\n tensor[i][:lengths[i]])\n\n return tensor, torch.tensor(lengths)\n","sub_path":"nmtg/data/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":9191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"143621758","text":"#!/usr/bin/env python\n# --*-- coding: UTF-8 --*--\n\nimport argparse\nimport parser\nimport os\nimport shutil\nimport metadata\nimport output\nimport process\n\ndef parseArgs():\n\t\"\"\" \n\tParse command line arguments.\n\t\n\t:return:\tcommand line \n\t:rtype:\targument object\n\t\"\"\"\n\tparser = argparse.ArgumentParser(description='add traces to .smali files with a given tag to be able to get the runtime method calls using logcat')\n\t\n\tparser.add_argument('-f', '--folder', dest = 'current_dir', help = 'root folder containing the .smali code files', type = str, required = True)\n\tparser.add_argument('-t', '--tag', dest = 'tag', help = 'tag name to use to debug with logcat (default: my_tag)', type = str, default = 'my_tag')\n\t\n\targs = parser.parse_args()\n\t\n\treturn args\n\t\t\t\ndef copy_my_custom_class(current_dir, my_tag):\n\tsubdirs = os.listdir(current_dir)\n\tfor subdir in subdirs:\n\t\t# We have to check that we are in the correct android directory (a hint is that there the UnusedStub.smali file)\n\t\tif (subdir == 'android'):\n\t\t\tif (os.path.exists(os.path.join(current_dir, subdir, 'support'))):\n\t\t\t\tmy_custom_class_path = os.path.join(current_dir, subdir, 'MyCustomClass.smali')\n\t\t\t\tshutil.copyfile('./files/MyCustomClass.smali', my_custom_class_path)\n\t\t\t\tprocess.edit_my_custom_class(my_custom_class_path, my_tag)\t\n\t\t\t\treturn (my_custom_class_path)\n\t\n\tmy_custom_class_path = copy_my_custom_class(os.path.dirname(current_dir), my_tag)\n\treturn (my_custom_class_path)\n\t\ndef main():\n\t\n\tprint('smali-code-injector')\n\tprint('by Alexandre Teyar\\n')\n\n\targs = parseArgs()\n\tif not os.path.exists(args.current_dir):\n\t\tprint('{0} does not exist, try with a valid folder containing .smali files... \\n ' .format(args.current_dir))\n\t\n\telse:\t\t\n\t\tcurrent_dir = args.current_dir\n\t\tmy_tag = args.tag\n\t\tmy_metadata = {}\n\t\t\n\t\tmy_metadata = metadata.get_metadata(current_dir, my_metadata)\n\t\toutput.print_processing_info(current_dir, my_metadata)\n\t\t\n\t\tmy_custom_class_path = copy_my_custom_class(current_dir, my_tag)\n\t\tprocess.process_all(current_dir, my_custom_class_path,my_metadata)\n\t\nif __name__ == '__main__':\n\tmain()\n","sub_path":"smali-code-injector.py","file_name":"smali-code-injector.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"322164755","text":"#! /data/data/com.termux/files/usr/bin/python3\n\n### This file contains a couple of input verification functions\n\nfrom database import Database\nimport os\nfrom serving import Serving\nimport sys\nimport time\nfrom utilities import *\n\nDEBUG=False\n\ndef add_meal(msg,db):\n list_items(db)\n meal_index = get_number(msg,int)\n while meal_index > len(db) or meal_index < 0:\n meal_index = get_number(msg)\n serving_type = db[meal_index].description\n if serving_type[-1] != 's':\n serving_type += 's'\n if serving_type == \"\":\n serving_type = \"servings\"\n servings = get_number(\"Enter the number of \" + serving_type + \": \",float)\n return db[meal_index],servings\n\ndef create_new_food_item(db):\n list_items(db)\n macros = [0,0,0]\n macros_dict = {0:\"Carbs: \",1:\"Fats: \",2: \"Protein: \"}\n\n food_name = get_string(\"Enter the name of the food: \")\n print(\"Enter the carbs, fats, and protein in grams per serving\")\n \n for i in range(3):\n macros[i] = get_number(macros_dict[i],float)\n if not isinstance(macros[i],float):\n print(\"Unable to parse macros.\")\n sys.exit(0)\n serving_description = get_string(\"Enter a serving description: (i.e. macros PER WHAT): \")\n new_serving = Serving(food_name,macros,serving_description)\n db.add(new_serving)\n\ndef get_current_log(log_path):\n lines = []\n quantities = []\n current_log = \"\"\n is_path = path_exists(log_path)\n if is_path:\n with open(log_path,\"r\") as f:\n for line in f:\n lines.append(line.split(\"\\t\")[1].strip())\n quantities.append(line.split(\"\\t\")[0].strip())\n f.seek(0)\n current_log = f.read()\n return [current_log,lines,quantities]\n\n# This will be used to write a meal entry to the file which reads the data from the log in the path provided\ndef add_to_log(serving,servings,log_path):\n current_log,lines,quantities = get_current_log(log_path)\n if current_log == \"\":\n with open(log_path,\"w\") as f:\n print(\"Writing in empty log\")\n f.write(str(servings)+\"\\t\" + repr(serving) + \"\\n\")\n f.write(str(format(servings*(serving.carbs*4 + serving.fats*9 + serving.protein*4),\".2f\")) + \"\\t\" + str(servings*serving.carbs) + \",\" + str(servings*serving.fats) + \",\" + str(servings*serving.protein))\n else:\n calories = float(quantities.pop(-1).strip())\n macros = lines.pop(-1).strip()\n\n carbs,fats,protein = macros.split(\",\")\n carbs = float(carbs) + servings*serving.carbs\n fats = float(fats) + servings*serving.fats\n protein = float(protein) + servings*serving.protein\n\n if repr(serving) in lines:\n index = lines.index(repr(serving))\n quantities[index] = float(quantities[index]) + servings\n else:\n for i in range(len(lines)):\n if serving.name <= lines[i]:\n lines.insert(i,repr(serving))\n quantities.insert(i,servings)\n break\n elif i == len(lines)-1:\n lines.append(repr(serving))\n quantities.append(servings)\n\n calories = carbs*4 + fats*9 + protein*4\n\n quantities.append(calories)\n lines.append(str(format(carbs,\".2f\")) + \",\" + str(format(fats,\".2f\")) + \",\" + str(format(protein,\".2f\")))\n\n with open(log_path,\"w\") as f:\n for i in range(len(lines)):\n f.write(str(quantities[i]) + \"\\t\" + lines[i] + \"\\n\")\n\ndef show_meals(log_path):\n if os.path.isfile(log_path):\n current_log,lines,quantities = get_current_log(log_path)\n calories = quantities.pop(-1)\n carbs,fats,protein = lines.pop(-1).split(\",\")\n for quantity,line in zip(quantities,lines):\n print(str(quantity) + \"\\t\" + str(line))\n print(\"\\nTotal Calories: %.2f\\nCarbs: %.2f\\nFats: %.2f g\\nProtein: %.2f g\" % (float(calories),float(carbs),float(fats),float(protein)))\n else:\n print(\"No logs exist currently.\")\n\n# Function to estimate the macronutrients of a food entry\ndef estimate_calories(log_path):\n print(\"Estimate entry calories called. (Functionality not yet added.)\")\n current_log,lines,quantities = get_current_log(log_path)\n\n## Delete entry from meal log (removal of calories and macros)\ndef delete_entry(db,log_path):\n current_log,lines,quantities = get_current_log(log_path)\n list_items(db)\n meal_index = get_number(\"Enter the index of the item to remove servings from: \",int) \n if not db[meal_index].name in current_log:\n print(\"Food not found in current log.\")\n return\n for i, line in enumerate(lines):\n if db[meal_index].name in line:\n quantity = quantities[i]\n break\n # Get the number of servings to remove. If the number exceeds the servings in the current logged entry then return to the main loop.\n serving_type = db[meal_index].description\n if not serving_type[-1] == 's':\n serving_type += \"s\"\n print(quantity + \" \" + serving_type + \":\\t\" + line)\n servings_to_remove = get_number(\"Enter number of \" + serving_type + \" to remove: \",float)\n if servings_to_remove > float(quantity):\n print(\"\\nNegative values encountered. Returning to main.\")\n return \n carb_ratio = db[meal_index].carbs\n fat_ratio = db[meal_index].fats\n protein_ratio = db[meal_index].protein\n\n # Macronutrients to be removed\n carbs_neg = servings_to_remove*carb_ratio\n fat_neg = servings_to_remove*fat_ratio\n protein_neg = servings_to_remove*protein_ratio\n\n carbs,fats,protein = convert(lines[-1].split(\",\"),float)\n carbs -= carbs_neg\n fats -= fat_neg\n protein -= protein_neg\n calories = str(carbs*4 + fats*9 + protein*4)\n carbs,fats,protein = convert([carbs,fats,protein],str)\n quantities[-1] = calories\n lines[-1] = carbs + \",\" + fats + \",\" + protein\n\n new_lines = []\n\n # Reassemble the lines for the food log\n for i, line in enumerate(lines):\n if db[meal_index].name in line:\n quantities[i] = str(float(quantities[i]) - servings_to_remove)\n if float(quantities[i]) != 0:\n new_lines.append(quantities[i] + \"\\t\" + line)\n print(\"Original: \\n\"+ current_log)\n with open(log_path,\"w\") as f:\n for line in new_lines:\n f.write(line + \"\\n\")\ndef search_database(db):\n list_items(db)\n search_string = input(\"Enter search string: \")\n results = find(search_string,db)\n for result in results:\n print(result)\n \n# TODO: \ndef view_previous_logs():\n year = get_number(\"Year: \", int)\n month = get_number(\"Month: \", int)\n day = get_number(\"Day: \", int)\n\n# This very simple program will execute sequentially, and will exit if anything goes wrong.\n# There are only two main options: 1. Meal entries, or 2. Create new food items for the database\n\n# There are some inconsistencies with how the global and local variables are handled inside functions...\n\n\n\n# First thing to do is get the database\nif DEBUG:\n # Debug dirs\n database_dir = \"/data/data/com.termux/files/home/diet/debug/\"\n log_dir = \"/data/data/com.termux/files/home/diet/debug/\"\n filename = \"debug_db.dat\"\n print(\"debug\")\nelse:\n # Directory strings (need to be changed depending on platform)\n database_dir = \"/data/data/com.termux/files/home/.food/\"\n log_dir = \"/data/data/com.termux/files/home/food_logs/\"\n filename = \"foods.dat\"\n\n# The directory name for the log file. Will use the same file for a 24 hour period because the name\n# will only change once a day has passed.\ndatabase = Database(dirpath=database_dir,filename=filename,fieldname=\"name\")\nlog_path = \"%s%d_%.2d_%.2d_%s\" % (log_dir,time.localtime()[0],time.localtime()[1],time.localtime()[2],time.ctime().split(\" \")[0] + \"_food_log.txt\")\nuse_current_log = get_string(\"Use log file: \" + log_path.split(\"/\")[-1] + \"? (Enter for yes. n for no) \")\nif use_current_log != \"\":\n logfile = get_log()\n log_path = log_dir + logfile\n print(\"Using logfile: %s\" % logfile)\n\n# Strings\nstart_msg = \"\\nEnter to exit.\\n\\n1. Enter new meal\\n2. Add a food item to the database\\n3. View Catalog\\n4. Show Current Log\\n5. Estimate calories (for meals too complex to calculate)\\n6. Delete meal entry\\n7. Remove database item\\n8. Search for database item\\n: \"\nadd_meal_msg = \"Add an item from the list\\n: \"\n\n\n# Get the first input from the user\nuser_input_1 = get_number(start_msg,int)\n\n# Clear the terminal\n#if not DEBUG: \n# cls()\n\n# TODO: Features: Access previous logs; Compare different logs with intersections and unions\n## 1 for meal entry and 2 for adding new food to database for future retreival\nwhile user_input_1 != 'q':\n if user_input_1 == 1:\n meal_entry,servings = add_meal(add_meal_msg,database)\n add_to_log(meal_entry,servings,log_path)\n if user_input_1 == 2:\n create_new_food_item(database)\n if user_input_1 == 3:\n list_items(database)\n if user_input_1 == 4:\n show_meals(log_path)\n if user_input_1 == 5:\n estimate_calories(log_path)\n if user_input_1 == 6:\n delete_entry(database,log_path)\n if user_input_1 == 7:\n remove_database_item(database)\n if user_input_1 == 8:\n search_database(database)\n if user_input_1 == 9:\n view_previous_logs()\n user_input_1 = get_number(start_msg,int)\n #if not DEBUG:\n # cls()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"506182498","text":"from HashAlgorithms import *\nimport os\nimport unittest\n\n\nclass Test(unittest.TestCase):\n\n def __init__(self):\n super().__init__()\n self.get_image_path = os.path.dirname(os.path.realpath(__file__)) + \"/images/\"\n self.hashed_path = os.path.dirname(os.path.realpath(__file__)) + \"/hashed_images/\"\n self.test_hasher_class = HashBuilder(self.get_image_path)\n self.test_hash_comparator = CheckHash()\n\n def test_compressing(self):\n try:\n self.test_hasher_class.__compress__(Image.open(self.get_image_path + \"Untitled.png\"))\n self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"photo_2018-12-10_22-28-40.jpg\")))\n self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"Ц.png\")))\n self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"kiev comic conS80922-141312.jpg\")))\n print(\"SUCCESS: Images compress\")\n except:\n print(\"FAIL: Images don't compress\")\n\n def test_saving(self):\n random_drawing = self.test_hasher_class.__compress__(Image.open(self.get_image_path + \"Untitled.png\"))\n parrot_image = self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"photo_2018-12-10_22-28-40.jpg\")))\n new_parrot_image = self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"edited photo_2018-12-10_22-28-40.jpg\")))\n letter_ts = self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"Ц.png\")))\n comic_con_photo = self.test_hasher_class.__compress__(Image.open(os.path.abspath(self.get_image_path + \"kiev comic conS80922-141312.jpg\")))\n\n try:\n self.test_hasher_class.__save_compressed__(self.test_hasher_class.__two_colored__(random_drawing), self.hashed_path + \"new random.png\")\n self.test_hasher_class.__save_compressed__(self.test_hasher_class.__two_colored__(parrot_image), self.hashed_path + \"new parrot.png\")\n self.test_hasher_class.__save_compressed__(self.test_hasher_class.__two_colored__(new_parrot_image), self.hashed_path + \"new edited parrot.png\")\n self.test_hasher_class.__save_compressed__(self.test_hasher_class.__two_colored__(letter_ts), self.hashed_path + \"new letter.png\")\n self.test_hasher_class.__save_compressed__(self.test_hasher_class.__two_colored__(comic_con_photo), self.hashed_path + \"new comic con photo.png\")\n print(\"SUCCESS: Compressed images save\")\n except Exception:\n print(\"FAIL: Compressed images are not saved\")\n\n def test_hashing(self):\n random_drawing = \"Untitled.png\"\n parrot_image = \"photo_2018-12-10_22-28-40.jpg\"\n new_parrot_image = \"edited photo_2018-12-10_22-28-40.jpg\"\n letter_ts = \"Ц.png\"\n comic_con_photo = \"kiev comic conS80922-141312.jpg\"\n\n try:\n self.assertIsInstance(self.test_hasher_class.hash_image(random_drawing)[1], bytes)\n self.assertIsInstance(self.test_hasher_class.hash_image(parrot_image)[1], bytes)\n self.assertIsInstance(self.test_hasher_class.hash_image(letter_ts)[1], bytes)\n self.assertIsInstance(self.test_hasher_class.hash_image(comic_con_photo)[1], bytes)\n self.assertIsInstance(self.test_hasher_class.hash_image(new_parrot_image)[1], bytes)\n print(\"SUCCESS: Images get hashed\")\n except:\n print(\"FAIL: Images don't get hashed\")\n\n def test_hash_determinance(self):\n parrot_image = \"photo_2018-12-10_22-28-40.jpg\"\n try:\n tuple_hash1 = self.test_hasher_class.hash_image(parrot_image)\n tuple_hash2 = self.test_hasher_class.hash_image(parrot_image)\n hash1 = tuple_hash1[1]\n hash2 = tuple_hash2[1]\n # check out if two hashes for the same images are equal\n self.assertEqual(self.test_hash_comparator.similarity_percent(hash1, hash2), 1)\n print(\"SUCCESS: The same images hash with the same hash\")\n except:\n print(\"FAIL: The same photos are hashed with different hashes\")\n\n # check out if similar photos are more than 90% similar\n def test_hash_similar(self):\n parrot_image = \"photo_2018-12-10_22-28-40.jpg\"\n new_parrot_image = \"edited photo_2018-12-10_22-28-40.jpg\"\n try:\n tuple_hash1 = self.test_hasher_class.hash_image(parrot_image)\n tuple_hash2 = self.test_hasher_class.hash_image(new_parrot_image)\n hash1 = tuple_hash1[1]\n hash2 = tuple_hash2[1]\n self.assertGreater(self.test_hash_comparator.similarity_percent(hash1, hash2), 0.9)\n print(\"SUCCESS: Similar images are recognised similar\")\n except:\n print(\"FAIL: Similar images were recognised not similar\")\n\n # check out if not similar photos are less than 20% similar\n def test_hash_not_similar(self):\n parrot_image = \"photo_2018-12-10_22-28-40.jpg\"\n random_drawing = \"Untitled.png\"\n letter_ts = \"Ц.png\"\n try:\n tuple_hash1 = self.test_hasher_class.hash_image(parrot_image)\n tuple_hash2 = self.test_hasher_class.hash_image(random_drawing)\n tuple_hash3 = self.test_hasher_class.hash_image(letter_ts)\n hash1 = tuple_hash1[1]\n hash2 = tuple_hash2[1]\n hash3 = tuple_hash3[1]\n self.assertLess(self.test_hash_comparator.similarity_percent(hash1, hash2), 0.2)\n # check out if the hash function recognises different random drawing and letter\n # fails here\n self.assertLess(self.test_hash_comparator.similarity_percent(hash2, hash3), 0.5)\n print(\"SUCCESS: Not similar images are recognised not similar\")\n except:\n print(\"FAIL: Not similar images were recognised similar\")\n","sub_path":"raw_algorithms_python/tests/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":5923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"640154816","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\nclass Solution:\n \"\"\"\n @param head: A ListNode\n @return: A ListNode\n \"\"\"\n def deleteDuplicates(self, head):\n # write your code here\n if head == None:\n return head\n \n curt = head\n while True:\n value = curt.val\n nxt = curt.next\n while nxt != None and nxt.val == value:\n nxt = nxt.next\n curt.next = nxt\n if nxt != None:\n curt = nxt\n else:\n break\n \n return head","sub_path":"algorithm/official_notes/4/problems_linkList/Remove Duplicates from Sorted List.py","file_name":"Remove Duplicates from Sorted List.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"351181302","text":"# This package will contain the spiders of your Scrapy project\n#\n# Please refer to the documentation for information on how to create and manage\n# your spiders.\n\nimport datetime\nimport scrapy\nfrom ScrapyProject.items import ScrapyItem\n\nclass WashingtonPostSpider(scrapy.Spider):\n\t#item_id = ScrapyItem()\n\tname = 'WP'\n\n\n\tallowed_domains = ['https://www.washingtonpost.com/']\n\n\tstart_urls = [('https://www.washingtonpost.com/newssearch/?query=space propulsion&utm_term=.2b4058aeca71&sort=Date&datefilter=All Since 2005&startat=%d&spellcheck#top' % (i*20)) for i in range (0,10)]\n\t\n\tdef parse(self, response):\n #iterate entries\n\t\t\n\t\tfor entry in response.css('div.pb-feed-headline.ng-scope'):\n \n #retrieve info for our current post\n\t\t\titem = ScrapyItem()\n\n\t\t\titem['source'] = 'WP'\n\t\t\titem['date'] = entry.css('span.pb-timestamp.ng-binding::text').extract_first()\n\t\t\titem['brief'] = entry.css('div.pb-feed-description.ng-binding').extract_first()\n\t\t\titem['url'] = entry.css('a.ng-binding::attr(href)').extract_first()\n\t\t\titem['title'] = entry.css('a.ng-binding::text').extract_first()\n\n\t\t\t# check time\n\t\t\tnow = datetime.datetime.now()\n\t\t\titem['tstamp'] = now\n\n\t\t\tprint(item)\n\n\t\t\tyield item\n\n\n","sub_path":"ScrapyProject/spiders/WashingtonPost.py","file_name":"WashingtonPost.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"155219092","text":"from appium import webdriver\r\nfrom time import sleep\r\nimport time\r\nimport unittest\r\nimport HTMLTestRunner\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\n\r\ncurrent_time = time.strftime(\"%Y-%m-%d-%H_%M_%S\", time.localtime(time.time()))\r\n\r\n\r\nclass MyTests(unittest.TestCase):\r\n\r\n def setUp(self):\r\n desired_caps = {}\r\n desired_caps['platformName'] = 'Android'\r\n desired_caps['platformVersion'] = '5.1.1'\r\n desired_caps['deviceName'] = '127.0.0.1:62001' # device\r\n desired_caps['appPackage'] = 'com.tencent.mm'\r\n desired_caps['appActivity'] = 'com.tencent.mm.ui.LauncherUI'\r\n\r\n self.driver = webdriver.Remote(\"http://localhost:4723/wd/hub\", desired_caps) # 連接Appium\r\n self.driver.implicitly_wait(8)\r\n\r\n def test_open(self):\r\n Flag = True\r\n try:\r\n self.driver.find_element_by_id('com.tencent.mm:id/ecv').click()\r\n self.driver.find_element_by_id('com.tencent.mm:id/lh').send_keys('0912681502')\r\n self.driver.find_element_by_id('com.tencent.mm:id/b02').click()\r\n self.driver.find_element_by_id('com.tencent.mm:id/lh').send_keys('s23321286')\r\n self.driver.find_element_by_id('com.tencent.mm:id/b02').click() # 登入\r\n sleep(8)\r\n self.driver.find_element_by_xpath(\"//*[@text='否']\").click() # 提示\r\n sleep(3)\r\n self.driver.find_element_by_xpath(\"//*[@text='發現']\").click()\r\n sleep(3)\r\n self.driver.find_element_by_xpath(\"//*[@text='小程式']\").click()\r\n sleep(3)\r\n self.driver.find_element_by_xpath(\"//*[@text='微友名片']\").click()\r\n sleep(10)\r\n self.driver.find_element_by_xpath(\"//*[@text='Jack Tsao']\").click()\r\n sleep(3)\r\n\r\n except:\r\n Flag = False\r\n if Flag == False:\r\n self.driver.save_screenshot('C:/Users/jack.tsao/PycharmProjects/PythonAutomation/scrpath/%s.png' % current_time)\r\n self.assertTrue(Flag, 'Execute Fail.')\r\n\r\nif __name__ == '__main__':\r\n filepath = ('C:/Users/jack.tsao/PycharmProjects/PythonAutomation/report/WeiXin_Report_%s.html' % current_time)\r\n ftp = open(filepath, 'wb')\r\n suite = unittest.TestSuite()\r\n suite.addTest(MyTests('test_open'))\r\n runner = HTMLTestRunner.HTMLTestRunner(stream=ftp, title='WeiXin Test Report')\r\n runner.run(suite)","sub_path":"Weixin.py","file_name":"Weixin.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"536830989","text":"import cv2\nimport numpy as np\n\n# Loading the image (in grayscale) from disk and resizing it to 3/4th of its original size.\nimg = cv2.imread('resources/itachi.jpg',0)\nrow,col = img.shape\nrow = int(row*.75)\ncol = int(col*.75)\nimg = cv2.resize(img,(col,row))\n#---------------------------------------------------------------------------------#\n\n# Creating noise matrix\nnoise = np.random.randn(row,col)*10\nnoise = noise.astype(dtype=np.int8)\n\n# Adding noise to the grayscale image\nimg_new = cv2.add(img,noise,dtype=cv2.CV_8U)\ncv2.imshow('original',img)\ncv2.imshow('new_img',img_new)\n\nres_img=cv2.GaussianBlur(src=img_new,ksize=(5,5),sigmaX=10,sigmaY=10)\n\ncv2.imshow('res2',res_img)\nfinal_img = np.hstack((img,img_new))\nfinal_img = np.hstack((final_img,res_img))\ncv2.imwrite('Ques6a.png',final_img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"ClassAssignments/Assignment1/gaussian_noise.py","file_name":"gaussian_noise.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"484571932","text":"\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\n\r\nK = np.array([[964.828979 , 0. , 643.788025], [ 0. , 964.828979 ,484.40799 ], [ 0. , 0. , 1. ]])\r\nR_t = np.identity(3)\r\nT_t = np.array([[0],[0],[0]])\r\npos = np.array([[0],[0]])\r\n\r\nfor i in range(1,3872):\r\n\r\n img1 = cv2.imread('Data\\Final_Image{}.png'.format(i))\r\n img2 = cv2.imread('Data\\Final_Image{}.png'.format(i+1))\r\n orb = cv2.ORB_create()\r\n\r\n # find the keypoints and descriptors with SIFT\r\n kp1, des1 = orb.detectAndCompute(img1, None)\r\n kp2, des2 = orb.detectAndCompute(img2, None)\r\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\r\n\r\n # Match descriptors.\r\n matches = bf.match(des1, des2)\r\n # print(matches)\r\n\r\n # Sort them in the order of their distance.\r\n matches = sorted(matches, key=lambda x: x.distance)\r\n good = []\r\n\r\n for match in matches:\r\n good.append(match)\r\n\r\n pts1 = np.float32([kp1[match.queryIdx].pt for match in good])\r\n pts2 = np.float32([kp2[match.trainIdx].pt for match in good])\r\n\r\n E , mask = cv2.findEssentialMat(pts1,pts2,K,method= cv2.FM_RANSAC)\r\n\r\n points, R, t, mask = cv2.recoverPose(E, pts1, pts2,K)\r\n\r\n T_t = T_t + np.matmul(R_t,t)\r\n R_t = np.matmul(R_t , R)\r\n\r\n plt.scatter(-T_t[0],T_t[2])\r\n\r\n plt.pause(.0001)\r\n\r\n\r\n\r\n\r\n","sub_path":"project5/Code/Inbuilt.py","file_name":"Inbuilt.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"414364330","text":"import math\nD = int(input(''))\nhour = 0\na = 0\nb = 0\nc = 0\nd = 0\nk = 0\nminute = 0\nsolutions = 0\nif D > 720:\n k = math.floor(D/720)\n D = D - k*720\n solutions += 31*k\nfor i in range(D):\n hour = math.floor(i / 60)\n minute = int(i - (60 * hour)+1)\n if hour > 12:\n hour = hour % 12\n if hour == 0:\n hour = 12\n if hour > 9:\n a = 1\n b = hour - 10\n if hour < 10:\n a = 0\n b = hour\n if minute < 10:\n c = 0\n d = minute\n if minute > 9:\n tens = math.floor(minute / 10)\n c = tens\n d = minute - (10 * tens)\n d1 = d - c\n d2 = c - b\n\n if a == 0:\n\n if d1 == d2:\n solutions += 1\n\n else:\n solutions += 0\n if a > 0:\n d1 = d-c\n d2 = c-b\n d3 = b-a\n if d1 == d2 == d3:\n solutions += 1\n\n else:\n solutions += 0\n minute += 1\nprint(solutions)","sub_path":"Contest Questions/CCC/2017JCCC4.py","file_name":"2017JCCC4.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"277845145","text":"N = int(input(\"Ile liczb pierwszych znaleźć: \"))\ndividors = 0\nprint(\"Liczby pierwsze:\", end=\" \")\nfor i in range(2, N):# 1 nie jest liczbą pierwszą\n for j in range(1, i+1):\n if i % j == 0:\n dividors += 1\n if dividors < 3:\n print(i, end=\" \")\n dividors = 0","sub_path":"02-ControlStructures/45.py","file_name":"45.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"93164569","text":"__author__ = 'Ayla'\nfrom ss import *\n\nclass Employee:\n def __init__(self,last=None,first=None,start=None,pay_rate=None,social=None):\n if last == None:\n self.last = input(\"Employee Last Name: \")\n else:\n self.last=last\n if first==None:\n self.first =input(\"Employee First Name: \")\n else:\n self.first=first\n if start == None:\n self.start=input(\"Employee Start Date: \")\n else:\n self.start=start\n if pay_rate == None:\n self.pay_rate=input(\"Employee Pay_rate: \")\n else:\n self.pay_rate=pay_rate\n if social == None:\n self.social = SS()\n else:\n self.social = social\n\n def __str__(self):\n return \"First Name:\"+' '+self.first+\"\\nLast Name:\"+' '+self.last+' '+\"\\nYear started:\"+' '+\\\n str(self.start)+'\\n'+ \"Salary:\"+' '+str(self.pay_rate)+'\\n'+\"Social Security Number:\"+' '+str(self.social)\n\n\n\n\n\n","sub_path":"employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"455396375","text":"'''\nNeoPhotonics CONFIDENTIAL\nCopyright 2008 NeoPhotonics Corporation All Rights Reserved.\n\nThe source code contained or described herein and all documents related to\nthe source code (\"Material\") are owned by NeoPhotonics Corporation or its\nsuppliers or licensors. Title to the Material remains with NeoPhotonics Corporation\nor its suppliers and licensors. The Material may contain trade secrets and\nproprietary and confidential information of NeoPhotonics Corporation and its\nsuppliers and licensors, and is protected by worldwide copyright and trade\nsecret laws and treaty provisions. No part of the Material may be used, copied,\nreproduced, modified, published, uploaded, posted, transmitted, distributed,\nor disclosed in any way without NeoPhotonics's prior express written permission.\nNo license under any patent, copyright, trade secret or other intellectual\nproperty right is granted to or conferred upon you by disclosure or delivery\nof the Materials, either expressly, by implication, inducement, estoppel or\notherwise. Any license under such intellectual property rights must be express\nand approved by NeoPhotonics in writing.\n\nInclude any supplier copyright notices as supplier requires NeoPhotonics to use.\n\nInclude supplier trademarks or logos as supplier requires NeoPhotonics to use,\npreceded by an asterisk. An asterisked footnote can be added as follows:\n*Third Party trademarks are the property of their respective owners.\n\nUnless otherwise agreed by NeoPhotonics in writing, you may not remove or alter this\nnotice or any other notice embedded in Materials by NeoPhotonics or NeoPhotonics's\nsuppliers or licensors in any way.\n'''\nimport PyTTXTalk\nimport Dictionary\nfrom Utility import *\nimport System\n\nimport Mask\n\nMODULE_INDEX = 7\n\nMETHOD_INDICES = {'frequency' : 0,\n 'powerTarget' : 1,\n 'status' : 2,\n 'powerVariance' : 3,\n 'powerError' : 4,\n 'powerOutput' : 5,\n 'maskElement' : 6,\n 'currentTarget' : 7,\n 'mode' : 8,\n 'coldStart' : 9,\n 'retries' : 10,\n 'frequencyOffset' : 11,\n 'powerState' : 12,\n 'tecClock' : 13\n }\n\nELEMENT_DATA = (('TUNER', ''),\n ('SBS_SUPPRESSION', ''),\n ('TX_TRACE', ''),\n ('AMBIENT_COMPENSATOR', ''))\n\nELEMENT_PROPERTIES = []\n\nfor index in range(len(ELEMENT_DATA)):\n\n data = ELEMENT_DATA[index]\n\n ELEMENT_PROPERTIES.append({'index':index,\n 'label':data[0],\n 'units':data[1],\n 'type':''})\n\nPROPERTIES = {'ELEMENT_PROPERTIES':ELEMENT_PROPERTIES}\n\nclass TunerManager:\n def __init__(self, ttx_interface, dictionary_manager, Nano=False):\n self.__current_tuner = CurrentTuner(ttx_interface)\n self.__power_tuner = PowerTuner()\n config = System.Configuration()\n if Nano: # NANO\n status_dictionary = {'11': 'CHANNEL_LOCK', '10': 'STABILIZE', '13': 'MZM_STATE',\n '12': 'FINE_TUNE', '1': 'IDLE', '0': 'COLD_START',\n '3': 'TEMPERATURE', '2': 'DARK', '5': 'ADJUSTMENT',\n '4': 'GAIN_MEDIUM', '7': 'CAVITY_LOCK', '6': 'FIRST_LIGHT',\n '9': 'CAVITY_OFFSET_LOCK', '8': 'POWER_LEVEL'}\n state_dictionary = {'1': 'POWER_STATE_LASER_PHOTODIODE', '0': 'POWER_STATE_DISABLE',\n '3': 'POWER_STATE_LOCK', '2': 'POWER_STATE_MZM_PHOTODIODE'}\n self.__current_tuner.statusDictionary(status_dictionary)\n self.__current_tuner.powerStateDictionary(state_dictionary)\n self.__power_tuner.statusDictionary(status_dictionary)\n self.__power_tuner.powerStateDictionary(state_dictionary)\n return\n status_dictionary = config.restore(ttx_interface.firmwareVersion(), 'TunerStatus')\n# print ttx_interface.firmwareVersion()\n if len(status_dictionary) == 0:\n raise 'TunerStatus undefined!'\n\n state_dictionary = config.restore(ttx_interface.firmwareVersion(), 'PowerState')\n if len(state_dictionary) == 0:\n raise 'Power States undefined!'\n\n dm = dictionary_manager\n d = Dictionary.Dictionary()\n# d.memory(dm.dictionary('MODEL_DICTIONARY').memory())\n# d.addEntry('model', dm.dictionary('MODEL_DICTIONARY'))\n ###d.addEntry('ambient_compensator', dm.dictionary('AMBIENT_COMPENSATOR_DICTIONARY'))\n self.__current_tuner.statusDictionary(status_dictionary)\n self.__current_tuner.powerStateDictionary(state_dictionary)\n self.__current_tuner.dictionary(d)\n\n d1 = Dictionary.Dictionary()\n# d1.memory(dm.dictionary('MODEL_DICTIONARY').memory())\n# d1.addEntry('model', dm.dictionary('MODEL_DICTIONARY'))\n ###d1.addEntry('power', dm.dictionary('POWER_DICTIONARY'))\n ###d1.addEntry('ambient_compensator', dm.dictionary('AMBIENT_COMPENSATOR_DICTIONARY'))\n self.__power_tuner.statusDictionary(status_dictionary)\n self.__power_tuner.powerStateDictionary(state_dictionary)\n self.__power_tuner.dictionary(d1)\n\n def currentTuner(self):\n return self.__current_tuner\n\n def powerTuner(self):\n return self.__power_tuner\n\nclass Tuner:\n\n '''\nClass to tune the laser to specified frequencies.\n '''\n\n def __init__(self):\n\n self.__dictionary = None\n self.__module_index = MODULE_INDEX\n self.__method_indices = METHOD_INDICES\n self.__mask = TunerMask()\n\n def statusDictionary(self, dictionary = None):\n if dictionary != None:\n self.__status_dictionary = dictionary\n return self.__status_dictionary\n\n def powerStateDictionary(self, dictionary = None):\n if dictionary != None:\n self.__power_state_dictionary = dictionary\n return self.__power_state_dictionary\n\n def __repr__(self):\n\n s = 'Frequency : %7.3f\\n' % self.frequency()\n s += 'Status : %s\\n' % self.status()\n s += 'Mask : %s\\n' % ['Unmasked', 'Masked'][self.mask().tuner()]\n s += 'Retries : %d' % self.retries()\n try:\n s += '\\nFrequency Offset: %d MHz' % self.frequencyOffset()\n except:\n pass\n s += '\\nPower State : %s' % self.powerState()\n\n return(s)\n\n def labels(self):\n data = []\n data.append('Frequency')\n data.append('Status')\n data.append('Mask')\n data.append('Retries')\n try:\n self.frequencyOffset()\n data.append('Frequency Offset')\n except:\n pass\n\n return data\n\n def elements(self):\n data = []\n data.append(self.frequency())\n data.append(self.status())\n data.append(self.mask().tuner())\n data.append(self.retries())\n try:\n data.append(self.frequencyOffset())\n except:\n pass\n\n return data\n\n def dictionary(self, d = None):\n\n if (d == None): return(self.__dictionary)\n\n self.__dictionary = d\n\n def frequency(self, THz = None):\n ' frequency = 0 disable lasers. '\n\n newOperation(self.__module_index, self.__method_indices['frequency'])\n\n if (THz != None): PyTTXTalk.pushF32(THz)\n\n sendPacket(1)\n\n if (THz == None): return(PyTTXTalk.popF32())\n\n def status(self):\n newOperation(self.__module_index, self.__method_indices['status'])\n\n sendPacket(1)\n s = PyTTXTalk.popU8()\n\n return(self.statusDictionary()[str(s)])\n\n def powerState(self):\n newOperation(self.__module_index, self.__method_indices['powerState'])\n\n sendPacket(1)\n s = PyTTXTalk.popU8()\n\n return(self.powerStateDictionary()[str(s)])\n\n def retries(self):\n '''\nReturns the total number of channel retries to lock the cavity within\nthe desired temperature range.\n '''\n newOperation(self.__module_index, self.__method_indices['retries'])\n sendPacket(1)\n return(PyTTXTalk.popU8())\n\n def mask(self):\n\n 'Returns the tuner mask. Use only if TRN disabled laser'\n\n return(self.__mask)\n\n def coldStart(self):\n '''\nThis turns off the tuner putting it in cold start. Note: This this is\nequivalent to t.off(). Standard way to disable laser is to set frequency to\n0.0\n '''\n newOperation(self.__module_index, self.__method_indices['coldStart'])\n sendPacket(1)\n\n def frequencyOffset(self, MHz = None):\n\n newOperation(self.__module_index, self.__method_indices['frequencyOffset'])\n\n if (MHz != None): PyTTXTalk.pushS16(MHz)\n\n sendPacket(1)\n\n if (MHz == None): return(PyTTXTalk.popS16())\n\n def __moduleIndex(self):\n return self.__module_index\n\n def __methodIndices(self):\n return self.__method_indices\n\nclass PowerTuner(Tuner):\n ' Tunes to channels allowing user to specify constant power. '\n\n __POWER_MODE = 0\n\n def __init__(self):\n self.__description = 'PowerTuner'\n self.__module_index = MODULE_INDEX\n self.__method_indices = METHOD_INDICES\n\n Tuner.__init__(self)\n\n def __repr__(self):\n s = 'Description : %s\\n' % self.__description\n s += Tuner.__repr__(self) + '\\n'\n s += 'Power Target : %f mW\\n' % self.powerTarget()\n s += 'Power Output : %f mW\\n' % self.powerOutput()\n s += 'Power Variance : %f uA\\n' % self.powerVariance()\n s += 'Power Error : %f uA^2' % self.powerError()\n return(s)\n\n def powerTarget(self, mW = None):\n 'Desired optical output power'\n\n newOperation(self.__module_index, self.__method_indices['powerTarget'])\n\n if (mW != None): PyTTXTalk.pushF32(mW)\n\n sendPacket(1)\n\n if (mW == None): return(PyTTXTalk.popF32())\n self.__setMode()\n\n def powerVariance(self):\n 'Variance of the photodiode current error (powerError())'\n newOperation(self.__module_index, self.__method_indices['powerVariance'])\n\n sendPacket(1)\n\n return(PyTTXTalk.popF32())\n\n def powerError(self):\n 'Photodiode error from target photodiode current'\n newOperation(self.__module_index, self.__method_indices['powerError'])\n\n sendPacket(1)\n\n return(PyTTXTalk.popF32())\n\n def powerOutput(self):\n 'Measured optical output.'\n newOperation(self.__module_index, self.__method_indices['powerOutput'])\n\n sendPacket(1)\n\n return(PyTTXTalk.popF32())\n\n def frequency(self, THz = None):\n ' Frequency = 0 disable lasers. '\n if (THz != None): self.__setMode()\n return(Tuner.frequency(self, THz))\n\n def __setMode(self):\n newOperation(self.__module_index, self.__method_indices['mode'])\n PyTTXTalk.pushS8(PowerTuner.__POWER_MODE)\n sendPacket(1)\n\n def setTEC_Clock(self, TEC_clock_state = None):\n '0:enable TEC Clock, 1:disable for 30 sec (repeat before to keep it disabled)'\n newOperation(self.__module_index, self.__method_indices['tecClock'])\n\n if(TEC_clock_state == None):\n sendPacket(1)\n return(PyTTXTalk.popS8())\n\n PyTTXTalk.pushS8(TEC_clock_state)\n sendPacket(1)\n\nclass CurrentTuner(Tuner):\n ' Tunes to channels allowing user to specify constant current. '\n __CURRENT_MODE = 1\n\n def __init__(self, ttx_interface):\n self.__description = 'CurrentTuner'\n self.__module_index = MODULE_INDEX\n self.__method_indices = METHOD_INDICES\n self.__ttx_interface = ttx_interface\n\n Tuner.__init__(self)\n\n def __repr__(self):\n s = 'Description : %s\\n' % self.__description\n s += Tuner.__repr__(self) + '\\n'\n s += 'Current Target : %f mA\\n' % self.currentTarget()\n s += 'Current Output : %f mA\\n' % self.currentOutput()\n return(s)\n\n def frequency(self, THz = None):\n ' Frequency = 0 disable lasers. '\n if (THz != None): self.__setMode()\n return(Tuner.frequency(self, THz))\n\n def currentTarget(self, mA = None):\n 'Desired optical output current'\n\n newOperation(self.__module_index, self.__method_indices['currentTarget'])\n\n if (mA!= None): PyTTXTalk.pushF32(mA)\n\n sendPacket(1)\n\n if (mA == None): return(PyTTXTalk.popF32())\n self.__setMode()\n\n\n def currentOutput(self):\n 'Measured current output.'\n '''return(self.__ttx_interface.domainStage().frame().gainMediumCurrent())\n '''\n return(self.__ttx_interface.controlStage().frame().gainMediumCurrent())\n\n\n def __setMode(self):\n newOperation(self.__module_index, self.__method_indices['mode'])\n PyTTXTalk.pushS8(CurrentTuner.__CURRENT_MODE)\n sendPacket(1)\n\n\nclass TunerMask(Mask.Mask):\n\n def __init__(self):\n\n Mask.Mask.__init__(self,\n 'Tuner mask.',\n PROPERTIES['ELEMENT_PROPERTIES'],\n MODULE_INDEX,\n METHOD_INDICES)","sub_path":"PythonFiles/TTM/Tuner.py","file_name":"Tuner.py","file_ext":"py","file_size_in_byte":13378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"133828257","text":"from src.DB import DB\n\n# Assuming that username is unique\ndef get_user_id_from_name(name_first):\n db = DB()\n query = \"\"\"\n SELECT customer_id\n FROM Customer\n WHERE name_first = \"{}\";\n \"\"\".format(name_first)\n response = db.read(query)\n if response is None:\n return -1\n else:\n return response[0]['customer_id']\n\ndef get_user_id_from_email(email):\n db = DB()\n query = \"\"\"\n SELECT customer_id\n FROM Customer\n WHERE email = \"{}\";\n \"\"\".format(email)\n response = db.read(query)\n if response is None:\n return -1\n else:\n return response[0]['customer_id']\n\n\ndef get_latest_customer_id():\n db = DB()\n query = \"\"\"\n SELECT MAX(customer_id) AS Latest\n FROM Customer;\n \"\"\"\n response = db.read(query)\n return response[0]['Latest'] + 1\n\n\ndef get_latest_account_no():\n db = DB()\n query = \"\"\"\n SELECT MAX(account_no) AS Latest\n FROM Account;\n \"\"\"\n response = db.read(query)\n return response[0]['Latest'] + 1\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"206244941","text":"\n\n#calss header\nclass _TAG():\n\tdef __init__(self,): \n\t\tself.name = \"TAG\"\n\t\tself.definitions = [u'a small piece of paper, cloth, or metal, on which there is information, tied or stuck onto something larger: ', u'a game played by two or more children in which one child chases the others and tries to touch one of them. This child then becomes the one who does the chasing.', u'a phrase such as \"he is\" or \"isn\\'t it?\", added on to a sentence for emphasis, or to turn it into a question, usually to get agreement or to check information', u'a type of graffiti\\x7f (= words and pictures drawn in public places on walls, etc.) that shows who has drawn it and that represents a signature : ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_tag.py","file_name":"_tag.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"566555286","text":"# Hardware wallet interaction script\n\nimport argparse\nimport hid\nimport json\n\nfrom device_ids import trezor_device_ids, keepkey_device_ids, ledger_device_ids,\\\n digitalbitbox_device_ids\nfrom serializations import PSBT\n\n# Error codes\nNO_DEVICE_PATH = -1\nNO_DEVICE_TYPE = -2\nDEVICE_CONN_ERROR = -3\nUNKNWON_DEVICE_TYPE = -4\nINVALID_TX = -5\n\n# This is an abstract class that defines all of the methods that each Hardware\n# wallet subclass must implement.\nclass HardwareWalletClient(object):\n\n # device is an HID device that has already been opened.\n def __init__(self, device):\n self.device = device\n self.message_magic = b\"\\x18Bitcoin Signed Message:\\n\"\n\n # Get the master BIP 44 pubkey\n def get_master_xpub(self):\n return self.get_pubkey_at_path('m/44\\'/0\\'/0\\'')\n\n # Must return a dict with the xpub\n # Retrieves the public key at the specified BIP 32 derivation path\n def get_pubkey_at_path(self, path):\n raise NotImplementedError('The HardwareWalletClient base class does not '\n 'implement this method')\n\n # Must return a hex string with the signed transaction\n # The tx must be in the combined unsigned transaction format\n def sign_tx(self, tx):\n raise NotImplementedError('The HardwareWalletClient base class does not '\n 'implement this method')\n\n # Must return a base64 encoded string with the signed message\n # The message can be any string. keypath is the bip 32 derivation path for the key to sign with\n def sign_message(self, message, keypath):\n raise NotImplementedError('The HardwareWalletClient base class does not '\n 'implement this method')\n\n # Setup a new device\n def setup_device(self):\n raise NotImplementedError('The HardwareWalletClient base class does not '\n 'implement this method')\n\n # Wipe this device\n def wipe_device(self):\n raise NotImplementedError('The HardwareWalletClient base class does not '\n 'implement this method')\n\n\n# Get a list of all available hardware wallets\ndef enumerate():\n result = []\n devices = hid.enumerate()\n for d in devices:\n # Get trezors\n if (d['vendor_id'], d['product_id']) in trezor_device_ids:\n result.append({'type':'trezor','path':d['path'].decode(\"utf-8\"),\n 'serial_number':d['serial_number']})\n # Get keepkeys\n elif (d['vendor_id'], d['product_id']) in keepkey_device_ids:\n result.append({'type':'keepkey', 'path':d['path'].decode(\"utf-8\"),\n 'serial_number':d['serial_number']})\n # Get ledgers\n elif (d['vendor_id'], d['product_id']) in ledger_device_ids:\n result.append({'type':'ledger', 'path':d['path'].decode(\"utf-8\"),\n 'serial_number':d['serial_number']})\n # Get DigitalBitboxes\n elif (d['vendor_id'], d['product_id']) in digitalbitbox_device_ids:\n result.append({'type':'digitalbitbox', 'path':d['path'].decode(\"utf-8\"),\n 'serial_number':d['serial_number']})\n return result\n\ndef process_commands(command, command_args, device_path, device_type):\n\n # List all available hardware wallet devices\n if command == 'enumerate':\n print(json.dumps(enumerate()))\n return\n\n if device_path is None:\n result = {'error':'You must specify a device path for all commands except enumerate','code':NO_DEVICE_PATH}\n print(json.dumps(result))\n return\n if device_type is None:\n result = {'error':'You must specify a device type for all commands except enumerate','code':NO_DEVICE_TYPE}\n print(json.dumps(result))\n return\n\n # Open the device\n try:\n device = hid.device()\n device_path = bytes(device_path.encode())\n device.open_path(device_path)\n except Exception as e:\n print(e)\n result = {'error':'Unable to connect to specified device','code':DEVICE_CONN_ERROR}\n print(json.dumps(result))\n return\n\n # Make a client\n if device_type == 'trezor':\n import trezori\n client = trezori.TrezorClient(device=device, path=device_path)\n elif device_type == 'keepkey':\n import keepkeyi\n client = keepkeyi.KeepKeyClient(device=device, path=device_path)\n elif device_type == 'ledger':\n # hack to use btchip-python's getDongle pipeline\n device.close()\n import ledgeri\n client = ledgeri.LedgerClient(device=device)\n elif device_type == 'digitalbitbox':\n import digitalbitboxi\n client = digitalbitboxi.DigitalBitboxClient(device=device, password='asdfasdf')\n else:\n result = {'error':'Unknown device type specified','code':UNKNWON_DEVICE_TYPE}\n print(json.dumps(result))\n exit\n\n # Do the commands\n if command == 'getmasterxpub':\n print(client.get_master_xpub())\n\n elif command == 'signtx':\n # Deserialize the transaction\n try:\n tx = PSBT()\n tx.deserialize(command_args[0])\n print(json.dumps(client.sign_tx(tx)))\n except Exception as e:\n import traceback\n traceback.print_exc()\n print(json.dumps({'error':'You must provide a PSBT','code':INVALID_TX}))\n exit\n\n elif command == 'getxpub':\n print(client.get_pubkey_at_path(command_args[0]))\n elif command == 'signmessage':\n print(client.sign_message(command_args[0], command_args[1]))\n else:\n print(json.dumps({'error':'Unknown command'}))\n\n # Close the device\n device.close()\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Access and send commands to a hardware wallet device. Responses are in JSON format')\n parser.add_argument('--device-path', '-d', help='Specify the device path of the device to connect to')\n parser.add_argument('--device-type', '-t', help='Specify the type of device that will be connected')\n parser.add_argument('command', help='The action to do')\n parser.add_argument('args', help='Arguments for the command', nargs='*')\n\n args = parser.parse_args()\n command = args.command\n device_path = args.device_path\n device_type = args.device_type\n command_args = args.args\n\n process_commands(command, command_args, device_path, device_type)\n","sub_path":"hwi.py","file_name":"hwi.py","file_ext":"py","file_size_in_byte":6334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"503365935","text":"# -*- coding: utf-8 -*-\n\nfrom mapi import db\nfrom mapi import mars\n\n\n# Tipos primitivos\nBool = db.Boolean\nDat = db.DateTime\nFloat = db.Float\nInt = db.Integer\nStr = db.String\n\n# Entidades & Objetos\nCol = db.Column\nModel = db.Model\n\n# Relacionamentos\nBR = db.backref\nFK = db.ForeignKey\nRel = db.relationship\n\n# Sessão do ORM\nsession = db.session\n\n\n# Classes do Marshmallow\nSchema = mars.ModelSchema\nNested = mars.Nested\n","sub_path":"src/mapi/orm.py","file_name":"orm.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"286950191","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 18 21:49:28 2021\n\n@author: johnsenaakoto\n\"\"\"\n\ndef solution(start, length):\n checksum = 0\n current = start\n current_len = length\n while current_len > 0:\n checksum ^= computeXOR(current) ^ computeXOR(current + current_len)\n current += length\n current_len -= 1\n\n return checksum\n\ndef computeXOR(n):\n \"\"\"\n Return 0^1^2^....^(n-1)\n \"\"\"\n if n == 0:\n return 0\n \n # if n-1 is multiple of 4 \n if (n-1) % 4 == 0:\n return n-1\n # If n-1 % 4 gives remainder 1\n elif (n-1) % 4 == 1:\n return 1\n # If n%4 gives remainder 2\n elif (n-1) % 4 == 2:\n return n\n else:\n return 0\n \nprint(solution(17,4))\n","sub_path":"queue_to_do_solution.py","file_name":"queue_to_do_solution.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"124760786","text":"from django.conf import settings\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom .utils import code_generator\nfrom django.core.mail import send_mail\nfrom django.core.urlresolvers import reverse\n# Create your models here.\nUser = settings.AUTH_USER_MODEL\n\n\nclass ProfileManager(models.Manager):\n\tdef toggle_follow(self, request_user, username_to_toggle):\n\t\tprofile_ = Profile.objects.get(user__username__iexact = username_to_toggle)\n\t\tuser = request_user\n\t\tis_following = False\n\t\tif user in profile_.followers.all():\n\t\t\tprofile_.followers.remove(user)\n\t\telse:\n\t\t\tprofile_.followers.add(user)\n\t\t\tis_following = True\n\t\tprint(user)\n\t\treturn profile_, is_following\n\n\nclass Profile(models.Model):\n\tuser \t\t\t= models.OneToOneField(User) #instead of using user.profile_set.all() we can use user.profile \n\tfollowers \t\t= models.ManyToManyField(User, related_name = 'is_following', blank = True)\t#user.followers.all() instead of user.profile_set.all()\n\t#following \t= models.ManyToManyField(User, related_name = 'following', blank = True) #user.following.all() instead of user.profile_set.all()\n\tactivation_key\t= models.CharField(max_length =120, blank =True, null = True )\n\tactivated\t\t= models.BooleanField(default= False)\n\ttimestamp\t\t= models.DateTimeField(auto_now_add= True)\n\tupdated\t\t\t= models.DateTimeField(auto_now= True)\n\n\n\tobjects = ProfileManager()\n\n\n\tdef __str__(self):\n\t\treturn self.user.username\n\n\tdef send_activation_email(self):\n\t\tif not self.activated:\n\t\t\tself.activation_key = code_generator()\n\t\t\tself.save()\n\t\t\tpath_ = reverse('activate', kwargs = {'code': self.activation_key})\n\t\t\tsubject = 'Activate Account'\n\t\t\tfrom_email = settings.DEFAULT_FROM_EMAIL\n\t\t\tmessage = 'Activate Your account here:{}'.format(path_)\n\t\t\trecipient_list = [self.user.email]\n\t\t\thtml_message = '

Activate Your account here:{}

'.format(path_)\n\t\t\tsent_mail = False\n\t\t\tprint(html_message)\n\t\t\t#sent_mail = send_mail(\n\t\t\t#\t\t\tsubject,\n\t\t\t#\t\t\tmessage,\n\t\t\t#\t\t\tfrom_email,\n\t\t\t#\t\t\trecipient_list,\n\t\t\t#\t\t\tfail_silently =\tFalse,\n\t\t\t#\t\t\thtml_message = html_message\t\n\t\t\t#\t\t\t)\n\t\t\treturn sent_mail\n\n\n\ndef post_save_user_reciever(sender, instance, created, *args, **kwargs):\n\tif created:\n\t\tprofile, is_created\t=Profile.objects.get_or_create(user= instance)\n\t\tdefault_user_profile =Profile.objects.get_or_create(user__id = 1)[0]\n\t\tdefault_user_profile.followers.add(instance) #creating a default user to all new created ones\n\t\tprofile.followers.add(default_user_profile.user) #to add users as default\n\t\tprofile.followers.add(3)\t\t#to add users as default\n\n\npost_save.connect(post_save_user_reciever , sender = User)\n\n","sub_path":"mypicky/profiles/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"372276235","text":"from dao.json_repository import JsonRepository\nfrom dao.repository import Repository\nfrom entity.book import Book\n\n\nclass BookRepository(JsonRepository):\n def find_by_title(self, title_part: str) -> list[Book]:\n title_part_lower = title_part.lower()\n books_list = self.find_all()\n results = [book for book in books_list if title_part_lower in book.title.lower()]\n return results\n\n def find_by_author(self, author_part: str) -> list[Book]:\n author_part_lower = author_part.lower()\n books_list = self.find_all()\n results = []\n for book in books_list:\n for author in book.authors:\n if author_part_lower in author.lower():\n results.append(book)\n break\n return results\n","sub_path":"09-mvc-library/dao/book_repository.py","file_name":"book_repository.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"324047416","text":"from scrapy.spiders import Spider\nfrom scrapy.selector import Selector\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.http import Request,FormRequest\nfrom scrapy.selector import HtmlXPathSelector\nfrom scrapy.selector import XmlXPathSelector\nfrom scrapy.linkextractors import LinkExtractor\nimport json\nimport re\nimport uuid\nimport hashlib\nimport logging\nimport subprocess\nimport requests\nimport csv\nimport io\nimport scrapy\nfrom datetime import datetime\nimport os\nfrom dateutil.relativedelta import relativedelta\nfrom autodata.items import AutodataItem, MetaItem\n\nclass GmcMauSpider(scrapy.Spider):\n name = 'gmc_mau'\n allowed_domains = []\n start_urls = [\"https://gmc.mannaiautos.com/pre-owned-vehicles/\"]\n\n def parse(self, response):\n \n path = response.xpath('//*[@id=\"content-wrap\"]/div[5]/div/div/div/div/div')\n print('##########')\n \n for url in path:\n url_details = url.xpath('.//div[@class =\"button module view-vehicle small\"]/a/@href').extract() \n url_det = ('https://gmc.mannaiautos.com'+ ''.join(url_details)).strip()\n yield Request (url_det,callback = self.parse_data,dont_filter=True)\n\n nex = ''.join(response.xpath('//li[@class = \"btn-next\"]/a/@href').extract()).strip()\n if nex != '':\n url = 'https://gmc.mannaiautos.com/pre-owned-vehicles' + nex\n yield Request(url, callback = self.parse, dont_filter=True)\n \n \n def parse_data(self,response):\n\n item=AutodataItem()\n item2 = MetaItem()\n item[\"Last_Code_Update_Date\"] = \"\"\n item[\"Scrapping_Date\"] = \"\"\n item[\"Country\"] = \"Qatar\"\n item[\"City\"] = \"\"\n item[\"Seller_Type\"] = \"Official Dealers\"\n item[\"Seller_Name\"] = \"Mannai Trading Co. WLL\"\n item[\"Car_URL\"] = \"\"\n item[\"Car_Name\"] = \"\"\n item[\"Year\"] = \"\"\n item[\"Make\"] = \"\"\n item[\"model\"] = \"\"\n item[\"Spec\"] = \"\"\n item[\"Doors\"] = \"\"\n item[\"transmission\"] = \"\"\n item[\"trim\"] = \"\"\n item[\"bodystyle\"] = \"\"\n item[\"other_specs_gearbox\"] = \"\"\n item[\"other_specs_seats\"] = \"\"\n item[\"other_specs_engine_size\"] = \"\"\n item[\"other_specs_horse_power\"] = \"\"\n item[\"colour_exterior\"] = \"\"\n item[\"colour_interior\"] = \"\"\n item[\"fuel_type\"] = \"\"\n item[\"import_yes_no_also_referred_to_as_GCC_spec\"] = \"\" \n item[\"mileage\"] = \"\"\n item[\"condition\"] = \"\"\n item[\"warranty_untill_when\"] = \"\"\n item['service_contract_untill_when'] = ''\n item['Price_Currency'] = ''\n item['asking_price_inc_VAT'] = ''\n item['asking_price_ex_VAT'] = ''\n item['warranty'] = 'yes'\n item['service_contract'] = ''\n item['vat'] = 'yes'\n item['mileage_unit'] = ''\n item['engine_unit'] = ''\n item['Last_Code_Update_Date'] = 'Thursday, June 04, 2019'\n item['Scrapping_Date'] = datetime.today().strftime('%A, %B %d, %Y')\n item['autodata_Make'] = ''\n item['autodata_Make_id'] = ''\n item['autodata_model'] = ''\n item['autodata_model_id'] = ''\n item['autodata_Spec'] = ''\n item['autodata_Spec_id'] = ''\n item['autodata_transmission'] = ''\n item['autodata_transmission_id'] = ''\n item['autodata_bodystyle'] = ''\n item['autodata_bodystyle_id'] = ''\n item['wheel_size'] = ''\n item['top_speed_kph'] = ''\n item['cylinders'] = ''\n item['acceleration'] = ''\n item['torque_Nm'] = ''\n\n item2['src'] = \"gmc.mannaiautos.com\"\n item2['ts'] = datetime.utcnow().isoformat()\n item2['name'] = \"gmc_mau\"\n item2['url'] = response.url\n item2['uid'] = str(uuid.uuid4())\n item2['cs'] = hashlib.md5(json.dumps(dict(item), sort_keys=True).encode('utf-8')).hexdigest()\n item['meta'] = dict(item2)\n item['Car_URL'] = response.url\n item['Source'] = item2['src']\n path = Selector(response)\n \n item['Year'] = ''.join(path.xpath('//div[@class=\"cell reg-year\"]/span[@class=\"value reg-year\"]/text()').extract()).strip()\n \n item['other_specs_engine_size'] =''.join(path.xpath('//div[@class=\"cell engine-size\"]/span[@class=\"value engine-size\"]/text()').extract()).strip().split(' ')[0]\n item['engine_unit'] = ''.join(path.xpath('//div[@class=\"cell engine-size\"]/span[@class=\"value engine-size\"]/text()').extract()).strip().split(' ')[1]\n item['colour_exterior'] =''.join(path.xpath('//div[@class=\"cell colour\"]/span[@class=\"value colour\"]/text()').extract()).strip()\n item['bodystyle'] =''.join(path.xpath('//div[@class=\"cell bodystyle\"]/span[@class=\"value bodystyle\"]/text()').extract()).strip()\n item['mileage'] =''.join(path.xpath('//div[@class=\"cell mileage\"]/span[@class=\"value mileage\"]/text()').extract()).strip().split(' ')[0]\n item['mileage_unit'] = ''.join(path.xpath('//div[@class=\"cell mileage\"]/span[@class=\"value mileage\"]/text()').extract()).strip().split(' ')[1]\n item['model'] = ''.join(path.xpath('//div[@class=\"title module\"]/h3/span[@class= \"model\"]//text()').extract()).strip()\n item['Year'] = ''.join(path.xpath('//div[@class=\"title module\"]/h3/span[@class= \"year\"]//text()').extract()).strip()\n item['Make'] = ''.join(path.xpath('//div[@class=\"title module\"]/h3/span[@class= \"make\"]//text()').extract()).strip()\n item[\"Spec\"] = ''.join(path.xpath('//div[@class=\"title module\"]/h3/span[@class= \"variant\"]//text()').extract()).strip()\n item['asking_price_inc_VAT'] = ''.join(path.xpath('//*[@id=\"content-wrap\"]/div[2]/div/div[1]/div/div[2]/div/div/span[2]/text()').extract()).strip().split('QAR')[1]\n item['Price_Currency'] = 'QAR'\n item['fuel_type'] = ''.join(path.xpath('//div[@class=\"cell fuel-type\"]/span[@class=\"value fuel-type\"]/text()').extract()).strip()\n item['colour_interior'] = ''.join(path.xpath('//div[@class=\"cell interior-colour\"]/span[@class=\"value interior-colour\"]/text()').extract()).strip()\n item['transmission'] = ''.join(path.xpath('//div[@class=\"cell transmission\"]/span[@class=\"value transmission\"]/text()').extract()).strip()\n item['Doors'] = ''.join(path.xpath('//div[@class=\"cell doors\"]/span[@class=\"value doors\"]/text()').extract()).strip()\n item['warranty_untill_when'] = (datetime.today() + relativedelta(months=+24)).strftime('%Y-%m-%d')\n det = ''.join(path.xpath('//div[@class=\"description-text\"]/text()').extract())\n if 'Cylinders' in det:\n item['cylinders'] = det.split('Cylinders')[0].strip().split(' ')[-1]\n item['Spec'] = det.replace(item['model'].upper() + ' ','').split(' ')[0]\n item['Car_Name'] = (item['Make'] + ' ' +item['model'] + ' ' + item[\"Spec\"] + ' ' + item['Year']).strip()\n\n yield item\n","sub_path":"spiders/gmc_mau.py","file_name":"gmc_mau.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"626829496","text":"from src.Relation import Relation\nfrom src.Attribute import Attribute\nfrom src.Database import Database, current\n\n\nclass Diff(Relation):\n\n def __init__(self, subrelation1, subrelation2):\n self.subrelation1, self.subrelation2 = subrelation1, subrelation2\n self.check_args()\n\n def check_args(self):\n if not (isinstance(self.subrelation1, Relation) or isinstance(self.subrelation2, Relation)):\n raise Exception('The subrelations must be relations')\n\n argtype = {}\n\n Database.current.c.execute(\"DROP TABLE IF EXISTS tmp1\")\n Database.current.c.execute(\"DROP TABLE IF EXISTS tmp2\")\n\n Database.current.c.execute(\n \"CREATE TABLE tmp1 AS SELECT * FROM ({0})\".format(self.subrelation1.compile()))\n Database.current.c.execute(\"PRAGMA table_info(tmp1)\")\n r1 = Database.current.c.fetchall()\n len_r1 = len(r1)\n Database.current.c.execute(\n \"CREATE TABLE tmp2 AS SELECT * FROM ({0})\".format(self.subrelation2.compile()))\n Database.current.c.execute(\"PRAGMA table_info(tmp2)\")\n r2 = Database.current.c.fetchall()\n len_r2 = len(r2)\n\n if len_r1 != len_r2:\n raise Exception(\n 'The two subrelations must have the same amount of columns.')\n for i in range(len_r2):\n if r1[i][2] != r2[i][2] or r1[i][1] != r2[i][1]:\n raise Exception(\n 'The elements of the two subrelations must be the same.')\n\n def compile(self):\n return \"SELECT * FROM ({0}) EXCEPT SELECT * FROM ({1})\".format(self.subrelation1.compile(), self.subrelation2.compile())\n","sub_path":"src/Diff.py","file_name":"Diff.py","file_ext":"py","file_size_in_byte":1646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"586878022","text":"# coding=utf-8\n\"\"\"\nA part of Source Detection.\nAuthor: Biao Chang, changb110@gmail.com, from University of Science and Technology of China\ncreated at 2017/1/9.\n\"\"\"\n\nimport decimal\n\nimport networkx as nx\n\nimport method\nimport rumor_center\nimport math\nfrom blist import blist\n\n\nclass ULBAA(method.Method):\n \"\"\"detect the source with lower and upper Bound Approximation.\n Please refer to the my paper for more details.\n \"\"\"\n prior = ''\n prior_detector = None\n\n def __init__(self, prior_detector):\n method.Method.__init__(self)\n self.method_name = self.__class__, prior_detector.method_name\n self.prior_detector = prior_detector\n\n def detect(self):\n \"\"\"detect the source with GSBA.\n\n Returns:\n @rtype:int\n the detected source\n \"\"\"\n self.reset_centrality()\n self.prior_detector.set_data(self.data)\n self.prior_detector.detect()\n self.prior = nx.get_node_attributes(self.subgraph, 'centrality')\n\n self.reset_centrality()\n rc = rumor_center.RumorCenter()\n rc.set_data(self.data)\n rc.detect()\n rumor_centralities = nx.get_node_attributes(self.subgraph, 'centrality')\n\n self.reset_centrality()\n infected_nodes = set(self.subgraph.nodes())\n n = len(infected_nodes)\n posterior = {}\n included = set()\n neighbours = set()\n weights = self.data.weights\n for v in infected_nodes:\n \"\"\"find the approximate upper bound by greedy searching\"\"\"\n included.clear()\n neighbours.clear()\n included.add(v)\n neighbours.add(v)\n likelihood_upper = 1\n w = {} # effective propagation probabilities: node->w\n w_key_sorted = blist()\n w[v] = 1\n w_key_sorted.append(v)\n while len(included) < n:\n w_sum = sum([w[j] for j in neighbours])\n u = w_key_sorted.pop() # pop out the last element from w_key_sorted with the largest w\n likelihood_upper *= w[u] / w_sum\n included.add(u)\n neighbours.remove(u)\n new = nx.neighbors(self.data.graph, u)\n for h in new:\n if h in included:\n continue\n neighbours.add(h)\n # compute w for h\n w_h2u = weights[self.data.node2index[u],self.data.node2index[h]]\n if h in w.keys():\n w[h] = 1-(1-w[h])*(1-w_h2u)\n else:\n w[h] = w_h2u\n # h_neighbor = nx.neighbors(self.data.graph, h)\n # w_h = 1\n # for be in included.intersection(h_neighbor):\n # w_h *= 1 - self.data.get_weight(h, be)\n # w[h] = 1 - w_h\n \"\"\"insert h into w_key_sorted, ranking by w from small to large\"\"\"\n if h in infected_nodes:\n if h in w_key_sorted:\n w_key_sorted.remove(h) # remove the old w[h]\n k = 0\n while k < len(w_key_sorted):\n if w[w_key_sorted[k]] > w[h]:\n break\n k += 1\n w_key_sorted.insert(k,h)\n #w_key_sorted[k:k] = [h]\n\n \"\"\"find the approximate lower bound by greedy searching\"\"\"\n included.clear()\n neighbours.clear()\n included.add(v)\n neighbours.add(v)\n likelihood_lower = 1\n w = {} # effective propagation probabilities: node->w\n w_key_sorted = blist()\n w[v] = 1\n w_key_sorted.append(v)\n while len(included) < n:\n w_sum = sum([w[j] for j in neighbours])\n u = w_key_sorted.pop() # pop out the last element from w_key_sorted with the largest w\n likelihood_lower *= w[u] / w_sum\n included.add(u)\n neighbours.remove(u)\n new = nx.neighbors(self.data.graph, u)\n for h in new:\n if h in included:\n continue\n neighbours.add(h)\n # compute w for h\n w_h2u = weights[self.data.node2index[u], self.data.node2index[h]]\n if h in w.keys():\n w[h] = 1 - (1 - w[h]) * (1 - w_h2u)\n else:\n w[h] = w_h2u\n \"\"\"insert h into w_key_sorted, ranking by w from large to small\"\"\"\n if h in infected_nodes:\n if h in w_key_sorted:\n w_key_sorted.remove(h) # remove the old w[h]\n k = 0\n while k < len(w_key_sorted):\n if w[w_key_sorted[k]] < w[h]:\n break\n k += 1\n w_key_sorted.insert(k, h)\n # w_key_sorted[k:k] = [h]\n likelihood = decimal.Decimal(likelihood_lower + likelihood_upper)*rumor_centralities[v]/2\n posterior[v] = decimal.Decimal(self.prior[v])* likelihood\n nx.set_node_attributes(self.subgraph, 'centrality', posterior)\n return self.sort_nodes_by_centrality()\n","sub_path":"jarden_center/research-master/research-master/SourceDetection/bao/map_ulbaa.py","file_name":"map_ulbaa.py","file_ext":"py","file_size_in_byte":5497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"401838875","text":"\n# standard\nimport json\nimport logging\n\n# packages\nimport requests\n\n# internal\nfrom context.context import Context\nfrom utility import const\n\n_LOGGER = logging.getLogger(__name__)\n\nbase_url = Context.data()[const.SILVER][const.BASE_URL]\nheaders = Context.data()[const.SILVER][const.HEADERS]\n\ndef list_customers():\n # get customer data from the silver api\n\n # build request url\n req_url = base_url + '/v2/customers'\n\n res = requests.get(\n url=req_url,\n headers=headers\n )\n\n if res.status_code == 200:\n return res.json()[const.RESULT]\n else:\n _LOGGER.error('Request error')\n return None","sub_path":"scripts/endpoints/list_customers.py","file_name":"list_customers.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"248364950","text":"\nfrom collections import Iterable\nfrom six import string_types\n\nclass ItemWare(object):\n def __init__(self, tag, options=None):\n self.set_tag(tag) \n\n def set_tag(self, tag):\n self.tag = tag\n\n def run(self, parser, structure, doc):\n return parser.extract_structure(structure.get(self.tag), doc)\n\n\nclass ListWare(object):\n def __init__(self, tag, options=None):\n self.set_tag(tag) \n if options and options.get('list_type'):\n self.list_type = options['list_type']\n else:\n self.list_type = None\n\n def set_tag(self, tag):\n self.tag = tag\n\n def run(self, parser, structure, doc):\n opts = {}\n if self.list_type:\n opts['query_type'] = self.list_type\n subdocs = parser.engine.run_query(structure.get(self.tag), doc, opts)\n \n # If the query isn't set up correctly, then this might return a string\n # or something that's not Iterable \n if isinstance(subdocs, string_types):\n subdocs = [subdocs]\n\n if not isinstance(subdocs, Iterable):\n raise Exception('Expression {0} produced a non-iterable result \\\n ({1}) instead of a list of nodes'.format(structure.get(self.tag), type(subdocs)))\n\n # Default item tag is '_item', make sure it exists\n # It's then up to the engine what to do for default / blank query\n if not '_item' in structure: \n structure['_item'] = '' \n\n # Extract results\n res = []\n for subdoc in subdocs:\n # if isinstance(subdoc, basestring):\n # raise Exception('Expression ' + structure.get('_list') + ' produced a string ' +\n # ' as an element instead of a node: ' + subdoc)\n res.append(parser.extract_structure(structure.get('_item'), subdoc))\n return res\n\n","sub_path":"strex/addins/basic_addins.py","file_name":"basic_addins.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"188058823","text":"#enter ten values\nprint(\"question1\")\nprint(\"enter the ten values\")\nfor i in range(10):\n x=int(input(\"enter your number\"))\n d=x\nprint(d)\nprint(\"\\n\")\n\n#infinite loop\nprint(\"question2\")\ni=1\nwhile i<10:\n print(\"hello world\")\n \nprint(i) \nprint(\"\\n\")\n\nprint(\"question3\")\n\n\n#list square\n\nl = []\ns = []\n\nfor x in range(3):\n\tl.append(int(input(\"Enter a number: \")))\n\nfor x in l:\n\t\ts.append(x**2)\n\nprint(l)\nprint(s)\n\n\n\n\n\nprint(\"\\n\")\n\n\nprint(\"question4\")\n#seprate the list of string, int and float\nlist = []\nfor x in range(0, 3):\n x = int(input(\"enter numbers\"))\n list.append(x)\nfor x in range(3, 6):\n x = input(\"enter strings\")\n list.append(x)\nfor x in range(6, 9):\n x = float(input(\"enter floats\"))\n list.append(x)\nprint(l)\na = []\nb = []\nc = []\nfor x in l:\n if type(x) == int:\n a.append(x)\n elif type(x) == str:\n b.append(x)\n elif type(x) == float:\n c.append(x)\nprint(a)\nprint(b)\nprint(c)\n\nprint(\"\\n\")\n\n\t\nprint(\"question5\")\n#range of even and odd\neven=[]\nodd=[]\nfor i in range(1,101):\n if i%2==0:\n even.append(i)\n else:\n odd.append(i)\nprint(even,\"\\n\",odd)\t\t\n\n\nprint(\"question6\")\n#print the pattern \ni = 1\nwhile (i <= 10):\n j = 1\n while (j <= i):\n print(\"*\", end=\"\")\n j = j + 1\n i = i + 1\n print()\nprint(\"\\n\")\t\nprint(\"question7\")\n#user define dictonary\nd = {}\nfor x in range(5):\n keys = int(input(\"enter the keys\"))\n values = input(\"enter value items\")\n d[keys] = values\nprint(d)\nprint(\"\\n\")\nprint(\"question8\")\n#list input search delete\n\nl = []\nflag = 0\nfor x in range(5):\n x = int(input(\"enter the numbers\"))\n l.append(x)\nprint(l)\ny = int(input(\"select any number you want to search\"))\nfor x in l:\n if x == y:\n l.remove(x)\n flag = 1\nprint(l)\nif flag == 0:\n print(\"the number you entered is not in the list\")","sub_path":"assignment6.py","file_name":"assignment6.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"543311761","text":"import time, sys, asyncio, functools\r\n\r\ndef all_stat(stats):\r\n cmd = sys.stdin.readline()\r\n if len(stats) <= 1:\r\n print('no traffic')\r\n return\r\n print('='*70)\r\n hstat = {}\r\n for remote_ip, v in stats.items():\r\n if remote_ip == 0: continue\r\n stat = [0]*6\r\n for host_name, v2 in v.items():\r\n for h in (stat, hstat.setdefault(host_name, [0]*6)):\r\n for i in range(6):\r\n h[i] += v2[i]\r\n stat = [(f'{i/1024/1024/1024:.1f}G' if i>=1024*1024*1024 else (f'{i/1024/1024:.1f}M' if i>=1024*1024 else f'{i/1024:.1f}K')) for i in stat[:4]] + stat[4:]\r\n print(remote_ip, f'\\tDIRECT: {stat[4]} ({stat[0]},{stat[2]}) PROXY: {stat[5]} ({stat[1]},{stat[3]})')\r\n print(' '*3+'-'*64)\r\n hstat = sorted(list(hstat.items()), key=lambda x: sum(x[1]), reverse=True)[:15]\r\n hlen = max(map(lambda x: len(x[0]), hstat)) if hstat else 0\r\n for host_name, stat in hstat:\r\n stat, conn = (stat[0]+stat[1], stat[2]+stat[3]), stat[4]+stat[5]\r\n stat = [(f'{i/1024/1024/1024:.1f}G' if i>=1024*1024*1024 else (f'{i/1024/1024:.1f}M' if i>=1024*1024 else f'{i/1024:.1f}K')) for i in stat]\r\n print(host_name.ljust(hlen+5), f'{stat[0]} / {stat[1]}', f'/ {conn}' if conn else '')\r\n print('='*70)\r\n\r\nasync def realtime_stat(stats):\r\n history = [(stats[:4], time.time())]\r\n while True:\r\n await asyncio.sleep(1)\r\n history.append((stats[:4], time.time()))\r\n i0, t0, i1, t1 = *history[0], *history[-1]\r\n stat = [(i1[i]-i0[i])/(t1-t0) for i in range(4)]\r\n stat = [(f'{i/1024/1024:.1f}M/s' if i>=1024*1024 else f'{i/1024:.1f}K/s') for i in stat]\r\n sys.stdout.write(f'DIRECT: {stats[4]} ({stat[0]},{stat[2]}) PROXY: {stats[5]} ({stat[1]},{stat[3]})\\x1b[0K\\r')\r\n sys.stdout.flush()\r\n if len(history) >= 10:\r\n del history[:1]\r\n\r\ndef setup(loop, args):\r\n args.verbose = lambda s: sys.stdout.write(s+'\\x1b[0K\\n') and sys.stdout.flush()\r\n args.stats = {0: [0]*6}\r\n def modstat(remote_ip, host_name, stats=args.stats):\r\n host_name_2 = '.'.join(host_name.split('.')[-3 if host_name.endswith('.com.cn') else -2:]) if host_name.split('.')[-1].isalpha() else host_name\r\n tostat = (stats[0], stats.setdefault(remote_ip, {}).setdefault(host_name_2, [0]*6))\r\n return lambda i: lambda s: [st.__setitem__(i, st[i] + s) for st in tostat]\r\n args.modstat = modstat\r\n loop.create_task(realtime_stat(args.stats[0]))\r\n loop.add_reader(sys.stdin, functools.partial(all_stat, args.stats))\r\n\r\n\r\n","sub_path":"pproxy/verbose.py","file_name":"verbose.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"297434755","text":"from collections import deque\n\n\nclass Solution:\n def clone_graph(self, root):\n dic = {}\n\n # 1st BFS: create node-to-node mapping\n q = deque([root])\n while q:\n node = q.popleft()\n dic[node] = Node(node.val, [])\n\n for nb in node.neighbors:\n if nb not in dic:\n q.append(nb)\n\n # 2nd BFS: associate nodes\n q = deque([root])\n s = set()\n while q:\n node = q.popleft()\n\n if node not in s:\n s.add(node)\n\n for nb in node.neighbors:\n if nb not in s:\n q.append(nb)\n # associate nodes\n dic[node].neighbors.append(dic[nb])\n\n return dic[root]\n\n\nclass Node:\n def __init__(self, val, neighbors):\n self.val = val\n self.neighbors = neighbors\n","sub_path":"A_Microsoft/clone_graph.py","file_name":"clone_graph.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"533533816","text":"import os\nfrom utils.logger import logging\n\n\nclass IRCSettingsError(Exception):\n pass\n\n\ndef check_settings(session):\n \"\"\"\n Settings checker for IRC protocol.\n \"\"\"\n req_attributes = {\"nickname\": str, \"server\": str, \"port\": int}\n missing_attributes = []\n for item in [item for item in req_attributes if not hasattr(session, item)]:\n missing_attributes.append(item)\n\n if missing_attributes:\n missing_attributes_string = ', '.join(missing_attributes)\n error = f\"Your session is missing the following required attributes: {missing_attributes_string}\"\n raise IRCSettingsError(error)\n\n for attr in [attr for attr in session.__dict__.keys() if attr in req_attributes]:\n is_type = type(getattr(session, attr))\n req_type = req_attributes[str(attr)]\n if is_type != req_type:\n error = f\"Wrong type for required attribute {attr}: {is_type} != {req_type}\"\n raise IRCSettingsError(error)\n\n\n # Checking optional attributes.\n optional_attributes = {\"channel\": str, \"alt_nick\": str, \"cert\": str}\n for attr in [attr for attr in session.__dict__.keys() if attr in optional_attributes]:\n is_type = type(getattr(session, attr))\n req_type = optional_attributes[str(attr)]\n if is_type != req_type:\n error = f\"Wrong type for optional attribute {attr}: {is_type} != {req_type}\"\n raise IRCSettingsError(error)\n\n if hasattr(session, 'cert'):\n if not os.path.isfile(session.cert):\n error = f\"You provied a TLS cert, but the file could not be found: {session.cert}\"\n raise IRCSettingsError(error)\n if not hasattr(session, 'tls') or not session.tls:\n logging.warning(\"You provided a TLS cert, but you have not enabled the TLS flag.\")\n","sub_path":"utils/settings/irc.py","file_name":"irc.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"394107279","text":"import requests\r\n\r\nurl = \"https://unfound-text-summarization-v1.p.rapidapi.com/summarization\"\r\n\r\npayload = \"{\\n \\\"input_data\\\": \\\"https://www.tesla.com/elon-musk\\\",\\n \\\"input_type\\\": \\\"url\\\",\\n \\\"summary_type\\\": \\\"general_summary\\\",\\n \\\"N\\\": 3\\n}\"\r\nheaders = {\r\n 'content-type': \"application/json\",\r\n 'x-rapidapi-key': \"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\r\n 'x-rapidapi-host': \"unfound-text-summarization-v1.p.rapidapi.com\"\r\n }\r\n\r\nresponse = requests.request(\"POST\", url, data=payload, headers=headers)\r\n\r\nprint(response.text)\r\n","sub_path":"image to text.py","file_name":"image to text.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"461971825","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport spacy\n\n\ndef data_load():\n data = pd.read_csv('cust_therm_comm.csv')\n data = data.loc[data['SATISFACTION_RATING_SCORE'] == 'bad']\n print(data)\n data = data.iloc[:, 4].dropna()\n print(data)\n return data\n\n\ndef preprocessing(data):\n nlp = spacy.load('en_core_web_lg')\n result = [[tkn.lemma_ for tkn in nlp(sentence) if\n (tkn.lower_ not in nlp.Defaults.stop_words and not tkn.is_punct and tkn.lemma_ != '-PRON-')]\n for sentence in data]\n result = [' '.join(i) for i in result]\n print(result)\n return result\n\n\ndef tf_pipeline(preprocessed_data):\n cv = CountVectorizer(stop_words='english', strip_accents='unicode', max_features=100, ngram_range=(3, 4))\n word_count_vector = cv.fit_transform(preprocessed_data)\n\n # print(word_count_vector)\n # print(word_count_vector.todense())\n # print(cv.vocabulary_)\n # print(cv.get_feature_names())\n\n tf_sums = np.array(word_count_vector.sum(axis=0)).flatten()\n\n word_and_tf = []\n for word, val in zip(cv.get_feature_names(), tf_sums):\n word_and_tf.append((word, val))\n return word_and_tf\n\n\ndef tfidf_pipeline(preprocessed_data):\n tfidf_vectorizer = TfidfVectorizer(use_idf=True, stop_words='english', max_features=50, ngram_range=(3, 5))\n tfidf_vector = tfidf_vectorizer.fit_transform(preprocessed_data)\n\n # print(f\"{tfidf_vectorizer_vectors}\\n\\n{tfidf_vectorizer_vectors.todense()}\\n\\n\\n\")\n # print(tfidf_vectorizer.get_stop_words())\n # print(tfidf_vectorizer.vocabulary_)\n\n tfidf_sums = np.array(tfidf_vector.sum(axis=0)).flatten()\n\n word_and_tfidf = []\n for word, val in zip(tfidf_vectorizer.get_feature_names(), tfidf_sums):\n word_and_tfidf.append((word, val))\n return word_and_tfidf\n\n\ndef export_tf(tf_pipeline_result):\n df = pd.DataFrame(tf_pipeline_result, columns=[\"term\", \"tf\"])\n df.sort_values(by=[\"tf\", \"term\"], ascending=False, inplace=True)\n print(df)\n with open('tf.csv', 'w', ) as f:\n df.to_csv(f)\n\n\ndef export_tfidf(tf_pipeline_result):\n df = pd.DataFrame(tf_pipeline_result, columns=[\"term\", \"tf_idf\"])\n df.sort_values(by=[\"tf_idf\", \"term\"], ascending=False, inplace=True)\n print(df)\n with open('tf_idf.csv', 'w', ) as f:\n df.to_csv(f)\n\n\nif __name__ == \"__main__\":\n pd.set_option('display.max_rows', None, 'display.max_columns', None)\n data = data_load()\n preprocessed_data = preprocessing(data)\n # tf_pipeline_result = tf_pipeline(preprocessed_data)\n tfidf_pipeline_result = tfidf_pipeline(preprocessed_data)\n # export_tf(tf_pipeline_result)\n export_tfidf(tfidf_pipeline_result)\n","sub_path":"python/ml/nlp/cust_therm_tf.py","file_name":"cust_therm_tf.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"308377615","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n def pathSum(self, root: TreeNode, summ: int) -> int:\n # path: count\n self.memo = {0:1}\n return self.dfs(root, 0, summ)\n\n def dfs(self, root, prevSum, summ):\n if not root:\n return 0\n count = 0\n cur_sum = prevSum + root.val\n\n if cur_sum - summ in self.memo:\n # sum of subtree's\n count += self.memo[cur_sum-summ]\n\n if cur_sum in self.memo:\n self.memo[cur_sum] += 1\n else:\n self.memo[cur_sum] = 1\n\n # start with different roots\n count += self.dfs(root.left, cur_sum, summ)\n count += self.dfs(root.right, cur_sum, summ)\n\n self.memo[cur_sum] -= 1\n return count\n\n \"\"\"\n # brute force\n def pathSum(self, root: TreeNode, summ: int) -> int:\n if not root:\n return 0\n \n return self.dfs(root, summ) + self.pathSum(root.left, summ) + self.pathSum(root.right, summ)\n\n def dfs(self, root, summ):\n if not root:\n return 0\n \n summ -= root.val\n\n return (1 if summ == 0 else 0) + self.dfs(root.left, summ) + self.dfs(root.right, summ)\n \"\"\"","sub_path":"Leetcode_By_Topic/bintree-437.py","file_name":"bintree-437.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"167863600","text":"from random import shuffle\n\nfrom Sapir.card import Card\nfrom Sapir.enum import Color, CardType\nfrom Sapir.human_player import HumanPlayer\nfrom Sapir.random_player import RandomPlayer\nfrom Sapir.smart_player import SmartPlayer\n\n\nclass Taki:\n def __init__(self):\n self.used_stop_in_top_card_in_stock = False\n self.amount_of_active_plus_two_in_stock = 0\n\n self.pack = self.init_pack()\n self.stock = [self.pack.pop()]\n self.players = self.init_players()\n self.winners = []\n self.strategies = [self.try_play_regular_card,\n self.try_play_stop_card,\n self.try_play_change_diraction_card,\n self.try_play_change_color_card,\n self.try_play_plus_two_card]\n\n # short funcs for ctor\n def init_pack(self):\n pack = []\n colors_for_creating_pack = [Color.RED.name, Color.BLUE.name, Color.YELLOW.name, Color.GREEN.name]\n # We dont have 2 cards (we have only +2)\n pack = [Card.regular_card(color, num_card) for num_card in range(1, 11) for color in colors_for_creating_pack]\n pack += [Card.changes_color_card() for num_card in range(4)]\n pack += [Card.changes_direction_card(color) for num_card in range(4) for color in colors_for_creating_pack]\n pack += [Card.stop_card(color) for num in range(4) for color in colors_for_creating_pack]\n pack += [Card.plus_two_card(color) for num in range(4) for color in colors_for_creating_pack]\n # pack += [Card.plus_card(color) for num in range(4) for color in colors_for_creating_pack]\n shuffle(pack)\n return pack\n\n def init_players(self):\n count_players = self.get_players_count()\n players = []\n for player in range(count_players):\n players.append(self.get_new_player())\n players.sort(key=lambda player: player.age, reverse=False)\n return players\n\n def get_new_player(self):\n dict_players_types = {1: SmartPlayer, 2: RandomPlayer, 3: HumanPlayer}\n while True:\n try:\n name = str(input(f'Player please enter your name'))\n if (len(name) > 2) and name.isalpha():\n break\n else:\n raise TypeError\n except TypeError:\n print(\"Enter only letters please.\")\n\n while True:\n try:\n print(f'Player please enter your age')\n age = int(input())\n break\n except ValueError:\n print(f\"your age must have be a number\")\n while True:\n try:\n print('Enter player type : 1 for a smart bot , 2 for a random bot or 3 for a human player')\n num_choice = int(input())\n if num_choice in dict_players_types.keys():\n player_type = dict_players_types[num_choice]\n player = player_type(name, self.pack[:3], age)\n del self.pack[:3]\n return player\n else:\n print(\"The input is not valid, please enter a number between 1 to 3\")\n except ValueError:\n print(f\"Enter a number between 1 to 3\")\n\n @property\n def top_card_in_stock(self):\n return self.stock[-1]\n\n def start_game(self):\n first_player = self.players[0]\n first_card_in_stock_is_changes_color = self.top_card_in_stock.card_type == CardType.CHANGES_COLOR and self.stock[0].color is None\n if first_card_in_stock_is_changes_color:\n first_player.change_color_of_top_card_in_stock(self)\n elif self.top_card_in_stock.card_type == CardType.PLUS_TWO:\n self.amount_of_active_plus_two_in_stock = 1\n\n while self.players:\n player = self.players[0]\n print()\n self.print_game_status()\n print()\n print(\"The current player is:\")\n player.print_player()\n print(f'The current top card in stock is {self.top_card_in_stock}')\n\n is_turn_finished = False\n if len(self.players) == 1:\n self.add_winner(player)\n elif self.top_card_in_stock.card_type == CardType.STOP and not self.used_stop_in_top_card_in_stock:\n print(f'There is a stop sign in stock , {player.name} you missed your turn ')\n self.used_stop_in_top_card_in_stock = True\n is_turn_finished = True\n self.next_in_line(player)\n elif self.top_card_in_stock.card_type == CardType.PLUS_TWO and self.amount_of_active_plus_two_in_stock != 0:\n is_turn_finished = player.play(self)\n if not is_turn_finished:\n if len(self.pack) >= 2 * self.amount_of_active_plus_two_in_stock:\n player.players_cards += self.pack[:2 * self.amount_of_active_plus_two_in_stock]\n del self.pack[:2 * self.amount_of_active_plus_two_in_stock]\n self.amount_of_active_plus_two_in_stock = 0\n else:\n player.players_cards.append(self.pack[:])\n is_turn_finished = True\n else:\n is_turn_finished = player.play(self)\n\n if is_turn_finished and not player.players_cards:\n self.add_winner(player)\n else:\n if self.pack:\n print(f'{player.name} doesnt have a fitting card, so {player.name} is taking from stock {player.players_cards[-1]}.')\n player.players_cards.append(self.pack.pop())\n else:\n raise Exception('Pack is empty')\n self.next_in_line(player)\n\n def try_play_card(self, card, player):\n same_color = self.top_card_in_stock.color == card.color\n same_type = self.top_card_in_stock.card_type == card.card_type\n same_number = self.top_card_in_stock.number == card.number\n\n if card.card_type == CardType.PLUS_TWO and (same_type or same_color):\n self.amount_of_active_plus_two_in_stock += 1\n return True\n\n if self.amount_of_active_plus_two_in_stock > 0:\n return False\n\n if card.card_type == CardType.CHANGES_COLOR:\n player.change_color_of_top_card_in_stock(self)\n return True\n\n if card.card_type == CardType.REGULAR_CARD and (same_color or same_number):\n self.put_card_in_stock(card, player)\n return True\n\n if card.card_type == CardType.CHANGES_DIRECTION and (same_color or same_type):\n self.players.reverse()\n return True\n\n if card.card_type == CardType.STOP and (same_color or same_type):\n self.used_stop_in_top_card_in_stock = False\n return True\n\n return False\n\n ########################################################################################################################\n\n # Strategies\n def try_play_regular_card(self, player):\n for card in player.players_cards:\n if card.card_type == CardType.REGULAR_CARD and self.try_play_card(card, player):\n return card\n return None\n\n def try_play_change_color_card(self, player):\n for card in player.players_cards:\n if card.card_type == CardType.CHANGES_COLOR and self.try_play_card(card, player):\n return card\n return None\n\n def try_play_stop_card(self, player):\n for card in player.players_cards:\n if card.card_type == CardType.STOP and self.try_play_card(card, player):\n return card\n return None\n\n def try_play_change_diraction_card(self, player):\n for card in player.players_cards:\n if card.card_type == CardType.CHANGES_DIRECTION and self.try_play_card(card, player):\n return card\n return None\n\n def try_play_plus_two_card(self, player):\n for card in player.players_cards:\n if card.card_type == CardType.PLUS_TWO and self.try_play_card(card, player):\n return card\n return None\n\n ########################################################################################################################\n\n def put_card_in_stock(self, card, player):\n print(f\"{player.name} have a fitting card {card}.\")\n player.players_cards.remove(card)\n self.stock.append(card)\n\n def next_in_line(self, player):\n self.players.remove(player)\n self.players.append(player)\n\n def change_color_of_top_card_in_stock_to_common_color_in_players_deck(self, player):\n common_color = player.get_common_color()\n self.top_card_in_stock.color = common_color\n print(f'we have a changing color card on stock, i choose {common_color} \\n')\n\n # ##prints\n def print_game_status(self):\n for player in self.players:\n print(f'{player.name} with {len(player.players_cards)} cards: {player.return_players_cards_status()}')\n print(f'Pack = {len(self.pack)}, table card is = {self.stock[-1]}\\n')\n\n def print_pack(self):\n for card in self.pack:\n print(card)\n\n def add_winner(self, player):\n self.winners.append(player)\n self.players.remove(player)\n winner_num = len(self.winners)\n print(f'{player.name} you are on number {winner_num} place')\n\n def print_list_of_winners(self):\n [print(f\"{player} you are in the {place} place\") for place, player in enumerate(self.winners, start=1)]\n\n def print_pack(self):\n [print(card) for card in self.pack]\n print(len(self.pack))\n\n def print_stock(self):\n [print(card) for card in self.stock]\n\n def print_players(self):\n [player.print_player() for player in self.players]\n\n def get_players_count(self):\n while True:\n try:\n count_of_players = int(input(\"How many players are you? - enter between 2-4 players\\n\"))\n if not (2 <= int(count_of_players) <= 4):\n count_of_players = input(\"you didn't enter an acceptable number, please enter again\\n\")\n else:\n return count_of_players\n except ValueError:\n print(\"Enter only a number between 2-4 \")\n","sub_path":"taki.py","file_name":"taki.py","file_ext":"py","file_size_in_byte":10375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"377343400","text":"# #/chrismattmann/tika-python/tika/tests/test_tika.py\n# import unittest\n# import tika.parser\n# class CreateTest(unittest.TestCase):\n# def test_remote_pdf(self):\n# #'parse remote PDF'\n# self.assertTrue(tika.parser.from_file('/input/tests/data/tikatest1.pdf'))\n# def test_remote_html(self):\n# #'parse remote HTML' \n# self.assertTrue(tika.parser.from_file('/input/tests/data/tikatest2.htm'))\n# def test_remote_mp3(self):\n# #'parese remote mp3'\n# self.assertTrue(tika.parser.from_file('/input/tests/data/tikatest3.mp3'))\n# def test_remote_jpg(self):\n# #'parse remote jpg'\n# self.assertTrue(tika.parser.from_file('/input/tests/data/tikatest4.jpg'))#\n\n# if __name__ == '__main__':\n# unittest.main()\n\nimport tika\nfrom tika import parser\n\nclass TestTika(unittest.TestCase):\n def test_tika(self):\n image = '/input/tests/data/tikatest.jpg'\n tika.initVM()\n parsed = parser.from_file(image)\n parsed.close()\n","sub_path":"tests/test_tika.py","file_name":"test_tika.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"66012053","text":"from dataclasses import dataclass\r\nfrom timeit import timeit\r\nfrom pympler import asizeof\r\n\r\n\r\n@dataclass\r\nclass Position:\r\n name: str\r\n lon: float = 0.0\r\n lat: float = 0.0\r\n\r\n\r\n@dataclass\r\nclass Capital(Position):\r\n country: str = 'Unknown'\r\n lat: float = 40.0\r\n\r\n\r\n@dataclass\r\nclass SlotPosition:\r\n __slots__ = ['name', 'lon', 'lat']\r\n name: str\r\n lon: float\r\n lat: float\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Capital('Oslo', country=\"Norway\"))\r\n pos = Position('London', -0.1, 51.5)\r\n slot = SlotPosition('Madrid', -3.7, 40.4)\r\n print(asizeof.asizeof(pos))\r\n print(asizeof.asizeof(slot))\r\n print(timeit('simple.name', setup=\"simple=Position('Oslo', 10.8, 59.9)\", globals=globals()))\r\n print(timeit('slot.name', setup=\"slot=SlotPosition('Oslo', 10.8, 59.9)\", globals=globals()))\r\n","sub_path":"basic_/dataclasses_/inheritance_.py","file_name":"inheritance_.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"378150026","text":"\"\"\"\r\ndemo11_anim.py 动画\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\nimport matplotlib.animation as ma\r\n\r\n\r\nmp.figure('Animation', facecolor='lightgray')\r\nmp.title('Animation', fontsize=14)\r\nmp.xlim(0, 10)\r\nmp.ylim(-3, 3)\r\n\r\npl = mp.plot([],[])[0]\r\n\r\n# 每30毫秒 更新\r\ndef update(data):\r\n\tt, v = data\r\n\t# 把新坐标加入曲线\r\n\tx, y = pl.get_data()\r\n\tx = np.append(x, t)\r\n\ty = np.append(y, v)\r\n\tpl.set_data(x, y)\r\n\tif x[-1]>10:\r\n\t\tmp.xlim(x[-1]-10, x[-1])\r\n\r\nx = 0\r\ndef generator():\r\n\tglobal x\r\n\ty = np.sin(2*np.pi*x) * \\\r\n\t\tnp.exp(np.sin(0.2*np.pi*x))\r\n\tyield (x,y)\r\n\tx+=0.05\r\n\r\nanim=ma.FuncAnimation(mp.gcf(), update, \r\n\tgenerator, interval=30)\r\n\r\nmp.show()\r\n","sub_path":"aid1812/day3/demo11_anim.py","file_name":"demo11_anim.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"192186355","text":"# This script runs all of the suites from each unit test file.\n# Run this file from the parent directory with the following command:\n# python -m tests.run_all\nfrom tests import *\nimport unittest \n\ndef main():\n test_suites = [\n test_reply.test_suite(),\n test_compiler.test_suite()\n ]\n all_tests = unittest.TestSuite(test_suites)\n unittest.TextTestRunner().run(all_tests)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"compilebot/tests/run_all.py","file_name":"run_all.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"80053157","text":"import unittest\nfrom selenium import webdriver\nfrom faker import Factory\nfrom pages.main_page import MainPage\nfrom pages.authoring_page import AuthoringPage\n\n\nclass WrapTests(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.driver = webdriver.Chrome()\n\t\tself.driver.implicitly_wait(2)\n\n\tdef test_create_wrap(self):\n\t\tfake = Factory.create()\n\t\tmain_page = MainPage(self.driver)\n\t\tauthoring_page = AuthoringPage(self.driver)\n\n\t\tself.driver.get('https://www.qa.wrapdev.net/')\n\t\tmain_page.signup(fake.email(), fake.user_name(), 'somePassword')\n\t\tmain_page.complete_account_info(fake.first_name(), fake.last_name(), fake.company())\n\n\t\tauthoring_page.create_new_wrap()\n\t\tauthoring_page.select_template()\n\t\tauthoring_page.create_template_wrap()\n\t\tauthoring_page.dismiss_tutorial()\n\t\tauthoring_page.publish_template_wrap()\n\t\tauthoring_page.success_image_present()","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"90712517","text":"import scipy as sp\nfrom scipy import integrate\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\nimport math as m\n\nfrom FunctionsGlobalBucklingAnalysis import segment_1,segment_2,segment_3, segment_4, segment_5\nfrom Definition_stringer_positions import Definition_stringer_position, stringer_distribution, a_stringer, h_stringer, t_stringer\nfrom Centroid import CentroidY\nimport Definition_stringer_positions\nt_wing_box_spar_cap = Definition_stringer_positions.t_wing_box_spar_cap\nt_wing_box_skin = Definition_stringer_positions.t_wing_box_skin\na_wing_box_spar_cap = Definition_stringer_positions.a_wing_box_spar_cap\n\ntaperRatio = 0.3 #[]\nrootChord = 11.95 #[m]\nwingSpan = 69.92 #[m]\n\n\n\ndef localChord(spanValue):\n localChord = rootChord - (rootChord - taperRatio * rootChord) / (wingSpan / 2) * spanValue\n return localChord\n\n\n\n#inputs stringer_positions: xpos, ypos, area, existence of stringer\n\ndef Ixx (y_span):\n stringer_positions = Definition_stringer_position(stringer_distribution, y_span)\n centroidY = CentroidY(stringer_distribution, y_span)\n\n #steinerTerms\n number_stringers = -4\n Ixx = 0\n for i in range(0, len(stringer_positions)):\n if stringer_positions[i][3]:\n #print(stringer_positions[i][3])\n Ixx += ((stringer_positions[i][1])-centroidY)**2 * (stringer_positions[i][2])\n number_stringers = number_stringers + 1\n #print(\"stringer pos: \", stringer_positions[i][1])\n #print(\"area: \", stringer_positions[i][2])\n #print(\"centroid: \", centroidY)\n\n\n #Non-steiner terms\n chord = localChord(y_span) * 1000 #chord in mm\n\n heightFrontSpar = 134.7 / 1000 * chord\n heightRearSpar = 109.1 / 1000 * chord\n frontSparCentroidY = heightFrontSpar / 2\n rearSparCentroidY = heightRearSpar / 2\n\n #spars contribution\n Ixx += (heightFrontSpar ** 3 * t_wing_box_spar_cap / 12) + 2 * (a_wing_box_spar_cap * t_wing_box_spar_cap ** 3 / 12 + a_wing_box_spar_cap * t_wing_box_spar_cap * (heightFrontSpar/2)**2)\n Ixx += (heightRearSpar **3 * t_wing_box_spar_cap / 12) + 2 * (a_wing_box_spar_cap * t_wing_box_spar_cap ** 3 / 12 + a_wing_box_spar_cap * t_wing_box_spar_cap * (heightRearSpar/2)**2)\n\n lengthSkin = 450 / 1000 * chord\n angleTopSkin = 2.08 * m.pi / 180\n angleBottomSkin = 1.18 * m.pi / 180\n\n #skin contribution\n Ixx += t_wing_box_skin * (lengthSkin/m.cos(angleTopSkin)) ** 3 * m.sin(angleTopSkin) ** 2 / 12\n Ixx += t_wing_box_skin * (lengthSkin/m.cos(angleBottomSkin)) ** 3 * m.sin(angleBottomSkin) ** 2 / 12\n\n #stringer contribution\n Ixx_stringer = h_stringer ** 3 * t_stringer / 12 + 2 * a_stringer * t_stringer** 3 / 12 + 2 * a_stringer * t_stringer * (h_stringer/2 + t_stringer/2)**2\n Ixx += number_stringers * Ixx_stringer\n return Ixx\n\n\n\"\"\"\n\nlistResolution = 80\nxList = []\nyList = []\n\nfor i in range(0, round(wingSpan / 2) * listResolution - 3):\n xList.append(i/listResolution)\n yList.append(Ixx(i / listResolution))\n\nplt.title('Moment of Inertia')\nplt.ylabel('Ixx [mm^4]')\nplt.xlabel('Span [m]')\nplt.plot(xList, yList)\nplt.show()\n\"\"\"\n\n\"\"\"\nprint(\"0:\",Ixx(0))\nprint(\"5:\", Ixx(5))\nprint(\"10:\", Ixx(10))\nprint(\"15:\", Ixx(15))\nprint(\"end - .5:\", Ixx(wingSpan /2 - .5))\nprint(\"end -0.1 :\", Ixx(wingSpan /2 - .1))\nprint(\"end:\", Ixx(wingSpan /2))\n\"\"\"","sub_path":"WP4/4.1/GlobalMomentofInertia.py","file_name":"GlobalMomentofInertia.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"205755628","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls.defaults import *\nfrom django.contrib.auth.decorators import login_required\nfrom cancellations.views import create_cancellation\n\nurlpatterns = patterns('cancellations.views',\n url(r'^(?P\\d+)/$', \n 'cancellation_detail', \n name='cancellations_cancellation_detail'\n ),\n url(r'^edit/(?P\\d+)/$',\n 'edit_cancellation',\n name='cancellations_edit_cancellation'\n ),\n url(r'^manage/$',\n 'manage',\n name='cancellations_manage',\n ),\n url(r'^create/$',\n 'create_cancellation',\n name='cancellations_create_cancellation',\n ),\n url(r'^search/$',\n 'search',\n name='cancellations_search',\n ),\n url(r'^$',\n 'home',\n name='cancellations_home',\n ),\n)\n\nurlpatterns += patterns('',\n #(r'^accounts/', include('registration.urls')),\n url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'registration/login.html'}, name='cancellations_login'),\n url(r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'registration/logout.html'}, name='cancellations_logout'),\n)\n","sub_path":"cancellations/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"141154931","text":"#coding=utf-8 \nimport cv2 \nimport numpy as np\n\nimg = cv2.imread(r'C:\\Users\\ticao\\Desktop\\electronic-system-practice\\photos\\3.jpg') #载入图像\nh, w = img.shape[:2] #获取图像的高和宽 \ncv2.namedWindow(\"Origin\",0)\ncv2.imshow(\"Origin\", img) #显示原始图像\n\nblured = cv2.blur(img,(5,5)) #进行滤波去掉噪声\ncv2.namedWindow(\"Blur\",0)\ncv2.imshow(\"Blur\", blured) #显示低通滤波后的图像\n\nmask = np.zeros((h+2, w+2), np.uint8) #掩码长和宽都比输入图像多两个像素点,满水填充不会超出掩码的非零边缘 \n#进行泛洪填充\ncv2.floodFill(blured, mask, (w-1,h-1), (255,255,255), (2,2,2),(3,3,3),8)\ncv2.namedWindow(\"floodfill\",0)\ncv2.imshow(\"floodfill\", blured) \n\n#得到灰度图\ngray = cv2.cvtColor(blured,cv2.COLOR_BGR2GRAY) \ncv2.namedWindow(\"gray\",0)\ncv2.imshow(\"gray\", gray) \n\n\n#定义结构元素 \nkernel = cv2.getStructuringElement(cv2.MORPH_RECT,(50, 50))\n#开闭运算,先开运算去除背景噪声,再继续闭运算填充目标内的孔洞\nopened = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel) \nclosed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel) \ncv2.namedWindow(\"closed\",0)\ncv2.imshow(\"closed\", closed) \n\n#求二值图\nret, binary = cv2.threshold(closed,250,255,cv2.THRESH_BINARY) \ncv2.namedWindow(\"binary\",0)\ncv2.imshow(\"binary\", binary) \n\n#找到轮廓\ncontours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) \n#绘制轮廓\n\ncv2.drawContours(img,contours,-1,(0,0,255),3) \n#绘制结果\ncv2.namedWindow(\"result\",0)\ncv2.imshow(\"result\", img)\n\ncv2.waitKey(0) \ncv2.destroyAllWindows()","sub_path":"practice/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"294215140","text":"\n\nfrom .line import Line\nfrom .string import String\nfrom core.compiler import Compiler\nfrom core.ti_basic import END_LINE\n\n\nclass RawInclusion(Line):\n\n\tdef __init__(self, names: [str], as_string: bool, value: str):\n\n\t\tself.names = names\n\t\tself.as_string = as_string\n\t\tself.value = value\n\n\tdef __str__(self) -> str:\n\t\treturn f\"include raw {self.names}\"\n\n\tdef eval(self, compiler: Compiler):\n\t\tif self.as_string:\n\t\t\tString(self.value).eval_as_raw(compiler, self.localize())\n\t\telse:\n\t\t\tcompiler.write_include_raw_ns(self.names, self.localize())\n","sub_path":"core/ast_nodes/raw_inclusion.py","file_name":"raw_inclusion.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"501393319","text":"#-*-coding:utf-8-*-\nfrom django.shortcuts import render,redirect,get_object_or_404\nfrom django.http import HttpResponse\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.decorators import login_required\nfrom mysite.models import Member_Model,Post_Model,Comment_Model\nimport json\n\n@login_required(login_url='/mysite/login/')\ndef comment(request):\n\tget_email = request.user.username\n\tobj = Member_Model.objects.get(email=get_email)\n\tget_nick_name = obj.nick_name\n\tif get_nick_name is None:\n\t\tget_nick_name = get_email\n\tprint(\"in comment\")\n\tif request.is_ajax():\n\t\tprint(\"in ajax\")\n\t\tid = request.POST[\"id\"]\n\t\tget_post= get_object_or_404(Post_Model, post_id=id)\n\t\tfloor_num = get_post.comment_model_set.all().count()\n\t\tget_parent_floor = request.POST[\"parent_floor\"]\n\t\tget_content = request.POST[\"content\"]\n\t\tif int(get_parent_floor) == 1 :\n\t\t\tprint(\"in if\")\n\t\t\tComment_Model.objects.create(ref_post=get_post,\n\t\t\t\t\t\t\t\t\t\tfloor=int(floor_num)+2,\n\t\t\t\t\t\t\t\t\t\tauthor=get_nick_name,\n\t\t\t\t\t\t\t\t\t\tcontent=get_content)\n\t\telse :\n\t\t\tprint(\"in else\")\n\t\t\tComment_Model.objects.create(ref_post=get_post,\n\t\t\t\t\t\t\t\t\t\tfloor=int(floor_num)+2,\n\t\t\t\t\t\t\t\t\t\tparent_floor=get_object_or_404(Comment_Model,ref_post=get_post,floor=int(get_parent_floor)),\n\t\t\t\t\t\t\t\t\t\tauthor=get_nick_name,\n\t\t\t\t\t\t\t\t\t\tcontent=get_content)\n\n\t\tprint(id+get_nick_name+get_content)\n\t\treturn HttpResponse(json.dumps({\"status\":\"200\"}))\n\t\t#if not is_exists:\n\t\t#\tSign_Model.objects.create(email=get_email,cost=5,last_sign=now())\n\t\t#\treturn HttpResponse(json.dumps({\"data\":\"post_success\"}))\n\t\t#obj = Sign_Model.objects.get(email=get_email)\n\t\t#if obj.last_sign.date() != now().date():\n\t\t#\tobj.cost = obj.cost + 5\n\t\t#\tobj.last_sign = now()\n\t\t#\tobj.save()\n\t\t#\treturn HttpResponse(json.dumps({\"data\":\"post_success\"}))\n\t\t#else:\n\t\t#\treturn HttpResponse(json.dumps({\"data\":\"post_again\"}))\n","sub_path":"IBMsite/mysite/views/comment_views.py","file_name":"comment_views.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"519415619","text":"import os\n\n#f = open('markUp_files/Update-CsUserDatabase.md', 'r')\n\npath_in = 'markup_files/'\npath_out = 'processed/'\n\nf_out = open('result', 'w', encoding='utf8')\n\nfor file in os.listdir(path_in):\n f_in = open(os.path.join(path_in, file), 'r', encoding='utf8')\n #f_out = open(os.path.join(path_out, file), 'w', encoding='utf8')\n f_out.write(file + '\\n')\n f_in.readline()\n a_string = f_in.readline()\n if not a_string.startswith(\"applicable\"):\n print('FOUND IT! ' + file)\n f_in.close()\n\nf_out.close()\n#for line in f:\n #print(line, end='')\n","sub_path":"misc/check_meta.py","file_name":"check_meta.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"375659510","text":"import logging\nimport random\nimport time\n\nfrom .exception import re_raisable\n\nlogger = logging.getLogger(__name__)\n\n\ndef retry(action, name, times=5):\n try:\n return action()\n except Exception as e:\n if times < 20:\n throttle_seconds = min(pow(2, times * random.uniform(0.1, 0.2)), 30)\n logger.warn('Retrying \"{0}\" in {1} seconds: {2}'.format(name, throttle_seconds, str(e)))\n time.sleep(throttle_seconds)\n return retry(action, times + 1)\n re_raisable()\n raise e\n","sub_path":"modules/google-earth-engine/docker/src/sepalinternal/retry.py","file_name":"retry.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"55003045","text":"def looper():\n#This prints a table of multiples in the range of 1-9 and highlights 42 \n for row in range(1, 10):\n print()\n \n\n for column in range(1, 10):\n if column == 6 and row == 7 or row == 7 and column == 6:\n print(format(\" >42\"),end='')\n else:\n print(format(row * column,'4d'),end='')\n","sub_path":"projects/looper.py","file_name":"looper.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"408889069","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCopyright 2018 NAVER Corp.\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and\nassociated documentation files (the \"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\nCONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE\nOR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport os\nimport csv\nimport math\n\nimport numpy as np\n\nimport torch.utils.data as data\nimport torchvision.transforms as transforms\nfrom reg.kor_char_parser import decompose_str_as_one_hot\n\npre_process = transforms.Compose([\n transforms.ToTensor(),\n])\n\nperson_len = 10 # 전체 사람 숫자\nmovie_len = 8259 # 전체 영화 개수 \n\n\nclass MoiveDataLoader(data.Dataset):\n\n def __init__(self, csv_path) -> None:\n super().__init__()\n\n self.person_arr = []\n self.movie_arr = []\n self.duration_arr = []\n\n # csv에 영화 정보 데이터를 넣어준다.\n with open(csv_path, 'r', encoding='utf-8') as f:\n rdr = csv.reader(f)\n\n for line in rdr:\n self.person_arr.append(int(line[0]))\n self.movie_arr.append(int(line[1]))\n self.duration_arr.append(math.log(int(line[2])))\n\n def __getitem__(self, index):\n \"\"\"\n 데이터 one hot으로 인코딩하여 리턴하자\n TODO: 임베딩 작업 필요하다.\n \"\"\"\n person_one_hot = [0 for _ in range(person_len)]\n person_one_hot[self.person_arr[index]] = 1\n p_np = np.array(person_one_hot, dtype=np.float32)\n\n movie_one_hot = [0 for _ in range(movie_len)]\n movie_one_hot[self.movie_arr[index]] = 1\n m_np = np.array(movie_one_hot, dtype=np.float32)\n\n d_np = np.array([self.duration_arr[index]], dtype=np.float32)\n\n return p_np, m_np, d_np\n\n def __len__(self):\n return len(self.person_arr)\n\n\nclass KinQueryDataset:\n \"\"\"\n 지식인 데이터를 읽어서, tuple (데이터, 레이블)의 형태로 리턴하는 파이썬 오브젝트 입니다.\n \"\"\"\n\n def __init__(self, dataset_path: str, max_length: int):\n \"\"\"\n :param dataset_path: 데이터셋 root path\n :param max_length: 문자열의 최대 길이\n \"\"\"\n # 데이터, 레이블 각각의 경로\n queries_path = os.path.join(dataset_path, 'train', 'train_data')\n labels_path = os.path.join(dataset_path, 'train', 'train_label')\n\n # 지식인 데이터를 읽고 preprocess까지 진행합니다\n with open(queries_path, 'rt', encoding='utf8') as f:\n self.queries = preprocess(f.readlines(), max_length)\n # 지식인 레이블을 읽고 preprocess까지 진행합니다.\n with open(labels_path) as f:\n self.labels = np.array([[np.float32(x)] for x in f.readlines()])\n\n def __len__(self):\n \"\"\"\n :return: 전체 데이터의 수를 리턴합니다\n \"\"\"\n return len(self.queries)\n\n def __getitem__(self, idx):\n \"\"\"\n :param idx: 필요한 데이터의 인덱스\n :return: 인덱스에 맞는 데이터, 레이블 pair를 리턴합니다\n \"\"\"\n return self.queries[idx], self.labels[idx]\n\n\ndef preprocess(data: list, max_length: int):\n \"\"\"\n 입력을 받아서 딥러닝 모델이 학습 가능한 포맷으로 변경하는 함수입니다.\n 기본 제공 알고리즘은 char2vec이며, 기본 모델이 MLP이기 때문에, 입력 값의 크기를 모두 고정한 벡터를 리턴합니다.\n 문자열의 길이가 고정값보다 길면 긴 부분을 제거하고, 짧으면 0으로 채웁니다.\n :param data: 문자열 리스트 ([문자열1, 문자열2, ...])\n :param max_length: 문자열의 최대 길이\n :return: 벡터 리스트 ([[0, 1, 5, 6], [5, 4, 10, 200], ...]) max_length가 4일 때\n \"\"\"\n vectorized_data = [decompose_str_as_one_hot(datum, warning=False) for datum in data]\n zero_padding = np.zeros((len(data), max_length), dtype=np.int32)\n for idx, seq in enumerate(vectorized_data):\n length = len(seq)\n if length >= max_length:\n length = max_length\n zero_padding[idx, :length] = np.array(seq)[:length]\n else:\n zero_padding[idx, :length] = np.array(seq)\n return zero_padding\n\n\ndef get_data(csv_path):\n with open(csv_path, 'r', encoding='utf-8') as f:\n rdr = csv.reader(f)\n\n person_arr = []\n movie_arr = []\n duration_arr = []\n\n person_len = 10\n movie_len = 8259\n\n for line in rdr:\n person_one_hot = [0 for _ in range(person_len)]\n movie_one_hot = [0 for _ in range(movie_len)]\n\n person_one_hot[int(line[0])] = 1\n movie_one_hot[int(line[1])] = 1\n\n person_arr.append(person_one_hot)\n movie_arr.append(movie_one_hot)\n duration_arr.append([math.log(int(line[2]))])\n\n return np.array(person_arr), np.array(movie_arr), np.array(duration_arr)\n","sub_path":"reg/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"26920230","text":"# --------------------------------------------------------\n# Tensorflow Faster R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Xinlei Chen\n# --------------------------------------------------------\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport cv2\nimport numpy as np\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\nimport os\nimport math\n\nfrom utils.timer import Timer\nfrom utils.blob import im_list_to_blob\n\nfrom model.config import cfg, get_output_dir\nfrom model.bbox_transform import clip_boxes, bbox_transform_inv\nfrom model.nms_wrapper import nms\nfrom utils.boxTools import *\nfrom utils.dppTools import DPP\nimport cPickle\n\ndef _get_image_blob(im):\n \"\"\"Converts an image into a network input.\n Arguments:\n im (ndarray): a color image in BGR order\n Returns:\n blob (ndarray): a data blob holding an image pyramid\n im_scale_factors (list): list of image scales (relative to im) used\n in the image pyramid\n \"\"\"\n im_orig = im.astype(np.float32, copy=True)\n im_orig -= cfg.PIXEL_MEANS\n\n im_shape = im_orig.shape\n im_size_min = np.min(im_shape[0:2])\n im_size_max = np.max(im_shape[0:2])\n\n processed_ims = []\n im_scale_factors = []\n\n for target_size in cfg.TEST.SCALES:\n im_scale = float(target_size) / float(im_size_min)\n # Prevent the biggest axis from being more than MAX_SIZE\n if np.round(im_scale * im_size_max) > cfg.TEST.MAX_SIZE:\n im_scale = float(cfg.TEST.MAX_SIZE) / float(im_size_max)\n im = cv2.resize(im_orig, None, None, fx=im_scale, fy=im_scale,\n interpolation=cv2.INTER_LINEAR)\n im_scale_factors.append(im_scale)\n processed_ims.append(im)\n\n # Create a blob to hold the input images\n blob = im_list_to_blob(processed_ims)\n\n return blob, np.array(im_scale_factors)\n\ndef _get_blobs(im):\n \"\"\"Convert an image and RoIs within that image into network inputs.\"\"\"\n blobs = {}\n blobs['data'], im_scale_factors = _get_image_blob(im)\n\n return blobs, im_scale_factors\n\ndef _clip_boxes(boxes, im_shape):\n \"\"\"Clip boxes to image boundaries.\"\"\"\n # x1 >= 0\n boxes[:, 0::4] = np.maximum(boxes[:, 0::4], 0)\n # y1 >= 0\n boxes[:, 1::4] = np.maximum(boxes[:, 1::4], 0)\n # x2 < im_shape[1]\n boxes[:, 2::4] = np.minimum(boxes[:, 2::4], im_shape[1] - 1)\n # y2 < im_shape[0]\n boxes[:, 3::4] = np.minimum(boxes[:, 3::4], im_shape[0] - 1)\n return boxes\n\ndef _rescale_boxes(boxes, inds, scales):\n \"\"\"Rescale boxes according to image rescaling.\"\"\"\n for i in range(boxes.shape[0]):\n boxes[i,:] = boxes[i,:] / scales[int(inds[i])]\n\n return boxes\n\ndef im_detect(sess, net, im):\n blobs, im_scales = _get_blobs(im)\n assert len(im_scales) == 1, \"Only single-image batch implemented\"\n\n im_blob = blobs['data']\n blobs['im_info'] = np.array([im_blob.shape[1], im_blob.shape[2], im_scales[0]], dtype=np.float32)\n\n _, scores, bbox_pred, rois = net.test_image(sess, blobs['data'], blobs['im_info'])\n \n boxes = rois[:, 1:5] / im_scales[0]\n scores = np.reshape(scores, [scores.shape[0], -1])\n bbox_pred = np.reshape(bbox_pred, [bbox_pred.shape[0], -1])\n if cfg.TEST.BBOX_REG:\n # Apply bounding-box regression deltas\n box_deltas = bbox_pred\n pred_boxes = bbox_transform_inv(boxes, box_deltas)\n pred_boxes = _clip_boxes(pred_boxes, im.shape)\n else:\n # Simply repeat the boxes, once for each class\n pred_boxes = np.tile(boxes, (1, scores.shape[1]))\n\n return scores, pred_boxes\n\ndef apply_nms(all_boxes, thresh):\n \"\"\"Apply non-maximum suppression to all predicted boxes output by the\n test_net method.\n \"\"\"\n num_classes = len(all_boxes)\n num_images = len(all_boxes[0])\n nms_boxes = [[[] for _ in range(num_images)] for _ in range(num_classes)]\n for cls_ind in range(num_classes):\n for im_ind in range(num_images):\n dets = all_boxes[cls_ind][im_ind]\n if dets == []:\n continue\n\n x1 = dets[:, 0]\n y1 = dets[:, 1]\n x2 = dets[:, 2]\n y2 = dets[:, 3]\n scores = dets[:, 4]\n inds = np.where((x2 > x1) & (y2 > y1))[0]\n dets = dets[inds,:]\n if dets == []:\n continue\n\n keep = nms(dets, thresh)\n if len(keep) == 0:\n continue\n nms_boxes[cls_ind][im_ind] = dets[keep, :].copy()\n return nms_boxes\n\ndef test_net(sess, net, imdb, weights_filename, max_per_image=100, thresh=0.):\n np.random.seed(cfg.RNG_SEED)\n \"\"\"Test a Fast R-CNN network on an image database.\"\"\"\n num_images = len(imdb.image_index)\n # all detections are collected into:\n # all_boxes[cls][image] = N x 5 array of detections in\n # (x1, y1, x2, y2, score)\n all_boxes = [[[] for _ in range(num_images)]\n for _ in range(imdb.num_classes)]\n\n output_dir = get_output_dir(imdb, weights_filename)\n # timers\n _t = {'im_detect' : Timer(), 'misc' : Timer()}\n\n for i in range(num_images):\n im = cv2.imread(imdb.image_path_at(i))\n\n _t['im_detect'].tic()\n scores, boxes = im_detect(sess, net, im)\n _t['im_detect'].toc()\n\n _t['misc'].tic()\n\n # skip j = 0, because it's the background class\n for j in range(1, imdb.num_classes):\n inds = np.where(scores[:, j] > thresh)[0]\n cls_scores = scores[inds, j]\n cls_boxes = boxes[inds, j*4:(j+1)*4]\n cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \\\n .astype(np.float32, copy=False)\n keep = nms(cls_dets, cfg.TEST.NMS)\n cls_dets = cls_dets[keep, :]\n all_boxes[j][i] = cls_dets\n\n # Limit to max_per_image detections *over all classes*\n if max_per_image > 0:\n image_scores = np.hstack([all_boxes[j][i][:, -1]\n for j in range(1, imdb.num_classes)])\n if len(image_scores) > max_per_image:\n image_thresh = np.sort(image_scores)[-max_per_image]\n for j in range(1, imdb.num_classes):\n keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]\n all_boxes[j][i] = all_boxes[j][i][keep, :]\n _t['misc'].toc()\n\n print('im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \\\n .format(i + 1, num_images, _t['im_detect'].average_time,\n _t['misc'].average_time))\n\n det_file = os.path.join(output_dir, 'detections.pkl')\n with open(det_file, 'wb') as f:\n pickle.dump(all_boxes, f, pickle.HIGHEST_PROTOCOL)\n\n print('Evaluating detections')\n imdb.evaluate_detections(all_boxes, output_dir)\n\n\ndef test_net_MC(sess, net, imdb,weights_filename, max_per_image=100, thresh=0.05, vis=False):\n \"\"\"Test a Fast R-CNN network on an image database.\"\"\"\n\n num_images = len(imdb.image_index)\n thresh = cfg.TEST.SCORE_THRESH\n # all detections are collected into:\n # all_boxes[cls][image] = N x 5 array of detections in\n # (x1, y1, x2, y2, score)\n print(\n \"score threshold:\", thresh)\n all_boxes = [[[] for _ in xrange(num_images)]\n for _ in xrange(imdb.num_classes)]\n\n output_dir = get_output_dir(imdb, weights_filename)\n\n # timers\n _t = {'im_detect': Timer(), 'misc': Timer()}\n\n if not cfg.TEST.HAS_RPN:\n roidb = imdb.roidb\n\n for i in xrange(num_images):\n\n # filter out any ground truth boxes\n if cfg.TEST.HAS_RPN:\n box_proposals = None\n else:\n # The roidb may contain ground-truth rois (for example, if the roidb\n # comes from the training or val split). We only want to evaluate\n # detection on the *non*-ground-truth rois. We select those the rois\n # that have the gt_classes field set to 0, which means there's no\n # ground truth.\n box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0]\n\n im = cv2.imread(imdb.image_path_at(i))\n _t['im_detect'].tic()\n scores, boxes = im_detect(sess, net, im)\n\n _t['im_detect'].toc()\n\n _t['misc'].tic()\n\n # skip j = 0, because it's the background class\n cls_dets_all = np.array(())\n box_inds = []\n for j in xrange(1, imdb.num_classes):\n inds = np.where(scores[:, j] > thresh)[0]\n cls_scores = scores[inds, j]\n cls_boxes = boxes[inds, j * 4:(j + 1) * 4]\n cls_dets = np.hstack((cls_boxes, cls_scores[:, np.newaxis])) \\\n .astype(np.float32, copy=False)\n keep = nms(cls_dets, cfg.TEST.NMS)\n cls_dets = cls_dets[keep, :]\n box_inds.extend(inds[keep])\n\n cls_lbl = j * np.ones((cls_dets.shape[0], 1))\n cls_dets = np.hstack((cls_dets, cls_lbl))\n if j == 1:\n cls_dets_all = cls_dets\n else:\n cls_dets_all = np.vstack((cls_dets_all, cls_dets)) \\\n .astype(np.float32, copy=False)\n box_inds = np.array(box_inds)\n keep_MC = nms(cls_dets_all[:, :-1], cfg.TEST.MC_NMS)\n cls_dets_all = cls_dets_all[keep_MC, :]\n\n for j in xrange(1, imdb.num_classes):\n keeps_j = np.where(cls_dets_all[:, -1] == j)[0]\n cls_dets_class_j = cls_dets_all[keeps_j, :-1]\n all_boxes[j][i] = cls_dets_class_j\n\n # if vis:\n # vis_detections(im, imdb.classes[j], cls_dets_class_j, cfg.TEST.SCORE_THRESH)\n\n # Limit to max_per_image detections *over all classes*\n if max_per_image > 0:\n image_scores = np.hstack([all_boxes[j][i][:, -1]\n for j in xrange(1, imdb.num_classes)])\n if len(image_scores) > max_per_image:\n image_thresh = np.sort(image_scores)[-max_per_image]\n for j in xrange(1, imdb.num_classes):\n keep = np.where(all_boxes[j][i][:, -1] >= image_thresh)[0]\n all_boxes[j][i] = all_boxes[j][i][keep, :]\n _t['misc'].toc()\n\n print(\n 'im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \\\n .format(i + 1, num_images, _t['im_detect'].average_time,\n _t['misc'].average_time))\n\n det_file = os.path.join(output_dir, 'detections.pkl')\n with open(det_file, 'wb') as f:\n cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL)\n\n print(\n 'Evaluating detections')\n imdb.evaluate_detections(all_boxes, output_dir)\n\n\ndef dpp_test_net(sess, net, imdb, weights_filename, max_per_image=100, thresh=0.2, vis=False):\n \"\"\"Test a Fast R-CNN network on an image database.\"\"\"\n num_images = len(imdb.image_index)\n thresh = cfg.TEST.SCORE_THRESH\n print(\n \"===> SCORE_THRESHOLD is: \", thresh)\n # all detections are collected into:\n # all_boxes[cls][image] = N x 5 array of detections in\n # (x1, y1, x2, y2, score)\n all_boxes = [[[] for _ in xrange(num_images)]\n for _ in xrange(imdb.num_classes)]\n\n output_dir = get_output_dir(imdb, weights_filename)\n\n # timers\n _t = {'im_detect': Timer(), 'misc': Timer()}\n\n if not cfg.TEST.HAS_RPN:\n roidb = imdb.roidb\n im_dets_pair = {}\n sim_classes = pickle.load(open(cfg.TRAIN.similarity_path, \"r\"))\n\n ff = {}\n for j in xrange(1, imdb.num_classes):\n cls_file = os.path.join(output_dir, '%s.txt' % imdb.classes[j])\n ff[j] = open(cls_file, 'a')\n\n for i in xrange(num_images):\n # filter out any ground truth boxes\n if cfg.TEST.HAS_RPN:\n box_proposals = None\n else:\n # The roidb may contain ground-truth rois (for example, if the roidb\n # comes from the training or val split). We only want to evaluate\n # detection on the *non*-ground-truth rois. We select those the rois\n # that have the gt_classes field set to 0, which means there's no\n # ground truth.\n box_proposals = roidb[i]['boxes'][roidb[i]['gt_classes'] == 0]\n im = cv2.imread(imdb.image_path_at(i))\n _t['im_detect'].tic()\n scores, boxes = im_detect(sess, net, im)\n\n _t['im_detect'].toc()\n _t['misc'].tic()\n # skip j = 0, because it's the background class\n im_dets_pair[i] = {}\n im_dets_pair[i]['im'] = im\n im_dets_pair[i]['lbl'] = imdb.classes\n score_thresh = thresh\n epsilon = 0.01\n DPP_ = DPP(epsilon=0.02)\n keep = DPP_.dpp_MAP(im_dets_pair[i], scores, boxes, sim_classes, score_thresh, epsilon, max_per_image,\n close_thr=0.00001)\n if len(keep['box_id']) > 0:\n for j in xrange(1, imdb.num_classes):\n inds = np.where(keep['box_cls'] == j)[0]\n box_ids = keep['box_id'][inds]\n for per_cls in box_ids:\n ff[j].write(\"%s %g %d %d %d %d\\n\" % (imdb.image_path_at(i), scores[per_cls, j], boxes[per_cls, 4 * j],\n boxes[per_cls, 4 * j + 1], boxes[per_cls, 4 * j + 2],\n boxes[per_cls, 4 * j + 3]))\n cls_dets = np.hstack((boxes[box_ids, 4 * j:(j + 1) * 4], scores[box_ids, j][:, np.newaxis])) \\\n .astype(np.float32, copy=False)\n all_boxes[j][i] = cls_dets\n im_dets_pair[i][j] = {}\n im_dets_pair[i][j]['dets'] = cls_dets\n # if vis:\n # vis_detections(im, imdb.classes[j], cls_dets, score_thresh)\n else:\n for j in xrange(1, imdb.num_classes):\n all_boxes[j][i] = np.array([])\n _t['misc'].toc()\n\n print(\n 'im_detect: {:d}/{:d} {:.3f}s {:.3f}s' \\\n .format(i + 1, num_images, _t['im_detect'].average_time,\n _t['misc'].average_time))\n\n for j in xrange(1, imdb.num_classes):\n ff[j].close()\n\n det_file = os.path.join(output_dir, 'detections_dpp.pkl')\n with open(det_file, 'wb') as f:\n cPickle.dump(all_boxes, f, cPickle.HIGHEST_PROTOCOL)\n\n print(\n 'Evaluating detections')\n imdb.evaluate_detections(all_boxes, output_dir)\n","sub_path":"lib/model/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":13110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"382702055","text":"# coding: utf-8\n'''程序主要部分'''\n\n# 外部依赖\nimport datetime\nimport threading\n# library依赖\nfrom sine.utils import ReStartableThread\n# 本地依赖\nfrom .globalData import clocks, data, config, eManager\nfrom .mydatetime import getNow\nfrom . import initUtil\nfrom . import player\nfrom . import mylogging\nfrom . import manager\nfrom . import userInterface\n\nlogger = mylogging.getLogger(__name__)\n\nalarmInterval = datetime.timedelta(0, config['alarm_interval'])\nalarmLast = config['alarm_last']\n\n# 监听线程,检查并更新闹钟状态\n\ndef _listen(stop_event):\n startTime = None\n\n prev = getNow()\n minGap = datetime.timedelta(0, 300) # 超过300秒,认为是睡眠/待机唤醒\n while not stop_event.wait(0.1):\n # 检查睡眠唤醒和跨越凌晨\n cur = getNow()\n gap = cur - prev\n if gap >= minGap:\n eManager.sendEvent('time_leap', {'gap':gap})\n stop_event.wait(1) # sleep\n elif datetime.datetime.date(cur) != datetime.datetime.date(prev):\n eManager.sendEvent('cross_day')\n prev = cur\n\n # 获取需要闹铃提醒的闹钟\n reminds = manager.getReminds()\n length = len(reminds)\n player.play(reminds[-1]['sound'] if length else None)\n \n # 响铃状态切换\n if startTime == None and length:\n startTime = getNow()\n eManager.sendEvent('alarm.start')\n if startTime and not length:\n startTime = None\n eManager.sendEvent('alarm.stop')\n if startTime and (getNow() - startTime).seconds > alarmLast:\n startTime = None\n eManager.sendEvent('alarm.timeout')\n logger.info('listenThread exit')\n return\n\nlistenThread = ReStartableThread(target=_listen)\n\n# 托盘图标 -----------------\n\ntry:\n from .trayIcon import createIcon, deleteIcon\nexcept Exception as e:\n initUtil.warn(u'不支持托盘图标(包括消息提示)。', e)\n createIcon = deleteIcon = initUtil.doNothing\n data['show_msg'] = False\n\n# 任务栏闪烁 -----------------\n\ntry:\n if config['taskbar_flash']:\n from .winUtil import flash, stopFlash, show as show_window\n eManager.addListener('alarm.start', lambda data:flash(3, alarmLast, 500))\n eManager.addListener('alarm.stop', lambda data:stopFlash())\nexcept ImportError as e:\n initUtil.warn(u'不支持任务栏闪烁。', e)\n flash = stopFlash = show_window = initUtil.doNothing\n\n# 响铃超时延迟提醒\neManager.addListener('alarm.timeout', lambda data:manager.later(getNow() + alarmInterval))\n\n# 停止响铃\neManager.addListener('alarm.stop', lambda data:player.play(None))\neManager.addListener('alarm.timeout', lambda data:player.play(None))\n\n# 退出事件\nquitEvent = threading.Event()\neManager.addListener('quit', lambda *args:quitEvent.set())\n\n\ndef mainLoop():\n # 初始化\n if config['warning_pause']:\n initUtil.warning_pause()\n eManager.clear()\n eManager.start()\n createIcon()\n listenThread.start()\n\n uiLoop = ReStartableThread(target=lambda stop_event:userInterface.mainLoop())\n uiLoop.start()\n\n # 阻塞等待退出事件\n logger.info('started')\n quitEvent.clear()\n quitEvent.wait()\n logger.info('begin quit')\n\n # 退出清理\n show_window(1)\n initUtil.reset()\n eManager.stop()\n deleteIcon()\n listenThread.stop(1)\n stopFlash()\n player.play(None)\n logger.info('exit')\n","sub_path":"sine/alarmclock/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"305452954","text":"import requests\nfrom urllib.parse import urlencode\n\nurls = [\"https://movie.douban.com/j/search_subjects\",\"https://movie.douban.com/j/search_subjects\"]\nd = {\n \"type\":\"tv\",\n \"tag\":\"热门\",\n \"page_limit\":10,\n \"page_start\":10\n}\nua = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36\"\n\nsession = requests.Session()\n\nwith session:\n for i in urls:\n res = session.get(\"{}?{}\".format(i,urlencode(d)),headers={\"User-agent\":ua})\n with res:\n print(res.headers)\n print(res.request.headers)\n print(res.cookies)\n print(\"*\"*20)","sub_path":"file/t1/t8.py","file_name":"t8.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"519588921","text":"from setuptools import setup, find_packages\n\nrequirements = [\"numpy\", \"pandas\", \"matplotlib\",\n \"scipy\", \"seaborn\", \"toolz\", \"dask\"]\n\nsetup(name=\"cflowpost\",\n author=\"Ricardo Franco Estrada\",\n author_email=\"ricardo.franco@pucp.edu.pe\",\n version=\"0.1.0\",\n packages=find_packages(where=\"src\", include=[\"cflowpost.*\"]),\n package_dir={\"\": \"src\"},\n install_requires=requirements,\n package_data={\"cflowpost.pvx\": [\"README.md\"]})\n","sub_path":"cflowpost-main/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"4286207","text":"# coding=utf-8\nimport os\nimport sys\nfrom os.path import getatime, getctime, getmtime\nimport time\nimport datetime\nimport importlib\nimport pkg_resources\nimport json\nimport importlib\nfrom importlib import find_loader\nfrom importlib.machinery import BuiltinImporter, FileFinder, SourceFileLoader, PathFinder\nfrom importlib.util import (_find_spec, _find_spec_from_path,\n\tresolve_name, spec_from_file_location, spec_from_loader)\nimport concepts\nfrom decimal import Decimal\nimport datetime, time, os, sys\nfrom operator import attrgetter, itemgetter, methodcaller\nfrom datetime import datetime as dt\nfrom xml.etree import *\nfrom inspect import (isbuiltin, isclass, iscode, isdatadescriptor, isframe, isfunction, getcallargs,\n getclasstree, getcomments, getdoc, getfile, getmodule, getmembers, getmro, isgeneratorfunction,\n isgetsetdescriptor, ismemberdescriptor, ismethod, ismodule, isroutine, istraceback, _check_class,\n _check_instance, _findclass, _finddoc, classify_class_attrs, getargs, getsource, getsourcefile,\n walktree)\nfrom click import echo, style, echo_via_pager\nfrom click.termui import get_terminal_size\nfrom collections import OrderedDict\nfrom dateutil.parser import parse as dateparse\nfrom enum import Enum\nfrom MyInflection import dash2under\nfrom operator import itemgetter\nfrom os import listdir as ls\nfrom pypi_cli import Searcher, Package\nfrom types import *\nfrom urllib.parse import quote as urlquote\nfrom xmlrpc.client import ServerProxy\nimport argparse\nimport click\nimport concepts\nimport imp\nimport imp, os, glob, sys\nimport importlib\nimport inspect\nimport json\nimport math\nimport os, sys, errno\nimport pdb\nimport pkgutil\nimport pydoc\nimport re\nimport requests\nimport sys\nimport textwrap\nimport time\nfrom xml.etree import ElementTree\nfrom urllib.request import urlopen\nimport xmlrpc.client as xmlrpclib\nfrom json import loads\nfrom requests import get, Session, session\n\nclient = xmlrpclib.ServerProxy('https://pypi.python.org/pypi')\n\n\n\n\n\ndef get_spec_from_module(mod): return _frozen_importlib._spec_from_module(mod)\n\ndef import_from_spec(name):\n\treturn module_from_spec(find_spec(name))\n\n\ndef spec_from_path(path): return importlib.util._find_spec_from_path(path)\n\ndef import_from_path(path):\n\ttry:\n\t\treturn module_from_spec(_find_spec_from_path(path))\n\texcept ImportError:\n\t\treturn 'Module Not Found at {}'.format(path)\n\ndef get_path(mod, split=None):\n\timport importlib, os, types\n\tif isinstance(mod, types.ModuleType):\n\t\tmodname = mod.__name__\n\telse: # isinstance(mod.__class__, str):\n\t\tmodname = mod\n\tif modname in sys.modules:\n\t\tfound_module = sys.modules[modname]\n\telse:\n\t\tfound_module = importlib.import_module(modname)\n\n\t#official_name = found_module.__name__\n\t#if official_name.__contains('.'):\n\n\n\tif os.path.isdir(found_module.__file__):\n\t\treturn found_module.__file__\n\n\telif os.path.isfile(found_module.__file__):\n\t\tfile = os.path.dirname(found_module.__file__)\n\t\tif os.path.isdir(file):\n\t\t\tif not file.endswith('/site-packages'):\n\t\t\t\treturn file\n\telif hasattr(found_module, '__spec__'):\n\t\tif hasattr(found_module.__spec__, 'submodule_search_locations'):\n\t\t\treturn found_module.__spec__.submodule_search_locations[0]\n\t\telif hasattr(found_module.__spec__, 'origin'):\n\t\t\treturn os.path.dirname(found_module.__spec__.origin)\n\telse:\n\t\treturn 'Path not found!'\n\ndef find_listdir(obj):\n\tpath = get_path(obj)\n\tprint(os.listdir(path))\n\ndef getpackage(filename):\n\tsrc_file = src(filename)\n\tif (os.path.isdir(src_file) or not src_file.endswith('.py')) and not ispackage(src_file):\n\t\treturn None\n\tbase, ext = os.path.splitext(os.path.basename(src_file))\n\tif base == '__init__':\n\t\tmod_parts = []\n\telse:\n\t\tmod_parts = [base]\n\tpath, part = os.path.split(os.path.split(src_file)[0])\n\twhile part:\n\t\tif ispackage(os.path.join(path, part)):\n\t\t\tmod_parts.append(part)\n\t\telse:\n\t\t\tbreak\n\t\tpath, part = os.path.split(path)\n\tmod_parts.reverse()\n\treturn '.'.join(mod_parts)\n\ndef test_address(test):\n\t\"\"\"Find the test address for a test, which may be a module, filename,\n\tclass, method or function.\n\t\"\"\"\n\tif hasattr(test, \"address\"):\n\t\treturn test.address()\n\t# type-based polymorphism sucks in general, but I believe is\n\t# appropriate here\n\tt = type(test)\n\tfile = module = call = None\n\tif t == types.ModuleType:\n\t\tfile = getattr(test, '__file__', None)\n\t\tmodule = getattr(test, '__name__', None)\n\t\treturn (src(file), module, call)\n\tif t == types.FunctionType or issubclass(t, type) or t == type:\n\t\tmodule = getattr(test, '__module__', None)\n\t\tif module is not None:\n\t\t\tm = sys.modules[module]\n\t\t\tfile = getattr(m, '__file__', None)\n\t\t\tif file is not None:\n\t\t\t\tfile = os.path.abspath(file)\n\t\tcall = getattr(test, '__name__', None)\n\t\treturn (src(file), module, call)\n\tif t == types.MethodType:\n\t\tcls_adr = test_address(test.__self__.__class__)\n\t\treturn (src(cls_adr[0]), cls_adr[1], \"%s.%s\" % (cls_adr[2], test.__name__))\n\t# handle unittest.TestCase instances\n\tif isinstance(test, unittest.TestCase):\n\t\tif (hasattr(test, '_FunctionTestCase__testFunc')): # pre 2.7 or hasattr(test, '_testFunc')): # 2.7\n\n\t\t\ttry:\n\t\t\t\treturn test_address(test._FunctionTestCase__testFunc)\n\t\t\texcept AttributeError:\n\t\t\t\treturn test_address(test._testFunc)\n\t\t# regular unittest.TestCase\n\t\tcls_adr = test_address(test.__class__)\n\t\t# 2.5 compat: __testMethodName changed to _testMethodName\n\t\ttry:\n\t\t\tmethod_name = test._TestCase__testMethodName\n\t\texcept AttributeError:\n\t\t\tmethod_name = test._testMethodName\n\t\treturn (src(cls_adr[0]), cls_adr[1], \"%s.%s\" % (cls_adr[2], method_name))\n\tif (hasattr(test, '__class__') and test.__class__.__module__ not in ('__builtin__', 'builtins')):\n\t\treturn test_address(test.__class__)\n\traise TypeError(\"I don't know what %s is (%s)\" % (test, t))\n\ndef is_executable(file):\n\tif not os.path.exists(file):\n\t\treturn False\n\tst = os.stat(file)\n\treturn bool(st.st_mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH))\n\n\n\ndef stats(path):\n\tstats = dict()\n\tfrom importlib import find_loader\n\tif os.path.isfile(path):\n\t\tstat_result = os.stat(path)\n\t\tstats['birth'] = dt.fromtimestamp(stat_result.st_birthtime).timetuple()\n\t\tstats['mtime'] = dt.fromtimestamp(stat_result.st_mtime).timetuple()\n\t\tstats['ctime'] = dt.fromtimestamp(stat_result.st_ctime).timetuple()\n\t\tstats['atime'] = dt.fromtimestamp(stat_result.st_atime).timetuple()\n\telse:\n\t\tstat_result = os.stat(find_loader(name).path)\n\t\tstats['birth'] = dt.fromtimestamp(stat_result.st_birthtime).timetuple()\n\t\tstats['mtime'] = dt.fromtimestamp(stat_result.st_mtime).timetuple()\n\t\tstats['ctime'] = dt.fromtimestamp(stat_result.st_ctime).timetuple()\n\t\tstats['atime'] = dt.fromtimestamp(stat_result.st_atime).timetuple()\n\treturn stats\n\ndef _stats(path):\n\tstats = dict()\n\tyear = dt.now().timetuple().tm_yday - 7\n\tfrom importlib import find_loader\n\tif os.path.isfile(path):\n\t\tstat_result = os.stat(path)\n\t\tstats['birth'] = dt.fromtimestamp(stat_result.st_birthtime).timetuple().tm_yday\n\t\tstats['mtime'] = dt.fromtimestamp(stat_result.st_mtime).timetuple().tm_yday\n\t\tstats['ctime'] = dt.fromtimestamp(stat_result.st_ctime).timetuple().tm_yday\n\t\tstats['atime'] = dt.fromtimestamp(stat_result.st_atime).timetuple().tm_yday\n\t\tstats['ref'] = year\n\telse:\n\t\tstat_result = os.stat(find_loader(name).path)\n\t\tstats['birth'] = dt.fromtimestamp(stat_result.st_birthtime).timetuple().tm_yday\n\t\tstats['mtime'] = dt.fromtimestamp(stat_result.st_mtime).timetuple().tm_yday\n\t\tstats['ctime'] = dt.fromtimestamp(stat_result.st_ctime).timetuple().tm_yday\n\t\tstats['atime'] = dt.fromtimestamp(stat_result.st_atime).timetuple().tm_yday\n\t\tstats['ref'] = year\n\treturn stats\n\nimportlib.find_loader('bitsets').path_stats(importlib.find_loader('bitsets').path)\n\ndef find_spec(name, path):\n\tprint(_find_spec(name, path))\n\treturn _find_spec(name, path)\n\ndef isproperty(obj):\n\treturn type(obj) == property\n\n\ndef spec_from_path(name, path=None):\n\t\"\"\"name(str) --> ModuleSpec\"\"\"\n\treturn _find_spec_from_path(name)\nprint(_find_spec_from_path('concepts'))\n\ndef spec_to_module(spec):\n\t\"\"\" spec(ModuleSpec) --> Module\n\t\"\"\"\n\treturn module_from_spec(spec)\n\n\n\nclass Distribution:\n\tdef __init__(self):\n\t\tself.metadata_version = None\n\t\tself.name = None\n\t\tself.version = None\n\t\tself.platforms = ()\n\t\tself.supported_platforms = ()\n\t\tself.summary = None\n\t\tself.description = None\n\t\tself.keywords = None\n\t\tself.home_page = None\n\t\tself.download_url = None\n\t\tself.author = None\n\t\tself.author_email = None\n\t\tself.license = None\n\n\t\tself.classifiers = ()\n\t\tself.requires = ()\n\t\tself.provides = ()\n\t\tself.obsoletes = ()\n\n\t\tself.maintainer = None\n\t\tself.maintainer_email = None\n\t\tself.requires_python = None\n\t\tself.requires_external = ()\n\t\tself.requires_dist = ()\n\t\tself.provides_dist = ()\n\t\tself.obsoletes_dist = ()\n\t\tself.project_urls = ()\n\ndef get_installed_names():\n\tworking_set = pkg_resources.working_set\n\tpaths = pkg_resources.working_set.entries\n\tkeys = working_set.__dict__['entry_keys']\n\tvals = set()\n\tfor k, v in keys.items():\n\t\tif len(v) != 0:\n\t\t\tfor val in v:\n\t\t\t\tvals.add(pkg_resources.get_distribution(val))\n\treturn sorted(vals)\n\n\n","sub_path":"package_info/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"78"} +{"seq_id":"469085658","text":"# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef load_wine_dataset():\n from sklearn import datasets\n wine = datasets.load_wine()\n X = wine.data\n y = wine.target\n return X, y\n \nX, y = load_wine_dataset()\n\nNumberOfSamples = X.shape[0]\nprint(\"Number of Samples:\",NumberOfSamples)\n\nNumberOfClass0 = y[y == 0].size\nNumberOfClass1 = y[y == 1].size\nNumberOfClass2 = y[y == 2].size\n\n#range(0,3) will iterate in 0,1,2 stop at 3\n#but 3 will not be included\nfor i in range(0,3):\n print(\"Number of class\",i,\"is:\", y[y == i].size)\n \n#####mean#####\nfeatureMean = np.mean(X, axis = 0) \nfeatureSTD = np.std(X, axis = 0)\nfor i in range(13):\n print(\"Mean of attribute \",i,\"is :\",featureMean[i] )\n print(\"STD of attribute \",i,\"is :\",featureSTD[i] )\n\n\n###plotting\nmerged_set = np.column_stack([y,X])\nAlcohol_set = merged_set[:,1]\nMagnesium_set = merged_set[:,5] \ncolor = []\nfor i in merged_set[:,0]:\n if i == 0:\n color.append(\"red\")\n if i == 1: \n color.append(\"blue\")\n if i == 2:\n color.append(\"green\")\nplt.scatter(Alcohol_set, Magnesium_set, c=color, alpha=0.5)\n \n##########\ndef train_test_split(X,y):\n pick_list = np.array(range(0,X.shape[0]))\n np.random.shuffle(pick_list)\n #now compute the size to split\n set_size = X.shape[0]\n train_size = int(set_size*0.7)\n #apply it as the index\n #checked: train_index+test_index = 178= pick_list\n train_index = pick_list[0 : train_size]\n test_index = pick_list[ (train_size): ]\n #now assign the origin data along the index\n X_train = np.ndarray(shape = (train_size, 13) )\n X_test = np.ndarray(shape = (( set_size- train_size), 13) )\n y_train = np.ndarray(shape = (train_size, 1))\n y_test = np.ndarray( shape = (( set_size- train_size), 1))\n #now put it inside the results sets\n for i in range(train_size):\n X_train[i, ] = X[ train_index[i] ,]\n y_train[i , ] = y[train_index[i] ,]\n for i in range(set_size - train_size ):\n X_test[i, ] = X[test_index[i], ]\n y_test[i , ] = y[test_index[i], ]\n\n return X_train, X_test, y_train, y_test \n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\n\n\n\n","sub_path":"Anaconda_workspace/Anaconda_workspace/assignment_1_playground.py","file_name":"assignment_1_playground.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"164666295","text":"from random import shuffle\n\nfrom random import seed\n\ndef shuffle_list(*ls):\n seed(0)\n l =list(zip(*ls))\n\n shuffle(l)\n return zip(*l)\n\n\n\nimport sys\nif sys.version_info[0] < 3:\n import Tkinter as tk\nelse:\n import tkinter as tk\nimport matplotlib.backends.tkagg as tkagg\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\n\n\ndef draw_figure(canvas, figure, loc=(0, 0)):\n \"\"\" Draw a matplotlib figure onto a Tk canvas\n\n loc: location of top-left corner of figure on canvas in pixels.\n Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py\n \"\"\"\n figure_canvas_agg = FigureCanvasAgg(figure)\n figure_canvas_agg.draw()\n figure_x, figure_y, figure_w, figure_h = figure.bbox.bounds\n figure_w, figure_h = int(figure_w), int(figure_h)\n photo = tk.PhotoImage(master=canvas, width=figure_w, height=figure_h)\n\n # Position: convert from top-left anchor to center anchor\n canvas.create_image(loc[0] + figure_w/2, loc[1] + figure_h/2, image=photo)\n\n # Unfortunately, there's no accessor for the pointer to the native renderer\n tkagg.blit(photo, figure_canvas_agg.get_renderer()._renderer, colormode=2)\n\n # Return a handle which contains a reference to the photo object\n # which must be kept live or else the picture disappears\n return photo\n\n\nimport os\ndef touch(path):\n with open(path, 'a'):\n os.utime(path, None)","sub_path":"LabelDrumFillSemiAuto/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"430970311","text":"#! /bin/env python3\n# -*- coding: ascii -*-\nimport sys, re, pprint, collections\n\n################################################################################\ndef count_words(text):\n global line_counter\n words = re.findall(r'\\w+', text)\n return collections.Counter(words)\n\n################################################################################\nif len(sys.argv) < 2:\n print('Usage: {} input_file'.format(sys.argv[0]))\n exit(1)\n\ncounter = collections.Counter()\nline_counter = 0\n\nwith open(sys.argv[1], 'rb') as file:\n for line in file:\n try:\n line = line.decode('ascii')\n except UnicodeDecodeError:\n continue\n\n if (line[:3] == '220'):\n line_counter += 1\n counter += count_words(line[3:])\n\nprint('{} lines'.format(line_counter))\nfor item in counter.most_common():\n print('{}\\t\\t{}\\t{} %'.format(item[0], item[1], item[1]/line_counter * 100))\n","sub_path":"mc_patterns/smtp.py","file_name":"smtp.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"390859400","text":"#!/usr/bin/env python\n\nimport pyqtgraph as pg\nfrom pyqtgraph.Qt import QtCore, QtGui\nimport sys\nimport os\n\nimport console_monitor_config\nimport robot\n\nCOLORS = [ ('red', (255, 0, 0, 100)), ('green', (0, 255, 0, 100)), ('blue', (0, 0, 255, 100)),\n ('yellow', (255, 255, 0, 100)), ('cyan', (0, 255, 255, 100)), ('magenta', (255, 0, 255, 100))]\n\nclass PingMonitor(QtGui.QMainWindow):\n def __init__(self, fileName):\n super(PingMonitor, self).__init__()\n\n self._cfgDict = console_monitor_config.ConsoleMonitorConfig()\n self._robotArr = []\n\n self.initUI()\n self.cfgToUi(fileName)\n\n\n\n def cfgToUi(self, fileName):\n self._cfgDict.parse_config_file(fileName)\n\n count = 0\n for robotName in self._cfgDict.keys():\n #print \"robot name: \", robotName, \"curve color (rgb): \", COLORS[count][1]\n self._robotArr.append(robot.Robot(robotName, self._cfgDict[robotName]['address'], self._plotItem, COLORS[count][1]))\n count += 1\n\n def initUI(self):\n self.outerLayout = QtGui.QGridLayout()\n\n # Create and add the plot\n self._win = pg.GraphicsLayoutWidget()\n self._plotItem = self._win.addPlot()\n self.setCentralWidget(self._win)\n\n\n self._plotItem.addLegend()\n\n\n\n def update(self):\n idx = 0\n for robot in self._robotArr:\n robot.updateUi()\n if(robot._isSuccess):\n self._plotItem.legend.items[idx][1].item.setHtml('
' + robot._robotName + '

')\n else:\n self._plotItem.legend.items[idx][1].item.setHtml('
' + robot._robotName + '

')\n idx += 1\n\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n\n ###\n\n pingMonitor = PingMonitor(\"res/config.cfg\")\n pingMonitor.show()\n\n # Create & start timer, which will update the plots\n timer = QtCore.QTimer()\n timer.timeout.connect(pingMonitor.update)\n timer.start(1000)\n\n app.exec_()","sub_path":"ping_monitor/ping_monitor.py","file_name":"ping_monitor.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"356313687","text":"# -*- coding: utf-8 -*-\n\ndef escribir_fibonacci(n): \n\t\"\"\"Escribe la sucesión de Fibonacci hasta n.\"\"\"\n\ta, b = 0, 1\n\twhile a < n:\n\t print (a, end=' ')\n\t a, b = b, a+b\n\tprint()\n\ndef obtener_fibonacci(n):\n\t\"\"\"Devuelve una lista conteniendo la serie de Fibonacci hasta n.\"\"\"\n\tresult = []\n\ta, b = 0, 1\n\twhile a < n:\n\t\tresult.append(a)\n\t\ta, b = b, a+b\n\treturn result\n\n\n","sub_path":"python/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"585459401","text":"from django.urls import path\nfrom .views import PostListView, UserPostListView, PostCreateView\nfrom . import views\n\nurlpatterns = [\n path('home', views.home, name='home-page'),\n path('', PostListView.as_view(), name='post-page'),\n path('user//', UserPostListView.as_view(), name='user-posts'),\n path('post/new/', PostCreateView.as_view(), name='post-create'),\n path('about/', views.about, name='about-page')\n]\n","sub_path":"gallery/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"36009108","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, LSTM\n# Plus l'erreur de librairie et plus le warning sur le fait que TensorFlow n'a pas été compilé pour mon type de processeur\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n# Plus l'erreur par rapport à l'assignation d'une dataframe à une autre pas forcément voulue (pandas)\npd.options.mode.chained_assignment = None\n# On configure le nombre de CPU par type de threads pour maximiser les performances\nfrom keras import backend as K\nimport tensorflow as tf\nconfig = tf.ConfigProto(device_count={\"CPU\":2},\n\t\t\t\t\t\tinter_op_parallelism_threads=2,\n\t\t\t\t\t\tintra_op_parallelism_threads=2)\nsession = tf.Session(config=config)\nK.set_session(session)\n\nclass Data():\n def __init__(self):\n # Lecture de nos fichiers .csv\n self.train = pd.read_csv(\"train.csv\")\n self.test = pd.read_csv(\"test.csv\")\n # On créer un liste avec train et test\n self.all = [self.train, self.test]\n\n def removeData(self):\n # On supprime certaines colonnes de nos données\n DataToRemoveTrain = [\"PassengerId\", \"Name\", \"SibSp\", \"Parch\", \"Ticket\", \"Cabin\", \"FamilySize\"]\n DataToRemoveTest = [\"Name\", \"SibSp\", \"Parch\", \"Ticket\", \"Cabin\", \"FamilySize\"]\n self.train = self.train.drop(DataToRemoveTrain, axis = 1)\n self.test = self.test.drop(DataToRemoveTest, axis = 1)\n\n def readData(self,column):\n # Affiche le nombre de valeurs totales de la colonne\n print(len(self.train[column]))\n # Affiche les valeurs possibles d'une certaine colonne\n print(self.train[column].unique())\n # Affiche le nombre de valeurs disponible selon la catégorie\n print(self.train[column].value_counts())\n\n def modifyData(self):\n # On modifie l'entiereté de nos valeurs (d'un coup \"train\" et d'un coup \"test\") pour qu'elles soient efficace et lisible par le modèle\n for dataSet in self.all:\n # On remplace les valeurs \"nan\" de la colonne \"Embarked\" par \"S\" car c'est le plus courant\n dataSet['Embarked'] = dataSet['Embarked'].fillna('S')\n # On convertit les caractères en nombre pour que ce soit compréhensible pour le modèle et on transforme bien en int\n dataSet['Embarked'] = dataSet['Embarked'].map( {'S': 0, 'C': 1, 'Q':2} ).astype(int)\n ###########################################################################################################################################\n # On convertit avec la fonction map qui applique \"female\" en 1 et \"male\" en 0 puis on transforme bien en int\n dataSet['Sex'] = dataSet['Sex'].map( {'female': 1, 'male': 0} ).astype(int)\n ###########################################################################################################################################\n # On calcule la moyenne et l'écart-type, on créer une liste de nombre random en fonction du nombre de \"nan\"\n # On attribut un nombre moyen random à un élement \"nan\" de la colonne puis on transforme bien en int\n ageAvg = dataSet['Age'].mean()\n ageStd = dataSet['Age'].std()\n ageNullCount = dataSet['Age'].isnull().sum()\n ageNullRandomList = np.random.randint(ageAvg - ageStd, ageAvg + ageStd, size = ageNullCount)\n dataSet['Age'][np.isnan(dataSet['Age'])] = ageNullRandomList\n dataSet['Age'] = dataSet['Age'].astype(int)\n # On attribut un nombre (transforme bien en int) selon la catégorie d'age pour faciliter l'extraction au modèle\n # Loc permet d'accéder à un groupe de colonne ou ligne par leurs noms et ensuite on leur attribut une valeur\n dataSet.loc[(dataSet['Age'] <= 16), 'Age'] = 0\n dataSet.loc[(dataSet['Age'] > 16) & (dataSet['Age'] <= 32), 'Age'] = 1\n dataSet.loc[(dataSet['Age'] > 32) & (dataSet['Age'] <= 48), 'Age'] = 2\n dataSet.loc[(dataSet['Age'] > 48) & (dataSet['Age'] <= 64), 'Age'] = 3\n dataSet.loc[(dataSet['Age'] > 64), 'Age'] = 4\n dataSet['Age'] = dataSet['Age'].astype(int)\n ###########################################################################################################################################\n # On remplace les valeurs \"nan\" de la colonne \"Fare\" (tarif) par la valeur médiane de cette colonne (valeur qui sépare le groupe en deux)\n dataSet['Fare'] = dataSet['Fare'].fillna(self.train['Fare'].median())\n # On attribut un nombre (transforme bien en int) selon la catégorie de tarif pour faciliter l'extraction au modèle\n # Loc permet d'accéder à un groupe de colonne ou ligne par leurs noms et ensuite on leur attribut une valeur\n dataSet.loc[(dataSet['Fare'] <= 8), 'Fare'] = 0\n dataSet.loc[(dataSet['Fare'] > 8) & (dataSet['Fare'] <= 15), 'Fare'] = 1\n dataSet.loc[(dataSet['Fare'] > 15) & (dataSet['Fare'] <= 31), 'Fare'] = 2\n dataSet.loc[(dataSet['Fare'] > 31), 'Fare'] = 3\n dataSet['Fare'] = dataSet['Fare'].astype(int)\n ###########################################################################################################################################\n # On créer une nouvelle colonne comprenant la taille de la famille (+1 pour nous-même)\n dataSet['FamilySize'] = dataSet['SibSp'] + dataSet['Parch'] + 1\n # De base IsAlone = 0 mais si on est tout seul alors IsAlone = 1\n # Cette variable est nécessaire car selon si l'on est seul ou pas les chances de survit augmente ou pas\n dataSet['IsAlone'] = 0\n dataSet.loc[dataSet['FamilySize'] == 1, 'IsAlone'] = 1\n ###########################################################################################################################################\n # On extrait les noms en créant une nouvelle colonne\n # On remplace des noms par d'autres pour que ca s'accorde\n # On convertit les noms en nombre pour que cela soit compréhensible pour le modèle\n dataSet['Title'] = dataSet.Name.str.extract(' ([A-Za-z]+)\\.')\n dataSet['Title'] = dataSet['Title'].replace(['Lady', 'Countess','Capt', 'Col', \\\n \t 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Other')\n dataSet['Title'] = dataSet['Title'].replace('Mlle', 'Miss')\n dataSet['Title'] = dataSet['Title'].replace('Ms', 'Miss')\n dataSet['Title'] = dataSet['Title'].replace('Mme', 'Mrs')\n dataSet['Title'] = dataSet['Title'].map({\"Mr\": 1, \"Miss\": 2, \"Mrs\": 3, \"Master\": 4, \"Other\": 5})\n dataSet['Title'] = dataSet['Title'].fillna(0)\n ###########################################################################################################################################\n\nclass Model():\n def __init__(self, data):\n # On enlève la colonne \"Survived\" pour X_train mais on créer Y_train qui contient seulement cela (donc les bonnes réponses)\n self.X_train = data.train.drop('Survived', axis=1)\n self.Y_train = data.train['Survived']\n # On créer une copie X_test sans l'Id des passagers à partir des données de test\n self.X_test = data.test.drop(\"PassengerId\", axis=1).copy()\n self.x_train, self.x_valid, self.y_train, self.y_valid = train_test_split(self.X_train, self.Y_train, test_size=0.33, shuffle= True)\n\n def TheModel(self):\n '''\n self.mdl = LogisticRegression()\n self.mdl.fit(self.X_train, self.Y_train)\n '''\n self.mdl = Sequential()\n self.mdl.add(Dense(200, input_dim = (self.X_train.shape[1]), activation = \"relu\"))\n self.mdl.add(Dropout(0.2))\n self.mdl.add(Dense(100, activation = \"relu\"))\n self.mdl.add(Dropout(0.2))\n self.mdl.add(Dense(1, activation = \"sigmoid\"))\n self.mdl.compile(optimizer = \"adam\", loss = \"mean_squared_error\", metrics = [\"accuracy\"])\n self.mdl.fit(self.x_train, self.y_train, epochs = 200, batch_size = 500, verbose = 2)\n self.mdl.summary()\n\n def Predict(self):\n self.prediction = self.mdl.predict(self.X_test)\n self.prediction = np.around(self.prediction)\n # Renvoit la loss value (plus c'est près de 0 mieux c'est là car MeanSquaredError) et la metrics value sur les données d'entrainements\n self.score, self.accuracy = self.mdl.evaluate(self.x_valid, self.y_valid)\n print(str(self.score) + ' %')\n\ndata = Data()\ndata.modifyData()\ndata.removeData()\n\nmodel = Model(data)\nmodel.TheModel()\nmodel.Predict()\n\nprediction = []\nfor i in range(len(data.test)):\n if int(model.prediction[i]) == -1:\n prediction.append(int(0))\n else:\n prediction.append(int(model.prediction[i]))\n\nsubmission = pd.DataFrame({\n \"PassengerId\": data.test[\"PassengerId\"],\n \"Survived\": prediction\n })\n\nsubmission.to_csv('submission.csv', index=False)","sub_path":"Python/MachineLearning_DeepLearning/Titanic/titanic.py","file_name":"titanic.py","file_ext":"py","file_size_in_byte":9215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"77"} +{"seq_id":"29766685","text":"import curses\n\ndef main(screen):\n l = 6\n i, j = 0, 0\n h, w = screen.getmaxyx()\n for c in range(32, 1500):\n screen.insstr(j, l * i, f\"{c} {chr(c)}\")\n i += 1\n if w - l * i < l:\n j += 1\n i = 0\n if j == h:\n break\n screen.getch()\n\nif __name__ == \"__main__\":\n curses.wrapper(main)","sub_path":"tests/ascii.py","file_name":"ascii.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"79"} +{"seq_id":"105575293","text":"#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n# Copyright 2008-2011, Milan Boers\r\n# Copyright 2012-2013, Marten de Vries\r\n#\r\n# This file is part of OpenTeacher.\r\n#\r\n# OpenTeacher is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the Free Software Foundation, either version 3 of the License, or\r\n# (at your option) any later version.\r\n#\r\n# OpenTeacher is distributed in the hope that it will be useful,\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n# GNU General Public License for more details.\r\n#\r\n# You should have received a copy of the GNU General Public License\r\n# along with OpenTeacher. If not, see .\r\n\r\nimport mimetypes\r\n\r\nclass MediaTypeModule(object):\r\n\tdef __init__(self, moduleManager, *args, **kwargs):\r\n\t\tsuper(MediaTypeModule, self).__init__(*args, **kwargs)\r\n\t\tself._mm = moduleManager\r\n\r\n\t\tself.uses = (\r\n\t\t\tself._mm.mods(type=\"settings\"),\r\n\t\t)\r\n\r\n\t\tself.phononControls = True\r\n\t\t\r\n\t\tself.type = \"mediaType\"\r\n\t\tself.extensions = [\".avi\", \".wmv\", \".flv\", \".mp4\", \".mpg\", \".mpeg\", \".mov\"]\r\n\t\tself.priorities = {\r\n\t\t\t\"default\": 400,\r\n\t\t}\r\n\r\n\tdef enable(self):\r\n\t\tglobal Phonon\r\n\t\ttry:\r\n\t\t\tfrom PyQt4.phonon import Phonon\r\n\t\texcept ImportError:\r\n\t\t\treturn\r\n\t\tself._modules = set(self._mm.mods(type=\"modules\")).pop()\r\n\t\t\r\n\t\ttry:\r\n\t\t\tself._settings = self._modules.default(type=\"settings\")\r\n\t\t\tself._html5 = self._settings.setting(\"org.openteacher.lessons.media.videohtml5\")[\"value\"]\r\n\t\texcept:\r\n\t\t\tself._html5 = False\r\n\t\t\r\n\t\tself.active = True\r\n\r\n\tdef disable(self):\r\n\t\tself.active = False\r\n\t\tdel self._modules\r\n\t\tif hasattr(self, \"_settings\"):\r\n\t\t\tdel self._settings\r\n\t\tdel self._html5\r\n\t\r\n\tdef supports(self, path):\r\n\t\ttry:\r\n\t\t\tif mimetypes.guess_type(str(path))[0] in Phonon.BackendCapabilities.availableMimeTypes() and \\\r\n\t\t\t mimetypes.guess_type(str(path))[0].split(\"/\")[0] == \"video\":\r\n\t\t\t\treturn True\r\n\t\t\telse:\r\n\t\t\t\treturn False\r\n\t\texcept:\r\n\t\t\treturn False\r\n\t\r\n\tdef path(self, path, autoplay):\r\n\t\treturn path\r\n\t\r\n\tdef showMedia(self, path, mediaDisplay, autoplay):\r\n\t\ttry:\r\n\t\t\tself._html5 = self._settings.setting(\"org.openteacher.lessons.media.videohtml5\")[\"value\"]\r\n\t\texcept:\r\n\t\t\tself._html5 = False\r\n\t\t\r\n\t\tif self._html5 or mediaDisplay.noPhonon:\r\n\t\t\tif not mediaDisplay.noPhonon:\r\n\t\t\t\t# Stop any media playing\r\n\t\t\t\tmediaDisplay.videoPlayer.stop()\r\n\t\t\t# Set the widget to the web view\r\n\t\t\tmediaDisplay.setCurrentWidget(mediaDisplay.webviewer)\r\n\t\t\t# Set the right html\r\n\t\t\tautoplayhtml = \"\"\r\n\t\t\tif autoplay:\r\n\t\t\t\tautoplayhtml = '''autoplay=\"autoplay\"'''\r\n\t\t\tmediaDisplay.webviewer.setHtml('''\r\n\t\t\t\r\n\t\t\tVideo\r\n\t\t\t\r\n\t\t\t