diff --git "a/2741.jsonl" "b/2741.jsonl"
new file mode 100644--- /dev/null
+++ "b/2741.jsonl"
@@ -0,0 +1,678 @@
+{"seq_id":"570805812","text":"import torch\nimport torch.nn as nn\n\ntry:\n import apex\nexcept:\n print('apex is not installed')\nfrom openselfsup.models import builder\nfrom openselfsup.models.registry import MODELS\n\n\n@MODELS.register_module\nclass SiameseSupernetsMBConv(nn.Module):\n \"\"\"Siamese Supernets for MBConv search space.\n\n BossNAS (https://arxiv.org/abs/2103.12424).\n\n Args:\n backbone (dict): Config dict for module of backbone ConvNet.\n neck (dict): Config dict for module of deep features to compact feature vectors.\n Default: None.\n head (dict): Config dict for module of loss functions. Default: None.\n pretrained (str, optional): Path to pre-trained weights. Default: None.\n base_momentum (float): The base momentum coefficient for the target network.\n Default: 0.996.\n \"\"\"\n\n def __init__(self,\n backbone,\n start_block,\n num_block,\n neck=None,\n head=None,\n pretrained=None,\n base_momentum=0.996,\n use_fp16=False,\n update_interval=None,\n **kwargs):\n super(SiameseSupernetsMBConv, self).__init__()\n\n self.start_block = start_block\n self.num_block = num_block\n\n self.online_backbone = builder.build_backbone(backbone)\n self.target_backbone = builder.build_backbone(backbone)\n self.backbone = self.online_backbone\n self.online_necks = nn.ModuleList()\n self.target_necks = nn.ModuleList()\n self.heads = nn.ModuleList()\n neck_in_channel_list = [cfg[0] for cfg in self.online_backbone.block_cfgs]\n for in_channel in neck_in_channel_list:\n neck['in_channels'] = in_channel\n self.online_necks.append(builder.build_neck(neck))\n self.target_necks.append(builder.build_neck(neck))\n self.heads.append(builder.build_head(head))\n\n for param in self.target_backbone.parameters():\n param.requires_grad = False\n for target_neck in self.target_necks:\n for param in target_neck.parameters():\n param.requires_grad = False\n\n self.init_weights(pretrained=pretrained)\n self.set_current_neck_and_head()\n\n self.base_momentum = base_momentum\n self.momentum = base_momentum\n self.forward_op_online = None\n self.forward_op_target = None\n self.best_paths = []\n self.optimizer = None\n self.use_fp16 = use_fp16\n self.update_interval = update_interval\n\n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights of model.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Default: None.\n \"\"\"\n self.online_backbone.init_weights() # backbone\n for online_neck in self.online_necks:\n online_neck.init_weights(init_linear='kaiming') # projection\n\n for param_ol, param_tgt in zip(self.online_backbone.parameters(),\n self.target_backbone.parameters()):\n param_tgt.data.copy_(param_ol.data)\n for param_ol, param_tgt in zip(self.online_necks.parameters(),\n self.target_necks.parameters()):\n param_tgt.data.copy_(param_ol.data)\n # init the predictor in the head\n for head in self.heads:\n head.init_weights()\n\n def set_current_neck_and_head(self):\n self.online_neck = self.online_necks[self.start_block]\n self.target_neck = self.target_necks[self.start_block]\n self.head = self.heads[self.start_block]\n self.online_net = nn.Sequential(self.online_backbone, self.online_neck)\n self.target_net = nn.Sequential(self.target_backbone, self.target_neck)\n\n @torch.no_grad()\n def _momentum_update(self):\n \"\"\"Momentum update of the target network.\"\"\"\n for param_ol, param_tgt in zip(self.online_net.parameters(),\n self.target_net.parameters()):\n param_tgt.data = param_tgt.data * self.momentum + \\\n param_ol.data * (1. - self.momentum)\n\n @torch.no_grad()\n def momentum_update(self):\n self._momentum_update()\n\n @torch.no_grad()\n def _batch_shuffle_ddp(self, x):\n \"\"\"Batch shuffle, for making use of BatchNorm.\n\n *** Only support DistributedDataParallel (DDP) model. ***\n \"\"\"\n # gather from all gpus\n batch_size_this = x.shape[0]\n x_gather = concat_all_gather(x)\n batch_size_all = x_gather.shape[0]\n\n num_gpus = batch_size_all // batch_size_this\n\n # random shuffle index\n idx_shuffle = torch.randperm(batch_size_all).cuda()\n\n # broadcast to all gpus\n torch.distributed.broadcast(idx_shuffle, src=0)\n\n # index for restoring\n idx_unshuffle = torch.argsort(idx_shuffle)\n\n # shuffled index for this gpu\n gpu_idx = torch.distributed.get_rank()\n idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx]\n\n return x_gather[idx_this], idx_unshuffle\n\n @torch.no_grad()\n def _batch_unshuffle_ddp(self, x, idx_unshuffle):\n \"\"\"Undo batch shuffle.\n\n *** Only support DistributedDataParallel (DDP) model. ***\n \"\"\"\n # gather from all gpus\n batch_size_this = x.shape[0]\n x_gather = concat_all_gather(x)\n batch_size_all = x_gather.shape[0]\n\n num_gpus = batch_size_all // batch_size_this\n\n # restored index for this gpu\n gpu_idx = torch.distributed.get_rank()\n idx_this = idx_unshuffle.view(num_gpus, -1)[gpu_idx]\n\n return x_gather[idx_this]\n\n def forward_train(self, img, forward_singleop_online, idx=0, **kwargs):\n \"\"\"Forward computation during training.\n\n Args:\n img (Tensor): Input of two concatenated images of shape (N, 2, C, H, W).\n Typically these should be mean centered and std scaled.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert img.dim() == 5, \\\n \"Input must have 5 dims, got: {}\".format(img.dim())\n\n v2_idx = img.shape[1] // 2\n img_v1 = img[:, idx, ...].contiguous()\n img_v2 = img[:, v2_idx + idx, ...].contiguous()\n if self.start_block > 0:\n for i, best_path in enumerate(self.best_paths):\n img_v1 = self.online_backbone(img_v1,\n start_block=i,\n forward_op=best_path,\n block_op=True)[0]\n img_v2 = self.online_backbone(img_v2,\n start_block=i,\n forward_op=best_path,\n block_op=True)[0]\n\n proj_online_v1 = self.online_neck(self.online_backbone(img_v1,\n start_block=self.start_block,\n forward_op=forward_singleop_online))[0]\n proj_online_v2 = self.online_neck(self.online_backbone(img_v2,\n start_block=self.start_block,\n forward_op=forward_singleop_online))[0]\n\n loss = self.head(proj_online_v1, self.proj_target_v2)['loss'] + \\\n self.head(proj_online_v2, self.proj_target_v1)['loss']\n\n return loss\n\n def forward_test(self, img, **kwargs):\n pass\n\n def forward(self, img, mode='train', **kwargs):\n if mode == 'train':\n return self.forward_train(img, **kwargs)\n elif mode == 'test':\n return self.forward_test(img, **kwargs)\n elif mode == 'extract':\n return self.backbone(img)\n elif mode == 'target':\n return self.forward_target(img, **kwargs)\n elif mode == 'single':\n return self.forward_single(img, **kwargs)\n else:\n raise Exception(\"No such mode: {}\".format(mode))\n\n @torch.no_grad()\n def forward_target(self, img, **kwargs):\n \"\"\"Forward computation during training.\n\n Args:\n img (Tensor): Input of two concatenated images of shape (N, 2, C, H, W).\n Typically these should be mean centered and std scaled.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert img.dim() == 5, \\\n \"Input must have 5 dims, got: {}\".format(img.dim())\n\n img_v_l = []\n idx_unshuffle_v_l = []\n for idx in range(img.shape[1]):\n img_vi = img[:, idx, ...].contiguous()\n img_vi, idx_unshuffle_vi = self._batch_shuffle_ddp(img_vi)\n img_v_l.append(img_vi)\n idx_unshuffle_v_l.append(idx_unshuffle_vi)\n\n if self.start_block > 0:\n for idx in range(img.shape[1]):\n for i, best_path in enumerate(self.best_paths):\n img_v_l[idx] = self.target_backbone(img_v_l[idx],\n start_block=i,\n forward_op=best_path,\n block_op=True)[0]\n\n self.forward_op_target = self.forward_op_online\n proj_target_v1 = 0\n proj_target_v2 = 0\n v2_idx = img.shape[1]//2\n with torch.no_grad():\n for op_idx, forward_singleop_target in enumerate(self.forward_op_target):\n temp_v1 = self.target_neck(self.target_backbone(img_v_l[op_idx],\n start_block=self.start_block,\n forward_op=forward_singleop_target))[\n 0].clone().detach()\n temp_v2 = self.target_neck(self.target_backbone(img_v_l[v2_idx + op_idx],\n start_block=self.start_block,\n forward_op=forward_singleop_target))[\n 0].clone().detach()\n temp_v1 = nn.functional.normalize(temp_v1, dim=1)\n temp_v1 = self._batch_unshuffle_ddp(temp_v1, idx_unshuffle_v_l[op_idx])\n\n temp_v2 = nn.functional.normalize(temp_v2, dim=1)\n temp_v2 = self._batch_unshuffle_ddp(temp_v2, idx_unshuffle_v_l[v2_idx + op_idx])\n\n proj_target_v1 += temp_v1\n proj_target_v2 += temp_v2\n\n self.proj_target_v1 = proj_target_v1 / (len(self.forward_op_target))\n self.proj_target_v2 = proj_target_v2 / (len(self.forward_op_target))\n\n def forward_single(self, img, forward_singleop, **kwargs):\n \"\"\"Forward computation during training.\n\n Args:\n img (Tensor): Input of two concatenated images of shape (N, 2, C, H, W).\n Typically these should be mean centered and std scaled.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n img_v1 = img[:, 0, ...].contiguous()\n img_v2 = img[:, 1, ...].contiguous()\n\n if self.start_block > 0:\n for i, best_path in enumerate(self.best_paths):\n img_v1 = self.target_backbone(img_v1,\n start_block=i,\n forward_op=best_path,\n block_op=True)[0]\n img_v2 = self.target_backbone(img_v2,\n start_block=i,\n forward_op=best_path,\n block_op=True)[0]\n\n self.target_neck(self.target_backbone(img_v1,\n start_block=self.start_block,\n forward_op=forward_singleop,\n block_op=True))\n self.target_neck(self.target_backbone(img_v2,\n start_block=self.start_block,\n forward_op=forward_singleop,\n block_op=True))\n\n self.online_neck(self.online_backbone(img_v1,\n start_block=self.start_block,\n forward_op=forward_singleop,\n block_op=True))\n self.online_neck(self.online_backbone(img_v2,\n start_block=self.start_block,\n forward_op=forward_singleop,\n block_op=True))\n\n\n# utils\n@torch.no_grad()\ndef concat_all_gather(tensor):\n \"\"\"Performs all_gather operation on the provided tensors.\n\n *** Warning ***: torch.distributed.all_gather has no gradient.\n \"\"\"\n tensors_gather = [\n torch.ones_like(tensor)\n for _ in range(torch.distributed.get_world_size())\n ]\n torch.distributed.all_gather(tensors_gather, tensor, async_op=False)\n\n output = torch.cat(tensors_gather, dim=0)\n return output\n","sub_path":"searching/bossnas/models/siamese_supernets/siamese_supernets_mbconv.py","file_name":"siamese_supernets_mbconv.py","file_ext":"py","file_size_in_byte":13474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"228572417","text":"# -*- coding: utf-8 -*-\n# @Author : Jing\n# @FileName: 49. Group Anagrams.py\n# @IDE: PyCharm\n# https://leetcode.com/problems/group-anagrams/\n# Solution 1: classifier the array after sort.\n# Only when string sorted is the same as other,\n# they are group anagrams.\n# O(NKlogK)Time O(NK)Space\n# Solution 2: classifier by count.\n# Only when the number of every char occur in string is the same as other,\n# they are group anagrams.O(NK)Time O(NK)Space\n\n\nclass Solution:\n def groupAnagrams1(self, strs):\n if not strs:\n return strs\n dic = {}\n for s in strs:\n tmp_s = list(s)\n tmp_s = sorted(tmp_s)\n tmp_s = ''.join(tmp_s)\n if tmp_s not in dic :\n dic[tmp_s] = [s]\n else:\n dic[tmp_s].append(s)\n res = []\n for val in dic.values():\n res.append(val)\n return res\n\n def groupAnagrams2(self, strs):\n if not strs:\n return strs\n dic = {}\n for string in strs:\n count = [0 for _ in range(26)]\n for s in string:\n count[ord(s)-ord('a')] += 1\n count = tuple(count)\n if count not in dic:\n dic[count] = [string]\n else:\n dic[count].append(string)\n res = []\n for li in dic.values():\n res.append(li)\n return res\n\n\nif __name__ == '__main__':\n strings = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]\n s = Solution()\n print(s.groupAnagrams2(strings))\n\n\n\n\n","sub_path":"string/49. Group Anagrams.py","file_name":"49. Group Anagrams.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"415282397","text":"from urllib.request import Request, urlopen\nfrom bs4 import BeautifulSoup\n\nreq = urlopen('https://www.10000recipe.com/recipe/6943674')\n\nprint(req.getcode())\n\nif req.getcode() == 200:\n html = req.read()\n #print(html)\n\n html = html.decode(\"utf-8\")\n #print(html)\nelse:\n print(\"HTTP ERROR\")\n\nsoup = BeautifulSoup(html, \"html.parser\")\n\nbody = soup.select(\"#stepDiv1 div\")\nbody1 = soup.select(\"#stepDiv2 div\")\nbody2 = soup.select(\"#stepDiv3 div\")\n\nprint(body ,body1 ,body2 , sep='\\n')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"377502103","text":"\"\"\"\n1차원 Convolution, Cross-Correlation 연산\n\"\"\"\nimport numpy as np\n\n\ndef convolution_1d(x, w):\n \"\"\" x, w : 1d ndarray, len(x) >= len(w) \"\"\"\n w_r = np.flip(w)\n conv = []\n len_result = len(x) - len(w) + 1\n for i in range(len_result):\n x_sub = x[i:i+len(w)]\n fma = np.sum(x_sub * w_r)\n conv.append(fma)\n conv = np.array(conv)\n return conv\n\n\ndef cross_correlation_1d(x, w, convolution=False):\n \"\"\" x, w : 1d ndarray, len(x) >= len(w) \"\"\"\n if convolution == True:\n w = np.flip(w)\n\n conv = []\n len_result = len(x) - len(w) + 1\n for i in range(len_result):\n x_sub = x[i:i + len(w)]\n fma = np.sum(x_sub * w)\n conv.append(fma)\n conv = np.array(conv)\n return conv\n\n\nif __name__ == '__main__':\n np.random.seed(113)\n x = np.arange(1, 6)\n w = np.array([2, 1])\n w_r = np.flip(w)\n\n conv = []\n for i in range(4):\n x_sub = x[i:i+len(w)] # (0,1), (1,2), (2,3), (3,4)\n fma = np.sum(x_sub * w_r) # 1차원인 경우, np.dot(x_sub, w_r) 동일\n conv.append(fma)\n conv = np.array(conv)\n print('conv =', conv)\n print('conv =', convolution_1d(x, w))\n\n x = np.arange(1, 6)\n w = np.array([2, 0, 1])\n print('conv =', convolution_1d(x, w))\n\n # 교차상관(Cross-correlation)\n # 합성곱 연산과 다른 점은 w를 반전시키지 않는 것\n # CNN(Convolutional Neural Network, 합성곱 신경망)에서는 대부분 교차상관 사용\n\n cross_correlation = cross_correlation_1d(x, w)\n print('cross_correlation =', cross_correlation)","sub_path":"ch07/ex01_convolution1d.py","file_name":"ex01_convolution1d.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"502013084","text":"from random import choice\n\ndef testround(filt_count, filtered):\n test = []\n testindex = []\n filtered_update = []\n numberset = list(range(0, filt_count))\n if filt_count == 1:\n print(\"Not enough common basis to test, protocol will be aborted\")\n exit() \n else:\n for i in range(int(filt_count / 2)):\n rannum = choice(numberset)\n numberset.remove(rannum)\n testindex.append(rannum)\n test.append(filtered[rannum])\n for i in range(filt_count):\n if not i in testindex:\n filtered_update.append(filtered[i])\n else:\n continue\n return test, testindex, filtered_update\n\n\ndef testing(test_alice, test_bob, testindex, commonbasis, filtered, basis):\n counter = -1\n errors = 0\n errorh = 0\n for i in testindex:\n counter += 1\n if not test_alice[counter] == test_bob[counter]:\n if basis[commonbasis[i]] == 0:\n errors += 1\n elif basis[commonbasis[i]] == 1:\n errorh += 1\n return errors, errorh\n\n\ndef update_filtered(testindex, filtered):\n filtered_update = []\n for i in range(len(filtered)):\n if not i in testindex:\n filtered_update.append(filtered[i])\n else:\n continue\n return filtered_update\n\n\ndef errorconversion(e_s, e_h, test):\n e_t = round(((e_s + e_h) / len(test)) * 100, 2)\n e_s2 = 0;\n e_h2 = 0\n\n if not e_t == 0:\n e_s2 = (e_s / (e_s + e_h)) * 100\n e_h2 = (e_h / (e_s + e_h)) * 100\n return e_t, round(e_s2, 2), round(e_h2, 2)\n","sub_path":"qkd/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"323886108","text":"# -*- coding: utf-8 -*-\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom config.translations import Translations\nfrom config.icons_pics import Icons, Pics\nfrom config import config\n\n\nclass ui_dialog_about(object):\n def setupUi(self, DialogAbout):\n DialogAbout.setObjectName(\"DialogAbout\")\n DialogAbout.resize(400, 446)\n icons = Icons()\n DialogAbout.setWindowIcon(QtGui.QIcon(icons.actionAboutIcon))\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred,\n QtWidgets.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(\n DialogAbout.sizePolicy().hasHeightForWidth())\n DialogAbout.setSizePolicy(sizePolicy)\n DialogAbout.setMinimumSize(QtCore.QSize(400, 446))\n DialogAbout.setMaximumSize(QtCore.QSize(400, 446))\n self.lblLogo = QtWidgets.QLabel(DialogAbout)\n self.lblLogo.setGeometry(QtCore.QRect(140, 70, 121, 20))\n self.lblLogo.setObjectName(\"lblLogo\")\n self.lblAppVersion = QtWidgets.QLabel(DialogAbout)\n self.lblAppVersion.setGeometry(QtCore.QRect(10, 160, 381, 41))\n font = QtGui.QFont()\n font.setPointSize(24)\n font.setBold(True)\n font.setWeight(75)\n self.lblAppVersion.setFont(font)\n self.lblAppVersion.setTextFormat(QtCore.Qt.RichText)\n self.lblAppVersion.setScaledContents(False)\n self.lblAppVersion.setAlignment(QtCore.Qt.AlignCenter)\n self.lblAppVersion.setObjectName(\"lblAppVersion\")\n self.lblAppDesc = QtWidgets.QLabel(DialogAbout)\n self.lblAppDesc.setGeometry(QtCore.QRect(10, 210, 381, 51))\n self.lblAppDesc.setAlignment(QtCore.Qt.AlignCenter)\n self.lblAppDesc.setWordWrap(True)\n self.lblAppDesc.setObjectName(\"lblAppDesc\")\n self.lblCopyright = QtWidgets.QLabel(DialogAbout)\n self.lblCopyright.setGeometry(QtCore.QRect(10, 270, 381, 51))\n font = QtGui.QFont()\n font.setPointSize(9)\n self.lblCopyright.setFont(font)\n self.lblCopyright.setAlignment(\n QtCore.Qt.AlignHCenter\n | QtCore.Qt.AlignTop)\n self.lblCopyright.setWordWrap(True)\n self.lblCopyright.setObjectName(\"lblCopyright\")\n\n self.retranslate_ui(DialogAbout)\n QtCore.QMetaObject.connectSlotsByName(DialogAbout)\n\n def retranslate_ui(self, DialogAbout):\n lingo = Translations()\n pics = Pics()\n this_config = config.Config()\n _translate = QtCore.QCoreApplication.translate\n DialogAbout.setWindowTitle(_translate(\"DialogAbout\",\n lingo.load(\"DialogAbout\")\n + \" \"\n + this_config.APP_NAME, None))\n self.lblAppVersion.setText(_translate(\"DialogAbout\",\n this_config.APP_NAME\n + \" \"\n + this_config.APP_VERSION, None))\n self.lblAppDesc.setText(_translate(\"DialogAbout\",\n this_config.APP_NAME\n + \" \" + lingo.load(\"lblAppDesc\"),\n None))\n self.lblCopyright.setText(_translate(\"DialogAbout\",\n \"
\"\n + \"\"\n + lingo.load(\"lblCopyright\")\n + \"
\"\n + this_config.APP_WEBSITE\n + \"
\",\n None))\n\n self.lblLogo.resize(250, 250)\n mastodome_mascot = QtGui.QPixmap(\n pics.aboutMascoutImg).scaled(\n self.lblLogo.size())\n self.lblLogo.setPixmap(mastodome_mascot)\n self.lblLogo.move(75, 20)\n self.lblAppVersion.move(10, 280)\n self.lblAppDesc.move(10, 310)\n self.lblCopyright.move(10, 360)\n","sub_path":"gui/about.py","file_name":"about.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"381300163","text":"\"\"\"\nUrls\n\"\"\"\nfrom django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^searching$', views.search, name='search'),\n url(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n url(r'^register_substitut$', views.register_substitut, name='register_substitut'),\n url(r'^account$', views.account, name='account'),\n url(r'^legal$', views.legal, name='legal'),\n url(r'^results', views.results, name='results'),\n url(r'^mysubstitutes', views.mysubstitutes, name='mysubstitutes'),\n url(r'^category-autocomplete/$',\n views.CategoryAutocomplete.as_view(), name='category-autocomplete', ),\n]\n","sub_path":"substitute/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"380880260","text":"import sys\nimport re\nimport pymongo\nimport json\nimport datetime\n\nclient = pymongo.MongoClient(host=\"da1.eecs.utk.edu\")\n\nDB = sys.argv[1]\nCOLL = sys.argv[2]\nfield = sys.argv[3]\n# allow multiple comma seperated targets simultaneoulsy, up to 2 maybe..\nTARGETS = sys.argv[4]\ntargets = map(lambda x: x.replace('.', '\\\\\\.'), TARGETS.split(','))\n\n\nif len(sys.argv) < 5:\n sys.exit('unexpected number of inputs')\nelif len(sys.argv) == 5:\n excludes = []\nelse:\n excludes = sys.argv[5:]\n\n\n# stdin assumes project + ';' + timestamp\ndef unixtime2timestamp(tmp):\n return datetime.datetime.fromtimestamp(int(tmp)).strftime('%Y-%m-%dT%H-%M-%S.500')\n\n\nprj2timestamp = {}\nfor line in sys.stdin:\n items = line.strip().split(';')\n prj = items[0]\n timestamp = unixtime2timestamp(items[1])\n prj2timestamp[prj] = timestamp\n\n\ndb = client[DB]\ncoll = db[COLL]\ncoll2 = db['Posts_title_' + TARGETS]\n#coll2 = db['Posts_titletidy_readr_tibble']\n# assume we only concern about questions, ignore answers\n\n# print(targets)\n#targets[0] = targets[0].replace('.', '\\.')\n\ntarget = '|'.join(targets)\nprint(target)\n\nfor prj in prj2timestamp:\n if len(excludes) != 0:\n results = coll.find({field: {'$regex': target, '$not': re.compile(excludes[0]), '$options': 'i'},\n 'PostTypeId': '1'}, {'_id': 0})\n else:\n results = coll.find({field: {'$regex': target, '$options': 'i'},\n 'PostTypeId': '1'}, {'_id': 0})\n\n for i in results:\n if int(i['Score']) > 0:\n # convert to int\n i['Score'] = int(i['Score'])\n i['CommentCount'] = int(i['CommentCount'])\n i['AnswerCount'] = int(i['AnswerCount'])\n i['ViewCount'] = int(i['ViewCount'])\n coll2.insert(i)\n\n # coll2.insert(i)\n","sub_path":"scripts/filterouttiydplusdatatable.py","file_name":"filterouttiydplusdatatable.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"231196001","text":"# Alexandros Gidarakos - https://www.linkedin.com/in/alexandrosgidarakos\n# My solution to MITx 6.00.1x Lecture 6 Problem 2\n\ndef oddTuples(aTup):\n '''\n aTup: a tuple\n\n returns: tuple, every other element of aTup.\n '''\n\n result = ()\n\n for i in range(0, len(aTup), 2):\n result += (aTup[i],)\n\n return result\n\nprint(oddTuples((1, 2, 3, 4, 5, 6, 7)))\n","sub_path":"lecture-6/lecture-6-problem-2.py","file_name":"lecture-6-problem-2.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"340734300","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport sys\nfrom six import print_\nfrom six.moves import input\n\ntotal = 0\nfor present in sys.stdin:\n l, w, h = map(int, present.split(\"x\"))\n a = l * w\n b = w * h\n c = h * l\n smallest = min([a, b, c])\n total += 2 * a + 2 * b + 2 * c + smallest\nprint_(\"{} ft²\".format(total))\n","sub_path":"day2-1.py","file_name":"day2-1.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"455023035","text":"# -*- coding: utf-8 -*-\r\nimport socket\r\nimport threading\r\nimport access\r\nHOST = ''\r\nPORT = 50007\r\nrpiaddr = ''\r\nrpiconn = None\r\ntoken = b'thisisraspberrypi'\r\n\r\n\r\ndef rpi_listener():\r\n global rpiaddr,rpiconn\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.bind((HOST, PORT))\r\n s.listen(1)\r\n while True:\r\n conn, addr = s.accept()\r\n print('Connected by', addr)\r\n access.intiative_send_msg('ov7o7t9E4Jbjl8CVaImoBl2oNDMI', '远程接入', 'text')\r\n conn.settimeout(55)\r\n while True:\r\n try:\r\n data = conn.recv(1024)\r\n except Exception as e:\r\n print('there is a socket error::',e)\r\n conn.close()\r\n access.intiative_send_msg('ov7o7t9E4Jbjl8CVaImoBl2oNDMI', '树莓派断线', 'text')\r\n break\r\n if data == token:\r\n print('data:', data)\r\n rpiaddr = addr[0]\r\n rpiconn = conn\r\n conn.send(b'thisisserver')\r\n else:\r\n print('attention error token:::',data)\r\n access.intiative_send_msg('ov7o7t9E4Jbjl8CVaImoBl2oNDMI', '收到了奇怪的接入口令:'+ data, 'text')\r\n if data == '':\r\n break\r\n\r\n conn.close()\r\n\r\n\r\ndef start_listen():\r\n t = threading.Thread(target=rpi_listener)\r\n t.setDaemon(True)\r\n t.start()\r\n return","sub_path":"Server plugin/rpi_addr_listener.py","file_name":"rpi_addr_listener.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"578981259","text":"import FWCore.ParameterSet.Config as cms\n\n#\n# module for b-tag study\n#\n\n\nanalyzeBtags = cms.EDAnalyzer(\"BtagAnalyzer\",\n ## collections of RA4b objects\n jets = cms.InputTag(\"goodJets\"),\n bjets = cms.InputTag(\"mediumTrackHighEffBjets\"),\n muons = cms.InputTag(\"goodMuons\"),\n electrons = cms.InputTag(\"goodElectrons\"),\n met = cms.InputTag(\"patMETsPF\"),\n ## collections of matched objects\n matchedLightJets = cms.InputTag(\"matchedLightJets\"),\n matchedBjets = cms.InputTag(\"matchedBjets\"),\n ## for event and jet weighting\n PVSrc = cms.InputTag(\"offlinePrimaryVertices\"),\n PUInfo = cms.InputTag(\"addPileupInfo\"),\n PUWeight = cms.InputTag(\"eventWeightPU:eventWeightPU\"),\n RA2Weight = cms.InputTag(\"weightProducer:weight\"),\n BtagEventWeights = cms.InputTag(\"btagEventWeight:RA4bEventWeights\"),\n BtagJetWeights = cms.InputTag(\"btagEventWeight:RA4bJetWeights\"),\n BtagJetWeightsGrid = cms.InputTag(\"BtagEventWeight:RA4bJetWeightsGrid\"),\n BtagEventWeightsGrid = cms.InputTag(\"btagEventWeight:RA4bJetWeightsGrid\"),\n BtagEffGrid = cms.InputTag(\"btagEventWeight:effBTagEventGrid\"),\n ## ...\n ## bool \n useEventWeight = cms.bool(False),\n useBtagEventWeight = cms.bool(False),\n ## 0: 0 btags, 1: 1 btag; 2: 2 btags, 3: 3 or more btags \n btagBin = cms.int32(0)\n )\n","sub_path":"Btagging/BtagAnalyzer/python/BtagAnalyzer_cfi.py","file_name":"BtagAnalyzer_cfi.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"37655910","text":"#!/usr/bin/env python\n# coding=utf-8\nimport codecs\nimport datetime\nfrom glob import glob\nimport os\nimport re\n\nclass Tester:\n \"\"\"\n Test all the text files to ensure:\n * Tweets are all in order - within each file the most recent should\n be first.\n * All Tweets should be <= 280 characters in length.\n\n Outputs a report listing all errors.\n \"\"\"\n\n def __init__(self):\n\n self.project_root = os.path.abspath(os.path.dirname(__file__))\n\n # Will be a list of dicts:\n self.errors = []\n\n def start(self):\n\n # Cycle through every directory in /tweets/ whose name is four digits:\n for d in glob('{}/tweets/{}'.format(self.project_root, '[0-9]' * 4)):\n for f in os.listdir(d):\n # Test every .txt file:\n if f.endswith('.txt'):\n self.test_file(\n os.path.join(self.project_root, 'tweets', d, f))\n\n last_file = None\n\n # Output all errors, if any.\n if len(self.errors) == 0:\n print(\"\\nEverything is OK.\")\n else:\n for err in self.errors:\n # err has 'filepath', 'time' and 'text' elements.\n if last_file is None or last_file != err['filepath']:\n # eg 'FILE: 1660/01.txt'\n dir_file = '/'.join(err['filepath'].split('/')[-2:])\n print(\"\\nFILE tweets/{}\".format(dir_file))\n\n print(\" {}: {}\".format(err['time'], err['text']).encode('utf-8'))\n\n last_file = err['filepath']\n\n\n def test_file(self, filepath):\n \"Test an individual file.\"\n\n f = codecs.open(filepath, 'r', 'utf-8')\n\n prev_time = None\n\n for line in f:\n line = line.strip()\n if line != '':\n # Use same match as in tweeter.py, and only test matching lines.\n line_match = re.match(\n '^(\\d{4}-\\d{2}-\\d{2}\\s\\d{2}\\:\\d{2})\\s(.*?)$', line)\n\n if line_match:\n [tweet_time, tweet_text] = line_match.groups()\n\n t = datetime.datetime.strptime(tweet_time, '%Y-%m-%d %H:%M')\n\n if prev_time is not None:\n if t > prev_time:\n self.add_error(\n filepath,\n tweet_time,\n \"Time is after previous time ({}).\".format(prev_time))\n elif t == prev_time:\n self.add_error(\n filepath,\n tweet_time,\n \"Time is the same as previous time ({}).\".format(prev_time))\n if len(tweet_text) > 280:\n self.add_error(\n filepath,\n tweet_time,\n \"Tweet is {} characters long.\".format(len(tweet_text)))\n\n prev_time = t\n f.close()\n\n def add_error(self, filepath, dt, txt):\n self.errors.append({\n 'filepath': filepath,\n 'time': dt,\n 'text': txt\n })\n\n\ndef main():\n tester = Tester()\n\n tester.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":3326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"298139905","text":"from selenium import webdriver\nimport time\n\noptions = webdriver.ChromeOptions()\nprefs = {\n \"download.default_directory\": \"C:\\\\MyNewFolder\",\n \"download.prompt_for_download\": False,\n \"download.directory_upgrade\": True\n }\noptions.add_experimental_option('prefs', prefs)\ndriver = webdriver.Chrome(options=options)\n\n\ndriver.get(\"https://docs.google.com/presentation/d/1n2TEPRiaRajUODFNNbNQCfKIwnSViLia8G9PWSlMAow/export/pptx\")\ntime.sleep(1)\ndriver.quit()\n","sub_path":"python/change_download_folder_chrome.py","file_name":"change_download_folder_chrome.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"621539814","text":"import pytest\nfrom unittest import mock\nfrom lca._prog import _blastn as blastn\n\n@mock.patch(\"lca._prog._blastn.shutil\")\n@mock.patch(\"lca._prog._blastn.subprocess\")\ndef test_run_blastn_raises_exception_when_blastn_called_with_help(mock_shutil,\n mock_subprocess):\n mock_shutil.which.return_value = \"not None\"\n with pytest.raises(blastn.BLASTNError):\n blastn._blastn_cmd([\"-help\"])\n\n@mock.patch(\"lca._prog._blastn.shutil\")\n@mock.patch(\"lca._prog._blastn.subprocess\")\ndef test_run_blastn_raises_exception_when_blastn_called_with_h(mock_shutil,\n mock_subprocess):\n mock_shutil.which.return_value = \"not None\"\n with pytest.raises(blastn.BLASTNError):\n blastn._blastn_cmd([\"-h\"])\n\n@mock.patch(\"lca._prog._blastn.shutil\")\ndef test_check_for_blastn_binary_looks_for_correct_name(mock_shutil):\n blastn._check_for_blastn_binary()\n mock_shutil.which.assert_called_with(\"blastn\")\n\n@mock.patch(\"lca._prog._blastn.shutil\")\ndef test_check_for_blastn_binary_raises_exception_if_blastn_binary_not_found(mock_shutil):\n mock_shutil.which.return_value = None\n with pytest.raises(blastn.BLASTNError):\n blastn._check_for_blastn_binary()\n\n@mock.patch(\"lca._prog._blastn.subprocess\")\ndef test_blastn_cmd_raises_exception_when_subprocess_retcode_is_1(mock_subprocess):\n mock_subprocess.run.return_value.returncode = 1\n with pytest.raises(blastn.BLASTNError):\n blastn._blastn_cmd([\"this is a test\"])\n\n@pytest.mark.parametrize(\"test_input\", [1, 1.1, b\"this is bytes\"])\ndef test_parse_stdout_raises_exception_when_input_not_string(test_input):\n with pytest.raises(TypeError):\n blastn._parse_stdout(test_input)\n\ndef test_get_header_raises_exception_with_unrecognized_column():\n with pytest.raises(blastn.BLASTNError):\n blastn._get_header(\"6 this_is_an_illegal_column_name\")\n\ndef test_check_outfmt_raises_exception_with_illegal_outfmt():\n with pytest.raises(blastn.BLASTNError):\n blastn._check_outfmt(\"101\")\n","sub_path":"test/test_blastn.py","file_name":"test_blastn.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"224986303","text":"import tensorflow as tf\nfrom tensorflow.keras.layers import *\n\n\ndef load_pretrained_model(model, hidden1=256, hidden2=256):\n \n pretrained_model = tf.keras.models.load_model(model)\n pretrained_model.trainable = True \n\n h1 = tf.keras.layers.Dense(hidden1, activation='elu', name='dense_ft_1')(pretrained_model.layers[-2].output)\n h1 = tf.keras.layers.Dropout(0.50)(h1)\n h2 = tf.keras.layers.Dense(hidden2, activation='elu', name='dense_ft_2')(h1)\n h2 = tf.keras.layers.Dropout(0.50)(h2)\n output = tf.keras.layers.Dense(1, activation='sigmoid', name='output')(h2)\n \n # define new model\n new_model = tf.keras.models.Model(inputs=pretrained_model.inputs, outputs=output)\n\n # Learning rate of 5e-5 used for finetuning based on hyperparameter evaluations\n ft_optimizer = tf.keras.optimizers.Adam(learning_rate=0.00005) \n \n # Compile model with Cross Entropy loss\n new_model.compile(loss=tf.keras.losses.BinaryCrossentropy(),\n optimizer=ft_optimizer,\n metrics=params.METRICS)\n\n return new_model\n\n\n\n\n","sub_path":"src/models/model_helper.py","file_name":"model_helper.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"233095811","text":"from PIL import Image\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport math\n\nimport torch\nfrom torchvision import transforms\n\nclass DataTransform():\n def __init__(self, resize, mean, std):\n self.img_transform = transforms.Compose([\n transforms.Resize(resize),\n transforms.CenterCrop(resize),\n transforms.ToTensor(),\n transforms.Normalize(mean, std)\n ])\n\n def __call__(self, img_path_list, acc_numpy, phase):\n img_tensor_list = self.transformImages(img_path_list)\n acc_numpy = acc_numpy.astype(np.float32)\n acc_numpy = acc_numpy / np.linalg.norm(acc_numpy)\n acc_tensor = torch.from_numpy(acc_numpy)\n return img_tensor_list, acc_tensor\n\n def transformImages(self, img_path_list):\n img_tensor_list = []\n for i in range(len(img_path_list)):\n img_tensor = self.img_transform(Image.open(img_path_list[i]))\n img_tensor_list.append(img_tensor)\n return img_tensor_list\n\n##### test #####\n# ## trans param\n# resize = 224\n# mean = ([0.5, 0.5, 0.5])\n# std = ([0.5, 0.5, 0.5])\n# ## image\n# img_path_list = [\n# \"../../../dataset_image_to_gravity/AirSim/5cam/example/camera_0.jpg\",\n# \"../../../dataset_image_to_gravity/AirSim/5cam/example/camera_72.jpg\",\n# \"../../../dataset_image_to_gravity/AirSim/5cam/example/camera_144.jpg\",\n# \"../../../dataset_image_to_gravity/AirSim/5cam/example/camera_216.jpg\",\n# \"../../../dataset_image_to_gravity/AirSim/5cam/example/camera_288.jpg\"\n# ]\n# ## label\n# acc_list = [0, 0, 1]\n# acc_numpy = np.array(acc_list)\n# ## transform\n# data_transform = DataTransform(resize, mean, std)\n# img_trans_list, acc_trans = data_transform(img_path_list, acc_numpy)\n# print(\"acc_trans = \", acc_trans)\n# ## tensor -> numpy\n# img_trans_numpy_list = [np.clip(img_trans.numpy().transpose((1, 2, 0)), 0, 1) for img_trans in img_trans_list] #(rgb, h, w) -> (h, w, rgb)\n# print(\"np.array(img_trans_numpy_list).shape = \", np.array(img_trans_numpy_list).shape)\n# ## imshow\n# for i in range(len(img_path_list)):\n# plt.subplot2grid((2, len(img_path_list)), (0, i))\n# plt.imshow(Image.open(img_path_list[i]))\n# plt.subplot2grid((2, len(img_path_list)), (1, i))\n# plt.imshow(img_trans_numpy_list[i])\n# plt.show()\n","sub_path":"pysrc/common_multi/data_transform_model.py","file_name":"data_transform_model.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"106065802","text":"#!/usr/bin/python\n\nimport os\npetsc_hash_pkgs=os.path.join(os.getenv('HOME'),'petsc-hash-pkgs')\n\nif __name__ == '__main__':\n import sys\n import os\n sys.path.insert(0, os.path.abspath('config'))\n import configure\n configure_options = [\n '--package-prefix-hash='+petsc_hash_pkgs,\n '--with-mpi=0',\n '--with-cc=gcc',\n '--with-cxx=g++',\n '--with-fc=gfortran',\n '--with-cuda=1',\n '--download-hdf5',\n '--download-metis',\n '--download-superlu',\n '--download-mumps',\n '--with-mumps-serial',\n '--with-shared-libraries=1',\n ]\n configure.petsc_configure(configure_options)\n\n","sub_path":"config/examples/arch-ci-linux-cuda-uni-pkgs.py","file_name":"arch-ci-linux-cuda-uni-pkgs.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"146212514","text":"from django import forms\nfrom django.forms import ModelForm\nfrom surveys.models import Question,Survey,Response,AnswerText,AnswerRadio,AnswerSelect,AnswerInteger,AnswerSelectMultiple,QuestionSet,Page\n\nclass ResponseForm(ModelForm):\n class Meta:\n model = Response\n #fields = ('interviewer', 'interviewee', 'conditions', 'comments')\n fields = ()\n def __init__(self, *args, **kwargs):\n page = kwargs.pop('page')\n survey = kwargs.pop('survey')\n user = kwargs.pop('user')\n self.page = page\n self.survey = survey\n self.user = user\n super(ResponseForm, self).__init__(*args, **kwargs)\n self.prefix = \"question\"\n\n data = kwargs.get('data')\n for q in page.questions.question_set.all():\n question = \"%s_%d\" % (self.prefix, q.pk)\n\n if q.question_type == Question.TEXT:\n form = forms.CharField(label=q.text, widget=forms.TextInput)\n elif q.question_type == Question.RADIO:\n question_choices = q.get_choices()\n form = forms.ChoiceField(label=q.text, widget=forms.RadioSelect, choices=question_choices)\n elif q.question_type == Question.SELECT:\n question_choices = q.get_choices()\n question_choices = tuple([('', '---------------')]) + question_choices\n form = forms.ChoiceField(label=q.text, widget=forms.Select, choices=question_choices)\n elif q.question_type == Question.SELECT_MULTIPLE:\n question_choices = q.get_choices()\n form = forms.MultipleChoiceField(label=q.text, widget=forms.CheckboxSelectMultiple, choices=question_choices)\n elif q.question_type == Question.INTEGER:\n form = forms.IntegerField(label=q.text)\n\n self.fields[question] = form\n\n if q.required:\n self.fields[question].required = True\n self.fields[question].widget.attrs[\"class\"] = \"required\"\n else:\n self.fields[question].required = False\n \n if data:\n self.fields[question].initial = data.get(question)\n def save(self,commit=True):\n response = super(ResponseForm, self).save(commit=False)\n response.page = self.page\n response.user = self.user\n response.save()\n\n for field_name,field_value in self.cleaned_data.items():\n if field_name.startswith(self.prefix):\n q_id = int(field_name.split(\"_\")[1])\n q = Question.objects.get(pk=q_id)\n if q.question_type == Question.TEXT:\n a = AnswerText(question = q)\n elif q.question_type == Question.RADIO:\n a = AnswerRadio(question = q)\n elif q.question_type == Question.SELECT:\n a = AnswerSelect(question = q)\n elif q.question_type == Question.SELECT_MULTIPLE:\n a = AnswerSelectMultiple(question = q)\n elif q.question_type == Question.INTEGER:\n a = AnswerInteger(question = q)\n a.body = field_value\n\n a.response = response\n a.save()\n return response\n\n","sub_path":"surveys/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"631024967","text":"import paho.mqtt.client as mqtt\nimport RPi.GPIO as GPIO\n\nMQTT_HOST = \"test.mosquitto.org\"\nMQTT_PORT = 1883\nMQTT_KEEPALIVE_INTERVAL = 60\nMQTT_TOPIC = \"gapple\"\n\nled_pin = 18 \n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(led_pin, GPIO.OUT)\n\ndef on_message(client, userdata, message):\n result = str(message.payload.decode(\"utf-8\"))\n print(\"received message = \", str(message.payload.decode(\"utf-8\")))\n \n if(result.upper() == \"ON\"):\n GPIO.output(led_pin,True)\n elif(result.upper() == \"OFF\"):\n GPIO.output(led_pin,False)\n else:\n print(\"Illegal Arugment Exception!\");\n \n\n# Initiate MQTT Client\nclient = mqtt.Client()\n\n# Register received message callback function\nclient.on_message = on_message\n\n# Connect with MQTT Broker\n# client.username_pw_set(\"\", \"\")\nclient.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)\n\nclient.subscribe(MQTT_TOPIC)\n\n# Loop from MQTT_Broker\nclient.loop_forever()\n","sub_path":"exercise/mqtt/subscribe.py","file_name":"subscribe.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"48807112","text":"from rest_framework import serializers, fields\nfrom events import models\nfrom users import (\n serializers as user_serializers,\n models as user_models\n)\n\n\nclass CampusSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Campus\n fields = ('id', 'name', 'description')\n read_only_fields = ('id', 'name', 'description')\n\n\nclass EventLocationSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.EventLocation\n fields = ('id', 'name', 'description', 'is_public', 'created_at', 'campus')\n read_only_fields = ('id', 'created_at', 'modified_at', 'is_public')\n\n def to_representation(self, instance):\n data = super(EventLocationSerializer, self).to_representation(instance)\n if instance.campus:\n data['campus'] = CampusSerializer(instance=instance.campus).data\n return data\n\n def save(self, **kwargs):\n self._validated_data.update({\n 'user_id': kwargs.pop('user_id')\n })\n return super(EventLocationSerializer, self).save(**kwargs)\n\n\nclass EventShoppingItemSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.EventShoppingItem\n fields = ('id', 'name', 'created_at', 'event', 'user_id', 'amount')\n read_only_fields = ('id', 'created_at', 'modified_at')\n\n def to_representation(self, instance):\n data = super(EventShoppingItemSerializer, self).to_representation(instance)\n data['creator'] = instance.user_id if instance.user_id else None\n data['bringer'] = instance.bringer_id if instance.bringer_id else None\n data.pop('user_id')\n return data\n\n\nclass EventShoppingItemBringSerializer(serializers.Serializer):\n bring = fields.BooleanField(required=True)\n\n def save(self, **kwargs):\n item_obj = kwargs.pop('item_obj')\n user_id = kwargs.pop('user_id')\n if self.validated_data.get('bring'):\n # add bringer_id to shopping item object\n item_obj.bringer_id = user_id\n else:\n # remove bringer_id to shopping item object\n item_obj.bringer_id = \"\"\n item_obj.save()\n return item_obj\n\n\nclass EventMealSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.EventMeal\n fields = ('id', 'name', 'created_at', 'event', 'meal_id', 'user_id')\n read_only_fields = ('id', 'created_at', 'modified_at')\n\n def to_representation(self, instance):\n data = super(EventMealSerializer, self).to_representation(instance)\n data['creator'] = instance.user_id\n data['voters'] = instance.votes.values_list('user_id', flat=True)\n data['votes'] = len(data['voters'])\n data.pop('user_id')\n return data\n\n\nclass EventMealVoteSerializer(serializers.Serializer):\n vote = fields.BooleanField(required=True)\n\n def save(self, **kwargs):\n meal_obj = kwargs.pop('meal_obj')\n user_id = kwargs.pop('user_id')\n if self.validated_data.get('vote'):\n # Create Vote\n meal_obj.votes.create(user_id=user_id)\n else:\n # Delete Vote\n meal_obj.votes.filter(user_id=user_id).delete()\n return meal_obj\n\n\nclass EventMessageSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.EventMessage\n fields = ('id', 'text', 'user_id', 'event', 'created_at')\n read_only_fields = ('id', 'created_at', 'modified_at')\n\n def to_representation(self, instance):\n data = super(EventMessageSerializer, self).to_representation(instance)\n data['creator'] = instance.user_id\n data.pop('user_id')\n return data\n\n\nclass EventPreferenceSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.EventPreference\n fields = ('event', 'food_preference')\n\n def to_representation(self, instance):\n return user_serializers.FoodPreferenceSerializer(instance=instance.food_preference).data\n\n\nclass EventUserSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.EventUser\n fields = ('event', 'user_id')\n\n def to_representation(self, instance):\n \"\"\"\n :param instance: EventUser instance\n :return: UserSerializer data\n \"\"\"\n return user_serializers.UserSerializer(instance=instance.user_id).data\n\n\nclass EventSerializer(serializers.ModelSerializer):\n preferenceids = fields.MultipleChoiceField(\n choices=user_models.FoodPreference.objects.all().values_list('pk', flat=True),\n allow_null=True,\n required=False,\n help_text=\"Food Preference IDs to save with event while creation\"\n )\n\n class Meta:\n model = models.Event\n fields = ('id', 'title', 'description', 'start_at', 'end_at', 'created_at', 'capacity', 'user_id', 'location',\n 'preferenceids')\n read_only_fields = ('id', 'created_at', 'user_id')\n\n def to_representation(self, instance):\n data = super(EventSerializer, self).to_representation(instance)\n data['creator'] = instance.user_id\n data.pop('user_id')\n if self.context.get('is_list', False):\n data['num_members'] = instance.users.count()\n data['members'] = []\n data['shoppingitems'] = []\n data['meals'] = []\n data['messages'] = []\n else:\n data['members'] = instance.users.all().values_list('user_id', flat=True)\n data['num_members'] = len(data['members'])\n data['shoppingitems'] = EventShoppingItemSerializer(instance=instance.shop_items.all(), many=True).data\n data['meals'] = EventMealSerializer(instance=instance.meals.all(), many=True).data\n data['messages'] = EventMessageSerializer(instance=instance.messages.all(), many=True).data\n\n data['preferences'] = EventPreferenceSerializer(\n instance=instance.preferences.all(),\n many=True\n ).data\n data['location'] = EventLocationSerializer(instance=instance.location).data\n return data\n\n def save(self, **kwargs):\n \"\"\"\n Create/Update Event Object.\n Then check is there are preferenceids.\n If yes, Delete old preferences. Create EventPreference objects\n \"\"\"\n self._validated_data.update({\n 'user_id': kwargs.pop('user_id')\n })\n preferenceids = self._validated_data.pop('preferenceids', [])\n event_obj = super(EventSerializer, self).save(**kwargs)\n if preferenceids:\n # Delete Old Preference objects\n models.EventPreference.objects.filter(event=event_obj).delete()\n # Create Event Preference objects\n data = [\n {\n \"event\": event_obj.id,\n \"food_preference\": pref_id\n } for pref_id in preferenceids\n ]\n pref_serializer = EventPreferenceSerializer(data=data, many=True)\n pref_serializer.is_valid(raise_exception=True)\n pref_serializer.save()\n\n return event_obj\n","sub_path":"events/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":7107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10957708","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 11:58:55 2019\n\n@author: Moha-Thinkpad\n\"\"\"\n\n## code for augmenting image + landmark locatios\n# based on skimage\n# and imgaug https://github.com/aleju/imgaug\n\n\nfrom skimage import io\nfrom numpy import genfromtxt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\nimport glob\nimport os\nfrom scipy import misc\n\n# image source directory\nSourcePath='./Sources'\n# image destination directory\nwrite_to_dir = \"./augmented\"\n\ntry:\n os.mkdir(write_to_dir)\nexcept:\n print('destination folder is already exist')\n\n\n\n# set your augmentation sequqnces here\n# in a list called AugCongigList \n \n \nAugCongigList=[ \n iaa.Sequential([iaa.Fliplr(1, name=\"Flipper\")\n ], name='first config, just flip')\n , \n iaa.Sequential([iaa.Fliplr(1, name=\"Flipper\"),\n iaa.Affine(scale={\"x\": 0.8, \"y\": 0.9}, \n translate_percent={\"x\": 0.2, \"y\": 0.1}, \n rotate= 45, name='affine 1')] , name='second config, sequential, flip + affine')\n ] \n\n\n\nfor filename in glob.glob(SourcePath+'/*.png'): #assuming png\n \n FileName=filename.replace(SourcePath,'')\n FileName=FileName[:len(FileName)-4]\n \n \n Image = io.imread(filename)\n \n \n \n Landmarks = genfromtxt(SourcePath+FileName+'.csv', delimiter=',') \n Landmarks = Landmarks.astype(int)\n Landmarks=Landmarks[1:] # remove the first row because it is just axis label \n \n #### visualization\n# plt.figure()\n# plt.imshow(Image)\n# plt.plot(Landmarks[0,1],Landmarks[0,0],marker=\"s\",color='red')\n# plt.plot(Landmarks[1,1],Landmarks[1,0],marker=\"s\",color='red')\n# plt.plot(Landmarks[2,1],Landmarks[2,0],marker=\"s\",color='red')\n# plt.plot(Landmarks[3,1],Landmarks[3,0],marker=\"s\",color='red')\n# plt.plot(Landmarks[4,1],Landmarks[4,0],marker=\"s\",color='red')\n # The augmenters expect a list of imgaug.KeypointsOnImage.\n try:\n images=np.zeros(shape=[1,Image.shape[0],Image.shape[1],Image.shape[2]], dtype='uint8')\n images[0,:,:,:]=Image\n except:\n images=np.zeros(shape=[1,Image.shape[0],Image.shape[1]], dtype='uint8')\n images[0,:,:]=Image\n \n # Generate random keypoints.\n # The augmenters expect a list of imgaug.KeypointsOnImage.\n keypoints_on_images = []\n for image in images:\n keypoints = []\n for _ in range(len(Landmarks)):\n keypoints.append(ia.Keypoint(x=Landmarks[_,1], y=Landmarks[_,0]))\n keypoints_on_images.append(ia.KeypointsOnImage(keypoints, shape=image.shape))\n \n\n for ConfCounter in range(len(AugCongigList)):\n \n seq=AugCongigList[ConfCounter]\n \n seq_det = seq.to_deterministic() # call this for each batch again, NOT only once at the start\n \n # augment keypoints and images\n images_aug = seq_det.augment_images(images)\n transformed_keypoints = seq_det.augment_keypoints(keypoints_on_images)\n \n X_new=[]\n Y_new=[]\n # Example code to show each image and print the new keypoints coordinates\n for keypoints_after in transformed_keypoints:\n for kp_idx, keypoint in enumerate(keypoints_after.keypoints):\n x_new, y_new = keypoint.x, keypoint.y\n X_new.append(x_new)\n Y_new.append(y_new)\n \n newLandmarks=np.zeros(Landmarks.shape) \n newLandmarks[:,0]=np.asarray(Y_new)\n newLandmarks[:,1]=np.asarray(X_new)\n newLandmarks=newLandmarks.astype(int)\n\n# plt.figure()\n# plt.imshow(images_aug[0,:,:])\n# plt.plot(newLandmarks[0,1],newLandmarks[0,0],marker=\"s\",color='red')\n# plt.plot(newLandmarks[1,1],newLandmarks[1,0],marker=\"s\",color='red')\n# plt.plot(newLandmarks[2,1],newLandmarks[2,0],marker=\"s\",color='red')\n# plt.plot(newLandmarks[3,1],newLandmarks[3,0],marker=\"s\",color='red')\n# plt.plot(newLandmarks[4,1],newLandmarks[4,0],marker=\"s\",color='red')\n \n try:\n misc.imsave(write_to_dir+FileName+'_'+str(ConfCounter)+'_aug.png', images_aug[0,:,:,:])\n except:\n misc.imsave(write_to_dir+FileName+'_'+str(ConfCounter)+'_aug.png', images_aug[0,:,:])\n\n np.savetxt(write_to_dir+FileName+'_'+str(ConfCounter)+'_aug.csv', \n newLandmarks , delimiter=\",\", fmt='%i' , header='row,col')\n \n text_file = open(write_to_dir+FileName+'_'+str(ConfCounter)+'_info.txt', \"w\")\n text_file.write(\"Augmentation Info \" + '\\n' + 'name:' + seq.name + '\\n' +'\\%s' % seq)\n text_file.close()","sub_path":"PrMain_batch_images.py","file_name":"PrMain_batch_images.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"511626469","text":"from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import url,include\nfrom payroll import views\nurlpatterns = [\n #url(r'fileupload/', views.FileUploadView,name='FileUploadView1'),\n #url(r'authenticate1/', views.authenticateuser1, name='authenticateuser1'),\n url(r'authenticate/', views.authenticateuser, name='authenticateuser'),\n url(r'^$', views.index, name='index'),\n url(r'comparision/', views.Comparision.as_view()),\n url(r'legacyempdata/', views.LegacyEmpData,name='LegacyEmpData'),\n url(r'newempdata/', views.NewEmpData, name='NewEmpData'),\n url(r'legacyemppaydata/', views.LegacyEmpPayData, name='LegacyEmpPayData'),\n url(r'newemppaydata/', views.NewEmpPayData, name='NewEmpPayData'),\n url(r'empmappingdata/', views.EmpMappingData, name='EmpMappingData'),\n url(r'legacyempcomponentmapping/', views.LegacyPayComponentMapping, name='LegacyPayComponentMapping'),\n url(r'newempcomponentmapping/', views.NewPayComponentMapping, name='NewPayComponentMapping'),\n\n\n\n]","sub_path":"payroll/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"586960221","text":"# Higher Lower\n# Program should work but will need to be usability tested\nimport random\n\n# Number checking function:\ndef int_check(question, low=None, high=None):\n\n # error messages\n if low is not None and high is not None:\n error = \"Please enter an integer between {} and {} \" \\\n \"(inclusive)\".format(low, high)\n elif low is not None and high is None:\n error = \"Please enter an integer that is more than or \" \\\n \"equal to {}\".format(low)\n elif low is None and high is not None:\n error = \"Please enter an integer that is less than or \" \\\n \"equal to {}\".format(high)\n\n else:\n error = \"Please enter an integer\"\n\n while True:\n\n try:\n response = int(input(question))\n\n # Checks response is not low\n if low is not None and response < low:\n print(error)\n continue\n\n # Checks response is not too high\n if high is not None and response > high:\n print(error)\n continue\n\n return response\n\n except ValueError:\n print(error)\n continue\n\n# Main routine\n\nlowest = int_check(\"Low Number: \")\nhighest = int_check(\"High Number: \", lowest + 1)\nrounds = int_check(\"Rounds: \", 1)\n# guess = int_check(\"Guess: \", lowest, highest)\n\n# Generate secret number between low and high\nLOW = lowest\nHIGH = highest\n\nfor item in range(LOW, HIGH):\n secret = random.randint(LOW, HIGH)\n\n# Compare users guess with secret number\nSECRET = secret\nGUESSES_ALLOWED = 10\n\nalready_guessed = []\nguesses_left = GUESSES_ALLOWED\nnum_won = 0\n\nguess = \"\"\n\n# Start game\nwhile guess != SECRET and guesses_left >= 1:\n\n guess = int(input(\"Guess: \")) # replace this with function call later\n\n # checks that guess is not a duplicate\n if guess in already_guessed:\n print(\"You have already guessed that number. Please try again. \"\n \"You still have {} guesses left\".format(guesses_left))\n continue\n\n guesses_left -= 1\n already_guessed.append(guess)\n\n # if user has guesses left\n if guesses_left > 1:\n if guess > SECRET:\n print(\"Too high, try a lower number. Guesses left: {}\".format(guesses_left))\n\n elif guess < SECRET:\n print(\"Too low, try a higher number. Guesses left: {}\".format(guesses_left))\n\n # if user has one guess left\n elif guesses_left == 1:\n if guess > SECRET:\n print(\"Too high, try a lower number. THIS IS YOUR FINAL GUESS!\")\n\n elif guess < SECRET:\n print(\"Too high, try a lower number. THIS IS YOUR FINAL GUESS!\")\n\nif guess == SECRET:\n if guesses_left == GUESSES_ALLOWED - 1:\n print(\"Good job! You got the secret number in one guess :)\")\n else:\n print(\"Congratulations, you got it in {} guesses\".format(len(already_guessed)))\n num_won += 1\nelse:\n print(\"Sorry, you lost this round because you have run out of guesses :(\")","sub_path":"Higher_Lower_Game_v2.py","file_name":"Higher_Lower_Game_v2.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"12378921","text":"'''\nImplement strStr() .\n\nReturn the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.\n\nExample 1:\n\nInput: haystack = \"hello\", needle = \"ll\"\nOutput: 2\n\nExample 2:\n\nInput: haystack = \"aaaaa\", needle = \"bba\"\nOutput: -1\n\nClarification:\n\nWhat should we return when needle is an empty string? This is a great question to ask during an interview.\n\nFor the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf() .\n'''\nimport time\nclass Solution():\n def __init__(self):\n self.haystack='afjlajldjncv,ndkhaljekjafnkeljelrjlndmn,mcnzkjhfaflkjajljiuieonaknjlkjhello'\n self.needle='ll'\n\n '''我的方法'''\n def myFun(self):\n lenHay=len(self.haystack)\n lenNee=len(self.needle)\n for i in range(lenHay-lenNee+1):\n flag=1\n for j in range(lenNee):\n if self.needle[j]!=self.haystack[i+j]:\n flag=-1\n break\n if flag==1:\n return i\n return -1\n\n '''答案方法1'''\n def strStr(self):\n lenHay = len(self.haystack)\n lenNee = len(self.needle)\n if lenHay==lenNee:\n if self.haystack==self.needle:\n return 0\n else:\n return -1\n for i in range(lenHay):\n k=i\n j=0\n while(j None:\n \"\"\"\n @param dot_file: The path to the DOT file\n @return A list of networkx MultiGraphs containing the graphs in the DOT file\n \"\"\"\n if exists(dot_file):\n self._parse_dot_file(dot_file)\n else:\n self._graph = []\n logger.error(f\"File {dot_file} not found\")\n \n def _parse_dot_file(self, path: str) -> None:\n logger.info(f\"Parsing dot file {path}\")\n graph = read_dot(path)\n\n if len(graph.nodes) > 0:\n self._graph = [self._filter_graph(graph)]\n return\n \n # handle subgraphs\n pydot_graph = graph_from_dot_file(path)\n self._graph = []\n for p in pydot_graph:\n for subgraph in p.get_subgraphs():\n graph = from_pydot(subgraph)\n self._graph.append(self._filter_graph_gcc(graph))\n \n def _filter_graph_gcc(self, graph: networkx.MultiGraph) -> networkx.MultiGraph:\n logger.debug(\"Filtering graph\")\n\n duplicate_nodes = [n for n in graph.nodes if n.endswith(':s') or n.endswith(':n')]\n for x in duplicate_nodes:\n in_edges = list(graph.in_edges(x))\n out_edges = list(graph.out_edges(x))\n actual_node = x.split(':')[0]\n for src, dst in in_edges:\n graph.add_edge(src, actual_node)\n graph.remove_edge(src, x)\n for src, dst in out_edges:\n graph.add_edge(actual_node, dst)\n graph.remove_edge(src, dst)\n graph.remove_node(x)\n\n flag = False\n for (u,v,_) in graph.edges:\n if 'label' in graph.nodes[u] and graph.nodes[u]['label'].strip(\"'\").strip('\"') == 'ENTRY':\n if 'label' in graph.nodes[v] and graph.nodes[v]['label'].strip(\"'\").strip('\"') == 'EXIT':\n flag = True\n break\n \n if flag is True:\n graph.remove_edge(u,v)\n \n return graph\n \n def _filter_graph(self, graph: networkx.MultiGraph) -> networkx.MultiGraph:\n \"\"\"\n Filter the graph by merging duplicate blocks with the original\n \"\"\"\n logger.debug(\"Filtering graph\")\n # Roots are identified by 0 incoming edges\n possible_roots = [n for n,d in graph.in_degree() if d == 0 ]\n possible_exits = [n for n,d in graph.out_degree() if d == 0 ]\n\n # Duplicate nodes also have 0 incoming edges\n # However, duplicate nodes do not have any instructions\n duplicate_nodes = [n for n in possible_roots if len(graph.nodes[n]) == 0 ]\n\n # Duplicates are identified by following the naming pattern {original}:s[0-9]\n duplicate_node_map = {}\n for tmp in set(possible_roots)-set(duplicate_nodes):\n duplicate_node_map[tmp] = [n for n in duplicate_nodes if n.startswith(tmp) and n[len(tmp)] == ':' ]\n \n # Merge duplicates with original\n for tmp in duplicate_node_map:\n for duplicate_node in duplicate_node_map[tmp]:\n out_edges = list(graph.out_edges(duplicate_node))\n for src, dst in out_edges:\n graph.add_edge(tmp, dst)\n graph.remove_edge(src, dst)\n graph.remove_node(duplicate_node)\n\n duplicate_nodes = [n for n in possible_exits if len(graph.nodes[n]) == 0 ]\n\n duplicate_node_map = {}\n for tmp in set(possible_exits)-set(duplicate_nodes):\n duplicate_node_map[tmp] = [n for n in duplicate_nodes if n.startswith(tmp) and n[len(tmp)] == ':' ]\n \n for tmp in duplicate_node_map:\n for duplicate_node in duplicate_node_map[tmp]:\n in_edges = list(graph.in_edges(duplicate_node))\n for src, dst in in_edges:\n graph.add_edge(src, tmp)\n graph.remove_edge(src, dst)\n graph.remove_node(duplicate_node)\n \n flag = False\n for (u,v,_) in graph.edges:\n if 'label' in graph.nodes[u] and graph.nodes[u]['label'].strip(\"'\").strip('\"') == 'ENTRY':\n if 'label' in graph.nodes[v] and graph.nodes[v]['label'].strip(\"'\").strip('\"') == 'EXIT':\n flag = True\n break\n \n if flag is True:\n graph.remove_edge(u,v)\n \n return graph\n \n @property\n def graph(self) -> List[networkx.MultiGraph]:\n return self._graph\n\n @staticmethod\n def get_roots(graph) -> List[str]:\n return [n for n,d in graph.in_degree() if d == 0 ]","sub_path":"bifrost/dot_parser.py","file_name":"dot_parser.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"313615531","text":"class Solution:\n def findContentChildren(self, g, s):\n g.sort()\n s.sort()\n res = 0\n i = 0\n j = 0\n while i < len(g) and j < len(s):\n if g[i] > s[j]:\n j += 1\n continue\n res += 1\n i += 1\n j += 1\n return res\n\nif __name__ == '__main__':\n sol = Solution()\n \n g = [1, 2]\n s = [1, 2, 3]\n r = sol.findContentChildren(g, s)\n print(r)","sub_path":"lc_455_assign_cookies.py","file_name":"lc_455_assign_cookies.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36605876","text":"1 # coding: utf-8\n2 # Team : None\n3 # Author:zl\n4 # Date :2020/6/30 0030 下午 12:08\n5 # Tool :PyCharm\n\n\nimport requests\nimport re\nimport os\nimport csv\nimport random\nimport time\n\nheaders={\n'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n'Accept-Encoding':'gzip, deflate',\n'Accept-Language':'zh-CN,zh;q=0.9',\n'Connection':'keep-alive',\n# 'Host':'www.hbjc.gov.cn',\n'Referer':'http://www.hbjc.gov.cn/',\n'Upgrade-Insecure-Requests':'1',\n'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',\n}\n\ntable_names=['title','content','riqi','desc','url']\n\nprint('111')\n\ndef qu_html_lable(s):\n reg = re.compile(r'<[^>]+>', re.S)\n if isinstance(s, str):\n return reg.sub('', s)\n else:\n print('老兄,给字符串')\n return 0\n\ndef parse_index(link,desc):\n response=requests.get(link,headers=headers)\n\n text=response.text\n\n result=re.findall('''''',text,re.S)[0]\n\n result=re.findall('''(.*?)\\[(.*?)\\]''',result,re.S)\n\n for url,title,riqi in result:\n if url in log:\n print('曾经已经下载,跳过')\n continue\n\n print(url)\n item = {}\n item['desc']=desc\n if '../.' in url:\n item['url']=url.replace('../../','http://www.hbjc.gov.cn/')\n else:\n item['url']=url.replace('./',desc)\n item['title']=title\n item['riqi']=riqi\n item['content']=get_content(item['url'])\n\n print(item)\n time.sleep(random.randint(1,3))\n write_csv(item)\n\n with open('./log.txt', 'a', encoding='utf-8') as f:\n f.write(url+'\\r\\n')\n\ndef get_content(page_url):\n\n print(page_url)\n response=requests.get(page_url,headers=headers)\n if 'www.spp.gov.cn/' in page_url:\n text=response.content.decode('utf-8')\n\n result=re.findall('(.*?)
',text,re.S)\n\n result = '.'.join(result)\n result=qu_html_lable(result)\n return(result)\n\n else:\n text=response.text\n result = re.findall(''' (.*?)''', text, re.S)[0]\n result = qu_html_lable(result)\n result = result.replace(' ', '').replace('\\u3000', '').replace('\\n', '').replace(' ','')\n return (result)\n\n\n\n\ndef write_csv(item):\n filename=item['desc'].split('/')[-2]\n if os.path.exists('./{}.txt'.format(filename)):\n with open('./{}.txt'.format(filename), 'a', newline='', encoding='utf-8-sig') as f:\n\n writer = csv.DictWriter(f, table_names)\n writer.writerow(item)\n f.flush()\n else:\n with open('./{}.txt'.format(filename), 'w', newline='', encoding='utf-8-sig') as f:\n # 标头在这里传入,作为第一行数据\n writer = csv.DictWriter(f, table_names)\n writer.writeheader()\n writer.writerow(item)\n f.flush()\n\n\n\n\n\n\najxx=['http://www.hbjc.gov.cn/qwfb/ajxx/'] #权威发布子版块案件信息索引页,共18页\nfor i in range(1,18):\n ajxx.append('http://www.hbjc.gov.cn/qwfb/ajxx/index_{}.shtml'.format(i))\n\nzdal=['http://www.hbjc.gov.cn/qwfb/zdal/',\n 'http://www.hbjc.gov.cn/qwfb/zdal/index_1.shtml'\n ] #权威发布子版块指导案例索引页,共2页\n\nndbg=['http://www.hbjc.gov.cn/gzbg/ndbg/',\n 'http://www.hbjc.gov.cn/gzbg/ndbg/index_1.shtml'\n ] #工作报告子版块年度报告索引页,共两页\n\nbnbg=['http://www.hbjc.gov.cn/gzbg/bnbg/'] #工作报告子版块半年报告索引页,一页\nztbg=['http://www.hbjc.gov.cn/gzbg/ztbg/']#工作报告子版块专题报告索引页,一页\n\n\nprint(ajxx)\nprint(zdal)\nprint(ndbg)\nprint(bnbg)\nprint(ztbg)\n\nlog=''\n\nif os.path.exists('./log.txt'):\n with open('./log.txt','r',encoding='utf-8') as f:\n log=f.read()\nelse:\n with open('./log.txt', 'w', encoding='utf-8') as f:\n f.write('')\n log=''\n\nfor i in bnbg:\n print('下载半年报告' + i)\n parse_index(i, desc='http://www.hbjc.gov.cn/gzbg/bnbg/')\n\nfor i in ztbg:\n print('下载工作报告' + i)\n parse_index(i, desc='http://www.hbjc.gov.cn/gzbg/ztbg/')\n\n\n\nfor i in zdal:\n print('下载指导案例' + i)\n parse_index(i,desc='http://www.hbjc.gov.cn/qwfb/zdal/')\n\n\n\nfor i in ndbg:\n print('下载年度报告' + i)\n parse_index(i, desc='http://www.hbjc.gov.cn/gzbg/ndbg/')\n\n\n\nfor i in ajxx:\n print('下载案件信息'+i)\n parse_index(i,desc='http://www.hbjc.gov.cn/qwfb/ajxx/')\n\n","sub_path":"湖北检察院.py","file_name":"湖北检察院.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"14507984","text":"#!/usr/bin/python\n\nimport os, math\nfrom flask import Flask, request, Response\nimport requests\nimport json\n\napp = Flask(__name__)\n\nPORT = 6000\n\n@app.route(\"/\")\ndef main():\n return \"Hellworld istio demo\"\n\n@app.route(\"/topstories\")\ndef topStories():\n url = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty'\n header = {\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\"\n }\n resp_data = requests.get(url, headers = header)\n if resp_data.ok:\n resp_json = resp_data.json()\n else:\n resp_json = { \"blocked\": \"true\" }\n\n resp_data = json.dumps(resp_json)\n return Response(resp_data , 200, content_type=\"application/json\")\n\n@app.route('/hello')\ndef hello():\n version = os.environ.get('SERVICE_VERSION')\n\n # do some cpu intensive computation\n x = 0.0001\n for i in range(0, 1000000):\n\t x = x + math.sqrt(x)\n\n return 'Hello version: %s, instance: %s\\n' % (version, os.environ.get('HOSTNAME'))\n\n@app.route('/health')\ndef health():\n return 'Helloworld is healthy', 200\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=PORT)\n","sub_path":"workshop03/warmup_exercise/istio/app-with-external-apicall/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"167982515","text":"# standart modules\nimport os\n\n# torch\nimport torch\nimport torchvision\nfrom torch import nn\n\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n# my libraries\nfrom not_functional.models.utils.BasicUtils import torch_image_to_numpy_image, rgb2gray\nfrom not_functional.models.utils.BasicUtils import data_getters\n\nmatplotlib.use('agg')\n\nclass matplotlib_visualization:\n def plot_loss(self, D_cost_train, D_wass_train, D_cost_valid, D_wass_valid,\n G_cost, save_path) -> None:\n \"\"\"\n Visualize Discriminators and Generator with respect to cost and Wasserstein(metric) loss using Matplotlib\n :param D_cost_train: Discriminators train cost\n :param D_wass_train: Discriminators train Wasserstein cost\n :param D_cost_valid: Discriminators validation cost\n :param D_wass_valid: Discriminators validation Wasserstein cost\n :param G_cost: Generator cost\n :param save_path: Image path. Save plot as image.\n :return: None\n \"\"\"\n assert len(D_cost_train) == len(D_wass_train) == len(D_cost_valid) == len(D_wass_valid) == len(G_cost)\n\n save_path = os.path.join(save_path, \"loss_curve.png\")\n\n x = range(len(D_cost_train))\n\n y1 = D_cost_train\n y2 = D_wass_train\n y3 = D_cost_valid\n y4 = D_wass_valid\n y5 = G_cost\n\n plt.plot(x, y1, label='D_loss_train')\n plt.plot(x, y2, label='D_wass_train')\n plt.plot(x, y3, label='D_loss_valid')\n plt.plot(x, y4, label='D_wass_valid')\n plt.plot(x, y5, label='G_loss')\n\n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n\n plt.legend(loc=4)\n plt.grid(True)\n plt.tight_layout()\n\n plt.savefig(save_path)\n\n def plot_conv2d_weights(self, net):\n for i, module in enumerate(net.modules()):\n if isinstance(module, nn.Conv1d) or isinstance(module, nn.Conv2d):\n module_name = \"Conv\" + str(i)\n weights = module.weight\n weights = weights.reshape(-1).detach().cpu().numpy()\n print(\"{} bias: \".format(module_name), module.bias) # Bias to zero\n plt.hist(weights)\n plt.title(module_name)\n plt.show()\n\n ## inspect the data, parameters and NN(Neural Network)\n def imshow(self, img):\n img_shape = img.shape\n print(\"img_shape: {}\".format(img.shape))\n img = img / 2 + 0.5 # unnormalize\n trans_img = torch_image_to_numpy_image(img)\n print(\"img_shape: {}\".format(img.shape))\n plt.imshow(trans_img) # numpy and torch dimension orders are different so that need to change dims.\n # torch dim order: CHW(channel, height, width)\n plt.show()\n # print(\"image size: {}\".format( np.transpose(npimg, (1, 2, 0)).size ) )\n\n def inspect_data(self, loader: torch.utils.data.dataloader.DataLoader):\n # get some random training images\n loader_type = loader.dataset.train\n if loader_type:\n images, labels = data_getters.get_one_iter(self.trainloader)\n else:\n images, labels = data_getters.get_one_iter(self.testloader)\n # show images\n self.imshow(torchvision.utils.make_grid(images))\n # print labels\n print('classes: ', ''.join('%5s' % self.classes[labels[j]] for j in range(self.batch_size)))\n\n def inspect_one_data(self, images):\n image = images[0, ...]\n img = np.squeeze(image)\n img = torch_image_to_numpy_image(img) # PIL or numpy image format\n img = rgb2gray(img) # gray scale\n\n fig = plt.figure(figsize=(12, 12))\n ax = fig.add_subplot(111)\n ax.imshow(img, cmap='gray')\n width, height = img.shape\n thresh = img.max() / 2.5\n for x in range(width):\n for y in range(height):\n val = round(img[x][y], 2) if img[x][y] != 0 else 0\n ax.annotate(str(val), xy=(y, x),\n horizontalalignment='center',\n verticalalignment='center',\n color='white' if img[x][y] < thresh else 'black')\n plt.show()\n","sub_path":"not_functional/models/utils/visualization/matplotlib_visualization.py","file_name":"matplotlib_visualization.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"54521541","text":"# Copyright (c) 2014, Dignity Health\n#\n# Author: Ashley Anderson III \n# Date: 2016-01-25 09:50\n\nimport gpi\nimport numpy as np\nimport bart.python.cfl as cfl\nimport os\n\nclass ExternalNode(gpi.NodeAPI):\n \"\"\"Uses the numpy save interface for writing arrays.\n\n INPUT - numpy array to write\n\n WIDGETS:\n File Browser - button to launch file browser, and typein widget, to give pathname for output file\n Write Mode - write at any event, or write only with new filename\n Write Now - write right now\n \"\"\"\n\n def initUI(self):\n\n # Widgets\n self.addWidget(\n 'SaveFileBrowser', 'File Browser', button_title='Browse',\n caption='Save File (*.npy)', filter='cfl (*.cfl)')\n self.addWidget('PushButton', 'Write Mode', button_title='Write on New Filename', toggle=True)\n self.addWidget('PushButton', 'Write Now', button_title='Write Right Now', toggle=False)\n\n # IO Ports\n self.addInPort('in', 'NPYarray', dtype=np.complex64)\n\n # store for later use\n self.URI = gpi.TranslateFileURI\n\n def validate(self):\n\n if self.getVal('Write Mode'):\n self.setAttr('Write Mode', button_title=\"Write on Every Event\")\n else:\n self.setAttr('Write Mode', button_title=\"Write on New Filename\")\n\n fname = self.URI(self.getVal('File Browser'))\n self.setDetailLabel(fname)\n\n return 0\n\n def compute(self):\n\n if self.getVal('Write Mode') or self.getVal('Write Now') or ('File Browser' in self.widgetEvents()):\n\n fpath = self.URI(self.getVal('File Browser'))\n basedir, fname = os.path.split(fpath)\n basename, ext = os.path.splitext(fname)\n\n outpath = os.path.join(basedir, basename)\n\n data = self.getData('in')\n cfl.writecfl(outpath, data)\n\n return(0)\n","sub_path":"gpi/WriteCFL_GPI.py","file_name":"WriteCFL_GPI.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"459295161","text":"import pandas as pd\nimport time\nimport os.path\n#All of the files should be located in C:\\Users\\FIY716\\Documents\\Projects\\New_Column but below are the full paths for ease of use\n#C:\\Users\\FIY716\\Documents\\Projects\\New_Column\\Prod_Debt.xlsx\n#C:\\Users\\FIY716\\Documents\\Projects\\New_Column\\QA_Debt.xlsx\n#C:\\Users\\FIY716\\Documents\\Projects\\New_Column\\Prod_IP.xlsx\n#C:\\Users\\FIY716\\Documents\\Projects\\New_Column\\QA_IP.xlsx\nPROD_debt_file = input(\"Please enter the file path of the Prod Debt file you are looking to compare:\")\nQA_debt_file = input(\"Please enter the file path of the QA Debt file you are looking to compare:\")\nPROD_IP_file = input(\"Please enter the file path of the Prod IP file you are looking to compare:\")\nQA_IP_file = input(\"Please enter the file path of the QA IP file you are looking to compare:\")\n\nif os.path.isfile(PROD_debt_file) and os.path.isfile(QA_debt_file) and os.path.isfile(PROD_IP_file) and os.path.isfile(QA_IP_file):\n print(\"Thank you, please allow a few minutes for the process to complete :)\")\n\n start = time.time()\n\n df1 = pd.read_excel(PROD_debt_file, index_col=0)\n df2 = pd.read_excel(QA_debt_file, index_col=0)\n df3 = pd.read_excel(PROD_IP_file, index_col=0)\n df4 = pd.read_excel(QA_IP_file, index_col=0)\n\n#The indicator parameter below adds a new column to the merged data set notifying you of which data set the info is comign from\n df_new_ip = df3.merge(df4, on = 'TRD_ID', how='outer', indicator=True)\n df_new_debt = df1.merge(df2, on = 'TRD_ID', how='outer', indicator=True)\n#The new column is called \"_merge\"\n df_common_ip = df_new_ip[df_new_ip['_merge'] == 'both']\n df_common_debt = df_new_debt[df_new_debt['_merge'] == 'both']\n#The below now create variables from prod and qa without the common rows between them\n df_prod_debt = df1[(~df1.TRD_ID.isin(df_common_debt.TRD_ID))]\n df_qa_debt = df2[(~df2.TRD_ID.isin(df_common_debt.TRD_ID))]\n df_prod_ip = df3[(~df3.TRD_ID.isin(df_common_ip.TRD_ID))]\n df_qa_ip = df4[(~df4.TRD_ID.isin(df_common_ip.TRD_ID))]\n#Displays out the diffs between the two files dataframe(df_po)\n prod_debt = pd.DataFrame(df_prod_debt)\n qa_debt = pd.DataFrame(df_qa_debt)\n prod_ip = pd.DataFrame(df_prod_ip)\n qa_ip = pd.DataFrame(df_qa_ip)\n#Converting df to csv\n debt_prod_csv = prod_debt.to_csv(r\"C:/Users/FIY716/Documents/Projects/New_Column/Unique_Prod_Debt.csv\", index = None, header=True)\n debt_qa_csv = qa_debt.to_csv(r\"C:/Users/FIY716/Documents/Projects/New_Column/Unique_QA_Debt.csv\", index = None, header=True)\n ip_prod_csv = prod_ip.to_csv(r\"C:/Users/FIY716/Documents/Projects/New_Column/Unique_PROD_IP.csv\", index = None, header=True)\n ip_qa_csv = qa_ip.to_csv(r\"C:/Users/FIY716/Documents/Projects/New_Column/Unique_QA_IP.csv\", index = None, header=True)\n\n print(\"...............................\")\n print('It Took', round(time.time()-start,2), 'seconds for this script to run, thank you for your patience.')\nelse:\n print(\"You have not entered in an invalid file path, please try again.\")\n\n","sub_path":"File_Compare.py","file_name":"File_Compare.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"161120019","text":"\"\"\"\nCopyright 2021 AI Singapore\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nimport numpy as np\n\nimport pytest\nfrom peekingduck.pipeline.nodes.input.recorded import Node\n\n\ndef create_reader():\n media_reader = Node({\"input\": \"source\",\n \"output\": \"img\",\n \"resize\": {\n \"do_resizing\": False,\n \"width\": 1280,\n \"height\": 720},\n \"mirror_image\": False,\n \"input_dir\": \".\"\n })\n return media_reader\n\n\ndef _get_video_file(reader, num_frames):\n \"\"\"Helper function to get an entire videofile\"\"\"\n video = []\n for _ in range(num_frames):\n output = reader.run({})\n video.append(output[\"img\"])\n return video\n\n\n@pytest.mark.usefixtures(\"tmp_dir\")\nclass TestMediaReader:\n\n def test_reader_run_throws_error_on_wrong_file_path(self):\n with pytest.raises(FileNotFoundError):\n file_path = 'path_that_does_not_exist'\n Node({\"input\": \"source\",\n \"output\": \"img\",\n \"resize\": {\n \"do_resizing\": False,\n \"width\": 1280,\n \"height\": 720},\n \"mirror_image\": False,\n \"input_dir\": file_path\n })\n\n def test_reader_run_throws_error_on_empty_folder(self):\n with pytest.raises(FileNotFoundError):\n reader = create_reader()\n reader.run({})\n\n def test_reader_reads_one_image(self, create_input_image):\n image1 = create_input_image(\"image1.png\", (900, 800, 3))\n reader = create_reader()\n output1 = reader.run({})\n assert np.array_equal(output1['img'], image1)\n\n def test_reader_reads_multi_images(self, create_input_image):\n image1 = create_input_image(\"image1.png\", (900, 800, 3))\n image2 = create_input_image(\"image2.png\", (900, 800, 3))\n image3 = create_input_image(\"image3.png\", (900, 800, 3))\n reader = create_reader()\n output1 = reader.run({})\n output2 = reader.run({})\n output3 = reader.run({})\n\n assert np.array_equal(output1['img'], image1)\n assert np.array_equal(output2['img'], image2)\n assert np.array_equal(output3['img'], image3)\n\n def test_reader_reads_one_video(self, create_input_video):\n num_frames = 30\n size = (600, 800, 3)\n video1 = create_input_video(\n \"video1.avi\", fps=10, size=size, nframes=num_frames\n )\n reader = create_reader()\n\n read_video1 = _get_video_file(reader, num_frames)\n assert np.array_equal(read_video1, video1)\n\n def test_reader_reads_multiple_videos(self, create_input_video):\n num_frames = 20\n size = (600, 800, 3)\n\n video1 = create_input_video(\n \"video1.avi\", fps=5, size=size, nframes=num_frames\n )\n video2 = create_input_video(\n \"video2.avi\", fps=5, size=size, nframes=num_frames\n )\n\n reader = create_reader()\n\n read_video1 = _get_video_file(reader, num_frames)\n assert np.array_equal(read_video1, video1)\n\n read_video2 = _get_video_file(reader, num_frames)\n assert np.array_equal(read_video2, video2)\n","sub_path":"tests/pipeline/nodes/input/test_recorded.py","file_name":"test_recorded.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555370107","text":"def gcd(a,b):\n if b==0:\n return a\n else:\n return gcd(b,a%b)\n\ndef modInverse(a, m) :\n a = a % m;\n for x in range(1, m) :\n if (a * x) % m == 1:\n return x\n return 1\n\ndef find_lambda_of_one_point(x, y, a, n):\n top = 3 * x * x + a\n bot = 2 * y\n inv_bot = modInverse(bot, n)\n if inv_bot == 1:\n print(\"ANSWER: \", bot, gcd(bot, n))\n return (top * inv_bot) % n\n\ndef find_lambda_of_two_points(x1, y1, x2, y2, n):\n top = (y2 - y1)\n bot = (x2 - x1)\n inv_bot = modInverse(bot, n)\n if inv_bot == 1:\n print(\"ANSWER: \", bot, gcd(bot, n))\n return (top * inv_bot) % n\n\ndef find_x3_y3(lam, x1, x2, y1, n):\n x3 = (lam * lam - x1 - x2) % n\n y3 = (lam * (x1 - x3) - y1) % n\n return x3, y3\n\n\ndef fuck_471(x, y, a, n, iter):\n # y^2 = x^3 + Ax + B\n lam = find_lambda_of_one_point(x, y, a, n)\n new_x = find_x3_y3(lam, x, x, y, n)[0]\n new_y = find_x3_y3(lam, x, x, y, n)[1]\n\n #print(x, y, new_x, new_y)\n for i in range(2, iter):\n lam = find_lambda_of_two_points(x, y, new_x, new_y, n)\n new_y = find_x3_y3(lam, x, new_x, y, n)[1]\n new_x = find_x3_y3(lam, x, new_x, y, n)[0]\n\n print(new_x, new_y)\n\n\nif __name__ == '__main__':\n n = 73\n a = 8\n k = 11\n x = 32\n y = 53\n fuck_471(x, y, a, n, k)\n\n","sub_path":"tester/lenstra.py","file_name":"lenstra.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"486965080","text":"import numpy as np\n\n# 添加工具函数\ndef tanh(x):\n return np.tanh(x)\ndef tanh_deriv(x):\n return 1.0 - pow(tanh(x), 2)\ndef logistic(x):\n return 1/(1 + np.exp(-x))\ndef logistic_deriv(x):\n return logistic(x)*(1-logistic(x))\n\n# 神经网络主类\nclass NeuralNetwork:\n def __init__(self, layers, activation='tanh'):\n \"\"\"\n :param layers: 一个list,包含每层的单元数目,至少含有两个值\n :param activation: 一个str,指明使用哪个激活函数。可以是'logistic'或'tanh'\n \"\"\"\n # 选择激活函数\n if activation == 'logistic':\n self.activation = logistic\n self.activation_deriv = logistic_deriv\n elif activation == 'tanh': \n self.activation = tanh\n self.activation_deriv = tanh_deriv\n # 初始化权重容器,[-0.25,0.25]。?此处的处理有疑问\n self.weights = []\n for i in range(1, len(layers) - 1): # 除了输出层\n self.weights.append((2*np.random.random((layers[i - 1] + 1, layers[i] + 1)) - 1)*0.25) # layers[i-1]行,layers[i]列\n# self.weights.append((2*np.random.random((layers[i] + 1, layers[i + 1] + 1)) - 1)*0.25)\n self.weights.append((2*np.random.random((layers[len(layers) - 2] + 1, layers[len(layers) - 1])) - 1)*0.25)\n# print(self.weights, len(self.weights))\n def fit(self, X, y, learning_rate = 0.2, epochs = 10000): # X:行数是实例数,列数是维度\n \"\"\"\n :param learning_rate: 反向修正weights和bias时的系数\n :param epochs: 抽取X中的数据对神经网络进行更新,利用循环次数停止训练\n \"\"\"\n X = np.atleast_2d(X) # X化为numpy二维数据\n temp = np.ones([X.shape[0], X.shape[1] + 1]) # 初始化全1矩阵,多的列用来添加bias\n temp[:, 0:-1] = X # 在输入层添加bias\n X = temp\n y = np.array(y) # y化为numpy的array\n# print(X, '\\n', y)\n # 神经网络训练\n for k in range(epochs): # 共epochs次循环,每次从样本中随机抽样一个\n i = np.random.randint(X.shape[0]) # 随机取一行\n a = [X[i]]\n for l in range(len(self.weights)): # a[l]是在利用上一层计算下一层节点;这里把bias也融入到了weight中,仔细思考可以看明白\n# print(l, a[l])\n a.append(self.activation(np.dot(a[l], self.weights[l])))\n error = y[i] - a[-1]\n deltas = [error * self.activation_deriv(a[-1])] # 误差\n # 反向更新weights和bias\n for l in range(len(a) - 2, 0, -1):\n deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_deriv(a[l]))\n deltas.reverse()\n for i in range(len(self.weights)):\n layer = np.atleast_2d(a[i])\n delta = np.atleast_2d(deltas[i])\n self.weights[i] += learning_rate * layer.T.dot(delta)\n def predict(self, x):\n \"\"\"\n :param x: 用来测试的样本\n \"\"\"\n x = np.array(x)\n temp = np.ones(x.shape[0] + 1)\n temp[0:-1] = x\n a = temp\n for l in range(0, len(self.weights)):\n a = self.activation(np.dot(a, self.weights[l]))\n return a","sub_path":"HandwriteNum_OpenDataSet_NeuralNetwork/implement/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"182741254","text":"#!/usr/bin/python3\n\"\"\"Base Class\"\"\"\nimport json\n\n\nclass Base:\n \"\"\"Base Class\"\"\"\n\n __nb_objects = 0\n\n def __init__(self, id=None):\n \"\"\"Args:\n id\n \"\"\"\n\n if id is not None:\n self.id = id\n else:\n Base.__nb_objects += 1\n self.id = Base.__nb_objects\n\n @staticmethod\n def to_json_string(list_dictionaries):\n \"\"\"Json to a string\"\"\"\n\n if list_dictionaries is None:\n return \"[]\"\n else:\n return(json.dumps(list_dictionaries))\n\n @classmethod\n def save_to_file(cls, list_objs):\n \"\"\"JSON write and save object to a file\"\"\"\n\n filename = cls.__name__ + '.json'\n data = []\n if list_objs is None:\n data = None\n else:\n for i in range(len(list_objs)):\n data.append(cls.to_dictionary(list_objs[i]))\n with open(filename, \"w\", encoding='utf-8') as f:\n f.write(cls.to_json_string(data))\n\n @staticmethod\n def from_json_string(json_string):\n \"\"\"Return JSON represenation\"\"\"\n nothing = []\n if json_string is None or len(json_string) == len(nothing):\n return []\n else:\n return(json.loads(json_string))\n\n @classmethod\n def create(cls, **dictionary):\n \"\"\"dummy class\"\"\"\n if cls.__name__ == 'Rectangle':\n dummy_class = cls(1, 1)\n dummy_class.update(**dictionary)\n else:\n if cls.__name__ == 'Square':\n dummy_class = cls(1)\n dummy_class.update(**dictionary)\n return dummy_class\n\n @classmethod\n def load_from_file(cls):\n new_list = []\n filename = cls.__name__ + \".json\"\n try:\n with open(filename, \"r\") as f:\n new_list = cls.from_json_string(f.read())\n for i, j in enumerate(new_list):\n new_list[i] = cls.create(**new_list[i])\n except:\n pass\n return new_list\n","sub_path":"0x0C-python-almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"609176364","text":"from tkinter import *\nfrom tkinter import ttk\nimport Match as Ma\nimport Team as Te\nimport Player as Pl\n\nprint(\"hi, this is Marissa :)\")\n\nclass GUI:\n\n def __init__(self, master): #-- magic funtion that builds GUI\n self.master = master\n master.title(\"Matchmaking GUI\")\n\n # -------------------------------------------------- FRAMES -------------------------------------------------\n self.button_frame = Frame(master) # - Frame BOTTOM\n self.button_frame.pack(side=BOTTOM, fill=X, padx=15)\n\n self.col0_frame = Frame(master) # - Frame 0\n self.col0_frame.pack(side=LEFT)\n\n self.playerq_frame = Frame(master) # - Frame 1\n self.playerq_frame.pack(side=LEFT)\n self.playerq_frame['borderwidth'] = 3\n self.playerq_frame['relief'] = 'sunken'\n\n self.col2_frame = Frame(master) # - Frame 2\n self.col2_frame.pack(side=LEFT)\n\n self.matchmaking_pr_frame = Frame(master) # - Frame 3\n self.matchmaking_pr_frame.pack(side=LEFT)\n self.matchmaking_pr_frame['borderwidth'] = 3\n self.matchmaking_pr_frame['relief'] = 'sunken'\n\n self.col4_frame = Frame(master) # - Frame 4\n self.col4_frame.pack(side=LEFT)\n\n self.finishmatch_frame = Frame(master) # - Frame 5\n self.finishmatch_frame.pack(side=LEFT)\n self.finishmatch_frame['borderwidth'] = 3\n self.finishmatch_frame['relief'] = 'sunken'\n\n self.col6_frame = Frame(master) # - Frame 6\n self.col6_frame.pack(side=LEFT)\n\n # -------------------------------------------------- FRAME 0 --------------------------------------------------\n self.spacing_col0 = Label(self.col0_frame, text=\" \") # - 3 spaces\n self.spacing_col0.config(height=2)\n self.spacing_col0.grid(row=0, column=0, sticky=W) # -- for spacing purposes\n # -------------------------------------------------- FRAME 1 --------------------------------------------------\n self.playerq_title = Label(self.playerq_frame, text=\"Player Queue\")\n self.playerq_title.grid(row=1, column=1, sticky=W)\n\n self.spacing_col1 = Label(self.playerq_frame, text=\"\\t\")\n self.spacing_col1.grid(row=2, column=1, sticky=W) # -- for spacing purposes\n\n self.playerq_box = Text(self.playerq_frame)\n self.playerq_box.config(height=36, width=25) # - this should have 'state=\"disabled\"'\n self.playerq_box.grid(row=3, column=1, sticky=W)\n # -------------------------------------------------- FRAME 2 --------------------------------------------------\n self.spacing_col2 = Label(self.col2_frame, text=\" \") # - 2 spaces\n self.spacing_col2.grid(row=0, column=2, sticky=W) # -- for spacing purposes\n # -------------------------------------------------- FRAME 3 --------------------------------------------------\n self.matchmaking_pr_title = Label(self.matchmaking_pr_frame, text=\"Matchmaking Process\")\n self.matchmaking_pr_title.grid(row=1, column=3, sticky=W)\n\n self.matches_option = ttk.Combobox(self.matchmaking_pr_frame, values=[\n \"Division1\",\n \"Division2\",\n \"Division3\",\n \"Division4\"])\n self.matches_option.grid(row=1, column=3, sticky=E)\n self.matches_option.current(0)\n\n self.spacing_col3 = Label(self.matchmaking_pr_frame, text=\"\\t\")\n self.spacing_col3.grid(row=2, column=3, sticky=W) # -- for spacing purposes\n\n self.matches_box = Text(self.matchmaking_pr_frame)\n self.matches_box.config(height=36, width=45, state=\"disabled\")\n self.matches_box.grid(row=3, column=3, sticky=N)\n # -------------------------------------------------- FRAME 4 --------------------------------------------------\n self.spacing_col4 = Label(self.col4_frame, text=\" \") # - 2 spaces\n self.spacing_col4.grid(row=0, column=4, sticky=W) # -- for spacing purposes\n # -------------------------------------------------- FRAME 5 --------------------------------------------------\n self.finishmatches_title = Label(self.finishmatch_frame, text=\"Finished Matches\")\n self.finishmatches_title.grid(row=1, column=5, sticky=W)\n\n self.finishmatches_option = ttk.Combobox(self.finishmatch_frame, values=[\n \"Division1\",\n \"Division2\",\n \"Division3\",\n \"Division4\"])\n self.finishmatches_option.grid(row=1, column=5, sticky=E)\n self.finishmatches_option.current(0)\n\n self.spacing_col5 = Label(self.finishmatch_frame, text=\"\\t\")\n self.spacing_col5.grid(row=2, column=5, sticky=W) # -- for spacing purposes\n\n self.finmatches_box = Text(self.finishmatch_frame)\n self.finmatches_box.config(height=36, width=45, state=\"disabled\")\n self.finmatches_box.grid(row=3, column=5, sticky=N)\n # -------------------------------------------------- FRAME 6 --------------------------------------------------\n self.spacing_col4 = Label(self.col6_frame, text=\" \") # - 2 spaces\n self.spacing_col4.grid(row=0, column=6, sticky=W) # -- for spacing purposes\n # -------------------------------------------------- FRAME BOTTOM --------------------------------------------------\n self.accept_p_button = Button(self.button_frame, text=\" ACCEPT PLAYERS \", command=self.accept_players())\n self.accept_p_button.grid(row=4, column=1, sticky=W)\n\n self.stop_p_button = Button(self.button_frame, text=\" STOP \")\n self.stop_p_button.grid(row=4, column=3, sticky=E, padx=80)\n\n\n def accept_players(self):\n tPlayer = Pl.Player(username=\"BOB\", summonerID=120385)\n print(tPlayer.username)\n\n self.playerq_box.insert(END, tPlayer.username + \" - \" + str(tPlayer.summonerID) + \"\\n\")\n\n\n def test(self): # - ?\n print(\"hi\")\n\nroot = Tk()\ngui = GUI(root)\nroot.mainloop()\n\n'''\ndef generateRandomPlayer(self):\n return Pl.Player();\n\n\ntestPlayer = Pl.Player(username=\"BOB\", summonerID=120385)\nprint(testPlayer.username)\n\ntestTeam = Te.Team()\ntestTeam.players['player1'] = testPlayer\nprint(testTeam.players['player1'])\nprint(testTeam.players['player1'].summonerID)\n\ntestMatch = Ma.Match()\nprint(testMatch.teams)\nprint(testMatch.teams['team1'])\ntestMatch = Ma.Match(testTeam, testTeam)\nprint(testMatch.teams['team1'])\n'''","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":6808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"20106973","text":"from django.test import TestCase\nfrom Assets.models import *\nimport re\n\n# Django的单元测试基于unittest库\nclass AssetsTestCase(TestCase):\n\n # 测试函数执行前执行\n def setUp(self):\n print(\"======in setUp\")\n\n # 需要测试的内容\n def test_add(self):\n filepath = 'static/upload/pf.log'\n f = open(filepath, 'r')\n fileContent = f.readlines()\n for line in fileContent:\n\n line = line.strip()\n # print(line)\n if line.startswith(\"rule add\"):\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n ruleId = ''\n for id in re.findall('id (.*?) name', line):\n ruleId = ruleId + \" \" + id\n\n ruleName = \"\"\n for name in re.findall('name \"(.*?)\" sa', line):\n ruleName = ruleName + \" \" + name\n\n ruleSa = \"\"\n for sa in re.findall('sa (.*?) da', line):\n ruleSa = ruleSa + \" \" + sa\n\n ruleDa = \"\"\n for da in re.findall('da \"(.*?)\" izone', line):\n ruleDa = ruleDa + \" \" + da\n\n ruleIzone = \"\"\n for izone in re.findall('izone (.*?) ozone', line):\n ruleIzone = ruleIzone + \" \" + izone\n\n ruleOzone = \"\"\n for ozone in re.findall('ozone (.*?) service', line):\n ruleOzone = ruleOzone + \" \" + ozone\n\n ruleService = \"\"\n for service in re.findall('service (.*?) time', line):\n ruleService = ruleService + \" \" + service\n\n ruleOpentime = \"\"\n for opentime in re.findall('time any log', line):\n ruleOpentime = ruleOpentime + \" \" + opentime\n\n ruleStatus = \"\"\n for service in re.findall('service (.*?) time', line):\n ruleStatus = ruleStatus + \" \" + service\n\n ruleActive = \"\"\n for active in re.findall('type (.*?) id', line):\n ruleActive = ruleActive + \" \" + active\n\n\n comment = line.split(\" \")[-1].replace('\"', \"\")\n\n # ruleAccount = \"\"\n # for service in re.findall('service (.*?) time', line):\n # ruleAccount = ruleAccount + \" \" + service\n\n\n\n\n\n\n\n\n print(ruleId, \"-\", ruleName, \"-\", ruleSa, \"-\", ruleDa, \"-\", ruleIzone, \"-\", ruleOzone, \"-\", ruleService, \"-\", ruleOpentime, \"-\", ruleStatus, \"-\", ruleActive, \"-\", comment)\n\n\n policy = PolicyManage()\n policy.ruleId = ruleId.encode('utf8')\n policy.ruleName = ruleName.encode('utf8')\n policy.ruleSa = ruleSa.encode('utf8')\n policy.ruleDa = ruleDa.encode('utf8')\n policy.ruleIzone = ruleIzone.encode('utf8')\n policy.ruleOzone = ruleOzone.encode('utf8')\n policy.ruleService = ruleService.encode('utf8')\n policy.ruleOpentime = ruleOpentime.encode('utf8')\n policy.ruleStatus = ruleStatus.encode('utf8')\n policy.ruleActive = ruleActive.encode('utf8')\n policy.ruleComment = comment.encode('utf8')\n policy.save()\n\n\n\n # self.assertEqual(student.name, 'aaa')\n\n # 需要测试的内容\n def test_check_exit(self):\n # self.assertEqual(0, FireWallFile.objects.count())\n print(\"======in test_check_exit\")\n\n\n# 测试函数执行后执行\n def tearDown(self):\n # pass\n print(\"======in tearDown\")\n # address = AddressName.objects.all()\n #\n # for line in address:\n # print(line.addressName)\n # print(line.addressIP)\n # print(line.aaddressComment)\n","sub_path":"FireWall/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"358417840","text":"import pandas as pd\nimport numpy as np\ndf = pd.read_csv(\"gossip_time_combied.csv\", index_col=None)\n\ncontents = list(df[\"content\"].values)\nprint(len(contents))\nlabels = list(df[\"label\"].values)\nprint(len(labels))\n\nnum_total = len(labels)\nnum_train = int(0.9 * num_total)\nnum_test = num_total-num_train\nprint(num_train, num_test)\n\nshuffled_arg = np.arange(num_total)\nnp.random.shuffle(shuffled_arg)\n\ncontents = np.asarray(contents)\nlabels = np.asarray(labels)\n\ncontents = contents[shuffled_arg]\nlabels = labels[shuffled_arg]\n\ndata = zip(contents, labels)\n\nl = open(\"gossip_labels.txt\", \"w\")\nc = open(\"gossip_corpus.txt\", \"w\")\nfor i, (content, label) in enumerate(data):\n if i<=num_train:\n dataset = \"train\"\n if i>num_train:\n dataset = \"test\"\n string = \"{}\\t{}\\t{}\".format(str(i), dataset, str(label))\n content = content.replace(\"\\n\", \"\").strip()\n l.write(string+\"\\n\")\n c.write(content+\"\\n\")\nl.close()\nc.close()\n","sub_path":"extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"282676989","text":"'''\nCopyright 2017 Recruit Institute of Technology\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\n\nimport sys\nimport logging\nfrom optparse import OptionParser\n\n# Parse commandline arguments\nop = OptionParser()\nop.add_option(\"--query_file\",\n action=\"store\", type=\"string\", dest=\"query_file\",\n help=\"Query file name.\")\nop.add_option(\"--doc_parser\",\n action=\"store\", type=\"string\", dest=\"doc_parser\",\n default=\"koko\",\n help=\"Text parser: koko or spacy.\")\nop.add_option(\"--output_format\",\n action=\"store\", type=\"string\", dest=\"output_format\",\n default=\"text\",\n help=\"Output format: text or json.\")\nop.add_option(\"--log_level\",\n action=\"store\", type=\"string\", dest=\"log_level\",\n default=\"error\",\n help=\"Logging level: info, warning, error.\")\n\n(opts, args) = op.parse_args()\nif len(args) > 0:\n logger.error(\"this script takes no arguments.\")\n\n# Set up logging\nlogging_level_dict = { 'info': logging.INFO,\n 'warning': logging.WARNING,\n 'error': logging.ERROR }\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\nch = logging.StreamHandler(sys.stdout)\nch.setLevel(logging_level_dict[opts.log_level])\nformatter = logging.Formatter('%(levelname)s %(asctime)s - %(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nwith open(opts.query_file, 'r') as qfile:\n query = qfile.read()\n\n# Process the KOKO query\n\nfrom koko.query_processor import QueryProcessor\nprocessor = QueryProcessor(opts.doc_parser)\nresponse = processor.ProcessQuery(query)\n\n# Print the results\nif opts.output_format == 'text':\n print(\"\\nResults:\\n\")\n print(\"%s %s\" % (\"{:<50}\".format(\"Entity name\"), \"Entity score\"))\n print(\"================================================================\")\n for entity in response.entities:\n print(\"%s %f\" % (\"{:<50}\".format(entity.name), entity.score))\nelse:\n import json\n import jsonpickle\n pickled = jsonpickle.encode(response, unpicklable=False)\n json_result = json.loads(pickled)\n print(json.dumps(json_result, sort_keys=False, indent=2))\n \n","sub_path":"examples/run_koko.py","file_name":"run_koko.py","file_ext":"py","file_size_in_byte":2669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"178878093","text":"\nimport pygame\nimport sys\n\nclass Game:\n \n def __init__(self):\n pygame.init()\n pygame.display.set_caption('buttonmoon')\n self.setup()\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n self.render()\n\n def setup(self):\n self.window = pygame.display.set_mode((1280, 720), 0, 32)\n self.font = pygame.font.SysFont('Arial', 24)\n\n def render(self):\n self.window.fill((0, 0, 0))\n message = self.font.render('hello, world!', True, (255, 30, 230), (0, 0, 0))\n self.window.blit(message, (0, 0))\n pygame.display.update()\n\nif __name__ == '__main__':\n Game()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"292377208","text":"import os\nimport unicodedata, re\nimport pandas as pd\n\nLIB_PATH = os.path.dirname(os.path.realpath(__file__))\nPOTCAR_PATH = \"/home/xzhang1/src/VASP_PSP/potpaw_PBE.54/\"\n\ndef periodic_table_lookup(symbol, column, periodic_table = pd.read_excel(LIB_PATH + '/data/periodic_table.xlsx')):\n \"\"\"\n Args:\n symbol (str): 'Pb'\n column (str): 'pot_encut'\n \"\"\"\n return periodic_table.loc[periodic_table.symbol == symbol, column].values[0]\n\ndef template(i, o, d):\n \"\"\"i.format(d)\n\n Args:\n i (str): input file path\n o (str): output file path\n d (dict):\n \"\"\"\n with open(i, \"r\") as i:\n with open(o, \"w\") as o:\n o.write(\n i.read().format(**d)\n )\n\ndef slugify(value):\n \"\"\"Make a string URL- and filename-friendly.\n\n Args:\n value (unicode): string to be converted\n\n Returns:\n unicode: filename-friendly string\n\n Raises:\n TypeError: if value is not unicode string\n \"\"\"\n value = unicodedata.normalize('NFKD', value)\n value = re.sub(r'[^\\w\\s-]', '', value).strip().lower()\n value = re.sub(r'[-\\s]+', '-', value)\n return value","sub_path":"codebase/toolkit/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"226027292","text":"import os\n\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping,ModelCheckpoint\nfrom tensorflow.keras.layers import LSTM,Dropout,Dense,Activation,Input\nfrom tensorflow.keras.models import Model\nfrom utility.dataset_utils import cut_dataset_by_range\n\ndef prepare_input_forecasting(DATA_PATH,crypto,features_to_use):\n df=pd.read_csv(os.path.join(DATA_PATH,crypto),usecols=features_to_use)\n #features_without_symbols = [feature for feature in df.columns if not feature.startswith(\"symbol\")]\n features_without_date_and_symbols = [feature for feature in df.columns if feature != \"Date\" and not feature.startswith(\"symbol\")]\n return df,features_without_date_and_symbols\n\ndef fromtemporal_totensor(dataset, window_considered, output_path, output_name):\n try:\n # pickling is also known as Serialization\n # The pickle module is not secure. Only unpickle data you trust.\n # load is for de-serialize\n # allow_pickle=True else: Object arrays cannot be loaded when allow_pickle=False\n file_path = output_path + \"/crypto_TensorFormat_\" + output_name + \"_\" + str(window_considered) + '.npy'\n lstm_tensor = np.load(file_path, allow_pickle=True)\n print('(LSTM Version found!)')\n return lstm_tensor\n except FileNotFoundError as e:\n print('Creating LSTM version..')\n # an array in this format: [ [[items],[items]], [[items],[items]],.....]\n # -num of rows: window_considered\n # -num of columns: \"dataset.shape[1]\"\n # 1 is the number of elements in\n lstm_tensor = np.zeros((1, window_considered, dataset.shape[1]))\n # for i between 0 to (num of elements in original array - window + 1)\n \"\"\"easy explanation through example:\n i:0-701 (730-30+1)\n i=0; => from day 0 + 30 days \n i=1 => from day 1 + 30 days \n \"\"\"\n for i in range(dataset.shape[0] - window_considered + 1):\n #note (i:i + window_considered) is the rows selection.\n element=dataset[i:i + window_considered, :].reshape(1, window_considered, dataset.shape[1])\n lstm_tensor = np.append(lstm_tensor, element,axis=0)#axis 0 in order to appen on rows\n\n #serialization\n output_path += \"/crypto_\"\n name_tensor = 'TensorFormat_' + output_name + '_' + str(window_considered)\n #since the first element is zero I'll skip it:\n lstm_tensor=lstm_tensor[1:,:]\n np.save(str(output_path + name_tensor),lstm_tensor)\n print('LSTM version created!')\n return lstm_tensor\n\ndef get_training_validation_testing_set(dataset_tensor_format, date_to_predict):\n train = []\n test = []\n index_feature_date = 0\n for sample in dataset_tensor_format:\n # Candidate is a date: 2018-01-30, for example.\n # -1 is used in order to reverse the list.\n #takes the last date in the sample: 2017-01-09, 2017-01..., ... , 2017-02-2019\n #since the last date is 2017-02-2019, then it is before the date to predict for example 2019-03-05, so this sample\n #will belong to the training set.\n candidate = sample[-1,index_feature_date]\n candidate = pd.to_datetime(candidate)\n\n #if the candidate date is equal to the date to predict then it will be in test set.\n #it happens just one time for each date to predict.\n #Test will be: [[items]] in which the items goes N(30,100,200) days before the date to predict.\n #d_validation = pd.to_datetime(date_to_predict) - timedelta(days=3)\n \"\"\"days=[]\n i=number_of_days_to_predict-1\n while i>0:\n d = pd.to_datetime(date_to_predict) - timedelta(days=i)\n days.append(d)\n i-=1\n days.append(pd.to_datetime(date_to_predict))\"\"\"\n if candidate == pd.to_datetime(date_to_predict):\n #remove the \"Data\" information\n sample = sample[:, 1:].astype('float')\n test.append(sample)\n elif candidate < pd.to_datetime(date_to_predict):\n # remove the \"Data\" information\n sample=sample[:,1:].astype('float')\n train.append(sample)\n #return np.array(train), np.array(validation),np.array(test)\n return np.array(train),np.array(test)\n\ndef train_single_target_model(x_train, y_train, num_neurons, learning_rate, dropout, epochs, batch_size,patience, num_categories,\n date_to_predict,model_path='', model=None):\n #note: it's an incremental way to get a final model.\n #\n callbacks = [\n EarlyStopping(monitor='val_loss', patience=patience,mode='min'),\n ModelCheckpoint(\n monitor='val_loss', save_best_only=True, mode='min',\n filepath=model_path+'lstm_neur{}-do{}-ep{}-bs{}-target{}.h5'.format(\n num_neurons, dropout, epochs, batch_size,date_to_predict))\n ]\n if model is None:\n model = Sequential()\n # Add a LSTM layer with 128/256 internal units.\n #model.add(LSTM(units=num_neurons,return_sequences=True,input_shape=(x_train.shape[1], x_train.shape[2])))\n model.add(LSTM(units=num_neurons,input_shape=(x_train.shape[1], x_train.shape[2])))\n #reduce the overfitting\n model.add(Dropout(dropout))\n model.add(Dense(units=num_neurons, activation='relu',name='ReLu'))\n model.add(Dense(units=num_categories, activation='softmax',name='softmax'))\n # optimizer\n adam = Adam(learning_rate=learning_rate)\n model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])\n\n history=model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size, validation_split = 0.001,\n verbose=0, shuffle=False,callbacks=callbacks)\n\n return model, history\n\ndef train_multi_target_model(x_train, y_trains_encoded, num_neurons, learning_rate, dropout, epochs, batch_size,patience, num_categories,\n date_to_predict,model_path='', model=None):\n callbacks = [\n EarlyStopping(monitor='val_loss', patience=patience, mode='min'),\n ModelCheckpoint(\n monitor='val_loss', save_best_only=True, mode='min',\n filepath=model_path + 'lstm_neur{}-do{}-ep{}-bs{}-target{}.h5'.format(\n num_neurons, dropout, epochs, batch_size, date_to_predict))\n ]\n #note: it's an incremental way to get a final model.\n #\n inputs_stm = Input(shape=(x_train.shape[1], x_train.shape[2]))\n lstm= LSTM(units=num_neurons)(inputs_stm)\n # reduce the overfitting\n \"\"\"lstm=Dropout(dropout)(lstm)\n lstm = Dense(units=num_neurons, activation='relu')(lstm)\"\"\"\n\n cryptocurrencies=[]\n losses = {}\n losses_weights = {}\n y_train_dict = {}\n loss = \"categorical_crossentropy\"\n loss_weight = 1.0\n i = 0\n while i < len(y_trains_encoded):\n losses['trend_' + str(i)] = loss\n losses_weights['trend_' + str(i)] = loss_weight\n y_train_dict['trend_' + str(i)] = y_trains_encoded[i]\n\n crypto_model = LSTM(units=num_neurons)(inputs_stm)\n # reduce the overfitting\n crypto_model= Dropout(dropout)(crypto_model)\n crypto_model= Dense(units=num_neurons, activation='relu',name=\"ReLu_\"+ str(i))(crypto_model)\n crypto_model=Dense(units=num_categories, activation='softmax', name='trend_' + str(i))(crypto_model)\n cryptocurrencies.append(crypto_model)\n\n \"\"\"crypto_model = Dropout(dropout)(lstm)\n crypto_model = Dense(units=num_neurons, activation='relu', name=\"ReLu_\" + str(i))(crypto_model)\n crypto_model = Dense(units=num_categories, activation='softmax', name='trend_' + str(i))(crypto_model)\n cryptocurrencies.append(crypto_model)\"\"\"\n i += 1\n\n model = Model(\n inputs=inputs_stm,\n outputs=cryptocurrencies,\n name=\"multitarget\")\n\n # initialize the optimizer and compile the model\n adam = Adam(learning_rate=learning_rate)\n model.compile(optimizer=adam, loss=losses, loss_weights=losses_weights,\n metrics=[\"accuracy\"])\n\n\n history = model.fit(x_train, y_train_dict,\n epochs=epochs, validation_split=0.02, batch_size=batch_size,\n verbose=0, shuffle=False, callbacks=callbacks)\n return model, history\n\n\"\"\"def train_model_new(x_train, y_trains_encoded, num_neurons, learning_rate, dropout, epochs, batch_size,patience, num_categories,\n date_to_predict,model_path='', model=None):\n #note: it's an incremental way to get a final model.\n #\n print(x_train.shape)\n inputs = Input(shape=(x_train.shape[1], x_train.shape[2]),batch_size=x_train.shape[0])\n #trend_btc= Sequential()\n trend_btc= LSTM(units=num_neurons)(inputs)\n print(LSTM)\n # reduce the overfitting\n trend_btc= Dropout(dropout)(trend_btc)\n trend_btc= Dense(units=num_neurons, activation='relu')(trend_btc)\n trend_btc=Dense(units=num_categories)(trend_btc)\n trend_btc= Activation('softmax',name=\"trend_btc\")(trend_btc)\n\n\n # trend_btc= Sequential()\n trend_eth = LSTM(units=num_neurons)(inputs)\n # reduce the overfitting\n trend_eth = Dropout(dropout)(trend_eth)\n trend_eth = Dense(units=num_neurons, activation='relu')(trend_eth)\n trend_eth= Dense(units=num_categories)(trend_eth)\n trend_eth = Activation('softmax', name=\"trend_eth\")(trend_eth)\n\n model = Model(\n inputs=inputs,\n outputs=[trend_btc,trend_eth],\n name=\"multitarget\")\n\n losses = {\n \"trend_btc\": \"categorical_crossentropy\",\n \"trend_eth\": \"categorical_crossentropy\",\n }\n loss_weights = {\"trend_btc\": 1.0, \"trend_eth\": 1.0}\n # initialize the optimizer and compile the model\n adam = Adam(learning_rate=learning_rate)\n model.compile(optimizer=adam, loss=losses, loss_weights=loss_weights,\n metrics=[\"accuracy\"])\n plot_model(model, to_file=\"neural_network.png\", show_shapes=True,\n show_layer_names=True, expand_nested=True, dpi=150)\n\n history=model.fit(x_train, {\"trend_btc\": y_trains_encoded[0], \"trend_eth\": y_trains_encoded[1]},\n epochs=epochs, validation_split = 0.02,\n verbose=0, shuffle=False)\n\n return model, history\"\"\"","sub_path":"modelling/techniques/forecasting/training/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":10297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"589386717","text":"VAR = {\n\"NAME\": \"test\", #Name of the project\n\"LIG1_FILE\" : \"LF1.mol2\", #Name of the mol2 of ligand1 (must be in the working directory)\n\"CAP1\" : \"N\",\t\t #Atom numbers (as in the mol2, likely to start in 1) to remove. Numbers separated by commas\n\n\"LIG2_FILE\" : \"LF2.mol2\", #Name of the mol2 of ligand2 (must be in the working directory)\n\"CAP2\" : \"N\", #Atom numbers (as in the mol2, likely to start in 1) to remove. Numbers separated by commas\n\"MORPHOLOGY\" : \"random\", #Morphology to distribute ligands1 and 2. random, janus, and stripe are allowed\n\"LIG1_FRAC\" : \"1.0\", #Fraction of ligand1 to place (0-1.0)\n\"RSEED\" : \"666\", #Random seed for random morphology\n\"STRIPES\" : \"1\", #Number of stripes for stripe morphology. It will start (bottom up with ligand 1)\n\n\"CORE\" : \"au144SR60_NM.pdb\", #Name of the core to coat. Found in COREDIR/CORE\n\n\"COREDIR\" : \"/DATA/SoftwareSFU/IN-HOUSE/NanoModeler/CORES\", #Path to folder containing all the available cores\n\"DEPENDS\" : \"/DATA/SoftwareSFU/IN-HOUSE/NanoModeler/DEPENDENCIES\" #Path to the folder containing all the dependencies that come with NanoModeler\n}\n\nimport numpy as np\ndef read_resname(lig_fname):\n mol2 = np.genfromtxt(lig_fname, delimiter=\"\\n\", dtype='str')\n for i in range(len(mol2)):\n if \"@ATOM\" in mol2[i]:\n resname = mol2[i+1].split()[7]\n return resname\n\ndef write_leap(fname, two_lig_func):\n msj = \"source leaprc.gaff \\n\\n\"\n msj += \"loadamberparams \" + \"TMP/\"+VAR[\"LIG1_FILE\"][:-5]+\".frcmod\\n\"\n\n msj += read_resname(VAR[\"LIG1_FILE\"]) + \" = loadmol3 \" + \"TMP/\"+VAR[\"LIG1_FILE\"]+\"\\n\"\n msj += \"check \" + read_resname(VAR[\"LIG1_FILE\"]) + \"\\n\"\n msj += \"saveoff \" + read_resname(VAR[\"LIG1_FILE\"]) + \" \" + \"TMP/\"+VAR[\"LIG1_FILE\"][:-5]+\".lib\\n\\n\"\n if two_lig_func:\n msj += \"loadamberparams \" + \"TMP/\"+VAR[\"LIG2_FILE\"][:-5]+\".frcmod\\n\"\n msj += read_resname(VAR[\"LIG2_FILE\"]) + \" = loadmol3 \" + \"TMP/\"+VAR[\"LIG2_FILE\"]+\"\\n\"\n msj += \"check \" + read_resname(VAR[\"LIG2_FILE\"]) + \"\\n\"\n msj += \"saveoff \" + read_resname(VAR[\"LIG2_FILE\"]) + \" \" + \"TMP/\"+VAR[\"LIG2_FILE\"][:-5]+\".lib\\n\\n\"\n\n msj += \"loadamberparams \" + VAR[\"DEPENDS\"]+\"/AU.frcmod\\n\"\n msj += \"loadamberparams \" + VAR[\"DEPENDS\"]+\"/ST.frcmod\\n\"\n msj += \"AU = loadmol3 \" + VAR[\"DEPENDS\"]+\"/AU.mol2\\n\"\n msj += \"ST = loadmol3 \" + VAR[\"DEPENDS\"]+\"/ST.mol2\\n\\n\"\n\n msj += \"loadoff \" + \"TMP/\"+VAR[\"LIG1_FILE\"][:-5]+\".lib\\n\"\n if two_lig_func:\n msj += \"loadoff \" + \"TMP/\"+VAR[\"LIG2_FILE\"][:-5]+\".lib\\n\"\n\n msj += VAR[\"NAME\"] + \" = loadpdb \" + \"TMP/\"+VAR[\"NAME\"]+\".pdb \\n\"\n msj += \"saveamberparm \" + VAR[\"NAME\"] + \" \" + \"TMP/\"+VAR[\"NAME\"]+\".prmtop\" + \" \" + \"TMP/\"+VAR[\"NAME\"]+\".inpcrd \\n\"\n msj += \"quit\"\n out = open(fname, \"w\")\n out.write(msj)\n out.close()\n","sub_path":"defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"400767317","text":"\"\"\"\n定义一个天山童姥类 ,类名为TongLao,属性有血量,武力值(通过传入的参数得到)。TongLao类里面有2个方法,\nsee_people方法,需要传入一个name参数,\n如果传入”WYZ”(无崖子),则打印,“师弟!!!!”,如果传入“李秋水”,打印“呸,贱人”,如果传入“丁春秋”,打印“叛徒!我杀了你”\nfight_zms方法(天山折梅手),调用天山折梅手方法会将自己的武力值提升10倍,血量缩减2倍。\n需要传入敌人的hp,power,进行一回合制对打,打完之后,比较双方血量。血多的一方获胜。\n定义一个XuZhu类,继承于童姥。虚竹宅心仁厚不想打架。所以虚竹只有一个read(念经)的方法。每次调用都会打印“罪过罪过”\n加入模块化改造\n\"\"\"\n\n\n# 定义一个天山童姥类 ,类名为TongLao\nclass TongLao:\n # 构造方法,定义童姥属性,血量hp,武力值power(通过传入的参数得到)\n def __init__(self, hp, power):\n self.hp = hp\n self.power = power\n\n # 定义see_people方法,传入一个name参数\n def see_people(self, name):\n # 传入”WYZ”(无崖子),则打印,“师弟!!!!”\n if name == \"无崖子\":\n print(\"师弟!!!!\")\n # 传入“李秋水”,打印“呸,贱人”\n elif name == \"李秋水\":\n print(\"呸,贱人!\")\n # 传入“丁春秋”,打印“叛���!我杀了你”\n elif name == \"丁春秋\":\n print(\"叛徒!我要杀了你!\")\n\n # 定义fight_zms方法(天山折梅手),调用此方法会将自己的武力值提升10倍,血量缩减2倍。\n # 传入敌人的血量en_hp,武力值en_power\n def fight_zms(self, en_hp, en_power):\n hp = self.hp / 2 - en_power\n en_hp = en_hp - self.power * 10\n # 打斗一局,比较胜负\n if hp < en_hp:\n print(\"你给我等着,终会有一天你会败在我的脚下!\")\n elif hp > en_hp:\n print(\"这一天终于到来了,哈哈哈哈哈!哈哈哈哈哈!\")\n else:\n raise Exception(\"哼!小子功夫不错嘛!继续,看我不把你打得落花流水,跪地求饶!\")\n\n\n# 实例化\ntl = TongLao(2000, 1000)\ntl.see_people(\"丁春秋\")\ntl.fight_zms(1000, 2000)\n","sub_path":"practice/python_oo/tonglao.py","file_name":"tonglao.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"280658647","text":"\"\"\"\n Called from Matlab: 12 arguments are xamp, xfreq, xphase, yamp, yfreq, \n yphase, zamp, zfreq, depth, anglex, \n angley, duration\n \n Motions for optimization tasks: 11D paramaterised space\n\"\"\"\n\nimport time\nimport serial\nimport math\nfrom math import pi\nimport numpy\nimport socket\nimport sys\nimport sched\n\nsys.path.append(\"C:/Users/David/Documents/PhD/ur5control\")\nimport waypoints as wp\nimport kg_robot as kgr\n\ntstart = time.time()\n\nurnie = kgr.kg_robot(port=30010,db_host=\"169.254.161.50\")\nurnie.set_tcp(wp.plunger_tcp)\n\n#scheduler used to regularly pass desired positions to servoj \nscheduler = sched.scheduler(time.time, time.sleep)\ndef schedule_it(dt, duration, callable, *args):\n for i in range(int(duration/dt)):\n scheduler.enter(i*dt, 1, callable, args)\n\n#calculate starting position of motion\ndef starting_pos(centrepose, xamp, xphase, yamp, yphase, depth, anglex, angley):\n npose = numpy.add(centrepose, [0, 0, 0.001*(30-depth), 0, 0, 0])\n npose = numpy.add(npose, [0, 0, 0, anglex, angley, 0])\n npose = numpy.add(npose, [xamp*math.sin(xphase), 0, 0, 0, 0, 0])\n npose = numpy.add(npose, [0, yamp*math.sin(yphase), 0, 0, 0, 0])\n urnie.movel(npose)\n \n# main function: moves to desired position at any moment in time\ndef parameter_move(t0, centrepose, xamp, xfreq, xphase, yamp, yfreq, yphase, zamp, zfreq, depth, anglex, angley):\n #start with z height\n npose = numpy.add(centrepose, [0, 0, 0.001*(30-depth), 0, 0, 0])\n #add angles\n npose = numpy.add(npose, [0, 0, 0, anglex, angley, 0])\n t = time.time() - t0\n #x vibrations\n npose = numpy.add(npose, [xamp*math.sin(xfreq*t+xphase), 0, 0, 0, 0, 0])\n #y vibrations\n npose = numpy.add(npose, [0, yamp*math.sin(yfreq*t+yphase), 0, 0, 0, 0])\n #zvibrations\n npose = numpy.add(npose, [0, 0, zamp*math.sin(zfreq*t), 0, 0, 0])\n #pass to UR5\n urnie.servoj(npose, vel=50, control_time=0.05)\n\nurnie.movel(wp.above_tubl, 0.5, 0.02) #move above tub\ncentrepose=numpy.add(wp.above_tubl, [0, 0, -0.03, 0, 0, 0])\n\n#move to starting position\nstarting_pos(centrepose, 0.001*float(sys.argv[1]), (pi/180)*float(sys.argv[3]),\n 0.001*float(sys.argv[4]), (pi/180)*float(sys.argv[6]),\n float(sys.argv[9]), (pi/180)*float(sys.argv[10]),\n (pi/180)*float(sys.argv[11]))\n\ntime.sleep(0.5)\n\nwhile (time.time() - tstart) < 5: #time with matlab script\n continue\n\nt0 = time.time()\n#initialise scheduler\nschedule_it(0.05, float(sys.argv[12]), parameter_move, t0, centrepose,\n 0.001*float(sys.argv[1]), 2*pi*float(sys.argv[2]),\n (pi/180)*float(sys.argv[3]), 0.001*float(sys.argv[4]), 2*pi*float(sys.argv[5]), \n (pi/180)*float(sys.argv[6]), 0.001*float(sys.argv[7]), 2*pi*float(sys.argv[8]),\n float(sys.argv[9]), (pi/180)*float(sys.argv[10]), (pi/180)*float(sys.argv[11]))\n\n#run scheduler calling servoj\nscheduler.run()\n\nurnie.close()\n\n","sub_path":"Call11D.py","file_name":"Call11D.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"603254321","text":"import requests\nimport json\nimport requests_cache\nimport time\nimport logging\nimport pandas as pd\nimport urllib.request\nfrom datetime import date, timedelta, datetime\nfrom pyquery import PyQuery\nfrom pandas_datareader.nasdaq_trader import get_nasdaq_symbols\nfrom .holding import Holding\nfrom financescraper import scraper, conversions\n\nsymbols = get_nasdaq_symbols()\nexpire_after = timedelta(days=5)\nrequests_cache.install_cache('cache_data', expire_after=expire_after)\n\nyahoo_scraper = scraper.YahooScraper()\nusd_converter = conversions.CurrencyConverter('USD')\n\n\n# Scrape name and holdings if any for a given ticker\ndef scrape_ticker(ticker, use_yahoo):\n holdings = []\n data = get_data(ticker, use_yahoo)\n\n # invalid ticker\n if data is None:\n return holdings\n\n if _is_etf(data):\n _get_etf_data(ticker, data, holdings)\n else:\n _get_stock_data(ticker, data, holdings)\n return holdings\n\n\n# Get the nasdaq data for a given ticker\ndef get_data(ticker, useYahoo):\n data = None\n tmp = {'Yahoo': False}\n try:\n data = pd.Series(tmp)\n data = data.append(symbols.loc[ticker])\n except KeyError:\n data = None\n if useYahoo:\n logging.info('Failed to retrieve data for ticker ', ticker, '. Attempting to get it from finance.yahoo.com')\n data = _get_data_from_yahoo(ticker)\n else:\n logging.info('Failed to retrieve data for ticker ', ticker)\n return data\n\n\n# Get latest price for a given ticker\ndef get_price(ticker):\n with requests_cache.disabled():\n quote = _get_iex_data([ticker], ['price'])\n return _round_price(quote[ticker]['price'])\n\n\ndef get_company_data(tickers):\n company_data = {}\n data = _get_iex_data(tickers, ['company'])\n for ticker in tickers:\n if (ticker not in data) and (ticker != ''):\n company = _get_company_from_yahoo(ticker)\n if company is not None:\n data[ticker] = company\n for ticker, stock in data.items():\n quote = stock['company']\n if quote is None:\n continue\n company_data[ticker] = {'name': quote['companyName'], 'sector': quote['sector'], 'link': quote['website']}\n return company_data\n\n\ndef get_stock_news(tickers):\n stock_news = {}\n with requests_cache.disabled():\n data = _get_iex_data(tickers, ['news'], ['last=5'])\n for ticker, stock in data.items():\n news = stock['news']\n if news is None:\n continue\n news_items = []\n for news_item in news:\n news_items.append({'title' : news_item['headline'], 'description' : news_item['summary'], \n 'image_url' : _get_ticker_image(ticker), 'datetime' : _convert_time(news_item['datetime']),\n 'url' : news_item['url'], 'source' : news_item['source']})\n stock_news[ticker] = news_items\n return stock_news\n\n\ndef get_holding_data(ticker):\n holding_data = {}\n with requests_cache.disabled():\n data = _get_iex_data([ticker], ['quote', 'chart'], ['displayPercent=true', 'range=1y'])\n return data\n\n\ndef _round_price(price):\n return format(price, '.2f')\n\n\ndef _is_etf(data):\n return data.loc['ETF']\n\n\ndef _convert_time(timestamp):\n timestamp = timestamp.replace('T', ' ')\n return datetime.fromisoformat(timestamp)\n\n\ndef _get_etf_data(ticker, data, holdings):\n response = _get_etf_page(ticker)\n if not _valid_request(response):\n logging.warning('Failed to get holdings for ticker',\n ticker, response.status_code)\n return\n\n page_content = response.content\n pq = PyQuery(page_content)\n table = pq.find('#etfs-that-own')\n\n # use secondary data source if none available\n if not table:\n _get_etf_data_backup(ticker, data, holdings)\n return\n\n for row in table('tbody tr').items():\n columns = list(row('td').items())\n ticker = columns[0].children(\"a\").text()\n # disable the backup scraping because it is just too slow for larger funds\n holding_data = get_data(ticker, False)\n if holding_data is None:\n # fall back to getting name from scraped data\n name = columns[1].children(\"a\").text()\n else:\n # make use of official nasdaq data if available\n name = holding_data.loc['Security Name']\n\n weight = columns[2].text()\n weight = weight[:-1]\n holdings.append(Holding(name, ticker, weight))\n\n\ndef _get_etf_data_backup(ticker, data, holdings):\n response = _get_etf_page_backup(ticker)\n if not _valid_request(response):\n logging.warning('Failed to get holdings for ticker ', ticker)\n return\n\n page_content = response.content\n title = data.loc['Security Name']\n\n url = _get_holdings_url(page_content)\n holdings_json = _make_request(url + str(0)).json()\n rows = holdings_json['total']\n # etfdb limits us to 15 tickers per page\n for i in range(0, rows, 15):\n for entry in holdings_json['rows']:\n holding = _get_etf_holding(entry)\n holdings.append(holding)\n holdings_json = _make_request(url + str(i + 15), throttle=0.7).json()\n\n\ndef _get_stock_data(ticker, data, holdings):\n title = data.loc['Security Name']\n holding = Holding(title, ticker)\n holdings.append(holding)\n\n\ndef _get_etf_page(ticker):\n url = 'https://etfdailynews.com/etf/{0}/'.format(ticker)\n return _make_request(url, redirects=False)\n\n\ndef _get_etf_page_backup(ticker):\n url = 'https://etfdb.com/etf/{0}/'.format(ticker)\n return _make_request(url, redirects=False)\n\n\ndef _get_ticker_image(ticker):\n return 'https://storage.googleapis.com/iex/api/logos/{0}.png'.format(ticker)\n\n\ndef _get_iex_data(tickers, options, settings=None):\n data = {}\n options = \",\".join(options)\n if settings:\n options = options + (\"&\" + \"&\".join(settings))\n for i in range(0, len(tickers), 100):\n subset = \",\".join(tickers[i:i+100])\n url = 'https://api.iextrading.com/1.0/stock/market/batch?symbols={0}&types={1}'.format(subset, options)\n data.update(_make_request(url, redirects=False).json())\n return data\n\n\ndef _make_request(url, redirects=True, throttle=0.0):\n response = None\n try:\n response = requests.get(url, hooks={'response': _throttle_hook(\n throttle)}, allow_redirects=redirects, timeout=3)\n except requests.exceptions.RequestException as e:\n raise ValueError('Request exception') from e\n return response\n\n\n# returns response hook function which sleeps for\n# timeout if the response is not yet cached\ndef _throttle_hook(timeout):\n def hook(response, *args, **kwargs):\n if not getattr(response, 'from_cache', False):\n time.sleep(timeout)\n return response\n return hook\n\n\ndef _valid_request(response):\n return response.status_code == requests.codes.ok\n\n\ndef _get_holdings_url(content):\n pq = PyQuery(content)\n url = 'https://etfdb.com/'\n sort = '&sort=weight&order=desc&limit=15&offset='\n url += pq(\"table[data-hash='etf-holdings']\").attr('data-url') + sort\n return url\n\n\ndef _get_etf_holding(entry):\n name = ticker = ''\n data = entry['holding']\n pq = PyQuery(data)\n\n # handle normal cases of actual stocks\n if pq('a').length:\n ticker = pq('a').attr('href').split('/')[2].split(':')[0]\n holding_data = get_data(ticker, False)\n if holding_data is None:\n # fall back to getting name from scraped data\n name = pq('a').text().split('(')[0]\n else:\n # make use of official nasdaq data if available\n name = holding_data.loc['Security Name']\n # handle special underlyings e.g. VIX futures\n elif pq('span').eq(2).length:\n name = data\n ticker = pq('span').eq(2).text()\n # handle further special cases e.g. Cash components, Hogs, Cattle\n else:\n name = data\n ticker = data\n weight = entry['weight'][:-1]\n return Holding(name, ticker, weight)\n\n\ndef _get_data_from_yahoo(ticker):\n scraped_data = yahoo_scraper.get_data(ticker)\n\n data_dict = {}\n\n try:\n data_dict['Yahoo'] = (scraped_data.source == \"Yahoo\")\n data_dict['Price'] = _round_price(scraped_data.price)\n data_dict['Currency'] = scraped_data.currency\n data_dict['Security Name'] = scraped_data.name\n data_dict['ETF'] = scraped_data.etf\n data = pd.Series(data_dict)\n except AttributeError:\n logging.warning(\"No valid data found for \" + ticker)\n\n return scraped_data if (scraped_data is None) else data\n\n\ndef _get_company_from_yahoo(ticker):\n data = yahoo_scraper.get_company_data(ticker)\n\n data_dict = {'company': {'symbol': ticker}}\n\n try:\n company = data_dict['company']\n company['companyName'] = data.name\n company['exchange'] = data.exchange\n company['industry'] = data.industry\n company['website'] = data.website\n company['description'] = data.description\n company['CEO'] = ''\n company['issueType'] = ''\n company['sector'] = data.sector\n company['tags'] = []\n except AttributeError:\n logging.warning(\"No valid company data found for \" + ticker)\n\n return data if (data is None) else data_dict\n\n\ndef to_usd(amount, base_currency_symbol):\n temp_amount = amount\n if base_currency_symbol == '€':\n temp_amount = usd_converter.convert('EUR', amount)\n elif base_currency_symbol == '¥':\n temp_amount = usd_converter.convert('JPY', amount)\n # expandable for a lot of different currencies\n else:\n logging.warning(\"Requested conversion from unknown currency symbol \" + base_currency_symbol +\n \" to USD. Using 1:1 conversion.\")\n return amount if (temp_amount is None) else temp_amount\n","sub_path":"etfcalc/util/webscraper.py","file_name":"webscraper.py","file_ext":"py","file_size_in_byte":9826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"233816825","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 18 21:52:30 2017\n\n@author: roy\n\"\"\"\nimport os\nimport pandas as pd\n\npath_dir= '/home/roy/classes/simulator/data_collect/data'\n\ndriving_info = pd.read_csv(os.path.join(path_dir, 'driving_log.csv'))\n\none_object = driving_info.ix[1]\nprint(type(one_object))\nprint(driving_info.ix[1]['steering'])\nprint(driving_info.shape)","sub_path":"pandas_test.py","file_name":"pandas_test.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"376847849","text":"from __future__ import unicode_literals\nimport warnings\nimport os\n\nwarnings.filterwarnings('ignore', category=FutureWarning)\nwarnings.filterwarnings('ignore', module='librosa')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport pickle\nimport sys\nimport tempfile\nimport time\nimport librosa\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport simpleaudio as sa\nimport tensorflow as tf\nimport youtube_dl\nfrom PIL import Image\nfrom scipy.io.wavfile import write\nfrom eyed3 import id3\n\nIMG_PIXELS = 67000\nIMG_WIDTH = 335\nIMG_HEIGHT = 200\nNUM_LABELS = 32\nMIN_CLIP_LENGTH = 29\nNUM_FEATURES = 44\nNUM_MFCC_COEFF = 20\nSONG_EXT = 'mp3'\nLABELS_DICT = pd.read_csv('./labels_key.csv')['category']\nFEATURE_COLS = pd.read_csv('./feature_cols.csv')['feature_columns']\n\n\nclass Song:\n def __init__(self):\n self.path = None\n self.clips = []\n self.features = []\n self.spectrograms = []\n self.sr = None\n self.genre_prediction = []\n self.title = None\n self.artist = None\n\n def get_predictions(self):\n return self.genre_prediction\n\n @staticmethod\n def __add_to_series(ds, name, values):\n \"\"\" Calculates mean, min, max, and std deviation of each list of values passed to function,\n then stores value in the data series\n :param pandas.Series ds: Data series that will store audio feature data\n :param string name: name of extracted feature. Must match column header\n :param list values: python list of audio extracted data from librosa\n \"\"\"\n # set mean of values\n ds['{}-mean'.format(name)] = np.mean(values)\n # set min of values\n ds['{}-min'.format(name)] = np.min(values)\n # set max of values\n ds['{}-max'.format(name)] = np.max(values)\n # set std of values\n ds['{}-std'.format(name)] = np.std(values)\n\n def __get_features(self, source, sr):\n \"\"\" Calls librosa library to extract audio feature data then stores in pandas data series\n :param string source: path to audio file\n :param string sr: name of audio file\n \"\"\"\n # ignore librosa warning regarding PySoundFile\n warnings.filterwarnings('ignore', module='librosa')\n\n try:\n # define panda series to hold song data\n ds = pd.Series(index=FEATURE_COLS, dtype=np.float32)\n # extract specral features\n self.__add_to_series(ds, 'chroma_stft', librosa.feature.chroma_stft(y=source, sr=sr))\n self.__add_to_series(ds, 'rms', librosa.feature.rms(y=source))\n self.__add_to_series(ds, 'spec_cent', librosa.feature.spectral_centroid(y=source, sr=sr))\n self.__add_to_series(ds, 'spec_bw', librosa.feature.spectral_bandwidth(y=source, sr=sr))\n self.__add_to_series(ds, 'spec_rolloff', librosa.feature.spectral_rolloff(y=source, sr=sr))\n self.__add_to_series(ds, 'zcr', librosa.feature.zero_crossing_rate(source))\n\n # add mfcc spectral coefficients\n mfcc = librosa.feature.mfcc(y=source, sr=sr, n_mfcc=NUM_MFCC_COEFF)\n for count, e in enumerate(mfcc, start=0):\n ds['mfcc{}'.format(count)] = np.mean(e)\n\n return ds\n\n except Exception as e:\n print('ERROR: {}'.format(repr(e)))\n\n def __extract_features(self, source, sr):\n \"\"\" Extract feture data from audio source using genreml\n :param source: raw audio data\n :param sr: sampling rate of audio data\n :returns array of feature data scaled and sorted based on FEATURE_COLS list\n \"\"\"\n features = self.__get_features(source, sr)\n features_sorted = []\n for col in FEATURE_COLS:\n features_sorted.append(features[col])\n features_sorted = np.array(features_sorted)\n features_sorted = features_sorted[np.newaxis, :]\n\n # load scaler object from binary exported from trained data\n sc = pickle.load(open('./std_scaler_B.pkl', 'rb'))\n features = sc.transform(features_sorted)[0]\n return features\n\n @staticmethod\n def __extract_spectrogram(source, sr, output_path, output_name):\n \"\"\" Extract spectrogram data from audio source using librosa package\n :param source: raw audio data\n :param sr: sampling rate of audio data\n :param output_path: path to ouput spectrogram image file\n :param output_name: name that will be given to spectrogram image file\n :returns pixel data of spectrogram image generated from audio data\n \"\"\"\n # generate mel-spectrogram image data from clip\n spect_path = f'{output_path}/img{output_name}'\n mel_spect = librosa.feature.melspectrogram(y=source, sr=sr, n_fft=2048, hop_length=1024)\n mel_spect = librosa.power_to_db(mel_spect, ref=np.max)\n\n # normalize image between min and max\n img = 255 * ((mel_spect - mel_spect.min()) /\n (mel_spect.max() - mel_spect.min()))\n\n # convert pixel values to 8 bit ints\n img = img.astype(np.uint8)\n\n # flip and invert image\n img = np.flip(img, axis=0)\n img = 255 - img\n\n # create and export\n fig = plt.figure(frameon=False)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n ax.imshow(img, aspect='auto', cmap='Greys')\n fig.savefig(spect_path)\n plt.close(fig)\n\n # open .png file and return raw pixel data\n spect_img = Image.open(f'{spect_path}.png').convert('L')\n spect_img = spect_img.resize((IMG_WIDTH, IMG_HEIGHT))\n spect_img = list(spect_img.getdata())\n return spect_img\n\n def download_song(self, url, output_path):\n \"\"\" Uses youtuble-dl package to download and extrat audio data from youtube url\n :param url: Valid youtuble url\n :param output_path: Output path to store audio file\n \"\"\"\n\n def path_hook(d):\n if not self.path:\n file = d['filename'].split('.')[0]\n self.path = f'{file}.{SONG_EXT}'\n\n ydl_opts = {\n 'format': 'bestaudio/best',\n 'outtmpl': output_path + '/%(title)s.%(ext)s',\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': SONG_EXT,\n 'preferredquality': '192',\n },\n {'key': 'FFmpegMetadata'}\n ],\n 'progress_hooks': [path_hook],\n 'keepvideo': True\n }\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([url])\n\n def play_clips(self):\n \"\"\" Function loops through and plays each audio clip from self.clips array\n \"\"\"\n count = 1\n filename = 'test.wav'\n for clip in self.clips:\n # export wav file\n scaled = np.int16(clip / np.max(np.abs(clip)) * 32767)\n write(filename, self.sr, scaled)\n wave_obj = sa.WaveObject.from_wave_file(filename)\n\n # play wav file\n print(f'Playing clip #{count}')\n play_obj = wave_obj.play()\n play_obj.wait_done()\n\n # Wait 2 seconds before playing next clip\n time.sleep(2)\n count += 1\n\n # delete wav file\n os.remove(filename)\n\n def extract_song_data(self):\n \"\"\" Clips song from raw audio data based on length of song:\n If song greater than 90sec, method will clip three 29sec sections from the middle of the song\n If song less than 90sec, only middle 29sec clip extracted\n If less than 29sec, error is thrown\n \"\"\"\n y, sr = librosa.load(self.path)\n self.sr = sr\n\n # length of song in seconds\n length = len(y) / sr\n\n # assert song length greater than or equal to minimum\n if length < MIN_CLIP_LENGTH:\n raise Exception('Song length too short for accurate prediction')\n\n # if length of song less than 3 * MIN_CLIP_LENGTH, take middle section\n elif length < MIN_CLIP_LENGTH * 3 + 1:\n mid_index = int(len(y) / 2)\n lower_index = mid_index - int(sr * MIN_CLIP_LENGTH / 2)\n upper_index = lower_index + int(sr * MIN_CLIP_LENGTH)\n self.clips.append(y[lower_index:upper_index])\n\n # else split song into three clips each at MIN_CLIP_LENGTH in duration\n else:\n num_clips = 3\n mid_index = int(len(y) / 2)\n lower_index = mid_index - int(\n sr * (MIN_CLIP_LENGTH * num_clips / 2))\n\n for i in range(num_clips):\n upper_index = lower_index + int(sr * MIN_CLIP_LENGTH)\n self.clips.append(y[lower_index:upper_index])\n lower_index = upper_index\n\n # get song title and artist if avaliable\n tag = id3.Tag()\n tag.parse(self.path)\n self.title = tag.title\n self.artist = tag.artist\n\n def extract_feature_data(self, spect_output_path: str):\n \"\"\" Method to extract feature data and spectrogram image file from each audio clip in self.clips\n :param spect_output_path: Output file path for spectrogram image file\n \"\"\"\n # loop through each track section and get prediction\n print(f'Extracting data from audio file...')\n count = 1\n for clip in self.clips:\n self.features.append(self.__extract_features(clip, self.sr))\n self.spectrograms.append(self.__extract_spectrogram(clip, self.sr, spect_output_path, count))\n count += 1\n\n def predict(self):\n \"\"\" Prediction method that loops through each clip in self.clips and runs ML prediction model to\n classify song into categories defined in LABELS_DICT\n \"\"\"\n print(f'Running prediction model...')\n self.genre_prediction = np.array(\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n dtype=np.float64)\n # model = tf.keras.models.load_model('FMA_model.h5')\n model = tf.keras.models.load_model('FMA_model_seperate_genres.h5')\n count = 0\n for image, features in zip(self.spectrograms, self.features):\n count += 1\n # get prediction for each clip and and calculate average\n image = np.array(image).reshape(IMG_HEIGHT, IMG_WIDTH, 1)\n features = np.array(features)\n prediction = model.predict([np.array([features]), np.array([image])])\n self.genre_prediction += prediction[0]\n\n # calculate average of each clip prediction\n self.genre_prediction = self.genre_prediction / count\n\n\ndef main(dl_type, url_path, n):\n song = Song()\n with tempfile.TemporaryDirectory() as tmp:\n print(f'Created temporary directory: {tmp}')\n\n try:\n # download song from youtube ('-y') or get local ('-l') file\n if dl_type == '-y':\n song.download_song(url_path, tmp)\n elif dl_type == '-l':\n song.path = url_path\n else:\n raise Exception(\n 'Invalid Input: -y (youtube url) or -l (local file) must be before url or path')\n\n # extract raw audio data from song and section according to length\n song.extract_song_data()\n\n # ====== CAREFUL WITH SYSTEM VOLUME!! ======\n # song.play_clips()\n\n # get feature data and spectrogram images from each clip\n song.extract_feature_data(tmp)\n\n # get top-n genre prediction\n song.predict()\n\n # log top-n genres to console\n prediction_arr = song.get_predictions()\n\n # Log top n predictions to console\n n = int(n)\n top_n_genres = []\n top_n = np.argsort(prediction_arr)\n top_n = top_n[::-1][:n]\n for i, val in enumerate(top_n, start=1):\n top_n_genres.append(LABELS_DICT[val])\n print(f'Top {n} classified genres for ', os.path.splitext(os.path.basename(song.path))[0])\n print(top_n_genres)\n sys.stderr.write(os.path.splitext(os.path.basename(song.path))[0] + ', ' + ', '.join(top_n_genres))\n\n except Exception as e:\n print('ERROR: {}'.format(repr(e)))\n return\n\n\nif __name__ == \"__main__\":\n assert(len(sys.argv) == 4)\n assert(0 < int(sys.argv[3]) < 33)\n main(sys.argv[1], sys.argv[2], sys.argv[3])\n","sub_path":"aws_containers/fma_predictor/audio_classifier.py","file_name":"audio_classifier.py","file_ext":"py","file_size_in_byte":12495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"359104244","text":"l = eval(input('Enter the list containing number between 1 to 12'))\n\nfor i in range(len(l)):\n if l[i] > 10:\n del(l[i])\n l.insert(i,10)\n\n \n\n\n\n\nprint(l)\n","sub_path":"py.py","file_name":"py.py","file_ext":"py","file_size_in_byte":175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"48656870","text":"#!/usr/bin/env python\nfrom xcp2k import CP2K\nfrom ase.build import surface\nfrom ase.constraints import FixAtoms\nfrom ase import Atoms, Atom\nfrom ase.io import write, read\nfrom ase.visualize import view\nfrom multiprocessing import Pool\nimport os\nimport numpy as np\nimport time\n\ndef sortz(atoms):\n tags = atoms.positions[:,2]\n deco = sorted([(tag, i) for i, tag in enumerate(tags)])\n indices = [i for tag, i in deco]\n return atoms[indices]\n\n#===============================================================================\na = 15.865/4\nxyz = a/2\n#atoms = read('~/xcp2k/bulks/pt-relax/relax/')\nbulk = Atoms([Atom('Pt', (0.0, 0.0, 0.0)),\n Atom('Pt', (xyz, xyz, 0.0)),\n Atom('Pt', (xyz, 0.0, xyz)),\n Atom('Pt', (0.0, xyz, xyz))])\nbulk.cell= a * np.array([[1.0, 0.0, 0.0],\n [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0]])\natoms = surface(bulk, (1, 1, 1), 4, vacuum=0.0)\natoms = atoms*[4, 4, 1]\natoms.pbc = [True, True, True]\nconstraint = FixAtoms(mask=[atom.position[2] < 3\n for atom in atoms])\natoms.set_constraint(constraint)\natoms.cell[2][2] = 25\natoms = sortz(atoms)\n#view(atoms)\natoms.write('datas/relax.in')\n#===============================================================================\ncalc = CP2K(cpu = 24)\n#===============================================================================\nCP2K_INPUT = calc.CP2K_INPUT # This is the root of the input tree\nGLOBAL = CP2K_INPUT.GLOBAL\nMOTION = CP2K_INPUT.MOTION\nFORCE_EVAL = CP2K_INPUT.FORCE_EVAL_add()\nSUBSYS = FORCE_EVAL.SUBSYS\nDFT = FORCE_EVAL.DFT\nSCF = DFT.SCF\n#===============================================================================\nGLOBAL.Run_type = \"GEO_OPT\" # energy_force, geo_opt, cell_opt\nGLOBAL.Print_level = \"MEDIUM\"\n\nFORCE_EVAL.Method = \"Quickstep\"\nFORCE_EVAL.Stress_tensor = 'ANALYTICAL'\nFORCE_EVAL.PRINT.FORCES.Section_parameters = \"ON\"\nFORCE_EVAL.PRINT.STRESS_TENSOR.Section_parameters = \"ON\"\n\nDFT.Basis_set_file_name = \"BASIS_MOLOPT\"\nDFT.Potential_file_name = \"POTENTIAL\"\nDFT.Charge = 0\n#DFT.Multiplicity = 1\nDFT.Uks = True\n\n\n#DFT.Surface_dipole_correction = True\n#DFT.Surf_dip_dir = 'Z'\n\nDFT.MGRID.Ngrids = 4\nDFT.MGRID.Cutoff = 500\nRS_GRID_add = DFT.MGRID.RS_GRID_add()\nRS_GRID_add.Distribution_type = 'DISTRIBUTED'\n\nDFT.XC.XC_FUNCTIONAL.Section_parameters = \"PBE\"\n#DFT.XC.XC_GRID.Xc_smooth_rho = 'NN50' # The density smoothing used for the xc calculation\n#DFT.XC.XC_GRID.Xc_deriv = 'NN50_SMOOTH' # The method used to compute the derivatives\n\n#DFT.POISSON.Periodic = 'XYZ'\n\n#DFT.QS.Method = 'GPW'\n#DFT.QS.Eps_default = 1.0E-12\n#DFT.QS.Map_consistent = True # Compute the exact derivative (Hks) of the energy with respect to the density matrix. \n#DFT.QS.Extrapolation = 'ASPC' # Extrapolation strategy for the wavefunction\n#DFT.QS.Extrapolation_order = 3 # Higher order might bring more accuracy, but comes, for large systems, also at some cost.\n\nSCF.Scf_guess = \"ATOMIC\"\nSCF.Eps_diis = 0.1\nSCF.Eps_scf = 1.0E-6\nSCF.Max_scf = 50\nSCF.OUTER_SCF.Eps_scf = 1.0E-6\nSCF.OUTER_SCF.Max_scf = 20\n\nSCF.Added_mos = 500\nSCF.SMEAR.Electronic_temperature = 300\nSCF.SMEAR.Method = 'FERMI_DIRAC'\n\nSCF.DIAGONALIZATION.Algorithm = 'STANDARD'\nSCF.MIXING.Method = 'BROYDEN_MIXING'\nSCF.MIXING.Alpha = 0.1\nSCF.MIXING.Beta = 1.5\nSCF.MIXING.Nbuffer = 8\n\nKIND = SUBSYS.KIND_add('Pt') # Section_parameters can be provided as argument.\nKIND.Element = 'Pt'\nKIND.Basis_set = \"DZVP-MOLOPT-SR-GTH\"\nKIND.Potential = 'GTH-PBE'\n\n#DFT.PRINT.PDOS.Nlumo = 900\n#DFT.PRINT.PDOS.EACH.Qs_scf = 0\n#DFT.PRINT.PDOS.EACH.Geo_opt = 0\n#DFT.PRINT.PDOS.EACH.Md = 0\n#DFT.PRINT.PDOS.Add_last = 'NUMERIC'\n#===============================================================================\n#view(atoms)\n#print(len(atoms))\n#calc.mode = 1\ncalc.directory = 'relax/444'\ncalc.prefix = 'pt'\ncalc.results = {}\ncalc.CP2K_INPUT.MOTION.CONSTRAINT.FIXED_ATOMS_list = []\n#===============================================================================\natoms.set_calculator(calc)\n###calc.write_input_file()\ne = atoms.get_potential_energy()\nt = calc.get_time()\nprint(' {0} {1}'.format( t, e))\n#===============================================================================\n","sub_path":"xcp2k/surfaces/pt/relax.py","file_name":"relax.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"310454469","text":"import math\nimport os\nimport random\nimport re\nimport sys\nfrom collections import defaultdict\n\n# Complete the freqQuery function below.\n\n\ndef freqQuery(queries):\n count = defaultdict(int)\n data = defaultdict(int)\n output = []\n for idx, item in enumerate(queries):\n if item[0] == 1:\n count[data[item[1]]] -= 1\n data[item[1]] += 1\n count[data[item[1]]] += 1\n\n elif item[0] == 2:\n if data[item[1]] > 0:\n count[data[item[1]]] -= 1\n data[item[1]] -= 1\n count[data[item[1]]] += 1\n\n elif item[0] == 3:\n if count[item[1]] > 0:\n output.append(1)\n else:\n output.append(0)\n return output\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input().strip())\n\n queries = []\n\n for _ in range(q):\n queries.append(list(map(int, input().rstrip().split())))\n\n ans = freqQuery(queries)\n\n print(ans)\n\n # fptr.write('\\n'.join(map(str, ans)))\n # fptr.write('\\n')\n\n # fptr.close()\n","sub_path":"Dictionaries and Hash-maps/frequencyQueries.py","file_name":"frequencyQueries.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"644413226","text":"from microservice import MicroService\nfrom modules.server import Server\n\nclass MainService(MicroService):\n def __init__(self):\n super().__init__('main.log', 'main.pid', 'config.yml')\n\n server = Server(\n self.config['servconf'], self.config['dbconf'],\n self.config['uniconf'], self.config['goipconf'])\n server.start()\n\nif __name__ == \"__main__\":\n service = MainService()","sub_path":"mainservice.py","file_name":"mainservice.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"646240353","text":"import config as cfg\r\nimport tensorflow as tf\r\nfrom tensorflow.contrib import slim\r\n\r\ndef conv_net(x, is_training):\r\n batch_norm_params = {\"is_training\": is_training, \"decay\": 0.9, \"updates_collections\": None}\r\n with slim.arg_scope([slim.conv2d, slim.fully_connected],\r\n activation_fn=tf.nn.relu,\r\n weights_initializer=tf.truncated_normal_initializer(mean=0.0, stddev=0.01),\r\n weights_regularizer=slim.l2_regularizer(0.0005),\r\n normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params):\r\n with tf.variable_scope(\"ConvNet\", reuse=tf.AUTO_REUSE):\r\n x = tf.reshape(x, [-1, 28, 28, 1])\r\n net = slim.conv2d(x, 6, [5, 5], scope=\"conv_1\")\r\n net = slim.max_pool2d(net, [2, 2], scope=\"pool_1\")\r\n net = slim.conv2d(net, 12, [5, 5], scope=\"conv_2\")\r\n net = slim.max_pool2d(net, [2, 2], scope=\"pool_2\")\r\n net = slim.flatten(net, scope=\"flatten\")\r\n net = slim.fully_connected(net, 100, scope=\"fc\")\r\n net = slim.dropout(net, is_training=is_training)\r\n net = slim.fully_connected(net, cfg.num_classes, scope=\"prob\", activation_fn=None, normalizer_fn=None)\r\n return net","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"605228511","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport evaluate\nimport argparse\nimport ma_util\nimport csv\n\n\ndef main(goldFile, predFile, outCSVFile):\n header = []\n data = []\n atN = evaluate.accuracyAtN(goldFile, predFile, ma_util.GRANULARITY_COARSE)\n for key in sorted(atN.keys()):\n header.append('Acc at %s' % key)\n data.append(atN[key][0])\n header.append('Support at %s' % key)\n data.append(atN[key][1])\n outFH = open(outCSVFile, 'w')\n writer = csv.writer(outFH)\n writer.writerow(header)\n writer.writerow(data)\n outFH.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='Evaluate system output against a gold standard.')\n parser.add_argument('--gold', required=True,\n help='Gold PTB file')\n parser.add_argument('--predicted', required=True,\n help='System output (PTB file)')\n parser.add_argument('--output-file', required=True,\n help='Where to store CSV results.')\n args = parser.parse_args()\n main(args.gold, args.predicted, args.output_file)\n","sub_path":"shared/evaluate_at_length.py","file_name":"evaluate_at_length.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"574717531","text":"'''\nA Tale of Two Fits\n------------------\n\n This simple example demonstrates the fitting of a linear function to\n two Datasets and plots both Fits into the same Plot.\n'''\n\n###########\n# Imports #\n###########\n\n# import everything we need from kafe\nimport kafe\n\n# additionally, import the model function we\n# want to fit:\nfrom kafe.function_library import linear_2par\n\n############\n# Workflow #\n############\n\n# Initialize the Datasets\nmy_datasets = [kafe.Dataset(title=\"Ohne Gewicht\", axis_labels=['Drehfrequenz', 'Nutationsfrequenz'], axis_units=['Hz', 'Hz']),\n kafe.Dataset(title=\"Mit Gewicht\", axis_labels=['Drehfrequenz', 'Nutationsfrequenz'], axis_units=['Hz', 'Hz'])]\n\n# Load the Datasets from files\nmy_datasets[0].read_from_file(input_file='../messwerte/3_ohne_gewicht.dat')\nmy_datasets[1].read_from_file(input_file='../messwerte/3_mit_gewicht.dat')\n\n# Create the Fits\nfit1 = kafe.Fit(my_datasets[0], linear_2par, fit_label=\"Lineare Regression ohne Gewicht\")\n\nfit2 = kafe.Fit(my_datasets[1], linear_2par, fit_label=\"Lineare Regression mit Gewicht\")\n\nmy_fits = [fit1, fit2]\n\n# Do the Fits\nfor fit in my_fits:\n fit.do_fit(quiet=True)\n\n# Create the plots\nmy_plot = kafe.Plot(my_fits[0], my_fits[1], axis_labels=['Drehfrequenz [Hz]', 'Nutationsfrequenz [Hz]'])\n\n# Draw the plots\nmy_plot.plot_all(show_band_for='all')\n\n###############\n# Plot output #\n###############\n\n# Save the plots\nmy_plot.save('fig_aufgabe_3.pdf')\n\n# Show the plots\nmy_plot.show()\n","sub_path":"71_kreisel/python/two_linear_fits.py","file_name":"two_linear_fits.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"4704463","text":"def two_sum(ls, ex_sum):\n if (ls == None) or (ex_sum==None):\n raise TypeError\n if len(ls)==0 or ex_sum==0:\n raise ValueError\n seen = set()\n op_ls = []\n for ele1 in ls:\n for ele2 in ls:\n if ele1+ele2 == ex_sum:\n print(ele1,ele2)\n index1 = ls.index(ele1)\n index2 = ls.index(ele2)\n seen.add(index1)\n seen.add(index2)\n return list(seen)\n\n\n#print two_sum([1,3,2,-7,5],7)\n#two_sum(None,None)\n#print (a,type(a))\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"151635256","text":"'''\nThis runs random search to find the optimized hyper-parameters using cross-validation\n\nINPUTS:\n - OUT_ITERATION: # of training/testing splits\n - RS_ITERATION: # of random search iteration\n - data_mode: mode to select the time-to-event data from \"import_data.py\"\n - seed: random seed for training/testing/validation splits\n - EVAL_TIMES: list of time-horizons at which the performance is maximized; \n the validation is performed at given EVAL_TIMES (e.g., [12, 24, 36])\n\nOUTPUTS:\n - \"hyperparameters_log.txt\" is the output\n - Once the hyper parameters are optimized, run \"summarize_results.py\" to get the final results.\n'''\nimport time, datetime, os\nimport get_main\nimport numpy as np\n\nimport import_data as impt\n\n\n# this saves the current hyperparameters\ndef save_logging(dictionary, log_name):\n with open(log_name, 'w') as f:\n for key, value in dictionary.items():\n f.write('%s:%s\\n' % (key, value))\n\n\n# this open can calls the saved hyperparameters\ndef load_logging(filename):\n data = dict()\n with open(filename) as f:\n def is_float(input):\n try:\n num = float(input)\n except ValueError:\n return False\n return True\n\n for line in f.readlines():\n if ':' in line:\n key, value = line.strip().split(':', 1)\n if value.isdigit():\n data[key] = int(value)\n elif is_float(value):\n data[key] = float(value)\n elif value == 'None':\n data[key] = None\n else:\n data[key] = value\n else:\n pass # deal with bad lines of text here\n return data\n\n\n# this randomly select hyperparamters based on the given list of candidates\ndef get_random_hyperparameters(out_path):\n SET_BATCH_SIZE = [32, 64, 128] # mb_size\n\n SET_LAYERS = [1, 2, 3, 5] # number of layers\n SET_NODES = [50, 100, 200, 300] # number of nodes\n\n SET_ACTIVATION_FN = ['relu', 'elu', 'tanh'] # non-linear activation functions\n\n SET_ALPHA = [0.1, 0.5, 1.0, 3.0, 5.0] # alpha values -> log-likelihood loss\n SET_BETA = [0.1, 0.5, 1.0, 3.0, 5.0] # beta values -> ranking loss\n SET_GAMMA = [0.1, 0.5, 1.0, 3.0, 5.0] # gamma values -> calibration loss\n\n new_parser = {'mb_size': SET_BATCH_SIZE[np.random.randint(len(SET_BATCH_SIZE))],\n\n 'iteration': 50000,\n\n 'keep_prob': 0.6,\n 'lr_train': 1e-4,\n\n 'h_dim_shared': SET_NODES[np.random.randint(len(SET_NODES))],\n 'h_dim_CS': SET_NODES[np.random.randint(len(SET_NODES))],\n 'num_layers_shared': SET_LAYERS[np.random.randint(len(SET_LAYERS))],\n 'num_layers_CS': SET_LAYERS[np.random.randint(len(SET_LAYERS))],\n 'active_fn': SET_ACTIVATION_FN[np.random.randint(len(SET_ACTIVATION_FN))],\n\n 'alpha': 1.0, # default (set alpha = 1.0 and change beta and gamma)\n 'beta': SET_BETA[np.random.randint(len(SET_BETA))],\n 'gamma': 0, # default (no calibration loss)\n # 'alpha':SET_ALPHA[np.random.randint(len(SET_ALPHA))],\n # 'beta':SET_BETA[np.random.randint(len(SET_BETA))],\n # 'gamma':SET_GAMMA[np.random.randint(len(SET_GAMMA))],\n\n 'out_path': out_path}\n\n return new_parser # outputs the dictionary of the randomly-chosen hyperparamters\n\n##### MAIN SETTING\nOUT_ITERATION = 1\nRS_ITERATION = 20\n\ndata_mode = 'MZZ_200_5' # 'SYNTHETIC''METABRIC'\nseed = 1234\n\n##### IMPORT DATASET\n'''\n num_Category = typically, max event/censoring time * 1.2 (to make enough time horizon)\n num_Event = number of evetns i.e. len(nap.unique(label))-1\n max_length = maximum number of measurements\n x_dim = data dimension including delta (num_features)\n mask1, mask2 = used for cause-specific network (FCNet structure)\n\n EVAL_TIMES = set specific evaluation time horizons at which the validatoin performance is maximized. \n \t\t\t\t\t\t (This must be selected based on the dataset)\n'''\n\n\ndef run_experiment(data_mode):\n\n if data_mode == 'SYNTHETIC':\n (x_dim), (data, time, label), (mask1, mask2) = impt.import_dataset_SYNTHETIC(norm_mode='standard')\n EVAL_TIMES = [12, 24, 36]\n elif data_mode == 'METABRIC':\n (x_dim), (data, time, label), (mask1, mask2) = impt.import_dataset_METABRIC(norm_mode='standard')\n EVAL_TIMES = [144, 288, 432]\n elif data_mode[0:3] == 'MZZ':\n first_ = data_mode.find(\"_\")\n second_ = data_mode[first_+1:].find(\"_\") + first_ +1\n num_samples = data_mode[first_+1: second_]\n num_features = data_mode[second_+1:]\n (x_dim), (data, time, label), (mask1, mask2) = impt.import_mzz_SYNTHETIC(num_samples=num_samples, num_features = num_features, norm_mode='standard')\n EVAL_TIMES = [50, 100, int(max(time))]\n else:\n print('ERROR: DATA_MODE NOT FOUND !!!')\n\n DATA = (data, time, label)\n MASK = (mask1, mask2) # masks are required to calculate loss functions without for-loops.\n\n out_path = os.path.join('experiments', data_mode, 'results')\n #out_path = data_mode + '/results/'\n for itr in range(OUT_ITERATION):\n\n if not os.path.exists(out_path + '/itr_' + str(itr) + '/'):\n os.makedirs(out_path + '/itr_' + str(itr) + '/')\n\n max_valid = 0.\n max_valid_list = []\n log_name = out_path + '/itr_' + str(itr) + '/hyperparameters_log.txt'\n\n for r_itr in range(RS_ITERATION):\n print('OUTER_ITERATION: ' + str(itr))\n print('Random search... itr: ' + str(r_itr))\n new_parser = get_random_hyperparameters(out_path)\n print(new_parser)\n\n # get validation performance given the hyper - parameters\n tmp_max = get_main.get_valid_performance(DATA, MASK, new_parser, itr, EVAL_TIMES, MAX_VALUE=max_valid)\n if tmp_max > max_valid:\n max_valid = tmp_max\n max_parser = new_parser\n save_logging(max_parser, log_name) # save the hyperparameters if this provides the maximum validation performance\n print('Current best: ' + str(max_valid))\n max_valid_list.append(max_valid)\n\n\n result_fpath = os.path.join(out_path, 'itr_' + str(itr), 'performance.txt' )\n with open(result_fpath, 'w') as f:\n f.write('Max:{}\\n'.format( np.max(max_valid) ) )\n f.write('Std:{}\\n'.format( np.std(max_valid_list)))\n print(np.max(max_valid))\n print(np.std(max_valid_list))\n\n\nif __name__ == '__main__':\n\n data_mode_list = ['MZZ_200_3', 'MZZ_200_5', 'MZZ_200_10',\n 'MZZ_500_3', 'MZZ_500_5', 'MZZ_500_10',\n 'MZZ_750_3', 'MZZ_750_5', 'MZZ_750_10',\n 'MZZ_1000_3', 'MZZ_1000_5', 'MZZ_1000_10',\n 'MZZ_2000_3', 'MZZ_2000_5', 'MZZ_2000_10',\n 'MZZ_5000_3', 'MZZ_5000_5', 'MZZ_5000_10'\n ]\n\n for data_mode in data_mode_list:\n run_experiment(data_mode)\n","sub_path":"main_RandomSearch.py","file_name":"main_RandomSearch.py","file_ext":"py","file_size_in_byte":7266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"112917495","text":"from flask import Blueprint, render_template, redirect, url_for, request, flash\nfrom pymongo import MongoClient\nfrom ssl_decorators import no_ssl_required\nfrom smtplib import SMTP\nfrom email.mime.text import MIMEText\n\nblueprint = Blueprint('book_event', __name__)\n\n@blueprint.route('/bookevent', methods=['GET','POST'])\n@no_ssl_required\ndef view():\n if request.method == 'POST':\n book_request = \"Name: \" + request.form['name'] + \"\\n\"\n book_request += \"Phone number: \" + request.form['phone'] + \"\\n\"\n book_request += \"Reason: \" + request.form['reason'] + \"\\n\"\n book_request += \"Location: \" + request.form['location'] + \"\\n\"\n book_request += \"Secrecy level: \" + request.form['secrecylevel'] + \"\\n\"\n book_request += \"Number of people: \" + request.form['numpeople'] + \"\\n\"\n book_request += \"Budget: \" + request.form['budget']\n\n msg = MIMEText(book_request)\n msg['Subject'] = \"Booking request\"\n msg['From'] = \"Off The Grid booking\"\n msg['To'] = \"kwyatt187@gmail.com\"\n \n s = SMTP('localhost')\n s.sendmail(\"Off_The_Grid_booking@offthegridadvertising.com\", [\"kwyatt187@gmail.com\"], msg.as_string())\n s.quit()\n flash('Booking request sent')\n return redirect(url_for('book_event.view'))\n else:\n db = MongoClient().offTheGrid\n locations = db.locations.find().sort([(\"name\" , 1)])\n return render_template('bookevent.html', locations=locations)\n","sub_path":"views/book_event.py","file_name":"book_event.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"178158525","text":"import os\nimport pickle\n\ndef read(path):\n data = {}\n if os.path.exists(path):\n with open(path, 'rb') as f:\n data = pickle.load(f)\n return data\n\ndef save(path,data):\n with open(path, 'wb') as f:\n pickle.dump(data, f, True)\n\n","sub_path":"pkl.py","file_name":"pkl.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"554257540","text":"#Types.\nfrom typing import Dict, List, Any\n\n#Transaction classs.\nfrom PythonTests.Classes.Transactions.Transaction import Transaction\n\n#BLS lib.\nimport blspy\n\n#Blake2b standard function.\nfrom hashlib import blake2b\n\n#Claim class.\nclass Claim(Transaction):\n #Constructor.\n def __init__(\n self,\n inputs: List[bytes],\n output: bytes,\n signature: bytes = bytes(96)\n ) -> None:\n self.inputs: List[bytes] = inputs\n self.output: bytes = output\n self.amount: int = 0\n\n self.signature: bytes = signature\n self.hash = blake2b(b'\\1' + self.signature, digest_size=48).digest()\n\n self.verified: bool = False\n\n #Transaction -> Claim. Satisifes static typing requirements.\n @staticmethod\n def fromTransaction(\n tx: Transaction\n ) -> Any:\n return tx\n\n #Sign.\n def sign(\n self,\n privKeys: List[blspy.PrivateKey]\n ) -> None:\n signatures: List[blspy.Signature] = [\n privKeys[0].sign(b'\\1' + self.inputs[0] + self.output)\n ]\n\n for i in range(1, len(self.inputs)):\n signatures.append(privKeys[i].sign(b'\\1' + self.inputs[i] + self.output))\n\n self.signature = blspy.Signature.aggregate(signatures).serialize()\n self.hash = blake2b(b'\\1' + self.signature, digest_size=48).digest()\n\n #Serialize.\n def serialize(\n self\n ) -> bytes:\n result: bytes = len(self.inputs).to_bytes(1, \"big\")\n for txInput in self.inputs:\n result += txInput\n result += self.output + self.signature\n return result\n\n #Claim -> JSON.\n def toJSON(\n self\n ) -> Dict[str, Any]:\n if self.amount == 0:\n raise Exception(\"Python tests didn't set this Claim's value.\")\n\n result: Dict[str, Any] = {\n \"descendant\": \"Claim\",\n \"inputs\": [],\n \"outputs\": [{\n \"key\": self.output.hex().upper(),\n \"amount\": str(self.amount)\n }],\n\n \"signature\": self.signature.hex().upper(),\n \"hash\": self.hash.hex().upper()\n }\n for txInput in self.inputs:\n result[\"inputs\"].append({\n \"hash\": txInput.hex().upper()\n })\n return result\n\n #Claim -> JSON with verified field.\n def toVector(\n self,\n ) -> Dict[str, Any]:\n result = self.toJSON()\n result[\"verified\"] = self.verified\n return result\n\n #JSON -> Claim.\n @staticmethod\n def fromJSON(\n json: Dict[str, Any]\n ) -> Any:\n inputs: List[bytes] = []\n for txInput in json[\"inputs\"]:\n inputs.append(bytes.fromhex(txInput[\"hash\"]))\n\n result: Claim = Claim(\n inputs,\n bytes.fromhex(json[\"outputs\"][0][\"key\"]),\n bytes.fromhex(json[\"signature\"])\n )\n result.amount = int(json[\"outputs\"][0][\"amount\"])\n if json[\"verified\"]:\n result.verified = True\n return result\n","sub_path":"PythonTests/Classes/Transactions/Claim.py","file_name":"Claim.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"448130786","text":"# coding: utf-8\n\nimport os.path as op\nimport numpy as np\nimport pandas as pd\nfrom pandas.api.types import CategoricalDtype as cdtype\n\nRENAME_COLS = dict(PATNO='PARTICIPANT',\n EVENT_ID='VISIT')\nASSIGN_COLS = dict(PAG_NAME='DATSCAN',\n VISIT_DATE=np.nan)\nRETAIN_COLS = ['PARTICIPANT', 'PAG_NAME', 'VISIT',\n 'VISIT_DATE', 'TEST', 'SCORE']\n\n\ndef get_data(fpath):\n \"\"\"\n Gets DaTscan data for PPMI subjects\n\n Parameters\n ----------\n fname : str\n Filepath to directory containing DaTScan_Analysis.csv file\n\n Returns\n -------\n data : pandas.core.frame.DataFrame\n DaTScan data\n \"\"\"\n\n visits = ['SC', 'BL', 'V01', 'V02', 'V03', 'V04', 'V05', 'V06', 'V07',\n 'V08', 'V09', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15']\n dtype = dict(PATNO=str,\n EVENT_ID=cdtype(visits, ordered=True))\n\n fname = op.join(fpath, 'DATScan_Analysis.csv')\n data = pd.read_csv(fname, dtype=dtype)\n\n # melt into tidy DataFrame\n data = pd.melt(data.rename(columns=RENAME_COLS),\n id_vars=RENAME_COLS.values(),\n var_name='TEST', value_name='SCORE')\n data = data.dropna(axis=0, subset=['SCORE'])\n data = data.assign(**ASSIGN_COLS)[RETAIN_COLS]\n\n return data\n","sub_path":"ppmi/datasets/datscan.py","file_name":"datscan.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"159198173","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.ram = [0] * 256\n self.reg = [0] * 8\n self.reg[7] = 0xF4 # set the last reg to the sp\n self.pc = 0\n\n # op codes and handler\n self.handler = {\n 0b10100000: self.handle_ADD,\n 0b01010000: self.handle_CALL,\n 0b00000001: self.handle_HLT,\n 0b10000010: self.handle_LDI,\n 0b10100010: self.handle_MUL,\n 0b01000110: self.handle_POP,\n 0b01000111: self.handle_PRN,\n 0b01000101: self.handle_PUSH,\n 0b00010001: self.handle_RET\n }\n\n def load(self, file):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n with open(file) as f:\n lines = f.readlines()\n lines = [\n line for line in lines if line.startswith('0') or line.startswith('1')\n ]\n program = [int(line[:8], 2) for line in lines]\n\n for instruction in program:\n self.ram[address] = instruction\n address += 1\n\n def handle_instructions(self, op, reg_a, reg_b):\n \"\"\"CU operations.\"\"\"\n try:\n self.handler[op](reg_a, reg_b)\n except KeyError:\n raise Exception(\"No such op code\")\n\n def handle_ADD(self, reg_a, reg_b):\n self.reg[reg_a] += self.reg[reg_b]\n self.pc += 3\n \n def handle_CALL(self, reg_a, reg_b):\n self.reg[7] -= 1\n self.ram_write(self.pc + 2, self.reg[7])\n self.pc = self.reg[reg_a]\n\n def handle_HLT(self, reg_a, reg_b):\n self.pc += 1\n self.running = False\n\n def handle_LDI(self, reg_a, reg_b):\n self.reg[reg_a] = reg_b\n self.pc += 3\n\n def handle_MUL(self, reg_a, reg_b):\n self.reg[reg_a] = (self.reg[reg_a] * self.reg[reg_b])\n self.pc += 3\n\n def handle_POP(self, reg_a, reg_b):\n self.reg[reg_a] = self.ram_read(self.reg[7])\n self.reg[7] += 1\n self.pc += 2\n return self.reg[reg_a]\n\n def handle_PRN(self, reg_a, reg_b):\n print(self.reg[reg_a])\n self.pc += 2\n\n def handle_PUSH(self, reg_a, reg_b):\n self.reg[7] -= 1\n self.ram_write(self.reg[reg_a], self.reg[7])\n self.pc += 2\n\n def handle_RET(self, reg_a, reg_b):\n self.pc = self.ram_read(self.reg[7])\n self.reg[7] += 1\n \n\n def ram_read(self, address):\n return self.ram[address]\n\n def ram_write(self, value, address):\n self.ram[address] = value\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n # self.fl,\n # self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n\n # set exit condition\n self.running = True\n\n # while loop\n while self.running:\n\n IR = self.ram_read(self.pc)\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n\n self.handle_instructions(IR, operand_a, operand_b)\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156013537","text":"#On my honor,as an Aggie, I have neither given nor received unauthorized aid on this academic work. An Aggie does not\r\n#lie, cheat or steal, or tolerate those who do\r\n\r\n\r\nfrom scipy.signal import find_peaks\r\n\r\n# this function diagnoses AV block first degree\r\ndef AV_firstdegree(PRinterval):\r\n # if there are no corresponding PR intervals for calculations, AV first degree is not the diagnosis\r\n if PRinterval == 0:\r\n value = False\r\n\r\n # AV first degree is diagnosed through a PR interval greater than .2 sec\r\n # the average of the PR intervals are used to determine if the interval exceeds .2 sec\r\n else:\r\n PRinterval = sum(PRinterval)/len(PRinterval)\r\n if PRinterval > .2:\r\n value = True\r\n else:\r\n value = False\r\n return value\r\n\r\n# this function diagnoses AV block second degree\r\ndef AV_seconddegree(PPinterval,RRinterval):\r\n # AV block second degree is diagnosed when there are missing QRS complexes\r\n\r\n # if there are no P waves or R waves diagnosis should be false\r\n if len(PPinterval) == 0 or len(RRinterval) == 0:\r\n diagnosis = False\r\n\r\n # if there are QRS complexes missing, the number of P intervals should be considerably bigger\r\n elif (len(PPinterval) - len(RRinterval)) > 2:\r\n diagnosis = True\r\n else:\r\n diagnosis = False\r\n return diagnosis\r\n\r\n# this function diagnoses tachycardia\r\ndef sinus_tachycardia (bpm):\r\n # tachycardia is diagnosed when the heart rate is over 100 bpm\r\n if bpm > 100:\r\n diagnosis = True\r\n else:\r\n diagnosis = False\r\n return diagnosis\r\n\r\n# this function diagnoses bradycardia\r\ndef sinus_bradycardia (bpm):\r\n # bradycardia is diagnosed when the heart rate is less than 60 bpm\r\n if bpm < 60:\r\n diagnosis = True\r\n else:\r\n diagnosis = False\r\n return diagnosis\r\n\r\n# this function diagnoses arrythmia\r\ndef arrythmia(PPinterval,RRinterval):\r\n # if any value of the RR interval is greater than 1, the diagnosis is false\r\n x = 0\r\n r = []\r\n # while loop looks for the values over 1 and append them to the r list\r\n while x != len(RRinterval):\r\n y = RRinterval[x]\r\n if y > 1:\r\n r.append(y)\r\n x += 1\r\n else:\r\n x += 1\r\n if len(r) > 0:\r\n diagnosis = False\r\n else:\r\n # if there are no PP intervals or RR interval, the diagnosis is false\r\n if len(PPinterval)==0 or len(RRinterval)==0:\r\n diagnosis = False\r\n else:\r\n # one way of diagnosing is finding the difference between the greatest PP interval and the smallest PP interval\r\n # the interval must be greater than .16\r\n max_interval = max(PPinterval)\r\n min_interval = min(PPinterval)\r\n PPinterval = max_interval - min_interval\r\n\r\n # another way of diagnosing is finding the difference between the greatest RR interval and the smallest RR interval\r\n # the interval must be greater than .16\r\n max_interval1 = max(RRinterval)\r\n min_interval1 = min(RRinterval)\r\n RRinterval = max_interval1 - min_interval1\r\n\r\n #if any of the two intervals are greater than .16, the diagnosis is true\r\n if PPinterval > .16 or RRinterval > .16:\r\n diagnosis = True\r\n else:\r\n diagnosis = False\r\n return diagnosis\r\n\r\n# this function diagnoses bundle branch block\r\ndef bundle_branch(QRS_interval,voltage):\r\n # to diagnose bundle branch block, the length of the QRS complex must be greater than .12 sec\r\n # the average of the QRS complexes is used to determine if it is greater than .12 sec\r\n QRS_interval = sum(QRS_interval)/len(QRS_interval)\r\n P_peaks, _ = find_peaks(voltage, height=(.25, .4))\r\n\r\n # if there are no P waves, diagnosis is false\r\n if len(P_peaks) == 0:\r\n value = False\r\n #if the average is greater than .12, the diagnosis is true\r\n elif QRS_interval>.120:\r\n value = True\r\n else:\r\n value = False\r\n return value\r\n\r\ndef atrial_fibrillation(voltage):\r\n # findpeaks is used to first find the P waves\r\n P_peaks, _ = find_peaks(voltage, height=(.25, .4))\r\n # when diagnosing atrial fibrillation, there are usually no P waves\r\n if len(P_peaks) == 0:\r\n diagnosis = True\r\n else:\r\n diagnosis = False\r\n return diagnosis","sub_path":"Diseases.py","file_name":"Diseases.py","file_ext":"py","file_size_in_byte":4401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"208396287","text":"import discord, os, operator, threading, time\nfrom discord.ext import commands, tasks\nfrom ledger import Ledger\nfrom stocks import (\n YahooFinance,\n PolygonRest,\n)\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport pandas as pd\nfrom datetime import datetime\nfrom config import TOKEN\n\nledger = Ledger('data.json')\nstocks = PolygonRest()\nintents = discord.Intents.default()\nintents.members = True\ncommand_prefix = \"!\"\nbot = commands.Bot(command_prefix=command_prefix, intents=intents)\nbot.remove_command('help')\nembed_color = 0x00ff00\n\ndef rnd(f):\n return round(f, 2)\n\ndef sdate():\n return str(datetime.now())[:19]\n\ndef add_embed(title=None, description=None, fields=None, inline=False, ctx=None,\n author=None, image=None, footer=None, timestamp=None, color=embed_color):\n embed = discord.Embed(\n title=title,\n description=description,\n color=color,\n )\n if fields != None:\n for name, value in fields:\n embed.add_field(\n name=name,\n value=value,\n inline=inline,\n )\n if author != None:\n embed.set_author(name=author.name, icon_url=author.avatar_url)\n if image != None:\n embed.set_image(url=image)\n if footer != None:\n embed.set_footer(text=footer)\n if timestamp != None:\n embed.set_timestamp(timestamp)\n return embed\n\n@bot.command()\nasync def help(ctx):\n fields = [\n ('!add', 'Sign up for StocksBot'),\n ('!buy (type) (symbol) (amount)', 'To purchase shares ex. !buy cash AAPL 1000'),\n ('!sell (type) (symbol) (amount)', 'To sell shares ex. !sell qty TSLA 1000'),\n ('!liquidate', 'To liquidate all assets'),\n ('!portfolio (id)', 'To view all your assets'),\n ('!stock (symbol)', 'To view the stock trend of a specific company ex. !stock AMZN'),\n ('!lookup (company name)', 'To get the information of a specific company ex. !lookup Starbucks'),\n ]\n embed = add_embed('Help', description='Descriptions for all the commmands', fields=fields)\n await ctx.send(embed=embed)\n\n@bot.command()\nasync def echo(ctx, *, content:str):\n print(ctx.author)\n await ctx.send(content)\n\n\n# @bot.command()\n# async def add(ctx):\n# id = ctx.author.id\n# name = ctx.author.name\n# if (ledger.contains(id)):\n# embed = add_embed('StocksBot', 'Error: Already registered with StocksBot!', color=0xFF0000, author=ctx.author)\n# else:\n# ledger.add_user(id, name)\n# embed = add_embed('StocksBot', 'You have been added to StocksBot!', author=ctx.author)\n# await ctx.send(embed=embed)\n\n@bot.command()\nasync def buy(ctx, type:str, symbol:str, amount:str):\n symbol = symbol.upper()\n id = str(ctx.author.id)\n name = ctx.author.name\n try:\n price = stocks.latest_price(symbol)\n if price == None:\n raise\n except:\n embed = add_embed(f'\"{symbol}\" couldn\\'t be found', author=ctx.author)\n await ctx.send(embed=embed)\n return\n if amount == 'all':\n qty = None\n elif type == 'cash':\n qty = float(amount)/price\n elif type == 'qty':\n qty = float(amount)\n else:\n await ctx.send(f'Invalid Command {ctx.author.mention}')\n\n if qty != None and qty < .1:\n embed = add_embed('Error in Transaction', f'{ctx.author.mention} need to buy more than .1 shares', author=ctx.author)\n await ctx.send(embed=embed)\n return\n pqty = ledger.enter_position(str(id), 'long', symbol, price, qty)\n if pqty == False:\n embed = add_embed('Error in Transaction', f'{ctx.author.mention} error processing transaction! (Maybe Overbought)', author=ctx.author)\n await ctx.send(embed=embed)\n else:\n fields = [\n ('Share Price', f'${rnd(price)}'),\n ('Quantity', f'{rnd(pqty)} shares'),\n ('Worth', f'${rnd(pqty * price)}')\n ]\n footer = f'Transaction at {sdate()}'\n embed = add_embed(f'Bought {symbol}', f'Remaining Balance: ${rnd(ledger.get_balance(id))}' , fields=fields, author=ctx.author, inline=True, footer=footer)\n await ctx.send(embed=embed)\n\n@bot.command()\nasync def sell(ctx, type:str, symbol:str, amount:str):\n symbol = symbol.upper()\n id = str(ctx.author.id)\n name = ctx.author.name\n price = stocks.latest_price(symbol)\n try:\n price = stocks.latest_price(symbol)\n if price == None:\n raise\n except:\n embed = add_embed(f'\"{symbol}\" couldn\\'t be found', author=ctx.author)\n await ctx.send(embed=embed)\n return\n if amount == 'all':\n qty = None\n elif type == 'cash':\n qty = float(amount)/price\n elif type == 'qty':\n qty = float(amount)\n else:\n await ctx.send(f'Invalid Command {ctx.author.mention}')\n\n if qty != None and qty < .1:\n embed = add_embed('Error in Transaction', f'{ctx.author.mention} need to sell more than .1 shares', author=ctx.author)\n await ctx.send(embed=embed)\n return\n pqty = ledger.exit_position(id, 'sell', symbol, price, qty)\n if pqty == False:\n embed = add_embed('Error in Transaction', f'{ctx.author.mention} error processing transaction! (Maybe Oversold)', author=ctx.author)\n await ctx.send(embed=embed)\n else:\n fields = [\n ('Share Price', f'${rnd(price)}'),\n ('Quantity', f'{rnd(pqty)} shares'),\n ('Worth', f'${rnd(pqty * price)}')\n ]\n footer = f'Transaction at {sdate()}'\n embed = add_embed(f'Sold {symbol}', f'Remaining Balance: ${rnd(ledger.get_balance(id))}', fields=fields, author=ctx.author, inline=True, footer=footer)\n await ctx.send(embed=embed)\n\n\n@bot.command()\nasync def stock(ctx, symbol:str):\n symbol = symbol.upper()\n try:\n price = stocks.latest_price(symbol)\n except:\n embed = add_embed(f'Could\\'t find information for \"{symbol}\"', 'check spelling and symbol!')\n await ctx.send(embed=embed)\n return\n open, high, low = stocks.get_stats(symbol)\n trend = rnd(price-open)\n trend_perc = rnd((price-open)/open*100)\n if trend > 0:\n trend = f'+${trend}'\n trend_perc = f'+{trend_perc}%'\n else:\n trend = f'-${abs(trend)}'\n trend_perc = f'-{abs(trend_perc)}%'\n fields = [\n ('Current Price', f'${price}'),\n ('Open Price', f'${open}'),\n ('High Price', f'${high}'),\n ('Low Price', f'${low}'),\n ('Trend Today', trend),\n ('Trend Today %', trend_perc),\n ]\n o, h, l, c = stocks.get_aggregate(symbol)\n layout = go.Layout(\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n width=1200,\n height=800,\n xaxis=go.layout.XAxis(\n showticklabels=False\n ),\n yaxis=go.layout.YAxis(\n color=\"white\"\n )\n )\n fig = go.Figure(data=[go.Candlestick(open=o, high=h, low=l, close=c)], layout=layout)\n fig.update_layout(xaxis_rangeslider_visible=False)\n fig.write_image(\"images/\" + symbol + \".png\")\n file = discord.File(\"images/\" + symbol + \".png\", filename='image.png')\n embed = add_embed(title=symbol, description=f'Stats as of ({sdate()})', fields=fields, author=ctx.author, inline=True, image='attachment://image.png')\n await ctx.send(file=file, embed=embed)\n os.remove('images/' + symbol + '.png')\n\n@bot.command()\nasync def liquidate(ctx):\n id = str(ctx.author.id)\n holdings = ledger.get_holdings(id)\n fields = []\n for symbol, qty in holdings:\n price = stocks.latest_price(symbol)\n ledger.exit_position(id, 'sell', symbol, price, qty)\n value = f'''\n {rnd(qty)} Shares\n ${rnd(qty * price)}\n '''\n fields.append((symbol, value))\n embed = add_embed(f'Portfolio Liquidated', fields=fields, author=ctx.author, inline=True)\n await ctx.send(embed=embed)\n\n@tasks.loop(seconds=30)\nasync def leaderboard():\n ports, i, fields = ledger.get_all_owned(), 1, []\n worths = {}\n for id in ports:\n worth = ledger.get_balance(id)\n for sym, qty in ports[id]:\n worth += qty * stocks.latest_price(sym)\n worths[id] = worth\n sorted_worths = sorted(worths.items(), key=operator.itemgetter(1))\n sorted_worths.reverse()\n for id, bal in sorted_worths:\n if i > 10: break\n user = await bot.fetch_user(int(id))\n fields.append((f'{i}: {user.name}', f'Net Worth: ${rnd(bal)}'))\n i += 1\n embed = add_embed(title='Leaderboard', fields=fields)\n for guild in bot.guilds:\n channel = discord.utils.get(guild.channels, name=\"leaderboard\")\n if channel == None:\n channel = await guild.create_text_channel('leaderboard')\n message_list = await channel.history(limit=1).flatten()\n if (len(message_list) == 0):\n await channel.send(embed=embed)\n else:\n try:\n await message_list[0].edit(embed=embed)\n except:\n await channel.purge(limit=100)\n await channel.send(embed=embed)\n\nasync def add_all():\n await bot.wait_until_ready()\n for user in bot.users:\n if not ledger.contains(user.id) and not user.bot:\n ledger.add_user(user.id, user.name)\n\nadd_all()\nleaderboard.start()\n\n@bot.command()\nasync def portfolio(ctx):\n after = ctx.message.content.lower().split(\"portfolio\")[1]\n if (len(ctx.message.mentions) > 0):\n author = ctx.message.mentions[0]\n elif (len(after) > 2 and ctx.guild.get_member(int(after.split(' ')[1])) != None):\n author = ctx.guild.get_member(int(after.split(' ')[1]))\n else:\n author = ctx.author\n id = str(author.id)\n port = ledger.portfolio(id)\n fields = []\n cash_balance = ledger.get_balance(id)\n total_worth = cash_balance\n for sym, qty, ptype, price in port:\n current_price = stocks.latest_price(sym)\n if ptype == 'long':\n profit = rnd((current_price-price)*qty)\n profit_perc = rnd((current_price-price)/price*100)\n total_worth += current_price * qty\n else:\n total_worth += qty * (2 * price - current_price)\n profit = rnd((price-current_price)*qty)\n profit_perc = rnd((price-current_price)/price*100)\n value = f'''\n Shares: {rnd(qty)}\n Position: {ptype}\n Worth: ${rnd(current_price*qty)} \n Profit: {profit}$\n Profit %: {profit_perc}%\n\n '''\n fields.append((f'{sym}', value))\n total_stats = f'''\n Net Worth: ${rnd(total_worth)}\n Cash Balance: ${rnd(cash_balance)}\n Total Profit:\n ${rnd(total_worth - 10e3)} | {rnd((total_worth - 10e3)/10e3 * 100)}%\n '''\n embed = add_embed(f'Portfolio', total_stats, fields=fields, inline=True, author=author)\n await ctx.send(embed=embed)\n\n\n@bot.command()\nasync def lookup(ctx):\n query = ctx.message.content.lower().split(\"lookup\")[1][1:]\n symbol = stocks.lookup(query)\n data = stocks.get_info(symbol)\n if data == False:\n embed = add_embed(f'Couldn\\'t find information for \"{query}\"', 'Make sure symbol exists!')\n await ctx.send(embed=embed)\n return\n fields = [\n ('Symbol', data['symbol']),\n ('Maket Cap', f'${data[\"marketcap\"]}'),\n ('Employees', data['employees']),\n ('Sector', data['sector']),\n ('Industry', data['industry']),\n ('Website', data['url'])\n ]\n embed = add_embed(data['name'], 'Basic Infomation', fields=fields, image=data['logo'], inline=True)\n await ctx.send(embed=embed)\n\n\nbot.run(TOKEN)\n","sub_path":"events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":11947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"177041675","text":"''' Crie um programa onde 4 jogadores joguem um dado e tenham resultados alestórios. Guarde esses resultados em\num dicionário. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado. '''\n\nfrom random import *\nfrom time import *\nfrom operator import *\n\njogadores = dict()\nranking = dict()\ncont = 1\nfor j in range(1, 5):\n jogadores[f'Jogador{j}'] = randint(1, 6)\n\nranking = sorted(jogadores.items(), key=itemgetter(1), reverse=True)\n\nfor k, v in jogadores.items():\n print(f'{k} = {v}')\n sleep(1)\nprint('-=' * 30)\nprint(' == RANKING DOS JOGADORES == ')\nfor k, v in ranking:\n print(f' {cont}º lugar: {k} com {v}.')\n cont += 1\n sleep(1)\n","sub_path":"pythonMundoTres/ex091.py","file_name":"ex091.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413496810","text":"# A4.py\n# %matplotlib inline\nimport scipy.interpolate, matplotlib.pyplot as plt # For plotting\n\nfrom set_t_values import set_t_values\nfrom construct_pols import construct_pols\n\n# 1. sets the x and y values according to the table above,\nx = [0, .5, 1.1, 1, .2]\ny = [2, 2.5, 2.7, 2, 2.1]\n\n# 2. calls the functions from parts (a) and (b) to find the interpolating polynomials\nt = set_t_values(x, y) # find values of t at which to interpolate\np_x, p_y = construct_pols(x, y, t) # find the interpolating polynomials\n\n# 3. plots the interpolating curve in the plane along with the interpolation points\nt = scipy.linspace(min(t) - .3, max(t) * 1.1) # linespace for x\nplt.plot(x, y, 's', # square points\n p_x(t), p_y(t)) # interpolating curve\nplt.xlabel(\"$x$\")\nplt.ylabel(\"$y$\")\nplt.title(\"Interpolating Curve\")\nplt.legend(['$(x_i,y_i)$', '$(x(t),y(t))=(p_x(t),p_y(t))$'], loc='best')\nplt.show()\n\n# t_spline = scipy.linspace(min(t_i), max(t_i)) # linespace for x cubic, shoots error otherwise\nx_plus2 = x + [0, -.3]\ny_plus2 = y + [2.15, 2.15]\nt_plus2 = set_t_values(x_plus2, y_plus2)\nt = scipy.linspace(min(t_plus2), max(t_plus2)) # linespace for x\np_x_plus2, p_y_plus2 = construct_pols(x_plus2, y_plus2, t_plus2)\n# spline=scipy.interpolate.interp1d(t_i, x, kind='cubic')\nspline_x_plus2 = scipy.interpolate.interp1d(t_plus2, x_plus2, kind='cubic')\nspline_y_plus2 = scipy.interpolate.interp1d(t_plus2, y_plus2, kind='cubic')\n\nwidth, height = 6, 15\n\nplt.figure(figsize=(width, height))\nplt.subplot(311)\nplt.plot(x_plus2, y_plus2, 's', # square points\n p_x_plus2(t), p_y_plus2(t),\n spline_x_plus2(t), spline_y_plus2(t))\nplt.ylabel(\"$y$\")\nplt.legend(['$(x_i,y_i)$', 'Lagrange', 'cubic'],\n bbox_to_anchor=(1, 1),\n loc='best')\nplt.title(\"Interpolation Plots\")\n\nplt.figure(figsize=(width, height))\nplt.subplot(311 + 1)\nplt.plot(x_plus2, y_plus2, 's', # square points\n p_x_plus2(t), p_y_plus2(t))\nplt.ylabel(\"$y$\")\nplt.legend(['', 'Lagrange', 'cubic'],\n bbox_to_anchor=(1, 1),\n loc='best')\n\nplt.figure(figsize=(width, height))\nplt.subplot(311 + 1 + 1)\nplt.plot(x_plus2, y_plus2, 's', # square points\n spline_x_plus2(t), spline_y_plus2(t))\nplt.xlabel(\"$x$\")\nplt.ylabel(\"$y$\")\nplt.legend(['', 'cubic'],\n bbox_to_anchor=(1, 1),\n loc='best')\nplt.tight_layout()\nplt.show()\n","sub_path":"Assignment 4/A4.py","file_name":"A4.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"345835011","text":"from django.shortcuts import render\nfrom .models import Award, Certificate, Projects, Doing, Tools\n# Create your views here.\n\n\ndef resume(request):\n def chk_img(x):\n if x.image:\n return x.image.url\n else:\n return None\n\n data = {\n \"awards\": [\n {\"date\": row.date.isoformat(), \"content\": row.content, \"image\": chk_img(row)}\n for row in Award.objects.all()\n ],\n \"certs\": [\n {\"cert\":row.cert, \"content\": row.content, \"image\": chk_img(row)}\n for row in Certificate.objects.all()\n ],\n\n \"doings\": [\n {\"content\":row.content, \"date\":row.date, \"image\":chk_img(row)}\n for row in Doing.objects.all()\n ],\n \"tools\": [row for row in Tools.objects.all()],\n\n }\n\n return render(request, 'blog/resume.html', {\"data\": data})\n\n\ndef projects(request):\n\n data = [row for row in Projects.objects.all()]\n\n return render(request, 'blog/project.html', {\"data\": data})","sub_path":"resume/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"27826673","text":"\"\"\"\nRainbow light effect unit tests\n\"\"\"\n\nimport socket\nimport threading\n\nimport pytest\n\nfrom hyperion2boblight import BoblightClient, PriorityList\n\nMY_PRIORITY_LIST = PriorityList()\n\nclass TestRainbowEffect:\n \"\"\" Raibow effect test class \"\"\"\n\n @pytest.fixture(scope='module')\n def server(self, request):\n \"\"\" Create a socket which play the server's role to get message from client \"\"\"\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server_socket.bind((\"localhost\", 19444))\n server_socket.listen(5)\n def end():\n \"\"\" Terminating function \"\"\"\n server_socket.close()\n request.addfinalizer(end)\n return server_socket\n\n @pytest.yield_fixture\n def client(self, request):\n \"\"\" Create the boblight client which will connect to our server socket \"\"\"\n my_priority_list = getattr(request.module, \"MY_PRIORITY_LIST\", None)\n my_priority_list .clear()\n client = BoblightClient(\n (\"localhost\", 19444),\n my_priority_list\n )\n\n client_thread = threading.Thread(target=client.run)\n client_thread.start()\n\n yield client\n\n my_priority_list.put(0, \"quit\")\n client_thread.join()\n\n @pytest.fixture\n def connection(self, request, server, client):\n \"\"\" Actually create server and client and connect them \"\"\"\n connection, _ = server.accept()\n # Receive the hello message\n connection.recv(1024)\n return connection\n\n def test_rainbow_effect(self, connection):\n \"\"\" Test that the rainbow effect actually display each rainbow color \"\"\"\n MY_PRIORITY_LIST.put(1, 'Rainbow')\n # Receive the priority\n connection.recv(1024)\n first_color_message = connection.recv(1024).decode()\n message = \"\"\n # Wait a full iteration of the effect\n while message.find(first_color_message) < 0:\n message = message + connection.recv(1024).decode()\n MY_PRIORITY_LIST.clear()\n # The message must contains command to light every rainbow color\n assert message.find(\"rgb %f %f %f\" % (1., 0., 0.)) != -1 # Red\n assert message.find(\"rgb %f %f %f\" % (1., 1., 0.)) != -1 # Yellow\n assert message.find(\"rgb %f %f %f\" % (0., 1., 0.)) != -1 # Green\n assert message.find(\"rgb %f %f %f\" % (0., 1., 1.)) != -1 # Turquoise\n assert message.find(\"rgb %f %f %f\" % (0., 0., 1.)) != -1 # Blue\n assert message.find(\"rgb %f %f %f\" % (1., 0., 1.)) != -1 # Purple\n\n","sub_path":"hyperion2boblight/tests/test_rainbow_effect.py","file_name":"test_rainbow_effect.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"471642409","text":"# =====================================================================\n# Course: CS219 -- Problem 1 -- Donor List\n# Filename: Problem 1__Problem 1.py\n# Author: \n# Purpose: \tProgram tht creates a multidimensional list of\n# donors and some information. Ability to edit and\n# print the data.\n# =====================================================================\n\n\ndonor_list = list()\n\n\ndef main():\n while True:\n print(\"Select an option:\")\n print(\" (A)dd a new donor\")\n print(\" (E)dit a record\")\n print(\" (L)ook up a record\")\n print(\" (Q)uit Program\")\n\n user_input = input(\"> \")\n\n if user_input == \"Q\":\n break\n elif user_input == \"A\":\n add_data()\n elif user_input == \"E\":\n edit_info()\n elif user_input == \"L\":\n look_up()\n else:\n print(\"Invalid Selection. Try again\\n\")\n\n\ndef add_data():\n # Add Data\n print(\"\\nADD INFORMATION\")\n print(\"How many records would you like to input\")\n num_records = int(input(\"> \"))\n\n while True:\n # Checks for a valid value. Must be an int greater than 0\n if num_records >= 1:\n\n # Check to see if the is any records\n list_len = len(donor_list)\n\n # Creates empty lists in donor_list = num_records\n i = 0\n while i < num_records:\n donor_list.append(list())\n i += 1\n\n j = 1\n # Checks to see if there is an empty list before the records are created\n if list_len == 0:\n while j <= num_records:\n record_num = j - 1\n print(\"\\nRecord Number:\", record_num + 1)\n donor_list[record_num].append(input(\"Name:\"))\n donor_list[record_num].append(input(\"Address:\"))\n donor_list[record_num].append(input(\"Contact:\"))\n j += 1\n else:\n while j <= num_records:\n record_num = list_len\n print(\"\\nRecord Number:\", j)\n donor_list[record_num].append(input(\"Name:\"))\n donor_list[record_num].append(input(\"Address:\"))\n donor_list[record_num].append(input(\"Contact:\"))\n\n j += 1\n list_len += 1\n\n print(\"Created\", i, \"record(s)\\n\")\n break\n elif num_records < 1:\n print(\"Must input at least 1 record\")\n else:\n print(\"Invalid value. Please Try again\")\n\n\ndef edit_info():\n # Edit info\n print(\"EDIT INFORMATION\")\n print(\"Enter the Record you wish to modify\")\n look_up()\n record_num = int(input(\"Record: \")) - 1\n\n print(\"Select which element of the record you wish to modify\")\n print(\"'0' = Name\")\n print(\"'1' = Address\")\n print(\"'2' = Contact\")\n element_num = int(input(\"Element: \"))\n\n while True:\n if element_num == 0:\n donor_list[record_num][element_num] = input(\"Name: \")\n break\n elif element_num == 1:\n donor_list[record_num][element_num] = input(\"Address: \")\n break\n elif element_num == 2:\n donor_list[record_num][element_num] = input(\"Contact: \")\n break\n else:\n print(\"Invalid Selection\")\n\n\ndef look_up():\n print(\"\\nINFO\")\n print(\n \"#\", \" \" * (2 - len(\"#\")),\n \"Name\", \" \" * (15 - len(\"Name\")),\n \"Address\", \" \" * (20 - len(\"Address\")),\n \"Contact\", \" \" * (10 - len(\"Contact\"))\n )\n j = 1\n for i in donor_list:\n if j < 10:\n record = \"0\" + str(j)\n else:\n record = str(j)\n\n print(\n record, \" \" * (2 - len(i)),\n i[0], \" \" * (15 - len(i[0])),\n i[1], \" \" * (20 - len(i[1])),\n i[2], \" \" * (10 - len(i[2])),\n )\n\n j += 1\n\n print(\"\\n\")\n\n\nmain()\n","sub_path":"Problem 1.py","file_name":"Problem 1.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"87550702","text":"from rlutilities.simulation import Car, Ball\r\nfrom rlutilities.mechanics import Aerial\r\nfrom rlutilities.linear_algebra import look_at\r\n\r\nfrom utils.vector_math import *\r\nfrom utils.math import *\r\nfrom utils.misc import *\r\n\r\n\r\nclass Intercept:\r\n def __init__(self, car: Car, ball_predictions, predicate: callable = None, backwards=False):\r\n self.ball: Ball = None\r\n self.is_viable = True\r\n\r\n #find the first reachable ball slice that also meets the predicate\r\n speed = 1000 if backwards else estimate_max_car_speed(car)\r\n # for ball in ball_predictions:\r\n for ball in ball_predictions:\r\n if estimate_time(car, ball.position, speed, -1 if backwards else 1) < ball.time - car.time \\\r\n and (predicate is None or predicate(car, ball)):\r\n self.ball = ball\r\n break\r\n\r\n #if no slice is found, use the last one\r\n if self.ball is None:\r\n if not ball_predictions:\r\n self.ball = Ball()\r\n else:\r\n self.ball = ball_predictions[-1]\r\n self.is_viable = False\r\n\r\n self.time = self.ball.time\r\n self.ground_pos = ground(self.ball.position)\r\n self.position = self.ball.position\r\n\r\nclass AerialIntercept:\r\n def __init__(self, car: Car, ball_predictions, predicate: callable = None):\r\n self.ball: Ball = None\r\n self.is_viable = True\r\n\r\n #find the first reachable ball slice that also meets the predicate\r\n test_car = Car(car)\r\n test_aerial = Aerial(car)\r\n \r\n for ball in ball_predictions:\r\n test_aerial.target = ball.position\r\n test_aerial.arrival_time = ball.time\r\n\r\n # fake our car state :D\r\n dir_to_target = ground_direction(test_car.position, test_aerial.target)\r\n test_car.velocity = dir_to_target * max(norm(test_car.velocity), 1200)\r\n test_car.orientation = look_at(dir_to_target, vec3(0,0,1))\r\n\r\n if test_aerial.is_viable() and (predicate is None or predicate(car, ball)):\r\n self.ball = ball\r\n break\r\n\r\n #if no slice is found, use the last one\r\n if self.ball is None:\r\n self.ball = ball_predictions[-1]\r\n self.is_viable = False\r\n\r\n self.time = self.ball.time\r\n self.ground_pos = ground(self.ball.position)\r\n self.position = self.ball.position\r\n","sub_path":"RLBotPack/BotimusPrime/utils/intercept.py","file_name":"intercept.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"645877029","text":"#!/usr/bin/python\n# coding:utf-8\n\n\n\"\"\"\nCreated on 2017-07-20\n\n@author: Wangchenyang\n\n@userdict: 测试Url接口\n\"\"\"\n\nimport login_Workbench\nimport htmlLogin\nimport print_Encounter\nimport history_Diagnosis\nimport history_OrderMedicines\nimport orderApply\n\n\nclass urlApi(object):\n def testcase(self):\n login_Workbench.login_workbench()\n htmlLogin.patient_info()\n htmlLogin.patient_encounter_info()\n htmlLogin.patient_scale_number()\n htmlLogin.patient_diagnosis_record()\n htmlLogin.patient_attach_number()\n print_Encounter.patient_print_encounter()\n history_Diagnosis.patient_historyDiagnosis()\n history_OrderMedicines.patient_historyOrderMedicines()\n orderApply.order_apply()\n\nif __name__ == '__main__':\n Test = urlApi()\n Test.testcase()","sub_path":"url_Api/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"466182834","text":"# -*- coding: utf-8 -*-\n\ndef count(start=0, step=1, stop=10):\n n = start\n while n <= stop:\n yield n\n n += step\n\nfor x in count(10, 2.5, 20):\n print(x)\n\n# example 1\nclass Count(object):\n def __init__(self, start=0, step=1, stop=10):\n self.n = start\n self.step = step\n self.stop = stop\n \n def __iter__(self):\n return self\n \n def __next__(self):\n n = self.n\n if n > self.stop:\n raise StopIteration()\n self.n += self.step\n return n\n\nfor x in Count(10, 2.5, 20):\n print(x)\n# example 2 \ndef generator():\n \"\"\"This example show that the statement is freeze. It is lazy\"\"\"\n print('Before 1')\n yield 1\n print('After 1')\n print('Before 2')\n yield 2\n print('After 2')\n print('Before 3')\n yield 3\n\ng = generator()\n\nprint('Got %d' % next(g))\nprint('Got %d' % next(g))\nprint('Got %d' % next(g))\n","sub_path":"_generator.py","file_name":"_generator.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36000109","text":"import pyodbc\nimport pandas as pd\nimport os\nfrom connection.connect_string import *\nfrom email_manager.quickstart import *\n\n\ndef main():\n po_number = input('Inscrire numéro de PO:')\n current_folder = os.path.dirname(os.path.abspath(__file__))\n save_path = \"%s\\\\T%s.xlsx\" % (current_folder, po_number)\n cursor = connect_to_erp()\n df = get_parts_po(cursor, po_number)\n print(df)\n save_to_excel(df, save_path)\n email_po(po_number, \"%s\\\\T%s.xlsx\" % (current_folder, po_number))\n\n\ndef get_parts_po(cursor, po_number):\n cursor.execute('SELECT * FROM P_ORDER_DTL WHERE PO={}'.format(po_number))\n column_title = ['NUMERO', 'DESCRIPTION', 'QTY']\n parts_no = []\n descriptions = []\n qantites = []\n for row in cursor:\n # print(\"%s, %s, %s\" % (row[3], row[5], int(row[6])))\n parts_no.append(row[3])\n descriptions.append(row[5])\n qantites.append(row[6])\n # print('\\n')\n return pd.DataFrame({column_title[0]: parts_no, column_title[1]: descriptions, column_title[2]: qantites})\n\n\ndef save_to_excel(df, save_path):\n writer = pd.ExcelWriter(save_path)\n df.to_excel(writer, sheet_name='sheet11', index=False)\n writer.save()\n\n\ndef connect_to_erp():\n cnxn = pyodbc.connect(connect_string())\n return cnxn.cursor()\n\n\ndef email_po(po_number, file):\n service = create_service()\n # results = service.users().labels().list(userId='me').execute()\n # labels = results.get('labels', [])\n\n # if not labels:\n # print('No labels found.')\n # else:\n # print('Labels:')\n # for label in labels:\n # print(label['name'])\n message = create_message_with_attachment('abechard@centreidnov.com',\n 'abechard@centreidnov.com',\n \"Commande PO#%s\" % po_number,\n \"Bonjour\\nVoici des pièces à produire\",\n file)\n #send_message(service, 'me', message)\n\n\nif __name__ == '__main__':\n # execute only if run as the entry point into the program\n main()\n","sub_path":"send_po_excel/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"135349655","text":"import functools\nimport json\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.files.base import ContentFile\nfrom django.db import transaction\nfrom django.db.models.fields.files import FieldFile\nfrom django.utils.translation import gettext_lazy as _\nfrom django_file_form.forms import FileFormMixin\n\nfrom hypha.apply.stream_forms.fields import MultiFileField, SingleFileField\n\nfrom ..models.payment import (\n CHANGES_REQUESTED,\n DECLINED,\n PAID,\n REQUEST_STATUS_CHOICES,\n SUBMITTED,\n UNDER_REVIEW,\n Invoice,\n PaymentReceipt,\n PaymentRequest,\n SupportingDocument,\n)\nfrom ..models.project import PacketFile\n\n\ndef filter_choices(available, choices):\n return [(k, v) for k, v in available if k in choices]\n\n\nfilter_request_choices = functools.partial(filter_choices, REQUEST_STATUS_CHOICES)\n\n\nclass ChangePaymentRequestStatusForm(forms.ModelForm):\n name_prefix = 'change_payment_request_status_form'\n\n class Meta:\n fields = ['status', 'comment', 'paid_value']\n model = PaymentRequest\n\n def __init__(self, instance, *args, **kwargs):\n super().__init__(instance=instance, *args, **kwargs)\n\n self.initial['paid_value'] = self.instance.requested_value\n\n status_field = self.fields['status']\n\n possible_status_transitions_lut = {\n CHANGES_REQUESTED: filter_request_choices([DECLINED]),\n SUBMITTED: filter_request_choices([CHANGES_REQUESTED, UNDER_REVIEW, DECLINED]),\n UNDER_REVIEW: filter_request_choices([PAID]),\n }\n status_field.choices = possible_status_transitions_lut.get(instance.status, [])\n\n if instance.status != UNDER_REVIEW:\n del self.fields['paid_value']\n\n def clean(self):\n cleaned_data = super().clean()\n status = cleaned_data['status']\n paid_value = cleaned_data.get('paid_value')\n\n if paid_value and status != PAID:\n self.add_error('paid_value', _('You can only set a value when moving to the Paid status.'))\n return cleaned_data\n\n\nclass ChangeInvoiceStatusForm(forms.ModelForm):\n name_prefix = 'change_invoice_status_form'\n\n class Meta:\n fields = ['status', 'comment', 'paid_value']\n model = Invoice\n\n def __init__(self, instance, *args, **kwargs):\n super().__init__(instance=instance, *args, **kwargs)\n\n self.initial['paid_value'] = self.instance.amount\n\n status_field = self.fields['status']\n\n possible_status_transitions_lut = {\n CHANGES_REQUESTED: filter_request_choices([DECLINED]),\n SUBMITTED: filter_request_choices([CHANGES_REQUESTED, UNDER_REVIEW, DECLINED]),\n UNDER_REVIEW: filter_request_choices([PAID]),\n }\n status_field.choices = possible_status_transitions_lut.get(instance.status, [])\n\n if instance.status != UNDER_REVIEW:\n del self.fields['paid_value']\n\n def clean(self):\n cleaned_data = super().clean()\n status = cleaned_data['status']\n paid_value = cleaned_data.get('paid_value')\n\n if paid_value and status != PAID:\n self.add_error('paid_value', _('You can only set a value when moving to the Paid status.'))\n return cleaned_data\n\n\nclass PaymentRequestBaseForm(forms.ModelForm):\n class Meta:\n fields = ['requested_value', 'invoice', 'date_from', 'date_to']\n model = PaymentRequest\n widgets = {\n 'date_from': forms.DateInput,\n 'date_to': forms.DateInput,\n }\n labels = {\n 'requested_value': _('Requested Value ({currency})').format(currency=settings.CURRENCY_SYMBOL)\n }\n\n def __init__(self, user=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['requested_value'].widget.attrs['min'] = 0\n\n def clean(self):\n cleaned_data = super().clean()\n date_from = cleaned_data['date_from']\n date_to = cleaned_data['date_to']\n\n if date_from > date_to:\n self.add_error('date_from', _('Date From must be before Date To'))\n\n return cleaned_data\n\n\nclass CreatePaymentRequestForm(FileFormMixin, PaymentRequestBaseForm):\n receipts = MultiFileField(required=False)\n\n def save(self, commit=True):\n request = super().save(commit=commit)\n\n receipts = self.cleaned_data['receipts'] or []\n\n PaymentReceipt.objects.bulk_create(\n PaymentReceipt(payment_request=request, file=receipt)\n for receipt in receipts\n )\n\n return request\n\n\nclass InvoiceBaseForm(forms.ModelForm):\n class Meta:\n fields = ['date_from', 'date_to', 'amount', 'document', 'message_for_pm']\n model = Invoice\n widgets = {\n 'date_from': forms.DateInput,\n 'date_to': forms.DateInput,\n }\n\n def __init__(self, user=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['amount'].widget.attrs['min'] = 0\n\n def clean(self):\n cleaned_data = super().clean()\n date_from = cleaned_data['date_from']\n date_to = cleaned_data['date_to']\n\n if date_from > date_to:\n self.add_error('date_from', _('Date From must be before Date To'))\n\n return cleaned_data\n\n\nclass CreateInvoiceForm(FileFormMixin, InvoiceBaseForm):\n document = SingleFileField(label='Invoice File', required=True)\n supporting_documents = MultiFileField(\n required=False,\n help_text=_('Files that are related to the invoice. They could be xls, microsoft office documents, open office documents, pdfs, txt files.')\n )\n\n field_order = ['date_from', 'date_to', 'amount', 'document', 'supporting_documents', 'message_for_pm']\n\n def save(self, commit=True):\n invoice = super().save(commit=commit)\n\n supporting_documents = self.cleaned_data['supporting_documents'] or []\n\n SupportingDocument.objects.bulk_create(\n SupportingDocument(invoice=invoice, document=document)\n for document in supporting_documents\n )\n\n return invoice\n\n\nclass EditPaymentRequestForm(FileFormMixin, PaymentRequestBaseForm):\n receipt_list = forms.ModelMultipleChoiceField(\n widget=forms.CheckboxSelectMultiple(attrs={'class': 'delete'}),\n queryset=PaymentReceipt.objects.all(),\n required=False,\n label=_('Receipts')\n )\n receipts = MultiFileField(label='', required=False)\n\n def __init__(self, user=None, instance=None, *args, **kwargs):\n super().__init__(*args, instance=instance, **kwargs)\n\n self.fields['receipt_list'].queryset = instance.receipts.all()\n\n self.fields['requested_value'].label = 'Value'\n\n @transaction.atomic\n def save(self, commit=True):\n request = super().save(commit=commit)\n\n removed_receipts = self.cleaned_data['receipt_list']\n\n removed_receipts.delete()\n\n to_add = self.cleaned_data['receipts']\n if to_add:\n PaymentReceipt.objects.bulk_create(\n PaymentReceipt(payment_request=request, file=receipt)\n for receipt in to_add\n )\n return request\n\n\nclass EditInvoiceForm(FileFormMixin, InvoiceBaseForm):\n document = SingleFileField(label=_('Invoice File'), required=True)\n supporting_documents = MultiFileField(required=False)\n\n field_order = ['date_from', 'date_to', 'amount', 'document', 'supporting_documents', 'message_for_pm']\n\n @transaction.atomic\n def save(self, commit=True):\n invoice = super().save(commit=commit)\n not_deleted_original_filenames = [\n file['name'] for file in json.loads(self.cleaned_data['supporting_documents-uploads'])\n ]\n for f in invoice.supporting_documents.all():\n if f.document.name not in not_deleted_original_filenames:\n f.document.delete()\n f.delete()\n\n for f in self.cleaned_data[\"supporting_documents\"]:\n if not isinstance(f, FieldFile):\n try:\n SupportingDocument.objects.create(invoice=invoice, document=f)\n finally:\n f.close()\n return invoice\n\n\nclass SelectDocumentForm(forms.ModelForm):\n document = forms.ChoiceField(\n label=\"Document\",\n widget=forms.Select(attrs={'id': 'from_submission'})\n )\n\n class Meta:\n model = PacketFile\n fields = ['category', 'document']\n\n def __init__(self, existing_files, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.files = existing_files\n\n choices = [(f.url, f.filename) for f in self.files]\n\n self.fields['document'].choices = choices\n\n def clean_document(self):\n file_url = self.cleaned_data['document']\n for file in self.files:\n if file.url == file_url:\n new_file = ContentFile(file.read())\n new_file.name = file.filename\n return new_file\n raise forms.ValidationError(_('File not found on submission'))\n\n @transaction.atomic()\n def save(self, *args, **kwargs):\n return super().save(*args, **kwargs)\n","sub_path":"hypha/apply/projects/forms/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":9139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"189310400","text":"import boto3\nimport json\nimport pytest\n\nfrom tempfile import NamedTemporaryFile\nfrom moto import mock_s3\nfrom mozetl.taar import taar_utils\n\nSAMPLE_DATA = {\"test\": \"data\"}\n\nFAKE_AMO_DUMP = {\n \"test-guid-0001\": {\n \"name\": {\"en-US\": \"test-amo-entry-1\"},\n \"default_locale\": \"en-US\",\n \"current_version\": {\n \"files\": [\n {\n \"status\": \"public\",\n \"platform\": \"all\",\n \"id\": 1,\n \"is_webextension\": True,\n }\n ]\n },\n \"guid\": \"test-guid-0001\",\n },\n \"test-guid-0002\": {\n \"name\": {\"en-US\": \"test-amo-entry-2\"},\n \"default_locale\": \"en-US\",\n \"current_version\": {\n \"files\": [\n {\n \"status\": \"public\",\n \"platform\": \"all\",\n \"id\": 2,\n \"is_webextension\": False,\n }\n ]\n },\n \"guid\": \"test-guid-0002\",\n },\n}\n\n\n@mock_s3\ndef test_read_from_s3():\n # Write a JSON blob\n bucket = \"test-bucket\"\n prefix = \"test-prefix/\"\n s3_json_fname = \"test.json\"\n\n conn = boto3.resource(\"s3\", region_name=\"us-west-2\")\n conn.create_bucket(\n Bucket=bucket,\n CreateBucketConfiguration={\n \"LocationConstraint\": \"us-west-2\",\n },\n )\n\n with NamedTemporaryFile(\"w\") as json_file:\n json.dump(SAMPLE_DATA, json_file)\n # Seek to the beginning of the file to allow the tested\n # function to find the file content.\n json_file.seek(0)\n # Upload the temp file to S3.\n taar_utils.write_to_s3(json_file.name, s3_json_fname, prefix, bucket)\n\n data = taar_utils.read_from_s3(s3_json_fname, prefix, bucket)\n assert data == SAMPLE_DATA\n\n\n@mock_s3\ndef test_write_to_s3():\n bucket = \"test-bucket\"\n prefix = \"test-prefix/\"\n dest_filename = \"test.json\"\n\n conn = boto3.resource(\"s3\", region_name=\"us-west-2\")\n bucket_obj = conn.create_bucket(\n Bucket=bucket,\n CreateBucketConfiguration={\n \"LocationConstraint\": \"us-west-2\",\n },\n )\n\n with NamedTemporaryFile(\"w\") as json_file:\n json.dump(SAMPLE_DATA, json_file)\n # Seek to the beginning of the file to allow the tested\n # function to find the file content.\n json_file.seek(0)\n # Upload the temp file to S3.\n taar_utils.write_to_s3(json_file.name, dest_filename, prefix, bucket)\n\n available_objects = list(bucket_obj.objects.filter(Prefix=prefix))\n assert len(available_objects) == 1\n\n # Check that our file is there.\n full_s3_name = \"{}{}\".format(prefix, dest_filename)\n keys = [o.key for o in available_objects]\n assert full_s3_name in keys\n\n stored_data = taar_utils.read_from_s3(dest_filename, prefix, bucket)\n assert SAMPLE_DATA == stored_data\n\n\n@mock_s3\ndef test_write_json_s3():\n bucket = \"test-bucket\"\n prefix = \"test-prefix/\"\n base_filename = \"test\"\n\n content = {\"it-IT\": [\"firefox@getpocket.com\"]}\n\n conn = boto3.resource(\"s3\", region_name=\"us-west-2\")\n bucket_obj = conn.create_bucket(\n Bucket=bucket,\n CreateBucketConfiguration={\n \"LocationConstraint\": \"us-west-2\",\n },\n )\n\n # Store the data in the mocked bucket.\n taar_utils.store_json_to_s3(\n json.dumps(content), base_filename, \"20171106\", prefix, bucket\n )\n\n # Get the content of the bucket.\n available_objects = list(bucket_obj.objects.filter(Prefix=prefix))\n assert len(available_objects) == 2\n\n # Get the list of keys.\n keys = [o.key for o in available_objects]\n assert \"{}{}.json\".format(prefix, base_filename) in keys\n date_filename = \"{}{}20171106.json\".format(prefix, base_filename)\n assert date_filename in keys\n\n\n@mock_s3\ndef test_load_amo_external_whitelist():\n conn = boto3.resource(\"s3\", region_name=\"us-west-2\")\n conn.create_bucket(\n Bucket=taar_utils.AMO_DUMP_BUCKET,\n CreateBucketConfiguration={\n \"LocationConstraint\": \"us-west-2\",\n },\n )\n\n # Make sure that whitelist loading fails before mocking the S3 file.\n EXCEPTION_MSG = \"Empty AMO whitelist detected\"\n with pytest.raises(RuntimeError) as excinfo:\n taar_utils.load_amo_external_whitelist()\n\n assert EXCEPTION_MSG in str(excinfo.value)\n\n # Store an empty file and verify that an exception is raised.\n conn.Object(taar_utils.AMO_DUMP_BUCKET, key=taar_utils.AMO_WHITELIST_KEY).put(\n Body=json.dumps({})\n )\n\n with pytest.raises(RuntimeError) as excinfo:\n taar_utils.load_amo_external_whitelist()\n\n assert EXCEPTION_MSG in str(excinfo.value)\n\n # Store the data in the mocked bucket.\n conn.Object(taar_utils.AMO_DUMP_BUCKET, key=taar_utils.AMO_WHITELIST_KEY).put(\n Body=json.dumps(FAKE_AMO_DUMP)\n )\n\n # Check that the web_extension item is still present\n # and the legacy addon is absent.\n whitelist = taar_utils.load_amo_external_whitelist()\n assert \"this_guid_can_not_be_in_amo\" not in whitelist\n\n # Verify that the legacy addon was removed while the\n # web_extension compatible addon is still present.\n assert \"test-guid-0001\" in whitelist\n assert \"test-guid-0002\" not in whitelist\n\n\ndef test_telemetry_hash():\n \"\"\"\n A JS snippet that will run in the Browser Toolbox is:\n\n let byteArr = new TextEncoder().encode(\"33c5c416-c57d-4eb7-bf58-beaf97a40332\")\n const CryptoHash = Components.Constructor(\"@mozilla.org/security/hash;1\",\n \"nsICryptoHash\",\n \"initWithString\");\n let hash = new CryptoHash(\"sha256\");\n hash.update(byteArr, byteArr.length);\n let clientId = CommonUtils.bytesAsHex(hash.finish(false));\n \"54e760dc799b24c6edc1a02b200db9b07d51a96b7dc7d4ebcd1d86ee8728f420\"\n \"\"\"\n\n uuid = \"33c5c416-c57d-4eb7-bf58-beaf97a40332\"\n hashed_id = taar_utils.hash_telemetry_id(uuid)\n assert (\n hashed_id == \"54e760dc799b24c6edc1a02b200db9b07d51a96b7dc7d4ebcd1d86ee8728f420\"\n )\n","sub_path":"tests/test_taar_utils.py","file_name":"test_taar_utils.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"641154290","text":"import environnement\r\nimport grille\r\n\r\n\"\"\"\r\nPetit programme de test de la classe Grille\r\n\"\"\"\r\n\r\nif __name__ == '__main__':\r\n noir = (0, 0, 0)\r\n rouge = (255, 0, 0)\r\n vert = (0, 255, 0)\r\n g = grille.Grille()\r\n p0 = environnement.Porte(vert, g)\r\n p1 = environnement.Porte(vert, g)\r\n p2 = environnement.Porte(vert, g)\r\n p3 = environnement.Porte(vert, g)\r\n v1 = environnement.Voyageur(rouge, [p0, p1], g)\r\n v2 = environnement.Voyageur(rouge, [p0, p1], g,0.5)\r\n v3 = environnement.Voyageur(rouge, [p2, p0, p3], g)\r\n listeVoyageurs = [v1, v2, v3]\r\n obs1 = environnement.Obstacle(noir, g)\r\n g.addObstacle([(0, 0), (5, 4), (5, 5), (6, 5), (9, 9), (8, 5), (9, 5), (10, 5), (11, 5)], obs1)\r\n g.addVoyageur((1, 1), v1)\r\n g.addVoyageur((2, 1), v2)\r\n g.addVoyageur((0, 9), v3)\r\n g.addPorte([(9, 3), (9, 4)], p0)\r\n g.addPorte([(7, 8), (7, 9)], p1)\r\n g.addPorte([(7, 5)], p2)\r\n g.addPorte([(11, 0)], p3)\r\n step = 0\r\n print(step)\r\n print(g)\r\n while list(filter(lambda v : v in g.getVoyageurs().values(),listeVoyageurs)) != []:\r\n step += 1\r\n g.deplacements()\r\n print(step)\r\n print(g)\r\n print(\"fini !\")","sub_path":"MouvementFoule/testGrille.py","file_name":"testGrille.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"351314723","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import TemplateView#class_based_view 汎用ビュー\n\nfrom .models import *\n\nfrom .forms import PostForm\n\n\n# Create your views here.\n\ndef index(request):\n memos = Memo.objects.all()\n params = {\n 'memos': memos\n }\n return render(request, 'index.html', params)#renderメソッドの第三引数に変数(辞書型)を入れることで、templateのhtmlファイルに使う変数を渡せる\n\n\ndef post(request):\n form = PostForm(request.POST, instance=Memo())\n if form.is_valid(): #validateで検証という英単語だから、formの内容が有効かどうかを観察するためのis_valid\n form.save() #formの保存\n else:\n print(form.errors)\n\n return redirect(to='/')\n\n","sub_path":"django_dotpro/django_app/memo_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"132264824","text":"from django.contrib import admin\nfrom .models import Car, Insurance, Tax, TechnicalCheckIn, Service\n\n\nclass CarAdmin(admin.ModelAdmin):\n list_display = ['name',\n 'firm',\n 'power',\n 'cylinder',\n 'fuel_consumption',\n 'fuel_type',\n 'registration_number',\n 'chassis']\n\n\nadmin.site.register(Car, CarAdmin)\n\n\nclass InsuranceAdmin(admin.ModelAdmin):\n list_display = ['insurance_company',\n 'vehicle',\n 'policy_number',\n 'activation_date',\n 'expiration_date',\n 'prime']\n\n\nadmin.site.register(Insurance, InsuranceAdmin)\n\n\nclass TaxAdmin(admin.ModelAdmin):\n list_display = ['vehicle',\n 'tax_amount',\n 'date_of_tax_payment',\n 'next_due_date',]\n\n\nadmin.site.register(Tax, TaxAdmin)\n\n\nclass TechnicalCheckInAdmin(admin.ModelAdmin):\n list_display = ['vehicle',\n 'check_in_number',\n 'comment',\n 'date_of_checkIn',\n 'date_of_next_checkIn',\n 'cost_of_checkIn']\n\n\nadmin.site.register(TechnicalCheckIn, TechnicalCheckInAdmin)\n\n\nclass ServiceAdmin(admin.ModelAdmin):\n list_display = ['vehicle',\n 'service_supplier',\n 'order_id',\n 'category',\n 'date_of_service',\n 'next_date',\n 'cost_of_service',\n 'cost_of_parts']\n\n\nadmin.site.register(Service, ServiceAdmin)\n\n\n\n\n","sub_path":"fleet/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"240407851","text":"# Website we want to scrape is: https://www.verizonwireless.com/smartphones/samsung-galaxy-s7/\n# The documentatio of selenium is here: http://selenium-python.readthedocs.io/index.html\n\n# Please follow the instructions below to setup the environment of selenium\n# Step #1\n# Windows users: download the chromedriver from here: https://chromedriver.storage.googleapis.com/index.html?path=2.30/\n# Mac users: Install homebrew: http://brew.sh/\n#\t\t\t Then run 'brew install chromedriver' on the terminal\n#\n# Step #2\n# Windows users: open Anaconda prompt and switch to python3 environment. Then run 'conda install -c conda-forge selenium'\n# Mac users: open Terminal and switch to python3 environment. Then run 'conda install selenium'\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import Select\nimport time\nimport csv\n\n# Windows users need to specify the path to chrome driver you just downloaded.\n# driver = webdriver.Chrome('path\\to\\where\\you\\download\\the\\chromedriver')\n\ndriver = webdriver.Chrome()\n# input the search condition\nsearch1 = \"(((cancer[Title/Abstract]) AND \\\"journal article\\\"[Publication Type]) AND \\\n(\\\"2000\\\"[Date - Publication] : \\\"3000\\\"[Date - Publication])) AND mutation[Title/Abstract]\"\n\nsearch2 = \"((cancer[Title/Abstract] AND gene[Title/Abstract] AND mutation[Title/Abstract]) AND \\\n(\\\"2000\\\"[Date - Publication] : \\\"3000\\\"[Date - Publication]))\" \n\n# add to the search engineer\nurl = \"https://www.ncbi.nlm.nih.gov/pubmed/?term=\" + search2\ndriver.get(url)\n\n# driver.find_elements_by_xpath(\".//input[@type='radio' and @value='SRF']\")[0].click\ncsv_file = open('pubmed.csv', 'w')\nwriter = csv.writer(csv_file)\nwriter.writerow(['pmid', 'title', 'author', 'journal', 'form'])\n# need to add abstract and key word before scraping the pages\n\n# Page index used to keep track of where we are.\nindex = 1\nwhile index < 3: # True\n\ttry:\n\t\tprint(\"Scraping Page number \" + str(index))\n\t\tindex = index + 1\n\t\t# Find the device name\n\t\t# Check the documentation here: http://selenium-python.readthedocs.io/locating-elements.html\n\n\t\t# Find all the reviews. The find_elements function will return a list of selenium select elements.\n\t\treviews = driver.find_elements_by_xpath('//*[@class=\"rprt\"]')\n\n\t\tprint('=' * 50)\n\t\tprint(len(reviews))\n\t\tprint(reviews[0])\n\t\tprint('=' * 50)\n\n\n\n\t\t# To test the xpath, you can comment out the following code in the try statement and print the length of reviews.\n\t\t# Iterate through the list and find the details of each review.\n\t\tfor review in reviews:\n\t\t\t# Initialize an empty dictionary for each review\n\t\t\treview_dict = {}\n\t\t\t\n\t\t\t# Use Xpath to locate the title, content, username, date.\n\t\t\t# Once you locate the element, you can use 'element.text' to return its string.\n\t\t\t# To get the attribute instead of the text of each element, use 'element.get_attribute()'\n\n\n\t\t\t#title = review.find_element_by_xpath('.//div[@class=\"bv-content-title-container\"]//h4').text\n\n\t\t\tpmid = review.find_element_by_xpath('.//*[@class=\"rprtid\"]/dd').text\n\t\t\ttitle = review.find_element_by_xpath('.//*[@class=\"title\"]/a').text\n\t\t\tauthor = review.find_element_by_xpath('.//*[@class=\"desc\"]').text\n\t\t\tjournal = review.find_element_by_xpath('.//*[@class=\"details\"]/span').text\n\t\t\tform = review.find_element_by_xpath('.//*[@class=\"details\"]/span').get_attribute(\"class\")\n\t\t\tlink = 'https://www.ncbi.nlm.nih.gov/pubmed/' + pmid\n\n\t\t\treview_dict['pmid'] = pmid\n\t\t\treview_dict['title'] = title\t\n\t\t\treview_dict['author'] = author\t\n\t\t\treview_dict['journal'] = journal\t\n\t\t\treview_dict['form'] = form\n\t\t\treview_dict['link'] = link\n\n\t\t\twriter.writerow(review_dict.values())\t\n\t\t\t\n\n\t\t\t# Your code here\n\n\t\t# Locate the next button on the page. Then call 'button.click()' to really click it.\n\t\tbutton = driver.find_element_by_xpath('.//*[@class=\"active page_link next\"]')\n\t\tbutton.click()\n\t\ttime.sleep(10)\n\n\n\n\texcept Exception as e:\n\t\tprint(e)\n\t\tdriver.close()\n\t\tbreak\n","sub_path":"data_selenium/pubmed/pubmed_final_title.py","file_name":"pubmed_final_title.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"29419703","text":"# coding: utf-8\ndef get_generic_list_view():\n return [\n {\n 'field_label': u'UUID',\n 'field_name': 'uuid',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Last update:',\n 'field_name': 'updated_at',\n 'field_type': 'date_time'\n },\n {\n 'field_label': u'Deleted?',\n 'field_name': 'is_deleted',\n 'field_type': 'boolean'\n },\n {\n 'field_label': u'Process completed?',\n 'field_name': 'process_completed',\n 'field_type': 'boolean'\n },\n {\n 'field_label': u'Must reprocess?',\n 'field_name': 'must_reprocess',\n 'field_type': 'boolean'\n },\n ]\n\n\ndef get_log_columns_list_view():\n return [\n {\n 'field_label': u'Timestamp',\n 'field_name': 'time',\n 'field_type': 'date_time'\n },\n {\n 'field_label': u'Name',\n 'field_name': 'name',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Function',\n 'field_name': 'funcName',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Message',\n 'field_name': 'message',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Line',\n 'field_name': 'lineno',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Level',\n 'field_name': 'levelname',\n 'field_type': 'string'\n },\n ]\n\n\ndef get_log_filters_list_view():\n return [\n {\n 'field_label': u'Timestamp',\n 'field_name': 'time',\n 'field_type': 'date_time'\n },\n {\n 'field_label': u'Name',\n 'field_name': 'name',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Function',\n 'field_name': 'funcName',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Message',\n 'field_name': 'message',\n 'field_type': 'string'\n },\n {\n 'field_label': u'Level',\n 'field_name': 'levelname',\n 'field_type': 'choices',\n 'field_options': (\n ('DEBUG', 'DEBUG'),\n ('INFO', 'INFO'),\n ('WARNING', 'WARNING'),\n ('ERROR', 'ERROR'),\n ('CRITICAL', 'CRITICAL'),\n )\n },\n ]\n\n\ndef get_collection_list_view():\n list = get_generic_list_view()\n\n list.insert(1, {\n 'field_label': u'Acrônimo',\n 'field_name': 'acronym',\n 'field_type': 'string'\n })\n\n list.insert(2, {\n 'field_label': u'Nome',\n 'field_name': 'name',\n 'field_type': 'string'\n })\n return list\n\n\ndef get_journal_list_view():\n list = get_generic_list_view()\n\n list.insert(1, {\n 'field_label': u'ISSN',\n 'field_name': 'code',\n 'field_type': 'string'\n })\n return list\n\n\ndef get_issue_list_view():\n list = get_generic_list_view()\n\n list.insert(1, {\n 'field_label': u'PID',\n 'field_name': 'code',\n 'field_type': 'string'\n })\n return list\n\n\ndef get_article_list_view():\n list = get_generic_list_view()\n\n list.insert(1, {\n 'field_label': u'PID',\n 'field_name': 'code',\n 'field_type': 'string'\n })\n return list\n\n\ndef get_press_release_list_view():\n return get_generic_list_view()\n","sub_path":"opac_proc/web/helpers/list_generator.py","file_name":"list_generator.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"500037181","text":"\"\"\"Product class.\"\"\"\n\n\nclass Product:\n def __init__(self, name=\"\", price=0.0, is_on_sale=False):\n self.name = name\n self.price = price\n self.is_on_sale = is_on_sale\n\n def __str__(self):\n on_sale_string = \"\"\n if self.is_on_sale:\n on_sale_string = \" (on sale!)\"\n return \"{} ${:.2f}{}\".format(self.name, self.price, on_sale_string)\n\n def __repr__(self):\n return str(self)\n\n\nif __name__ == '__main__':\n print(\"I'm in product.py\")\n products = [Product(\"Phone\", 340, False), Product(\"PC\", 1420.95, True), Product(\"Plant\", 24.5, True)]\n on_sale_products = [product for product in products if product.is_on_sale]\n print(on_sale_products)\n","sub_path":"week_067/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"593033067","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.forms import (\n TextInput,\n CharField,\n HiddenInput,\n Textarea)\n\nfrom django.core.exceptions import ValidationError\n\nfrom availableworks.core.forms import AWBaseModelForm\nfrom availableworks.core.widgets import CustomSelectWidget\nfrom availableworks.core.models.work import Work\n\n\nclass AccountAddWorkForm(AWBaseModelForm):\n\n class Meta:\n model = Work\n\n fields = (\n 'owner',\n 'title',\n 'original_artist',\n 'primary_category',\n 'secondary_category',\n 'width',\n 'length',\n 'depth',\n 'weight',\n 'signed',\n 'year_created',\n 'total_stock',\n 'price',\n 'description',\n 'shipping_area',\n 'handling_time',\n 'domestic_shipping_cost_est',\n 'intl_shipping_cost_est',\n 'is_retrievable')\n\n labels = {\n 'primary_category': 'Primary Medium',\n 'total_stock': 'Quantity You\\'ll Sell',\n 'is_retrievable': 'Buyer(s) Can Pick Up',\n 'price': 'Item Price (USD)'}\n\n help_texts = {\n 'title': '150 characters left',\n 'original_artist': '80 characters left',\n 'secondary_category': 'Optional 2nd Medium',\n 'width': 'Width',\n 'length': 'Length',\n 'depth': 'Depth',\n 'year_created': 'Example: 2004',\n 'total_stock': 'Example: 3, must be 1 or greater.',\n 'price': 'Example: 45.00 (include cents)',\n 'description': '300 characters remaining',\n 'shipping_area': 'Where will you send it?',\n 'handling_time': 'Handling time needed?',\n 'domestic_shipping_cost_est': 'Domestic',\n 'intl_shipping_cost_est': 'International',\n 'is_retrievable': 'If marked \"Yes\", you will need to message the buyer your address.'}\n\n widgets = {\n 'owner': HiddenInput,\n 'primary_category': CustomSelectWidget,\n 'secondary_category': CustomSelectWidget,\n 'width': TextInput,\n 'length': TextInput,\n 'depth': TextInput,\n 'weight': TextInput,\n 'signed': CustomSelectWidget,\n 'year_created': TextInput,\n 'total_stock': TextInput,\n 'price': TextInput,\n 'shipping_area': CustomSelectWidget,\n 'handling_time': CustomSelectWidget,\n 'domestic_shipping_cost_est': TextInput,\n 'intl_shipping_cost_est': TextInput,\n 'is_retrievable': CustomSelectWidget}\n\n def clean(self):\n cleaned = super(AWBaseModelForm, self).clean()\n\n if cleaned['shipping_area'] == Work.SHIPPING_AREA_GLOBAL:\n if not cleaned['intl_shipping_cost_est']:\n self._errors['intl_shipping_cost_est'] = self.error_class(['Required outside US.'])\n\n return cleaned\n\nclass AccountEditWorkForm(AccountAddWorkForm):\n pass\n","sub_path":"availableworks/account/forms/works.py","file_name":"works.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"649985842","text":"from registers import *\nfrom config import DEFAULT_CONFIG, DEFAULT_PA_TABLE\nfrom time import sleep\nfrom packets import AckPacket\nfrom packets import CounterPacket\nimport time\n\nSTATE_MASK = 0b01110000\nCHIP_RDY_MASK = 0b10000000\nFIFO_MASK = 0b00001111\n\nclass State(Enum):\n IDLE = 0b0000000\n RX = 0b0010000\n TX = 0b0100000\n FSTXON = 0b0110000\n CALIBRATE = 0b1000000\n SETTLING = 0b1010000\n RXFIFO_OVERFLOW = 0b1100000\n TXFIFO_UNDERFLOW = 0b1110000\n\nclass StatusByte(object):\n def __init__(self, status_byte):\n self.chip_ready = not (status_byte & CHIP_RDY_MASK == 0b10000000)\n self.state = State(status_byte & STATE_MASK)\n self.fifo = status_byte & FIFO_MASK\n\n def __str__(self):\n s = \"\"\n if (not self.chip_ready):\n s = \"CHIP NOT READY, \"\n s = s + \"State:\" + self.state.name\n s = s + \" Nr byte: >= \" + str(self.fifo)\n return s\n\ndef wreg(spi, reg: Register , val: int) -> StatusByte:\n \"\"\"\n Write via ``spi'' interface the value ``val'' into register with address ``reg''.\n\n Parameters\n ----------\n spi : spi object\n reg : register address\n val : value\n\n Returns\n -------\n out : state\n \"\"\"\n return StatusByte(spi.xfer2([reg.value, val])[-1])\n\ndef rreg(spi, reg: Register):\n \"\"\"\n Read register with address ``reg'' via ``spi'' interface.\n\n Parameters\n ----------\n spi : spi object\n reg: register address\n\n Returns\n -------\n out : register value\n\n \"\"\"\n # First byte contains the status byte while the second the register value\n # ([1]).\n return spi.xfer2([reg.value + Offset.READ_SINGLE.value, 0])[1]\n\ndef init(spi, cfg=DEFAULT_CONFIG, pa=DEFAULT_PA_TABLE) -> StatusByte:\n _ = reset(spi)\n _ = config(spi, cfg, pa)\n _ = flush_rx(spi)\n _ = flush_tx(spi)\n return status(spi)\n\ndef reset(spi) -> StatusByte:\n return StatusByte(spi.xfer2([Strobe.SRES.value])[0])\n\ndef config(spi, cfg=DEFAULT_CONFIG, pa=DEFAULT_PA_TABLE) -> StatusByte:\n _ = config_regs(spi)\n _ = config_pa_table(spi)\n return status(spi)\n\n\n\n\n\ndef config_regs(spi, cfg=DEFAULT_CONFIG) -> StatusByte:\n return StatusByte(spi.xfer2([x for k, v in cfg.items() for x in [k.value, v]])[-1])\n\ndef config_pa_table(spi, pa=DEFAULT_PA_TABLE) -> StatusByte:\n return StatusByte(spi.xfer2([Special.PATABLE.value + Offset.WRITE_BURST.value]\n + pa)[-1])\n\ndef status(spi) -> StatusByte:\n return StatusByte(spi.xfer2([Strobe.SNOP.value\n + Offset.READ_SINGLE.value])[0])\n\n\ndef status_tx(spi) -> StatusByte:\n return StatusByte(spi.xfer2([Strobe.SNOP.value + Offset.WRITE_SINGLE.value])[0])\n################################################################################\n# Strobe\n\ndef send_strobe(spi, cmd: Command) -> StatusByte:\n return StatusByte(spi.xfer2([cmd.value])[0])\n\ndef set_rx(spi) -> StatusByte:\n return send_strobe(spi, Strobe.SRX)\n\ndef set_tx(spi) -> StatusByte:\n return send_strobe(spi, Strobe.STX)\n\ndef set_idle(spi) -> StatusByte:\n return send_strobe(spi, Strobe.SIDLE)\n\ndef flush_rx(spi) -> StatusByte:\n return send_strobe(spi, Strobe.SFRX)\n\ndef flush_tx(spi) -> StatusByte:\n return send_strobe(spi, Strobe.SFTX)\n\ndef isRX(spi) -> bool:\n return status(spi).state == State.RX\n\ndef isTX(spi) -> bool:\n return status(spi).state == State.TX\n\ndef rssi(spi) -> int:\n rssi = rreg(spi, Status.RSSI)\n if (rssi >= 128):\n rssi = rssi - 256\n return rssi // 2 - 70\n\ndef enter_rx_mode(spi):\n while not isRX(spi):\n set_rx(spi)\n\ndef enter_tx_mode(spi):\n while not isTX(spi):\n set_tx(spi)\n\n\ndef tx_fifo_byte_count(spi):\n return spi.xfer2([0xFA, 0x00])[-1] \n\ndef rx_fifo_byte_count(spi):\n return spi.xfer2([0xFB, 0x00])[-1]\n\n\n###########################################################################\n# Transmission and reception.\n\ndef tx_data2fifo(spi, data):\n #map(lambda x: spi.xfer2([Special.FIFO.value, x]) ,data)\n return StatusByte(spi.xfer2([Special.FIFO.value\n + Offset.WRITE_BURST.value]\n + data)[-1])\n\n\n\n\ndef set_inf_pkt_mode(spi):\n pktctrl0_setting = rreg(spi, Config.PKTCTRL0)\n wreg(spi, Config.PKTCTRL0, ((pktctrl0_setting & 0xFC) | 0x02))\n #wreg(spi, Config.PKTCTRL0, 0x04)\n wreg(spi, Config.PKTCTRL1, 0x04)\n \ndef set_fix_pkt_mode(spi):\n pktctrl0_setting = rreg(spi, Config.PKTCTRL0)\n wreg(spi, Config.PKTCTRL0, (pktctrl0_setting & 0xFC))\n \n\ndef set_pkt_len(spi, length):\n wreg(spi, Config.PKTLEN, length)\n\n\n\n\ndef tx_sync_infinite(spi, pkt) -> bool: \n pkt_size = len(pkt) \n print(\"pkt size:\", pkt_size)\n print(\"mod:\", pkt_size % 256)\n\n flush_tx(spi);\n set_inf_pkt_mode(spi)\n set_pkt_len(spi, pkt_size % 256)\n \n \n \n bytes_sent = 0\n\n\n while len(pkt) > 255:\n while tx_fifo_byte_count(spi) > 2:\n sleep(0.0001)\n\n tx_data2fifo(spi, pkt[:30])\n \n enter_tx_mode(spi)\n \n pkt = pkt[30:] \n bytes_sent += 30\n while tx_fifo_byte_count(spi) > 2:\n sleep(0.0001)\n wreg(spi, Config.PKTCTRL0, 0x00)\n\n while len(pkt):\n while tx_fifo_byte_count(spi) > 2:\n sleep(0.0001)\n\n tx_data2fifo(spi, pkt[:30])\n pkt = pkt[30:]\n enter_tx_mode(spi)\n bytes_sent += len(pkt)\n \n while isTX(spi):\n sleep(0.0001)\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\ndef tx_sync(spi, gpio, pin, data) -> bool:\n wreg(spi, Config.PKTCTRL0, 0x05)\n wreg(spi, Config.PKTCTRL1, 0x08)\n\n t_poll = .001\n _ = set_idle(spi)\n _ = flush_tx(spi)\n sleep(.1)\n _ = tx_data2fifo(spi, data)\n enter_tx_mode(spi)\n\n # Wait for SYNC signal\n while gpio.input(pin) == 0:\n sleep(t_poll)\n while gpio.input(pin):\n sleep(t_poll)\n print(\"TRANSMITTED!\")\n return status(spi)\n\n\ndef rx_sync_counter(spi, gpio, pin, time_threshold):\n wreg(spi, Config.PKTCTRL0, 0x05)\n wreg(spi, Config.PKTCTRL1, 0x08)\n return rx_sync(spi, gpio, pin, CounterPacket.LENGTH.value, time_threshold)\n\ndef rx_sync_ack(spi, gpio, pin, time_threshold):\n wreg(spi, Config.PKTCTRL0, 0x05)\n wreg(spi, Config.PKTCTRL1, 0x08)\n return rx_sync(spi, gpio, pin, AckPacket.LENGTH.value, time_threshold)\n\ndef rx_fifo2data(spi, n):\n return spi.xfer2([Special.FIFO.value + Offset.READ_BURST.value] + ([0] * (n)))\n\ndef rx_sync_infinite(spi, gpio, pin, time_threshold):\n payload = []\n passed_time = 0\n set_inf_pkt_mode(spi)\n enter_rx_mode(spi)\n while gpio.input(pin) == 0:\n sleep(.001)\n passed_time += .001\n if passed_time >= time_threshold:\n print(\"timeout\")\n set_idle(spi)\n return -1\n while rx_fifo_byte_count(spi) > 4:\n sleep(0.0005)\n\n payload_len = rxfifo2data(spi, 2)\n address = rxfifo2data(spi, 1)\n pkt_type = rxfifo2data(spi, 1)\n\n bytes_left = payload_len\n \n set_pkt_len(spi, (payload_len + 4) % 256)\n\n while bytes_left > 255:\n while rx_fifo_byte_count() < 30:\n sleep(0.0005)\n\n rx_bytes_avail = rx_fifo_byte_count() - 1\n payload += rxfifo2data(spi, rx_bytes_avail)\n bytes_left -= rx_bytes_avail\n\n\n \n set_fix_pkt_mode(spi)\n \n while (bytes_left > 30):\n while rx_fifo_byte_count() < 30:\n sleep(0.0005)\n \n rx_bytes_avail = rx_fifo_byte_count() - 1\n payload += rxfifo2data(spi, rx_bytes_avail)\n bytes_left -= rx_bytes_avail\n\n while rx_fifo_byte_count() < bytes_left:\n sleep(0.0005)\n\n\n payload += rxfifo2data(spi, bytes_left)\n\n while rx_fifo_byte_count() < 2:\n sleep(0.0005)\n\n \n status_byte1 = rxfifo2data(spi, 1)\n status_byte2 = rxfifo2data(spi, 1)\n\n while(1):\n print(\"Done!\")\n sleep(1)\n\n\n\n\n\ndef rx_sync(spi, gpio, pin, n, time_threshold):\n passed_time = 0 \n enter_rx_mode(spi)\n while gpio.input(pin) == 0:\n sleep(.001)\n passed_time += .001\n if passed_time >= time_threshold:\n print(\"timeout\")\n _ = set_idle(spi)\n _ = flush_rx(spi)\n return -1\n \n while gpio.input(pin) != 0:\n sleep(.001)\n \n if rx_fifo_byte_count(spi) == 0: #CRC check failed\n #print(\"crc failed!\")\n return -1\n data = rx_fifo2data(spi, n)\n while isRX(spi):\n sleep(0.001)\n _ = set_idle(spi)\n _ = flush_rx(spi)\n return data[1:]\n\n","sub_path":"edge/cc2500/cc2500.py","file_name":"cc2500.py","file_ext":"py","file_size_in_byte":8448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"17894312","text":"import logging\nfrom smtplib import SMTPException\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.core.mail import send_mail\nfrom django.http import HttpRequest\nfrom django.urls import reverse\n\nfrom voseq.celery import app\n\nlog = logging.getLogger(__name__)\n\n\n@app.task\ndef log_email_error(\n request: HttpRequest, exc: str, traceback: str, task_id: str\n) -> None:\n log.error(\n f\"log_email_error\\n--\\n\\nrequest {request} \\n\\nexc {exc}\"\n f\"\\n\\ntraceback {traceback}\"\n )\n\n\n@app.task\ndef notify_user(dataset_obj_id, user_id) -> None:\n \"\"\"Send an email notification to user\n\n If the gui_user is specified, we will send the notification to the person\n that is doing actions via the GUI. Otherwise, we will notify the user that\n created the ContactJob.\n \"\"\"\n user = User.objects.get(id=user_id)\n log.debug(f\"notify_user {dataset_obj_id}\")\n\n subject = f\"Dataset creation completed - {dataset_obj_id}\"\n relative_url = reverse('create_dataset.results', args=(dataset_obj_id,))\n result_url = \"http://voseq.com\" + relative_url\n content = \"Your dataset has successfully completed. \" \\\n \"Please verify and download the results from: \" \\\n f\"{result_url}\"\n from_email = 'noreply@voseq.com'\n\n if user and user.email:\n to_emails = [user.email] + [email for name, email in settings.ADMINS]\n try:\n send_mail(subject, content, from_email, to_emails)\n except SMTPException:\n log.exception(\"Failed to notify_user for dataset \" + str(dataset_obj_id))\n else:\n log.debug(\"sent dataset status email to \" + str(to_emails))\n else:\n log.debug('Cannot send notification email. '\n 'No user / email assigned to job ' + str(dataset_obj_id))","sub_path":"public_interface/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"538676465","text":"import sphero\nfrom time import sleep\n\nourSphero = sphero.Sphero()\nourSphero.connect()\nsleep(0.5)\nourSphero.set_rgb(0,0,0)\n\nheading = 0\ncolor = [255,0,0]\n\ndef switchcolor(color):\n return [color[2],color[0],color[1]]\n\ndef switchheading(heading):\n heading += 90\n return heading % 360\n\nfor i in range(1,10):\n ourSphero.roll(50,heading,10)\n for j in range(1,3):\n sleep(1)\n ourSphero.set_rgb(color[0],color[1],color[2])\n color = switchcolor(color)\n heading = switchheading(heading)","sub_path":"firstSpheroApp.py","file_name":"firstSpheroApp.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"345649994","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport locale\nos.environ[\"PYTHONIOENCODING\"] = \"utf-8\"\n# myLocale=locale.setlocale(category=locale.LC_ALL, locale=\"en_GB.UTF-8\")\nimport sys\nimport time\nimport torch\nprint('Checking CUDA status:')\nprint(torch.cuda.is_available())\nif torch.cuda.is_available():\n\tprint(torch.cuda.current_device())\n\tprint(torch.cuda.device(0))\n\tprint(torch.cuda.device_count())\n\tprint(torch.cuda.get_device_name(0))\n\nimport numpy as np\nfrom reader import dataset_str\nfrom config import config\nimport csv\nconfig=config()\nimport os \n# os.environ['CUDA_VISIBLE_DEVICES']=config.GPU\nnp.random.seed(config.seed)\n\nfrom utils import choose_action, similarity, similarity_batch, normalize, sample_from_candidate, just_acc, \\\n\tget_sample_positions, mask_sentence, generate_candidate_input_with_mask, MASK_IDX, PAD_IDX, bert_scorer, \\\n\tgpt2_scorer, tokenizer, ConstraintSearch, penalty_constraint, get_sentiment_score, \\\n\tget_batch_sentiment_scores, reverse_label\n\ndef_sent_scorer = bert_scorer.sent_score\nsentiment = 'positive'\n\ndef main():\n\tif os.path.exists(config.use_output_path):\n\t\tos.system('rm ' + config.use_output_path)\n\twith open(config.use_output_path, 'a') as g:\n\t\tg.write(str(config) + '\\n\\n')\n\t# for item in config.record_time:\n\t# \tif os.path.exists(config.use_output_path + str(item)):\n\t# \t\tos.system('rm ' + config.use_output_path + str(item))\n\t#CGMH sampling for paraphrase\n\tsim=config.sim\n\t# sta_vec=list(np.zeros([config.num_steps-1]))\n\tconfig.shuffle=False\n\t#original sentence input\n\tuse_data = dataset_str(config.use_data_path)\n\tconfig.batch_size=1\n\tstep_size = config.step_size\n\n\tstart_time = time.time()\n\tproposal_cnt = 0\n\taccept_cnt = 0\n\tall_samples = []\n\tall_acc_samples = []\n\tall_chosen_samples = []\n\tfor sen_id in range(use_data.length):\n\t\tsent_ids = use_data.token_ids[sen_id]\n\t\tkeys = use_data.keys[sen_id]\n\t\tsearcher = ConstraintSearch(keys)\n\t\tsequence_length = len(sent_ids)\n\t\t#generate for each sentence\n\t\tsta_vec = np.zeros(sequence_length)\n\t\tinput_ids = np.array(sent_ids)\n\t\tinput_original = use_data.tokens[sen_id]\n\t\tprev_inds = []\n\t\told_prob = def_sent_scorer(tokenizer.decode(input_ids))\n\t\told_prob *= penalty_constraint(searcher.count_unsafisfied_constraint(searcher.sent2tag(input_ids)))\n\t\tif config.mode == 'sentiment':\n\t\t\told_prob *= get_sentiment_score(input_ids, sentiment)\n\t\tif sim != None:\n\t\t\told_prob *= similarity(input_ids, input_original, sta_vec)\n\n\t\toutputs = []\n\t\toutput_p = []\n\t\tfor iter in range(config.sample_time):\n\t\t\t# if iter in config.record_time:\n\t\t\t# \twith open(config.use_output_path, 'a', encoding='utf-8') as g:\n\t\t\t# \t\tg.write(bert_scorer.tokenizer.decode(input_ids)+'\\n')\n\t\t\t# print(bert_scorer.tokenizer.decode(input_ids).encode('utf8', errors='ignore'))\n\t\t\tpos_set = get_sample_positions(sequence_length, prev_inds, step_size)\n\t\t\taction_set = [choose_action(config.action_prob) for i in range(len(pos_set))]\n\t\t\t# if not check_constraint(input_ids):\n\t\t\t# \tif 0 not in pos_set:\n\t\t\t# \t\tpos_set[-1] = 0\n\t\t\tkeep_non = config.keep_non\n\t\t\tmasked_sent, adjusted_pos_set = mask_sentence(input_ids, pos_set, action_set)\n\t\t\tprev_inds = pos_set\n\n\t\t\tproposal_prob = 1.0 # Q(x'|x)\n\t\t\tproposal_prob_reverse = 1.0 # Q(x|x')\n\t\t\tinput_ids_tmp = np.array(masked_sent) # copy\n\t\t\tsequence_length_tmp = sequence_length\n\n\t\t\tfor step_i in range(len(pos_set)):\n\n\t\t\t\tind = adjusted_pos_set[step_i]\n\t\t\t\tind_old = pos_set[step_i]\n\t\t\t\taction = action_set[step_i]\n\t\t\t\tif config.restrict_constr:\n\t\t\t\t\tif step_i == len(pos_set) - 1:\n\t\t\t\t\t\tuse_constr = True\n\t\t\t\t\telse:\n\t\t\t\t\t\tuse_constr = False\n\t\t\t\telse:\n\t\t\t\t\tuse_constr = True\n\t\t\t\t#word replacement (action: 0)\n\t\t\t\tif action==0:\n\t\t\t\t\tprob_mask = bert_scorer.mask_score(input_ids_tmp, ind, mode=0)\n\t\t\t\t\tinput_candidate, prob_candidate, reverse_candidate_idx, _ = \\\n\t\t\t\t\t\tgenerate_candidate_input_with_mask(input_ids_tmp, sequence_length_tmp, ind, prob_mask, config.search_size,\n\t\t\t\t\t\t old_tok=input_ids[ind_old], mode=action)\n\t\t\t\t\tif sim is not None and use_constr:\n\t\t\t\t\t\tsimilarity_candidate=similarity_batch(input_candidate, input_original,sta_vec)\n\t\t\t\t\t\tprob_candidate=prob_candidate*similarity_candidate\n\t\t\t\t\tprob_candidate_norm=normalize(prob_candidate)\n\t\t\t\t\tprob_candidate_ind=sample_from_candidate(prob_candidate_norm)\n\t\t\t\t\tinput_ids_tmp = input_candidate[prob_candidate_ind] # changed\n\t\t\t\t\tproposal_prob *= prob_candidate_norm[prob_candidate_ind] # Q(x'|x)\n\t\t\t\t\tproposal_prob_reverse *= prob_candidate_norm[reverse_candidate_idx] # Q(x|x')\n\t\t\t\t\tsequence_length_tmp += 0\n\t\t\t\t\tprint('action:0', prob_candidate_norm[prob_candidate_ind], prob_candidate_norm[reverse_candidate_idx])\n\n\t\t\t\t#word insertion(action:1)\n\t\t\t\tif action==1:\n\t\t\t\t\tprob_mask = bert_scorer.mask_score(input_ids_tmp, ind, mode=0)\n\n\t\t\t\t\tinput_candidate, prob_candidate, reverse_candidate_idx, non_idx = \\\n\t\t\t\t\t\tgenerate_candidate_input_with_mask(input_ids_tmp, sequence_length_tmp, ind, prob_mask, config.search_size,\n\t\t\t\t\t\t mode=action, old_tok=input_ids[ind_old], keep_non=keep_non)\n\n\t\t\t\t\tif sim is not None and use_constr:\n\t\t\t\t\t\tsimilarity_candidate=similarity_batch(input_candidate, input_original,sta_vec)\n\t\t\t\t\t\tprob_candidate=prob_candidate*similarity_candidate\n\t\t\t\t\tprob_candidate_norm=normalize(prob_candidate)\n\t\t\t\t\tprob_candidate_ind=sample_from_candidate(prob_candidate_norm)\n\t\t\t\t\tinput_ids_tmp = input_candidate[prob_candidate_ind]\n\t\t\t\t\tif prob_candidate_ind == non_idx:\n\t\t\t\t\t\tif input_ids_tmp[-1] == PAD_IDX:\n\t\t\t\t\t\t\tinput_ids_tmp = input_ids_tmp[:-1]\n\t\t\t\t\t\tprint('action:1 insert non', 1.0, 1.0)\n\t\t\t\t\telse:\n\t\t\t\t\t\tproposal_prob *= prob_candidate_norm[prob_candidate_ind] # Q(x'|x)\n\t\t\t\t\t\tproposal_prob_reverse *= 1.0 # Q(x|x'), reverse action is deleting\n\t\t\t\t\t\tsequence_length_tmp += 1\n\t\t\t\t\t\tprint('action:1', prob_candidate_norm[prob_candidate_ind], 1.0)\n\n\t\t\t\t#word deletion(action: 2)\n\t\t\t\tif action==2:\n\t\t\t\t\tinput_ids_for_del = np.concatenate([input_ids_tmp[:ind], [MASK_IDX], input_ids_tmp[ind:]])\n\t\t\t\t\tif keep_non:\n\t\t\t\t\t\tnon_cand = np.array(input_ids_for_del)\n\t\t\t\t\t\tnon_cand[ind] = input_ids[ind_old]\n\t\t\t\t\t\tinput_candidate = np.array([input_ids_tmp, non_cand])\n\t\t\t\t\t\tprob_candidate = np.array([bert_scorer.sent_score(x) for x in input_candidate])\n\t\t\t\t\t\tnon_idx = 1\n\t\t\t\t\t\tif sim is not None and use_constr:\n\t\t\t\t\t\t\tsimilarity_candidate=similarity_batch(input_candidate, input_original,sta_vec)\n\t\t\t\t\t\t\tprob_candidate=prob_candidate*similarity_candidate\n\t\t\t\t\t\tprob_candidate_norm=normalize(prob_candidate)\n\t\t\t\t\t\tprob_candidate_ind=sample_from_candidate(prob_candidate_norm)\n\t\t\t\t\t\tinput_ids_tmp = input_candidate[prob_candidate_ind]\n\t\t\t\t\telse:\n\t\t\t\t\t\tnon_idx = -1\n\t\t\t\t\t\tprob_candidate_ind = 0\n\t\t\t\t\t\tinput_ids_tmp = input_ids_tmp # already deleted\n\n\t\t\t\t\tif prob_candidate_ind == non_idx:\n\t\t\t\t\t\tprint('action:2 delete non', 1.0, 1.0)\n\t\t\t\t\telse:\n\t\t\t\t\t\t# add mask, for evaluating reverse probability\n\t\t\t\t\t\tprob_mask = bert_scorer.mask_score(input_ids_for_del, ind, mode=0)\n\t\t\t\t\t\tinput_candidate, prob_candidate, reverse_candidate_idx, _ = \\\n\t\t\t\t\t\t\tgenerate_candidate_input_with_mask(input_ids_for_del, sequence_length_tmp, ind, prob_mask,\n\t\t\t\t\t\t\t config.search_size, mode=0, old_tok=input_ids[ind_old])\n\n\t\t\t\t\t\tif sim!=None:\n\t\t\t\t\t\t\tsimilarity_candidate=similarity_batch(input_candidate, input_original,sta_vec)\n\t\t\t\t\t\t\tprob_candidate=prob_candidate*similarity_candidate\n\t\t\t\t\t\tprob_candidate_norm = normalize(prob_candidate)\n\n\t\t\t\t\t\tproposal_prob *= 1.0 # Q(x'|x)\n\t\t\t\t\t\tproposal_prob_reverse *= prob_candidate_norm[reverse_candidate_idx] # Q(x|x'), reverse action is inserting\n\t\t\t\t\t\tsequence_length_tmp -= 1\n\n\t\t\t\t\t\tprint('action:2', 1.0, prob_candidate_norm[reverse_candidate_idx])\n\n\t\t\tnew_prob = def_sent_scorer(tokenizer.decode(input_ids_tmp))\n\t\t\tnew_prob *= penalty_constraint(searcher.count_unsafisfied_constraint(searcher.sent2tag(input_ids_tmp)))\n\t\t\tif config.mode == 'sentiment':\n\t\t\t\tnew_prob *= get_sentiment_score(input_ids_tmp, sentiment)\n\t\t\tif sim != None:\n\t\t\t\tsim_constr = similarity(input_ids_tmp, input_original, sta_vec)\n\t\t\t\tnew_prob *= sim_constr\n\t\t\tinput_text_tmp = tokenizer.decode(input_ids_tmp)\n\t\t\tall_samples.append([input_text_tmp,\n\t\t\t new_prob,\n\t\t\t searcher.count_unsafisfied_constraint(searcher.sent2tag(input_ids_tmp)),\n\t\t\t bert_scorer.sent_score(input_ids_tmp, log_prob=True),\n\t\t\t gpt2_scorer.sent_score(input_text_tmp, ppl=True)])\n\t\t\tif tokenizer.decode(input_ids_tmp) not in output_p:\n\t\t\t\toutputs.append(all_samples[-1])\n\t\t\tif outputs != []:\n\t\t\t\toutput_p.append(outputs[-1][0])\n\t\t\tif proposal_prob == 0.0 or old_prob == 0.0:\n\t\t\t\talpha_star = 1.0\n\t\t\telse:\n\t\t\t\talpha_star = (proposal_prob_reverse * new_prob) / (proposal_prob * old_prob)\n\t\t\talpha = min(1, alpha_star)\n\t\t\tprint(tokenizer.decode(input_ids_tmp).encode('utf8', errors='ignore'))\n\t\t\tprint(alpha, old_prob, proposal_prob, new_prob, proposal_prob_reverse)\n\t\t\tproposal_cnt += 1\n\t\t\tif choose_action([alpha, 1 - alpha]) == 0 and (\n\t\t\t\t\tnew_prob > old_prob * config.threshold or just_acc() == 0):\n\t\t\t\tif tokenizer.decode(input_ids_tmp) != tokenizer.decode(input_ids):\n\t\t\t\t\taccept_cnt += 1\n\t\t\t\t\tprint('Accept')\n\t\t\t\t\tall_acc_samples.append(all_samples[-1])\n\t\t\t\tinput_ids = input_ids_tmp\n\t\t\t\tsequence_length = sequence_length_tmp\n\t\t\t\told_prob = new_prob\n\n\n\t\t# choose output from samples\n\t\tfor num in range(config.min_length, 0, -1):\n\t\t\toutputss = [x for x in outputs if len(x[0].split()) >= num]\n\t\t\tprint(num, outputss)\n\t\t\tif outputss != []:\n\t\t\t\tbreak\n\t\tif outputss == []:\n\t\t\toutputss.append([tokenizer.decode(input_ids), 0])\n\t\toutputss = sorted(outputss, key=lambda x: x[1])[::-1]\n\t\twith open(config.use_output_path, 'a') as g:\n\t\t\tg.write(outputss[0][0] + '\\t' + str(outputss[0][1]) + '\\n')\n\t\tall_chosen_samples.append(outputss[0])\n\n\t\tprint('Sentence %d, used time %.2f\\n' % (sen_id, time.time()-start_time))\n\tprint(proposal_cnt, accept_cnt, float(accept_cnt/proposal_cnt))\n\n\tprint(\"All samples:\")\n\tall_samples_ = list(zip(*all_samples))\n\tfor metric in all_samples_[1:]:\n\t\tprint(np.mean(np.array(metric)))\n\n\tprint(\"All accepted samples:\")\n\tall_samples_ = list(zip(*all_acc_samples))\n\tfor metric in all_samples_[1:]:\n\t\tprint(np.mean(np.array(metric)))\n\n\tprint(\"All chosen samples:\")\n\tall_samples_ = list(zip(*all_chosen_samples))\n\tfor metric in all_samples_[1:]:\n\t\tprint(np.mean(np.array(metric)))\n\n\twith open(config.use_output_path + '-result.csv', 'w', newline='') as f:\n\t\tcsv_writer = csv.writer(f, delimiter='\\t')\n\t\tcsv_writer.writerow(['Sentence', 'Prob_sim', 'Constraint_num', 'Log_prob', 'PPL'])\n\t\tcsv_writer.writerows(all_samples)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"key_gen/sentiment_key_gen_base.py","file_name":"sentiment_key_gen_base.py","file_ext":"py","file_size_in_byte":10763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"218607906","text":"# INSERT Command\n\n# import the sqlite3 library \nimport sqlite3\n\n# create the connection object\nconn = sqlite3.connect(\"new.db\")\n\n# get a cursor object to execute SQL commands\nc = conn.cursor()\n\ntry:\n\t# insert data\n\tc.execute(\"INSERT INTO population VALUES('New York City', 'NY', 8400000)\")\n\tc.execute(\"INSERT INTO population VALUES('San Francisco', 'CA', 800000)\")\n\n\t# commit the changes\n\tconn.commit()\nexcept sqlite3.OperationalError:\n\tprint(\"Oops! Something went wrong. Try again...\")\n\n# close the database connection\nconn.close()\n\n","sub_path":"02_sql.py","file_name":"02_sql.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"264993353","text":"#!/usr/bin/env python3\n\nimport os\nimport numpy as np\nimport tensorflow as tf\ntf.compat.v1.reset_default_graph\n\nsess = tf.compat.v1.Session()\n\nx_vals = np.concatenate((np.random.normal(-1, 1, 50), np.random.normal(3, 1, 50)))\ny_vals = np.concatenate((np.repeat(0., 50), np.repeat(1., 50)))\nx_data = tf.compat.v1.placeholder(shape=[1], dtype=tf.float32)\ny_target = tf.compat.v1.placeholder(shape=[1], dtype=tf.float32)\n\nA = tf.compat.v1.Variable(tf.compat.v1.random_normal(mean=10, shape=[1]))\n\nmy_output = tf.compat.v1.add(x_data, A)\n\nmy_output_expanded = tf.compat.v1.expand_dims(my_output, 0)\ny_target_expanded = tf.compat.v1.expand_dims(y_target, 0)\n\ninit = tf.compat.v1.global_variables_initializer()\nsess.run(init)\n\nxentropy = tf.compat.v1.nn.sigmoid_cross_entropy_with_logits(logits=my_output_expanded, labels=y_target_expanded)\n\nmy_opt = tf.compat.v1.train.GradientDescentOptimizer(0.05)\ntrain_step = my_opt.minimize(xentropy)\n\nfor i in range(1400):\n rand_index = np.random.choice(100)\n rand_x = [x_vals[rand_index]]\n rand_y = [y_vals[rand_index]]\n\n sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y})\n if (i + i) % 200 == 0:\n print('Step #' + str(i + 1) + ' A = ' + str(sess.run(A)))\n print('Loss = ' + str(sess.run(xentropy, feed_dict={x_data: rand_x, y_target: rand_y})))\n\npredictions = []\nfor i in range(len(x_vals)):\n x_val = [x_vals[i]]\n prediction = sess.run(tf.compat.v1.round(tf.compat.v1.sigmoid(my_output)), feed_dict={x_data: x_val})\n predictions.append(prediction[0])\n\naccuracy = sum(x==y for x,y in zip(predictions, y_vals)) / 100.\nprint('Ending Accuracy = ' + str(np.round(accuracy, 2)))","sub_path":"01_TensorFlow_Way/05_Implementing_Back_Propagation/05_back_propagation_classification.py","file_name":"05_back_propagation_classification.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"97039413","text":"import tensorflow as tf\nimport math\n\ndef mlp(input_x, image_pixels=28, hidden_units=100, num_classes=10):\n hid_w = tf.Variable(tf.truncated_normal([image_pixels * image_pixels, hidden_units],stddev=1.0 / image_pixels), name='hid_w')\n hid_b = tf.Variable(tf.zeros([hidden_units]), name='hid_b')\n\n sm_w = tf.Variable(tf.truncated_normal([hidden_units, 10], stddev=1.0 / math.sqrt(hidden_units)), name='sm_w')\n sm_b = tf.Variable(tf.zeros([num_classes]), name='sm_b')\n\n hid_lin = tf.nn.xw_plus_b(input_x, hid_w, hid_b)\n hid = tf.nn.relu(hid_lin)\n\n logits = tf.add(tf.matmul(hid, sm_w), sm_b)\n return logits\n\n\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"353765637","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass FilesNotSyncingError(Model):\n \"\"\"Files not syncing error object.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar error_code: Error code (HResult)\n :vartype error_code: int\n :ivar persistent_count: Count of persistent files not syncing with the\n specified error code\n :vartype persistent_count: long\n :ivar transient_count: Count of transient files not syncing with the\n specified error code\n :vartype transient_count: long\n \"\"\"\n\n _validation = {\n 'error_code': {'readonly': True},\n 'persistent_count': {'readonly': True},\n 'transient_count': {'readonly': True},\n }\n\n _attribute_map = {\n 'error_code': {'key': 'errorCode', 'type': 'int'},\n 'persistent_count': {'key': 'persistentCount', 'type': 'long'},\n 'transient_count': {'key': 'transientCount', 'type': 'long'},\n }\n\n def __init__(self, **kwargs) -> None:\n super(FilesNotSyncingError, self).__init__(**kwargs)\n self.error_code = None\n self.persistent_count = None\n self.transient_count = None\n","sub_path":"sdk/storage/azure-mgmt-storagesync/azure/mgmt/storagesync/models/files_not_syncing_error_py3.py","file_name":"files_not_syncing_error_py3.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"598823371","text":"\"\"\"\n求解最长公共子序列\n\nref:http://wordaligned.org/articles/longest-common-subsequence\n\"\"\"\n\nfrom collections import defaultdict, namedtuple\nfrom itertools import product\n\n\ndef lcs_grid(xs, ys, eq):\n \"\"\"Create a grid for longest common subsequence calculations.\n \n Returns a grid where grid[(j, i)] is a pair (n, move) such that\n - n is the length of the LCS of prefixes xs[:i], ys[:j]\n - move is \\, ^, <, or e, depending on whether the best move\n to (j, i) was diagonal, downwards, or rightwards, or None.\n \n Example:\n T A R O T\n A 0< 1\\ 1< 1< 1<\n R 0< 1^ 2\\ 2< 2<\n T 1\\ 1< 2^ 2< 3\\\n \"\"\"\n Cell = namedtuple('Cell', 'length move')\n grid = defaultdict(lambda: Cell(0, 'e'))\n sqs = product(enumerate(ys), enumerate(xs))\n for (j, y), (i, x) in sqs:\n if eq(x, y):\n cell = Cell(grid[(j - 1, i - 1)].length + 1, '\\\\')\n else:\n left = grid[(j, i - 1)].length\n over = grid[(j - 1, i)].length\n if left < over:\n cell = Cell(over, '^')\n else:\n cell = Cell(left, '<')\n grid[(j, i)] = cell\n return grid\n\n\ndef lcs(xs, ys, eq=lambda x, y: x == y):\n \"\"\"Return a longest common subsequence of xs, ys.\"\"\"\n # Create the LCS grid, then walk back from the bottom right corner\n grid = lcs_grid(xs, ys, eq)\n i, j = len(xs) - 1, len(ys) - 1\n lcs = list()\n for move in iter(lambda: grid[(j, i)].move, 'e'):\n if move == '\\\\':\n lcs.append((i, j))\n i -= 1\n j -= 1\n elif move == '^':\n j -= 1\n elif move == '<':\n i -= 1\n lcs.reverse()\n return lcs\n","sub_path":"grader/common/lcs.py","file_name":"lcs.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"402091000","text":"# 215\n# 排序算法联系写个快排\n\ndef quicksort(arr, left, right):\n if left >= right:\n return\n key = arr[left]\n l, r = left, right\n while l < r:\n while arr[r] >= key and l < r:\n r -= 1\n while arr[l] < key and l < r:\n l += 1\n \n arr[l], arr[r] = arr[r], arr[l]\n quicksort(arr, left, l)\n quicksort(arr, r + 1, right)\n\ndef quick(arr):\n quicksort(arr, 0, len(arr) - 1)\n\n\ndef findKthLargest(nums, k):\n quick(nums)\n return nums[-k]\n\nt = [3, 2, 1, 5, 6, 4]\nt.sort()\nprint(t)\n","sub_path":"algorithm/leetcode/数组问题/数组中的第k个最大元素.py","file_name":"数组中的第k个最大元素.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"110484302","text":"# -*- coding: utf-8 -*- \n\"\"\"\nAnalog In Plugin\nCopyright (C) 2011-2012 Olaf Lüke \nCopyright (C) 2014 Matthias Bolte \n\nanalog_in.py: Analog In Plugin Implementation\n\nThis program is free software; you can redistribute it and/or\nmodify it under the terms of the GNU General Public License \nas published by the Free Software Foundation; either version 2 \nof the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public\nLicense along with this program; if not, write to the\nFree Software Foundation, Inc., 59 Temple Place - Suite 330,\nBoston, MA 02111-1307, USA.\n\"\"\"\n\nfrom brickv.plugin_system.plugin_base import PluginBase\nfrom brickv.plot_widget import PlotWidget\nfrom brickv.bindings.bricklet_analog_in import BrickletAnalogIn\nfrom brickv.async_call import async_call\n\nfrom PyQt4.QtGui import QVBoxLayout, QLabel, QHBoxLayout, QComboBox, QSpinBox\nfrom PyQt4.QtCore import pyqtSignal, Qt\n \nclass VoltageLabel(QLabel):\n def setText(self, text):\n text = \"Voltage: \" + text + \" V\"\n super(VoltageLabel, self).setText(text)\n \nclass AnalogIn(PluginBase):\n qtcb_voltage = pyqtSignal(int)\n \n def __init__(self, *args):\n PluginBase.__init__(self, BrickletAnalogIn, *args)\n \n self.ai = self.device\n \n self.qtcb_voltage.connect(self.cb_voltage)\n self.ai.register_callback(self.ai.CALLBACK_VOLTAGE,\n self.qtcb_voltage.emit) \n \n self.voltage_label = VoltageLabel('Voltage: ')\n \n self.current_value = None\n \n plot_list = [['', Qt.red, self.get_current_value]]\n self.plot_widget = PlotWidget('Voltage [mV]', plot_list)\n\n layout_h2 = QHBoxLayout()\n layout_h2.addStretch()\n layout_h2.addWidget(self.voltage_label)\n layout_h2.addStretch()\n\n layout = QVBoxLayout(self)\n layout.addLayout(layout_h2)\n layout.addWidget(self.plot_widget)\n\n if self.firmware_version >= (2, 0, 1):\n self.combo_range = QComboBox()\n self.combo_range.addItem('Automatic', BrickletAnalogIn.RANGE_AUTOMATIC)\n if self.firmware_version >= (2, 0, 3):\n self.combo_range.addItem('0V - 3.30V', BrickletAnalogIn.RANGE_UP_TO_3V)\n self.combo_range.addItem('0V - 6.05V', BrickletAnalogIn.RANGE_UP_TO_6V)\n self.combo_range.addItem('0V - 10.32V', BrickletAnalogIn.RANGE_UP_TO_10V)\n self.combo_range.addItem('0V - 36.30V', BrickletAnalogIn.RANGE_UP_TO_36V)\n self.combo_range.addItem('0V - 45.00V', BrickletAnalogIn.RANGE_UP_TO_45V)\n self.combo_range.currentIndexChanged.connect(self.range_changed)\n\n layout_h1 = QHBoxLayout()\n layout_h1.addStretch()\n layout_h1.addWidget(QLabel('Range:'))\n layout_h1.addWidget(self.combo_range)\n\n if self.firmware_version >= (2, 0, 3):\n self.spin_average = QSpinBox()\n self.spin_average.setMinimum(0)\n self.spin_average.setMaximum(255)\n self.spin_average.setSingleStep(1)\n self.spin_average.setValue(50)\n self.spin_average.editingFinished.connect(self.spin_average_finished)\n\n layout_h1.addStretch()\n layout_h1.addWidget(QLabel('Average Length:'))\n layout_h1.addWidget(self.spin_average)\n\n layout_h1.addStretch()\n layout.addLayout(layout_h1)\n\n def get_range_async(self, range_):\n self.combo_range.setCurrentIndex(self.combo_range.findData(range_))\n\n def get_averaging_async(self, average):\n self.spin_average.setValue(average)\n\n def start(self):\n if self.firmware_version >= (2, 0, 1):\n async_call(self.ai.get_range, None, self.get_range_async, self.increase_error_count)\n if self.firmware_version >= (2, 0, 3):\n async_call(self.ai.get_averaging, None, self.get_averaging_async, self.increase_error_count)\n async_call(self.ai.get_voltage, None, self.cb_voltage, self.increase_error_count)\n async_call(self.ai.set_voltage_callback_period, 100, None, self.increase_error_count)\n \n self.plot_widget.stop = False\n \n def stop(self):\n async_call(self.ai.set_voltage_callback_period, 0, None, self.increase_error_count)\n \n self.plot_widget.stop = True\n\n def destroy(self):\n pass\n\n def get_url_part(self):\n return 'analog_in'\n\n @staticmethod\n def has_device_identifier(device_identifier):\n return device_identifier == BrickletAnalogIn.DEVICE_IDENTIFIER\n\n def get_current_value(self):\n return self.current_value\n\n def cb_voltage(self, voltage):\n self.current_value = voltage\n self.voltage_label.setText(str(voltage/1000.0))\n\n def range_changed(self, index):\n if index >= 0 and self.firmware_version >= (2, 0, 1):\n range_ = self.combo_range.itemData(index)\n async_call(self.ai.set_range, range_, None, self.increase_error_count)\n\n def spin_average_finished(self):\n self.ai.set_averaging(self.spin_average.value())\n","sub_path":"src/brickv/plugin_system/plugins/analog_in/analog_in.py","file_name":"analog_in.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"501082031","text":"\n# coding: utf-8\n\n# Guided Project\n# ----\n# Preparing Data for SQLite\n\n# **Part 1:** Introduction to the Data\n\n# In[50]:\n\nimport pandas as pd\nimport sqlite3 as sql\n\nacademy_awards = pd.read_csv(\"academy_awards.csv\", encoding=\"ISO-8859-1\")\n\nprint(\"PREVIEW OF ROWS\")\nprint(academy_awards.head(5))\nprint('\\n')\nprint(\"SUMMARY OF UNNAMED COLUMN VALUES\")\nprint(academy_awards[\"Unnamed: 5\"].value_counts())\nprint(academy_awards[\"Unnamed: 6\"].value_counts())\nprint(academy_awards[\"Unnamed: 7\"].value_counts())\nprint(academy_awards[\"Unnamed: 8\"].value_counts())\nprint(academy_awards[\"Unnamed: 9\"].value_counts())\nprint(academy_awards[\"Unnamed: 10\"].value_counts())\n\n\n# **Part 2:** Filtering the Data\n\n# In[51]:\n\nacademy_awards[\"Year\"] = academy_awards[\"Year\"].str[0:4]\nacademy_awards[\"Year\"] = academy_awards[\"Year\"].astype(\"int64\")\n\nlater_than_2000 = academy_awards.loc[academy_awards[\"Year\"] > 2000]\n\naward_categories = [\"Actor -- Leading Role\", \"Actor -- Supporting Role\", \"Actress -- Leading Role\", \"Actress -- Supporting Role\"]\nnominations = later_than_2000.loc[later_than_2000[\"Category\"].isin(award_categories)]\n\n\n# **Part 3:** Cleaning Up the Won? and Unnamed Columns\n\n# In[52]:\n\nreplace_dict = {\"YES\": 1, \"NO\": 0}\nnew_won = nominations[\"Won?\"].map(replace_dict)\nnominations = nominations.assign(Won=new_won)\n\ncols_to_drop = [\"Won?\", \"Unnamed: 5\", \"Unnamed: 6\", \"Unnamed: 7\", \"Unnamed: 8\", \"Unnamed: 9\", \"Unnamed: 10\"]\nfinal_nominations = nominations.drop(cols_to_drop, axis=1)\nfinal_nominations\n\n\n# **Part 4:** Cleaning Up the Additional Info Column\n\n# In[53]:\n\ndef movie_char(row):\n parts = row.split(\" {'\")\n movie = parts[0]\n character = parts[1][0:len(parts[1])-2]\n vals = [movie, character]\n return vals\n\nadd_list = list(final_nominations[\"Additional Info\"])\nparts_list = [movie_char(row) for row in add_list]\nmovie_list = [x[0] for x in parts_list]\nchar_list = [x[1] for x in parts_list]\n\nfinal_nominations = final_nominations.assign(Movie = movie_list)\nfinal_nominations = final_nominations.assign(Character = char_list)\nfinal_nominations = final_nominations.drop(\"Additional Info\", axis=1)\nfinal_nominations\n\n\n# **Part 5:** Exporting to SQLite\n\n# In[54]:\n\nconn = sql.connect(\"nominations.db\")\nfinal_nominations.to_sql(\"nominations\", conn, index=False, if_exists=\"replace\")\n\n\n# **Part 6:** Verifying in SQL\n\n# In[55]:\n\nc = conn.cursor()\n\nquery1 = \"PRAGMA TABLE_INFO(nominations);\"\nc.execute(query1)\nresults = c.fetchall()\nprint(\"TABLE SCHEMA\")\nprint(results)\nprint('\\n')\n\nquery2 = \"SELECT * FROM nominations LIMIT 10;\"\nc.execute(query2)\nresults = c.fetchall()\nprint(\"FIRST 10 ROWS\")\nprint(results)\n\nconn.close()\n\n\n# **Part 7:** Next Steps\n# \n# The suggestions for additonal work all center around the task of getting the entire dataset (not just recent entries, as we did above) into an SQL table with a consistent format. In order to make that happen, we need to understand how the data formats have changed through time.\n# \n# For now, I'm going to park this project, but I may come back at a later time.\n","sub_path":"dataquest_projects/preparing_data_sqlite/preparing_data_sqlite.py","file_name":"preparing_data_sqlite.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"107196275","text":"# Ex. 1\n\ndef u():\n u = 1.0\n while 1 + u != 1:\n u /= 10\n return u * 10\n\nprint('precision is', u())\n\n# Ex. 2\n\ndef ver_add():\n x = 1.0\n y = u()\n z = u()\n return ((x + y) + z) == (x + (y + z))\n\ndef ver_mul():\n x = 3\n y = 0.7\n z = 0.3\n\n # assoc = False\n # Explanation: \n # (x * y) = 2.099999999\n # ((x * y) * z) = 0.6299999999\n # but \n # (y * z) = 0.21\n # (x * (y * z)) = 0.63 \n return ((x * y) * z) == (x * (y * z))\n\nprint('add asoc?', ver_add())\nprint('mul asoc?', ver_mul())\n\n# Ex. 3\n\nimport numpy as np\n\ndef create_sample_matrix(n):\n sample = np.zeros(shape=(n,n))\n for i in range(0,n):\n for j in range(0,n):\n sample[i,j] = i * n + j\n return sample\n\ndef strassen_partition(X, n):\n mid = n//2\n X11 = X[0:mid, 0:mid]\n X12 = X[0:mid, mid:]\n X21 = X[mid:, 0:mid]\n X22 = X[mid:, mid:]\n\n return (X11, X12, X21, X22)\n\ndef strassen_result(C11, C12, C21, C22, n):\n result = np.zeros(shape=(n,n))\n\n mid = n//2\n result[0:mid, 0:mid] = C11\n result[0:mid, mid:] = C12\n result[mid:, 0:mid] = C21\n result[mid:, mid:] = C22\n\n return result\n\ndef strassen_mul(A, B, n, n_min):\n if n <= n_min:\n return A.dot(B)\n else:\n A11, A12, A21, A22 = strassen_partition(A, n)\n B11, B12, B21, B22 = strassen_partition(B, n)\n\n P1 = strassen_mul((A11 + A22), (B11 + B22), n//2, n_min)\n P2 = strassen_mul((A21 + A22), B11, n//2, n_min)\n P3 = strassen_mul(A11, (B12 - B22), n//2, n_min)\n P4 = strassen_mul(A22, (B21 - B11), n//2, n_min)\n P5 = strassen_mul((A11 + A12), B22, n//2, n_min)\n P6 = strassen_mul((A21 - A11), (B11 + B12), n//2, n_min)\n P7 = strassen_mul((A12 - A22), (B21 + B22), n//2, n_min)\n\n C11 = P1 + P4 - P5 + P7\n C12 = P3 + P5\n C21 = P2 + P4\n C22 = P1 + P3 - P2 + P6\n \n return strassen_result(C11, C12, C21, C22, n)\n\nsize = 8\n\nA = create_sample_matrix(size)\nB = create_sample_matrix(size)\n\nprint(A, '\\n')\nprint(B, '\\n')\nprint(strassen_mul(A, B, size, 2))","sub_path":"H1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"109502660","text":"# -*- coding: utf-8 -*-\nimport hashlib\nimport web\nimport lxml\nimport time\nimport os\nimport urllib2,json,urllib\nfrom lxml import etree\nimport pylibmc\nimport random\n \nclass WeixinInterface:\n \n def __init__(self):\n self.app_root = os.path.dirname(__file__)\n self.templates_root = os.path.join(self.app_root, 'templates')\n self.render = web.template.render(self.templates_root)\n \n def GET(self):\n #获取输入参数\n data = web.input()\n signature=data.signature\n timestamp=data.timestamp\n nonce=data.nonce\n echostr=data.echostr\n #自己的token\n token=\"tutuxsfly\"\n #字典序排序\n list=[token,timestamp,nonce]\n list.sort()\n sha1=hashlib.sha1()\n map(sha1.update,list)\n hashcode=sha1.hexdigest()\n #sha1加密算法 \n \n #如果是来自微信的请求,则回复echostr\n if hashcode == signature:\n #print \"true\"\n return echostr\n #return '欢迎光临'\n \n \n def POST(self): \n str_xml = web.data()\n xml = etree.fromstring(str_xml)\n #xml = urllib.unquote(xml)\n content=xml.find(\"Content\").text\n mstype=xml.find(\"MsgType\").text \n fromUser=xml.find(\"FromUserName\").text\n toUser=xml.find(\"ToUserName\").text\n mc = pylibmc.Client() #初始化一个memcache实例用来保存用户的操作\n \n \n \n #下面创建一个欢迎消息,通过判断Event类型\n if mstype == \"event\":\n mscontent = xml.find(\"Event\").text\n if mscontent == \"subscribe\":\n replayText = u'''欢迎关注本微信,这个微信是本人业余爱好所建立,也是想一边学习Python一边玩的东西,\n 现在还没有什么功能,只是弄了个翻译与豆瓣图书查询的小工具,你们有什么好的文章也欢迎反馈给我,我会不定期的分享给大家,输入help查看操作指令'''\n return self.render.reply_text(fromUser,toUser,int(time.time()),replayText)\n if mscontent == \"unsubscribe\":\n replayText = u'我现在功能还很简单,知道满足不了您的需求,但是我会慢慢改进,欢迎您以后再来' \n return self.render.reply_text(fromUser,toUser,int(time.time()),replayText)\n if mstype == 'text':\n content=xml.find(\"Content\").text\n \n if content.lower() == 'bye':\n mc.delete(fromUser+'_xhj')\n return self.render.reply_text(fromUser,toUser,int(time.time()),u'您已经跳出了和小黄鸡的交谈中,输入help来显示操作指令')\n if content.lower() == 'xhj':\n mc.set(fromUser+'_xhj','xhj')\n return self.render.reply_text(fromUser,toUser,int(time.time()),u'您已经进入与小黄鸡的交谈中,请尽情的蹂躏它吧!输入bye跳出与小黄鸡的交谈')\n if content.lower() == 'm':\n musicList = [\n [r'http://bcs.duapp.com/yangyanxingblog3/music/destiny.mp3','Destiny',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/5days.mp3','5 Days',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/Far%20Away%20%28Album%20Version%29.mp3','Far Away (Album Version)',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/%E5%B0%91%E5%B9%B4%E6%B8%B8.mp3',u'少年游',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/%E8%8F%8A.mp3',u'菊--关喆',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/%E7%A6%BB%E4%B8%8D%E5%BC%80%E4%BD%A0.mp3',u'离不开你',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/%E9%99%8C%E7%94%9F%E4%BA%BA.mp3',u'陌生人',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/%E8%8A%B1%E5%AE%B9%E7%98%A6.mp3',u'花容瘦',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/%E4%B9%98%E5%AE%A2.mp3',u'乘客',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/If%20My%20Heart%20Was%20A%20House.mp3',u'If My Heart Was A House',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/Hello%20Seattle%EF%BC%88Remix%E7%89%88%EF%BC%89.mp3',u'Hello Seattle(Remix版',u'献给我的宝贝晶晶'],\n [r'http://bcs.duapp.com/yangyanxingblog3/music/Everybody%20Hurts.mp3',u'Everybody Hurts',u'献给我的宝贝晶晶'] \n ]\n music = random.choice(musicList)\n musicurl = music[0]\n musictitle = music[1]\n musicdes =music[2]\n return self.render.reply_music(fromUser,toUser,int(time.time()),musictitle,musicdes,musicurl)\n \n #读取memcache中的缓存数据\n \n mcxhj = mc.get(fromUser+'_xhj')\n \n if mcxhj =='xhj':\n res = xiaohuangji(content)\n reply_text = res['sentence_resp']\n if u'微信' in reply_text or u'微 信' in reply_text:\n reply_text = u\"小黄鸡脑袋出问题了,请换个问题吧~\"\n return self.render.reply_text(fromUser,toUser,int(time.time()),reply_text) \n \n if content == 'help':\n replayText = u'''1.输入中文或者英文返回对应的英中翻译\n2.输入m随机听一首音乐\n3.输入xhj进入调戏小黄鸡模式'''\n return self.render.reply_text(fromUser,toUser,int(time.time()),replayText)\n elif type(content).__name__ == \"unicode\":\n content = content.encode('UTF-8')\n Nword = youdao(content) \n return self.render.reply_text(fromUser,toUser,int(time.time()),Nword)\n \ndef youdao(word):\n qword = urllib2.quote(word)\n baseurl = r'http://fanyi.youdao.com/openapi.do?keyfrom=yyxweixintranslate&key=1581042900&type=data&doctype=json&version=1.1&q='\n url = baseurl+qword\n resp = urllib2.urlopen(url)\n fanyi = json.loads(resp.read())\n if fanyi['errorCode'] == 0: \n if 'basic' in fanyi.keys():\n trans = u'%s:\\n%s\\n%s\\n网络释义:\\n%s'%(fanyi['query'],''.join(fanyi['translation']),' '.join(fanyi['basic']['explains']),'\\n'.join(fanyi['web'][0]['value']))\n return trans\n else:\n trans = u'%s:\\n基本翻译:%s\\n'%(fanyi['query'],''.join(fanyi['translation'])) \n return trans\n elif fanyi['errorCode'] == 20:\n return u'对不起,要翻译的文本过长'\n elif fanyi['errorCode'] == 30:\n return u'对不起,无法进行有效的翻译'\n elif fanyi['errorCode'] == 40:\n return u'对不起,不支持的语言类型'\n else:\n return u'对不起,您输入的单词%s无法翻译,请检查拼写'% word\n \ndef xiaohuangji(ask):\n ask = ask.encode('UTF-8')\n enask = urllib2.quote(ask)\n send_headers = {\n 'Cookie':''\n }\n baseurl = r'http://www.simsimi.com/func/reqN?lc=zh&ft=0.0&req='\n url = baseurl+enask\n req = urllib2.Request(url,headers=send_headers)\n resp = urllib2.urlopen(req)\n reson = json.loads(resp.read())\n return reson","sub_path":"work for 2015-2016/py2/shijian-2016/新建文件夹/weix2.py","file_name":"weix2.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"604603677","text":"import yaml\nimport os\n\ncurrent_path = os.path.abspath(os.path.dirname(__file__))\ndefault_conf=current_path + '/../config/merge_handle_rule.yaml'\n\ndef ReadYaml(configPath,root=None):\n\n print(\"get configPath: \"+configPath)\n\n if configPath == None:\n configfile = default_conf\n\n with open(configPath, 'r',encoding='utf8') as f:\n yaml_config = yaml.load(f.read())\n\n if root==None:\n resp = yaml_config\n else:\n resp= yaml_config[root]\n\n return resp\n","sub_path":"common_utils/configHandler.py","file_name":"configHandler.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"471756525","text":"import os, sys, logging\nimport pymysql.cursors\n\nlogger = logging.getLogger()\ndef get_db_connection():\n try:\n return pymysql.connect(os.environ[\"DB_HOST\"],\n user=os.environ[\"DB_USER\"],\n passwd=os.environ[\"DB_PASSWORD\"],\n db=os.environ[\"DB_NAME\"],\n connect_timeout=5)\n except pymysql.MySQLError as e:\n logger.error(\"ERROR: Unexpected error: Could not connect to MySQL instance.\")\n logger.error(e)\n sys.exit() \n\n\ndef lambda_handler(event, context):\n connection = get_db_connection()\n try:\n with connection.cursor() as cursor:\n for event in event[\"Records\"]:\n sql = \"INSERT INTO `files` (`bucket`, `bucket_key`) VALUES (%s, %s)\"\n cursor.execute(sql, (event[\"s3\"][\"bucket\"][\"name\"], event[\"s3\"][\"object\"][\"key\"]))\n connection.commit()\n print(\"Exceuction completed!!!\")\n logger.info(\"Successful!!!\")\n finally:\n connection.close()\n\n\n\n","sub_path":"aws/lambda/python-rds/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"616883214","text":"from sympy import *\n\nx = Symbol('x')\ny = Symbol('y')\n\nxlist = [0, 0.5, 1, 2]\nylist = [0, y, 3, 2]\n\ndef neville(xlist, ylist, point):\n top = 1\n bottom = 1\n L_coef = []\n\n for x_1 in xlist:\n for x_2 in xlist:\n if x_1 != x_2:\n top *= (x - x_2)\n bottom *= (x_1 - x_2)\n L_coef.append(top/bottom)\n \n equation = 0\n for idx in range(len(ylist)):\n equation += L_coef[idx]*ylist[idx]\n\n estimate_poly = equation.subs({x : point})\n return solve(estimate_poly)","sub_path":"neville_method.py","file_name":"neville_method.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"101371014","text":"import _plotly_utils.basevalidators\n\n\nclass LeafValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(self, plotly_name=\"leaf\", parent_name=\"icicle\", **kwargs):\n super(LeafValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Leaf\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n opacity\n Sets the opacity of the leaves. With colorscale\n it is defaulted to 1; otherwise it is defaulted\n to 0.7\n\"\"\",\n ),\n **kwargs,\n )\n","sub_path":"packages/python/plotly/plotly/validators/icicle/_leaf.py","file_name":"_leaf.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"374578308","text":"from typing import Dict\nfrom cloudrail.knowledge.context.aws.resources.athena.athena_workgroup import AthenaWorkgroup\nfrom cloudrail.knowledge.context.aws.cloudformation.cloudformation_constants import CloudformationResourceType\nfrom cloudrail.knowledge.context.aws.resources_builders.cloudformation.base_cloudformation_builder import BaseCloudformationBuilder\n\n\nclass CloudformationAthenaWorkgroupBuilder(BaseCloudformationBuilder):\n\n def __init__(self, cfn_by_type_map: Dict[CloudformationResourceType, Dict[str, Dict]]) -> None:\n super().__init__(CloudformationResourceType.ATHENA_WORKGROUP, cfn_by_type_map)\n\n def parse_resource(self, cfn_res_attr: dict) -> AthenaWorkgroup:\n properties: dict = cfn_res_attr['Properties']\n workgroup_configuration = properties.get('WorkGroupConfiguration', {})\n result_configuration = workgroup_configuration.get('ResultConfiguration', {})\n encryption_config = result_configuration.get('EncryptionConfiguration', {})\n encryption_option = self.get_property(encryption_config, 'EncryptionOption')\n kms_key_id: str = self.get_property(encryption_config, 'KmsKey')\n\n return AthenaWorkgroup(self.get_property(properties, 'Name'),\n self.get_property(properties, 'State', 'ENABLED'),\n encryption_config,\n self.get_property(workgroup_configuration, 'EnforceWorkGroupConfiguration', False),\n encryption_option,\n None,\n cfn_res_attr['region'],\n cfn_res_attr['account_id'],\n kms_key_id)\n","sub_path":"cloudrail/knowledge/context/aws/resources_builders/cloudformation/athena/cloudformation_athena_workgroup_builder.py","file_name":"cloudformation_athena_workgroup_builder.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"530327673","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLucas Fontenla & Victor Hugo - Engenharia 1B\nEP3_JogoDaVelha\n\"\"\"\n#NOTAS\n#começa com X\nimport numpy as np #importa numpy para gerar a matrizes\n\nclass Jogo:\n\tdef __init__(self):\n\t\t#jogadores\n\t\tself.jogador1 = str()\n\t\tself.vitorias_jogador1 = int()\n\t\tself.jogador2 = str()\n\t\tself.vitorias_jogador2 = int()\n\t\t#contador de número de partidas\n\t\tself.contador = int()\n\t\tself.contador_max = int()\n\t\t#mostra vencedor dos dois modos\n\t\tself.vencedor = str()\n\t\tself.vencedor_melhor3 = str()\n\n\t\tself.modo_jogo = int()\n\n\t\tself.tabuleiro_virtual = np.zeros([3,3]) #gera o tabuleiro como uma matriz 3x3 de zeros\n\n\t\tself.jogada = \"X\" #define a primeira jogada como \"X\"\n\t\tself.proxima_jogada = \"O\"\n\n\tdef recebe_jogadores(self, jogador1, jogador2):\n\t\tself.jogador1 = \"{0}\".format(jogador1) #X\n\t\tself.jogador2 = \"{0}\".format(jogador2) #O\n\n\tdef registra_modo(self, modo):\n\t\tself.modo_jogo = modo\n\n\tdef recebe_jogada(self, posicao_jogada_tupla): #função que recebe a jogada do tabuleiro\n\t\t\n\t\tself.registra_jogada(posicao_jogada_tupla) #chama a função registra jogada para ser registrada na matriz\n\n\t\tif self.jogada == \"X\": #sempre que o númeoro for par, escreve \"X\"\n\t\t\tself.proxima_jogada = \"O\"\n\n\t\telif self.jogada == \"O\":\n\t\t\tself.proxima_jogada = \"X\"\n\n\tdef registra_jogada(self, posicao_jogada_tupla): #função responsável por registrar a jogada na matriz\n\t\tif self.jogada == \"X\":\n\t\t\tvalor = 1\n\t\telif self.jogada == \"O\":\n\t\t\tvalor = 2\n\n\t\tself.tabuleiro_virtual[posicao_jogada_tupla[0]][posicao_jogada_tupla[1]] = valor\n\n\t\tself.jogada = self.proxima_jogada\n\n\t#função que verifica se há ganhador\t\n\t#a função multiplica os valores das linhas, colunas e diagonais. Como X = 1, se \"X\" ganhar, a multiplicação da linha é 1\n\t#o mesmo para \"O\", só que como seu valor é 2, a multiplicação será 8. Espaços vazios são 0, desse modo qualquer multiplicação\n\t#com resultado 0 significa que o jogo ainda não acabou pois há espaço livre. Se nem 0, nem 1, nem 8 for encontrado, houve empate.\n\tdef verifica_ganhador(self):\n\t\tvalores_resultados = list()\n\n\t\tadd_valor_diagonal1 = 1\n\t\tadd_valor_diagonal2 = 1\n\n\t\tfor i in range(0, 3):\n\t\t\tadd_valor_linhas = 1\n\t\t\tadd_valor_colunas = 1\n\n\t\t\tfor j in range(0, 3):\n\t\t\t\tadd_valor_linhas *= self.tabuleiro_virtual[i][j]\n\t\t\t\tadd_valor_colunas *= self.tabuleiro_virtual[j][i]\n\t\t\t\t\n\t\t\tadd_valor_diagonal1 *= self.tabuleiro_virtual[i][i]\n\t\t\tadd_valor_diagonal2 *= self.tabuleiro_virtual[i][(i*(-1)-1)]\n\n\t\t\tvalores_resultados.append(add_valor_linhas)\n\t\t\tvalores_resultados.append(add_valor_colunas)\n\n\t\tvalores_resultados.append(add_valor_diagonal1)\n\t\tvalores_resultados.append(add_valor_diagonal2)\n\n\t\tif valores_resultados.count(1) > 0:\n\t\t\tself.contador += 1\n\t\t\tself.vencedor = \"X\"\n\t\t\tself.vitorias_jogador1 += 1\n\t\t\treturn 1\n\t\telif valores_resultados.count(8) > 0:\n\t\t\tself.contador += 1\n\t\t\tself.vencedor = \"O\"\n\t\t\tself.vitorias_jogador2 += 1\n\t\t\treturn 2\t\n\t\telif valores_resultados.count(0) > 0:\n\t\t\treturn -1\n\t\telse:\n\t\t\tself.vencedor = 0\n\t\t\tself.contador += 1\n\t\t\treturn 0\n\n\tdef limpa_jogadas(self): #Função que reseta todo o tabuleiro\n\t\tif self.vencedor == \"X\":\n\t\t\tself.jogada = \"X\"\n\t\t\tself.proxima_jogada = \"O\"\n\n\t\telif self.vencedor == \"O\":\n\t\t\tself.jogada = \"O\"\n\t\t\tself.proxima_jogada = \"X\"\n\n\t\telif self.vencedor == -1: \n\t\t\tself.jogada = self.proxima_jogada\n\t\t\tif self.jogada == \"X\":\n\t\t\t\tself.proxima_jogada = \"O\"\n\t\t\telse:\n\t\t\t\tself.proxima_jogada = \"X\"\n\n\t\tself.tabuleiro_virtual = np.zeros([3,3])\n\n\tdef verifica_modo(self):\n\t\tcontador_max = 3\n\n\t\tif self.vitorias_jogador1 > self.vitorias_jogador2:\n\t\t\tself.vencedor_melhor3 = \"Vencedor(a) {0}\".format(self.jogador1)\n\t\telif self.vitorias_jogador1 < self.vitorias_jogador2:\n\t\t\tself.vencedor_melhor3 = \"Vencedor(a) {0}\".format(self.jogador2)\n\t\telse:\n\t\t\tself.vencedor_melhor3 = \"Empate\"\n\n\t\tif self.modo_jogo == 1:\n\t\t\tif self.vitorias_jogador1 == 2 or self.vitorias_jogador2 == 2 and self.contador == 2:\n\t\t\t\tself.contador = 0\n\t\t\t\tself.vitorias_jogador1 = self.vitorias_jogador2 = 0\n\t\t\t\treturn -1\n\t\t\telif self.contador == contador_max:\n\t\t\t\tself.contador = 0\n\t\t\t\tself.vitorias_jogador1 = self.vitorias_jogador2 = 0\n\t\t\t\treturn -1\n\t\t\telse:\n\t\t\t\treturn 1\n\n\t\treturn 0","sub_path":"Desenvolvimentos extras/Jogo_da_Velha_extra_por_Lucas_Fontenla.py","file_name":"Jogo_da_Velha_extra_por_Lucas_Fontenla.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"103639252","text":"#Importing Adafruit_CharLCD library and Configuring LCD\nimport Adafruit_CharLCD as LCD\nlcd = LCD.Adafruit_CharLCD(27,22,25,24,23,18,16,2,4)\n\n#Importing other things like FTP and datetime tags\nimport ftplib\nfrom datetime import datetime\nimport sys, time, json, os, os.path\n\n#Loading config.json file\nif (os.path.isfile('config.json') == True):\n cfgfile = open('config.json','r')\n config = json.load(cfgfile)\n cfgfile.close()\nelse: #If there is no config, ask for info\n server = raw_input(\"Server ip: \")\n username = raw_input(\"Username: \")\n password = raw_input(\"Password: \")\n directory = raw_input(\"Directory: \")\n debug = raw_input(\"Debug Output(y/n)?:\")\n config = {'server':server,\n 'username':username,\n 'password':password,\n 'directory':directory,\n 'debug':debug}\n cfgfile = open('config.json','w')\n json.dump(config,cfgfile)\n cfgfile.close()\n\n#Functions:\ndef genFileCache():\n cache = list(os.listdir(config['directory']))\n return cache\n\ndef debug(text):\n if (config['debug'] == 'y'):\n print(text)\n\ndef disp(text, delay=None):\n lcd.clear()\n lcd.message(text)\n if (delay != None):\n time.sleep(delay)\n\ndef status(message):\n lcd.clear()\n lcd.message(\" \" + datetime.now().strftime('%b %d %H:%M') + \"\\n\" + message)\n\n\n#Declaring FTP\nftp = ftplib.FTP(config['server'])\n\ntry:\n ftp.login(config['username'],config['password'])\n debug(\"Login Successful to \" + config['server'])\n disp(\"Connected to:\\n\" + config['server'],1)\nexcept ftplib.all_errors:\n debug(\"Cannot connect to \" + config['server'])\n disp(\"Connection Error\\n\" + config['server'],1)\n status(\"Connection Error\")\n sys.exit()\n\nlocalfiles = list(genFileCache()) #Declares localfiles as filelist \nremotefiles = ftp.nlst() #Getting filelist from server \n#Checking what server has more than local, and queuing to download\ndownloadList = list(set(remotefiles) - set(localfiles))\n\nif (len(downloadList) == 0):\n debug(\"All files up to date, exiting...\")\n disp(\"All files are\\nup to date!\",2)\n status(\" All Synced\")\n sys.exit()\n\nitemCount = len(downloadList) #Total number of items to be downloaded\nconnFailCount = 0 #Will be used in except block to not continiously try\n #connecting to server\n\nlcd.blink(True) #To show activity\nfor i in range(itemCount):\n try:\n fileName = downloadList[i]\n currentCount = i + 1 #i will start with 0, so this is for humans.\n debug(str(currentCount) + \"/\" + str(itemCount) + \" Downloading \" + fileName)\n disp(str(currentCount)+\"/\"+str(itemCount)+'\\nDownloading ')\n ftp.retrbinary('RETR ' + fileName, open(config['directory'] + fileName,'wb').write)\n except:\n disp(\" DOWNLOAD\\n FAILED\",2)\n if connFailCount >= 3:\n break\n else:\n connFailCount += 1\n\nlcd.blink(False)\ndisp(\" Syncing...\")\nlocalfiles = list(genFileCache())\ndownloadList = list(set(remotefiles) - set(localfiles))\nif (connFailCount >= 3):\n disp(\" Connection\\n Failed\")\n status(\" Conn. Failed\")\nelif (len(downloadList) > 0):\n disp(str(len(downloadList)) + \" FILES\\n NOT DOWNLOADED\",3)\n status(\" Some Issues...\")\nelif (len(downloadList) == 0):\n status(\" All Synced\")\nelse:\n status(\" Unknown Issue?\")","sub_path":"PiFtp2.py","file_name":"PiFtp2.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305742847","text":"\"\"\"Tests src/common/metrics.py\"\"\"\nimport os\nimport pytest\nfrom unittest.mock import Mock, patch\nimport time\nimport platform\n\nfrom common.metrics import MetricsLogger\n\n@patch('mlflow.start_run')\ndef test_unique_mlflow_initialization(mlflow_start_run_mock):\n \"\"\" Tests MetricsLogger() unique initialization of mlflow\"\"\"\n metrics_logger = MetricsLogger()\n metrics_logger_2 = MetricsLogger()\n mlflow_start_run_mock.assert_called_once()\n\n\n@patch('mlflow.log_metric')\ndef test_metrics_logger_log_metric(mlflow_log_metric_mock):\n \"\"\" Tests MetricsLogger().log_metric() \"\"\"\n metrics_logger = MetricsLogger()\n\n metrics_logger.log_metric(\"foo\", \"bar\")\n mlflow_log_metric_mock.assert_called_with(\n \"foo\", \"bar\"\n )\n\n\n@patch('mlflow.log_metric')\ndef test_metrics_logger_log_metric_too_long(mlflow_log_metric_mock):\n \"\"\" Tests MetricsLogger().log_metric() \"\"\"\n metrics_logger = MetricsLogger()\n\n metric_key = \"x\" * 250\n assert len(metric_key), 250\n\n short_metric_key = \"x\" * 50\n assert len(short_metric_key), 50\n\n metrics_logger.log_metric(\n metric_key, \"bar\"\n )\n mlflow_log_metric_mock.assert_called_with(\n short_metric_key, \"bar\"\n )\n\n\n@patch('mlflow.set_tags')\ndef test_metrics_logger_set_properties(mlflow_set_tags_mock):\n \"\"\" Tests MetricsLogger().set_properties() \"\"\"\n metrics_logger = MetricsLogger()\n\n metrics_logger.set_properties(\n key1 = \"foo\",\n key2 = 0.45\n )\n mlflow_set_tags_mock.assert_called_with(\n { 'key1' : \"foo\", 'key2' : 0.45 }\n )\n\n\n@patch('mlflow.set_tags')\ndef test_metrics_logger_set_platform_properties(mlflow_set_tags_mock):\n \"\"\" Tests MetricsLogger().set_properties() \"\"\"\n metrics_logger = MetricsLogger()\n\n platform_properties = {\n \"machine\":platform.machine(),\n \"processor\":platform.processor(),\n \"system\":platform.system(),\n \"system_version\":platform.version(),\n \"cpu_count\":os.cpu_count()\n }\n metrics_logger.set_platform_properties()\n\n mlflow_set_tags_mock.assert_called_with(\n platform_properties\n )\n\n@patch('mlflow.set_tags')\ndef test_metrics_logger_set_properties_from_json(mlflow_set_tags_mock):\n \"\"\" Tests MetricsLogger().set_properties_from_json() \"\"\"\n metrics_logger = MetricsLogger()\n\n metrics_logger.set_properties_from_json(\n \"{ \\\"key1\\\" : \\\"foo\\\", \\\"key2\\\" : 0.45 }\"\n )\n mlflow_set_tags_mock.assert_called_with(\n { 'key1' : \"foo\", 'key2' : '0.45' }\n )\n\n # test failure during json parsing\n with pytest.raises(ValueError) as exc_info:\n metrics_logger.set_properties_from_json(\n \"{ 'foo': NOTHING }\"\n )\n # making sure it's the right exception\n assert str(exc_info.value).startswith(\"During parsing of JSON properties\")\n\n # test failure if dict is not provided\n with pytest.raises(ValueError) as exc_info:\n metrics_logger.set_properties_from_json(\n \"[\\\"bla\\\", \\\"foo\\\"]\"\n )\n # making sure it's the right exception\n assert str(exc_info.value).startswith(\"Provided JSON properties should be a dict\")\n\n@patch('mlflow.log_params')\ndef test_metrics_logger_log_parameters(mlflow_log_params_mock):\n \"\"\" Tests MetricsLogger().log_parameters() \"\"\"\n metrics_logger = MetricsLogger()\n\n metrics_logger.log_parameters(\n key1 = \"foo\",\n key2 = 0.45\n )\n mlflow_log_params_mock.assert_called_with(\n { 'key1' : \"foo\", 'key2' : 0.45 }\n )\n\n\n@patch('mlflow.log_metric')\ndef test_metrics_logger_log_time_block(mlflow_log_metric_mock):\n \"\"\" Tests MetricsLogger().log_time_block() \"\"\"\n metrics_logger = MetricsLogger()\n\n with metrics_logger.log_time_block(\"foo_metric\"):\n time.sleep(0.01)\n\n mlflow_log_metric_mock.assert_called_once()\n","sub_path":"tests/common/test_metrics.py","file_name":"test_metrics.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"440017891","text":"import xlwt\nimport pymssql\nfrom test.读取花名册excel数据 import renyuan\n\n\nclass MSSQL:\n def __init__(self,host,user,pwd,db):\n self.host=host\n self.user=user\n self.pwd=pwd\n self.db=db\n\n def GetConnect(self):\n if not self.db:\n raise(NameError,'没有目标数据库')\n self.connect=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset='utf8')\n cur=self.connect.cursor()\n if not cur:\n raise(NameError,'数据库访问失败')\n else:\n return cur\n\n def ExecSql(self,sql,para):#带变量的sql语句\n cur=self.GetConnect()\n cur.execute(sql,para)\n self.connect.commit()\n self.connect.close()\n\n def ExecQuery(self,sql):\n cur= self.GetConnect()\n cur.execute(sql)\n resList = cur.fetchall()\n self.connect.close()\n return resList\n\n\ndef main():\n ms = MSSQL(host=\"192.168.10.77\", user=\"sa\", pwd=\"sa\", db=\"STCard_Enp\")\n resList = ms.ExecQuery(\"select *from ST_Person where Person_Name <>'外来' and Is_Del <>1 and Dept_ID <>9 and Dept_ID <>3 \"\n \"and Dept_ID <>7 and Dept_ID <>8 and Card_No <>''\")\n k = 0\n path = r\"D:\\非在职人员名单.xls\"\n workbook = xlwt.Workbook() # 新建一个工作簿\n sheet = workbook.add_sheet(\"非在职人员名单\") # 在工作簿中新建一个表格\n for i in range(0,len(resList)):\n if resList[i][4] not in renyuan():\n x=resList[i][4]\n # ms.ExecSql(\"update ST_person set is_del=1 where person_name =%s and Is_Del <>1 and Dept_ID <>9 and Dept_ID <>3 \"\n # \"and Dept_ID <>7 and Dept_ID <>8 and Card_No <>''\",x)\n #清理姓名时去掉注销\n print(resList[i][4])\n sheet.write(k, 0, resList[i][4]) # 像表格中写入数据(对应的行和列)\n k=k+1\n workbook.save(path) # 保存工作簿\n print(\"xls格式表格写入数据成功!\")\n\n\nif __name__ == '__main__':\n main()\n input(\"执行完成................!\")\n","sub_path":"test/MSSQL_Connect.py","file_name":"MSSQL_Connect.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"180881658","text":"def solve(nm_set):\n for i in range(len(nm_set)):\n n = int(nm_set[i][0])\n m = int(nm_set[i][1])\n cnt = 0\n\n for num in range(n, m + 1):\n cnt += str(num).count('0')\n\n print(cnt)\n\n\n\nif __name__ == '__main__':\n t = int(input())\n input_set = list()\n for i in range(t):\n input_set.append(input().split())\n\n solve(input_set)","sub_path":"박민/[20.09.10]11170.py","file_name":"[20.09.10]11170.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"64006747","text":"import json, sys, subprocess, os, argparse, logging\nfrom collections import deque\nimport numpy as np\nfrom noodle.scorematrix import ScoreMatrixReader\nfrom noodle.evaluation import get_precision_recall\n\ndef parse_output(matrix, runfile, threshold, mask):\n with open(runfile) as f:\n results = json.load(f)\n ps, rs, ts = deque([]), deque([]), deque([])\n names = np.array(matrix.get_attr_names())[mask]\n for q, r in results.items():\n runtime = r['runtime']\n result = r['results']\n scores = matrix.get_scores(q)[mask]\n ref = names[scores >= threshold]\n precision, recall = get_precision_recall(result, ref)\n ps.append(precision)\n rs.append(recall)\n ts.append(runtime) \n return list(ps), list(rs), list(ts) \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-m\", \"--matrix-dir\", type=str,\n default=\"_matrix\")\n parser.add_argument(\"-a\", \"--index-attr\", type=str,\n default=\"_index_attrs_10_9999999.json\")\n parser.add_argument(\"-i\", \"--result-dir\", type=str)\n args = parser.parse_args(sys.argv[1:])\n\n matrix = ScoreMatrixReader(args.matrix_dir, cache_size=1000)\n index_attrs = set(json.load(open(args.index_attr)))\n mask = np.array([i in index_attrs for i in matrix.get_attr_names()])\n\n results = {}\n for f in os.listdir(args.result_dir):\n t = float(os.path.splitext(f)[0])\n results[t] = os.path.join(args.result_dir, f)\n \n precisions = []\n recalls = []\n runtimes = []\n thresholds = sorted(results.keys())\n for t in thresholds:\n ps, rs, ts = parse_output(matrix, results[t], t, mask)\n precisions.append(np.mean(ps))\n recalls.append(np.mean(rs))\n runtimes.append(np.mean(ts))\n\n import matplotlib\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n #plt.style.use(\"/home/ekzhu/noodle/acm-2col.mplstyle\")\n # Plot precision vs recalls\n fig, axes = plt.subplots(1, 2, figsize=(10, 5))\n axes[0].plot(thresholds, precisions, marker=\"+\")\n axes[1].plot(thresholds, recalls, marker=\"+\")\n # Labels\n axes[0].set_ylabel(\"Precision\")\n axes[1].set_ylabel(\"Recall\")\n for ax in axes:\n ax.set_xlim(0,1)\n ax.set_ylim(0,1)\n ax.grid()\n ax.set_xlabel(\"Containment Threshold\")\n# box = ax.get_position()\n# ax.set_position([box.x0, box.y0 + box.height * 0.15, \n# box.width, box.height * 0.85])\n fig.savefig(\"linearscan.png\")\n plt.close()\n # Plot runtime\n fig, axes = plt.subplots(1, 1)\n axes.plot(thresholds, runtimes, marker=\"+\")\n axes.set_ylabel(\"Runtime (ms)\")\n axes.set_xlabel(\"Containment Threshold\")\n axes.set_ylim(ymin=0)\n axes.grid()\n fig.savefig(\"linearscan_runtime.png\")\n plt.close()\n","sub_path":"linearscan.py","file_name":"linearscan.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"622948560","text":"# Copyright (C) 2013 Google Inc., authors, and contributors \n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n# Created By:\n# Maintained By: vraj@reciprocitylabs.com\n\nfrom ggrc import db\nfrom .mixins import deferred, Base\n\nclass PbcList(Base, db.Model):\n __tablename__ = 'pbc_lists'\n\n audit_cycle_id = deferred(\n db.Column(db.Integer, db.ForeignKey('cycles.id'), nullable=False),\n 'PbcList')\n\n requests = db.relationship(\n 'Request', backref='pbc_list', cascade='all, delete-orphan')\n control_assessments = db.relationship(\n 'ControlAssessment', backref='pbc_list', cascade='all, delete-orphan')\n\n _publish_attrs = [\n 'audit_cycle',\n 'requests',\n 'control_assessments',\n ]\n\n @classmethod\n def eager_query(cls):\n from sqlalchemy import orm\n\n query = super(PbcList, cls).eager_query()\n return query.options(\n orm.joinedload('audit_cycle'),\n orm.subqueryload('requests'),\n orm.subqueryload('control_assessments'))\n","sub_path":"src/ggrc/models/pbc_list.py","file_name":"pbc_list.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"89918688","text":"# Author: Izaak Neutelings (July 2019)\n# https://twiki.cern.ch/twiki/bin/viewauth/CMS/TauIDRecommendation13TeV\nimport os\nfrom TauPOG.TauIDSFs import ensureTFile, extractTH1\ndatapath = os.environ['CMSSW_BASE']+\"/src/TauPOG/TauIDSFs/data\"\n\nclass TauIDSFTool:\n \n def __init__(self, year, id, wp='Tight', dm=False, path=datapath):\n \"\"\"Choose the IDs and WPs for SFs. For available tau IDs and WPs, check\n https://cms-nanoaod-integration.web.cern.ch/integration/master-102X/mc102X_doc.html#Tau\"\"\"\n \n years = ['2016Legacy','2017ReReco','2018ReReco']\n assert year in years, \"You must choose a year from %s.\"%(', '.join(years))\n self.ID = id\n self.WP = wp\n \n if id in ['MVAoldDM2017v2','DeepTau2017v2p1VSjet']:\n if dm:\n file = ensureTFile(\"%s/TauID_SF_dm_%s_%s.root\"%(path,id,year))\n self.hist = extractTH1(file,wp)\n self.hist.SetDirectory(0)\n file.Close()\n self.DMs = [0,1,10] if 'oldDM' in id else [0,1,10,11]\n self.getSFvsPT = self.disabled\n self.getSFvsEta = self.disabled\n else:\n file = ensureTFile(\"%s/TauID_SF_pt_%s_%s.root\"%(path,id,year))\n self.func = { }\n self.func[None] = file.Get(\"%s_cent\"%(wp))\n self.func['Up'] = file.Get(\"%s_up\"%(wp))\n self.func['Down'] = file.Get(\"%s_down\"%(wp))\n file.Close()\n self.getSFvsDM = self.disabled\n self.getSFvsEta = self.disabled\n elif id in ['antiMu3','antiEleMVA6']:\n file = ensureTFile(\"%s/TauID_SF_eta_%s_%s.root\"%(path,id,year))\n self.hist = extractTH1(file,wp)\n self.hist.SetDirectory(0)\n file.Close()\n self.genmatches = [1,3] if 'ele' in id.lower() else [2,4]\n self.getSFvsPT = self.disabled\n self.getSFvsDM = self.disabled\n else:\n raise IOError(\"Did not recognize tau ID '%s'!\"%id)\n \n def getSFvsPT(self, pt, genmatch=5, unc=None):\n \"\"\"Get tau ID SF vs. tau pT.\"\"\"\n if genmatch==5:\n return self.func[unc].Eval(pt)\n return 1.0\n \n def getSFvsDM(self, pt, dm, genmatch=5, unc=None):\n \"\"\"Get tau ID SF vs. tau DM.\"\"\"\n if dm in self.DMs or pt<40:\n if genmatch==5:\n bin = self.hist.GetXaxis().FindBin(dm)\n SF = self.hist.GetBinContent(bin)\n if unc=='Up':\n SF += self.hist.GetBinError(bin)\n elif unc=='Down':\n SF -= self.hist.GetBinError(bin)\n return SF\n return 1.0\n return 0.0\n \n def getSFvsEta(self, eta, genmatch, unc=None):\n \"\"\"Get tau ID SF vs. tau eta.\"\"\"\n eta = abs(eta)\n if genmatch in self.genmatches:\n bin = self.hist.GetXaxis().FindBin(eta)\n SF = self.hist.GetBinContent(bin)\n if unc=='Up':\n SF += self.hist.GetBinError(bin)\n elif unc=='Down':\n SF -= self.hist.GetBinError(bin)\n return SF\n return 1.0\n \n @staticmethod\n def disabled(*args,**kwargs):\n raise AttributeError(\"Disabled method.\")\n \n","sub_path":"python/TauIDSFTool.py","file_name":"TauIDSFTool.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10147643","text":"from app import sns_client, sns_resource\nimport os\n\nBASE_ARN = os.environ.get('SNS_BASE_ARN', '')\nPLATFORM_ARN = os.environ.get('SNS_PLATFORM_ARN', '')\nANDROID_ARN = os.environ.get('SNS_ANDROID_ARN', '')\n\ndef subscribe_device(user_id, device_token, ios=True):\n arn_platform = PLATFORM_ARN if ios else ANDROID_ARN\n resp = sns_client.create_platform_endpoint(\n PlatformApplicationArn=arn_platform,\n Token=device_token\n )\n \n endpoint_arn = resp.get('EndpointArn', None)\n if endpoint_arn is None:\n return\n\n # Subscribe this device to user's notifications\n resp = sns_client.create_topic(Name=user_id)\n topic_arn = resp.get('TopicArn', None)\n if topic_arn is None:\n return\n\n sns_client.subscribe(\n TopicArn=topic_arn,\n Protocol='application',\n Endpoint=endpoint_arn\n )\n\ndef publish_to_user(user_id, message):\n topic_arn = BASE_ARN + user_id\n topic = sns_resource.Topic(topic_arn)\n topic.publish(\n TopicArn=topic_arn,\n Message=message\n )\n\n","sub_path":"server/app/aws_sns.py","file_name":"aws_sns.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"450586454","text":"\n\nfrom xai.brain.wordbase.adjectives._arctic import _ARCTIC\n\n#calss header\nclass _ARCTICS(_ARCTIC, ):\n\tdef __init__(self,): \n\t\t_ARCTIC.__init__(self)\n\t\tself.name = \"ARCTICS\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"arctic\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_arctics.py","file_name":"_arctics.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"123015139","text":"\"\"\"\nTODO: None!\n\"\"\"\nimport numpy as np\nimport keras.backend as K\nfrom keras.models import Model\nfrom keras.layers import concatenate, multiply\nfrom keras.layers import BatchNormalization, Dropout, SpatialDropout1D\nfrom keras.layers import GlobalMaxPool1D\nfrom keras.layers import Activation, Lambda, Permute, Reshape, RepeatVector, TimeDistributed\nfrom keras.layers import Bidirectional, CuDNNGRU, Dense, Embedding, Input\n\nfrom utils import get_embeddings\nfrom utils import shuffle_data\n\n\nclass ToxicClassifier(object):\n \"\"\"Class for classifying the toxicity of a sentence.\n\n Parameters\n ----------\n embedding_dim : Scalar dimension of input embeddings.\n num_timesteps : Maximum number of timesteps to be processed (i.e. num. words in input).\n word_index : List of all tokens (words) in the corpus.\n weight_path : String specifying where to save weights during training.\n use_aux_input : Boolean, use auxilliary input during training and testing.\n average_attention : Boolean, verage attention values over the time dimension for each input.\n use_ft : Boolean, use fasttext embeddings instead of GloVe embeddings.\n visualize : Boolean, create plots of attention activations.\n \"\"\"\n\n def __init__(self, embedding_dim, num_timesteps, word_index, weight_path,\n use_aux_input=False, average_attention=False,\n use_ft=False, visualize=False):\n self.embedding_dim = embedding_dim\n self.num_timesteps = num_timesteps\n self.attention_layer_count = 0\n\n self.weight_path = weight_path\n\n self.average_attention = average_attention\n self.use_aux_input = use_aux_input\n self.use_ft = use_ft\n self.visualize = visualize\n\n self.CLASS_LIST = ['toxic', 'severe_toxic', 'obscene',\n 'threat', 'insult', 'identity_hate']\n\n def get_attention_output(self):\n \"\"\"Return attention of a single input to the model.\n\n Returns\n -------\n attention: Array of attention weight for teach element in input.\n\n \"\"\"\n self.load_best_weights\n if self.use_aux_input:\n attention = self.attention_layer_model.predict(\n [self.sample_sequence.reshape(1, self.num_timesteps),\n self.sample_aux.reshape(1, 3)],\n batch_size=1)\n else:\n attention = self.attention_layer_model.predict(\n self.sample_sequence.reshape(1, self.num_timesteps), batch_size=1)\n\n return attention[0, -self.sample_length:, 0]\n\n def get_sample_labels(self):\n \"\"\"Return class names corresponding to sample target.\"\"\"\n labels = [i for i, j in zip(self.CLASS_LIST, self.sample_target) if j]\n if labels == []:\n labels = ['not_toxic']\n\n return labels\n\n def get_training_predictions(self):\n return self.model.predict_on_dataset([self.X_train, self.X_aux])\n\n def set_input_and_labels(self, X_train, y_train, X_aux=None):\n \"\"\"Set training input and -labels.\n\n Parameters\n ----------\n X_train : Array of input features.\n y_train : Array of output labels.\n X_aux : Optional array of auxilliary inputs, i.e. engineered features.\n\n \"\"\"\n self.X_train = X_train\n self.y_train = y_train\n self.X_aux = X_aux\n\n def set_sample_sentence(self, sample_text, sample_sequence,\n sample_target, sample_aux=None):\n \"\"\"Set sample sentence and variables to store attention activations.\n\n Parameters\n ----------\n sample_text : Preprocessed text of sample.\n sample_sequence : Padded and tokenized representation of sample text.\n sample_aux : Optional auxilliary input for sample, i.e. engineered features.\n \"\"\"\n self.sample_text = sample_text\n self.sample_sequence = sample_sequence\n self.sample_target = sample_target\n self.sample_aux = sample_aux\n self.sample_length = len(self.sample_text.split(' '))\n if self.visualize:\n self.attention_history = np.zeros((1, self.sample_length))\n\n def _attention_3d_block(self, inputs):\n \"\"\"Return attention vector evaluated over input. If SINGLE_ATTENTION_VECTOR\n argument is given a temporal mean is taken over the time_step dimension.\n\n Parameters\n ----------\n inputs : A tensor of shape (batch_size, time_steps, input_dim).\n Time_steps is represented by the input length, i.e. the number of tokens,\n while input_dim is the number of nodes in the previous nn layer.\n\n Returns\n -------\n output_attention : A tensor of shape (batch_size, time_steps, input_dim),\n representing the attention given to each input token.\n\n \"\"\"\n self.attention_layer_count += 1\n input_dim = int(inputs.shape[2])\n a = Permute((2, 1))(inputs)\n a = Reshape((input_dim, self.num_timesteps))(a)\n a = Dense(self.num_timesteps, activation='softmax')(a)\n\n if self.average_attention:\n a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a)\n a = RepeatVector(input_dim)(a)\n\n attention_layer_name = 'attention_layer_' + str(self.attention_layer_count)\n context_name = 'context_vec_' + str(self.attention_layer_count)\n self.last_attention_layer_name = attention_layer_name\n\n a_probs = Permute((2, 1), name=attention_layer_name)(a)\n output_attention = multiply([inputs, a_probs], name=context_name)\n\n return output_attention\n\n def build_model(self, word_index, use_skipgram=True):\n \"\"\"Return a compiled Keras model for sentence classification.\n\n Parameters\n ----------\n word_index : List of tokens in input data\n use_skipgram : Boolean, whether to use fasttext skipgram word vectors.\n If false, cbow model word vectors will be used instead.\n\n Returns\n -------\n model : A compiled Keras model for predicting six types of toxicity\n in a sentencee.\n attention_layer_model : A Keras model for extracting the attention\n layer output.\n\n \"\"\"\n\n gru_units = [96]\n dense_units = [64]\n\n dropout_prob = 0.4\n\n model_input = Input(shape=(self.num_timesteps, ), name='model_input')\n embedding_matrix = get_embeddings(word_index=word_index,\n embedding_dim=self.embedding_dim,\n use_ft_embeddings=self.use_ft,\n use_skipgram=use_skipgram)\n x = Embedding(len(word_index) + 1, # +1 for 0 padding token\n self.embedding_dim,\n weights=[embedding_matrix],\n input_length=self.num_timesteps,\n trainable=False)(model_input)\n\n for n in range(len(gru_units)):\n x = SpatialDropout1D(dropout_prob)(x)\n x = Bidirectional(CuDNNGRU(units=gru_units[n],\n return_sequences=True))(x)\n x = BatchNormalization()(x)\n x = TimeDistributed(Activation('tanh'))(x)\n\n x = SpatialDropout1D(dropout_prob)(x)\n attention = self._attention_3d_block(inputs=x)\n dense_input = GlobalMaxPool1D()(attention)\n\n if self.use_aux_input:\n aux_input = Input(shape=(3, ), name='aux_input')\n dense_input = concatenate([dense_input, aux_input])\n\n for n in range(len(dense_units)):\n dense = Dropout(dropout_prob)(dense_input)\n dense = Dense(dense_units[n], activation=None)(dense)\n dense = BatchNormalization()(dense)\n dense = Activation('elu')(dense)\n\n dense = Dropout(dropout_prob)(dense)\n probs = Dense(6, activation='sigmoid')(dense)\n\n if self.use_aux_input:\n self.model = Model(inputs=[model_input, aux_input], output=probs)\n else:\n self.model = Model(inputs=model_input, output=probs)\n\n self.model.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n print(self.last_attention_layer_name)\n self.attention_layer_model = Model(inputs=self.model.input,\n outputs=self.model.get_layer(\n self.last_attention_layer_name).output)\n\n def load_best_weights(self):\n \"\"\"Load best weights into model.\"\"\"\n self.model.load_weights(self.weight_path)\n\n def train(self, max_epochs, batch_size, val_split, callbacks):\n \"\"\"Train model, using specified epoch number, batch_size and callbacks.\n\n Parameters\n ----------\n max_epochs : The maximum number of epochs to train for.\n batch_size : Batch size used during training, i.e. the number of sentences.\n callbacks : List of Keras callbacks.\n\n \"\"\"\n if self.use_aux_input:\n _X_train, _y_train, _X_aux = shuffle_data(self.X_train, self.y_train, self.X_aux)\n else:\n _X_train, _y_train = shuffle_data(self.X_train, self.y_train)\n\n if self.visualize:\n for epoch in range(max_epochs):\n if self.use_aux_input:\n self.model.fit([_X_train, _X_aux], _y_train,\n batch_size=batch_size,\n epochs=epoch + 1,\n initial_epoch=epoch,\n validation_split=val_split,\n callbacks=callbacks)\n attention_output = self.attention_layer_model.predict(\n [self.sample_sequence.reshape(1, self.num_timesteps),\n self.sample_aux.reshape(1, 3)], batch_size=1)\n else:\n self.model.fit(_X_train, _y_train,\n batch_size=batch_size,\n epochs=epoch + 1,\n initial_epoch=epoch,\n validation_split=val_split,\n callbacks=callbacks)\n attention_output = self.get_attention_output\n\n self.attention_history = np.append(\n self.attention_history,\n [attention_output[0, -self.sample_length:, 0]],\n axis=0)\n else:\n if self.use_aux_input:\n self.model.fit([_X_train, _X_aux], _y_train,\n batch_size=batch_size,\n epochs=max_epochs,\n validation_split=0.15,\n callbacks=callbacks)\n else:\n self.model.fit(_X_train, _y_train,\n batch_size=batch_size,\n epochs=max_epochs,\n validation_split=0.1,\n callbacks=callbacks)\n print('Training done\\n')\n\n def predict_on_dataset(self, data, aux_input=None):\n \"\"\"Predict on an entire dataset at once using trained model.\n\n Parameters\n ----------\n data : Numpy array containing input data.\n aux_input : Optional auxilliary input (i.e. engineered features).\n\n Returns\n pred : Array of probabilities for the different types of toxicity.\n\n \"\"\"\n self.load_best_weights\n if aux_input is not None:\n try:\n assert self.use_aux_input\n except AssertionError:\n print('ERROR: Unexpexcted auxilliary input passed to predict function')\n exit\n preds = self.model.predict([data, aux_input])\n else:\n preds = self.model.predict(data)\n\n return preds\n\n def predict_sample_output(self):\n \"\"\"Predict on a single sample text using trained model.\n\n Returns\n -------\n pred : Array of probabilities for the different types of toxicity.\n\n \"\"\"\n self.load_best_weights\n if self.use_aux_input:\n pred = self.model.predict([self.sample_sequence.reshape(1, self.num_timesteps),\n self.sample_aux.reshape(1, 3)],\n batch_size=1)\n else:\n pred = self.model.predict(self.sample_sequence.reshape(1, self.num_timesteps),\n batch_size=1)\n\n return pred\n","sub_path":"toxic_classifier.py","file_name":"toxic_classifier.py","file_ext":"py","file_size_in_byte":12674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"516781443","text":"#!/usr/bin/env python\nimport pandas as pd\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\n\nimg = sys.argv[1]\n\nlabels = ['1', '2', '4', '8', '10']\n\nplt.figure()\nfor label in labels:\n try:\n df = pd.read_csv('%s/cpu_stats.csv' % (label))\n sel = df['com.docker.compose.service'] == 'idlememstat'\n X = df['time'][sel]\n X = np.array(X, dtype='datetime64[ns]')\n Y = df['percent_usage'][sel]\n X = X - X[0]\n plt.plot(X,Y,label=label)\n except Exception as e:\n print(e)\nplt.legend()\nplt.savefig(img)\n","sub_path":"lab/eval/ir/cpucost/data/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"450374094","text":"import os\nimport numpy\nimport yaml\nimport pandas\nimport mujoco_py\nimport json\nfrom gym.envs.robotics import rotations, robot_custom_env, utils\nfrom gym.envs.robotics.ur10 import randomize\nfrom scipy.signal import lfilter, lfilter_zi, butter\n#from utils.saving import NumpyEncoder\n\nPROJECT_PATH = os.path.join(*[os.getenv(\"HOME\"), \"DRL_AI4RoMoCo\"])\nMODEL_PATH = os.path.join(*[PROJECT_PATH, \"code\", \"environment\", \"UR10_new\"])\nCONFIG_PATH = os.path.join(*[PROJECT_PATH, \"code\", \"config\", \"environment\"])\nSAVE_PATH = os.path.join(*[\n PROJECT_PATH, \n \"code\", \n \"data\", \n \"EVAL_SOURCESIM\", \n \"StaticPositionEnv\",\n ])\nGOAL_PATH = os.path.join(*[\n PROJECT_PATH, \n \"code\", \n \"environment\", \n \"experiment_configs\", \n \"goal_ur10_simpheg_conf2.json\"\n ])\n\ndef goal_distance(obs, goal):\n '''Computation of the distance between gripper and goal'''\n obs = obs[:6]\n assert obs.shape == goal.shape\n return numpy.linalg.norm(obs*numpy.array([1, 1, 1, 0.3, 0.3, 0.3]), axis=-1)\n\ndef normalize_rad(angles):\n '''Normalizing Euler angles'''\n angles = numpy.array(angles)\n angles = angles % (2*numpy.pi)\n angles = (angles + 2*numpy.pi) % (2*numpy.pi)\n for i in range(len(angles)):\n if (angles[i] > numpy.pi):\n angles[i] -= 2*numpy.pi\n return angles\n\nclass NumpyEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, numpy.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\nclass Ur10Env(robot_custom_env.RobotEnv):\n \"\"\"Superclass for all Ur10 environments.\"\"\"\n\n def __init__(self, env_config,):\n \n with open(env_config) as cfg:\n env_config = yaml.load(cfg, Loader=yaml.FullLoader)\n\n self.save_data = env_config[\"Saving\"]\n self.start_flag = True\n self.episode = 0\n if self.save_data:\n self.fts = []\n self.fxs = []\n self.fys = []\n self.fzs = []\n self.obs = []\n self.rewards = []\n self.poses = []\n self.SEED = env_config[\"SEED\"]\n self.run_info = env_config[\"info\"]\n self.results = list() #list(numpy.zeros(10,).astype(int))\n self.R1 = env_config[\"Reward\"][\"R1\"]\n self.R2 = env_config[\"Reward\"][\"R2\"]\n self.success_reward = env_config[\"Reward\"][\"success_reward\"]\n self.model_path = os.path.join(*[MODEL_PATH, env_config[\"model_xml_file\"]]) \n self.initial_qpos = numpy.array(env_config[\"initial_qpos\"]) \n self.sim_ctrl_q = self.initial_qpos \n self.reward_type = env_config[\"reward_type\"] \n self.ctrl_type = env_config[\"ctrl_type\"] \n self.n_substeps = env_config[\"n_substeps\"]\n self.action_rate = env_config[\"action_rate\"] \n self.distance_threshold = env_config[\"Learning\"][\"distance_threshold\"]\n self.cur_eps_threshold = env_config[\"Learning\"][\"cur_eps_threshold\"]\n self.curriculum_learning = env_config[\"Learning\"][\"curriculum_learning\"]\n self.initial_distance_threshold = env_config[\"Learning\"][\"initial_distance_threshold\"]\n self.final_distance_threshold = env_config[\"Learning\"][\"final_distance_threshold\"] \n self.fail_threshold = env_config[\"Learning\"][\"fail_threshold\"] \n self.n_actions = env_config[\"n_actions\"]\n self.corrective = env_config[\"corrective\"]\n self.vary = env_config[\"vary\"]\n self.dx_max = env_config[\"dx_max\"]\n \n ########################\n \n super(Ur10Env, self).__init__(\n model_path=self.model_path, n_substeps=self.n_substeps,\n n_actions=self.n_actions,initial_qpos=self.initial_qpos, \n seed=self.SEED, success_reward=self.success_reward,\n action_rate = self.action_rate)\n\n def activate_noise(self):\n self.vary=True\n print('noise has been activated.')\n \n def compute_reward(self, obs, goal, info):\n d = goal_distance(obs,goal)\n f = numpy.absolute(obs[7])\n + numpy.absolute(obs[8])\n + numpy.absolute(obs[9])\n rew = self.R1 * (-d) + self.R2 *(-f)\n if self.save_data:\n self.rewards.append(rew)\n self.step_count += 1\n return rew\n\n def _step_callback(self):\n pass\n \n def set_state(self, qpos):\n old_state = self.sim.get_state()\n new_state = mujoco_py.MjSimState(\n old_state.time,\n qpos, \n old_state.qvel,\n old_state.act, \n old_state.udd_state)\n self.sim.set_state(new_state)\n self.sim.forward()\n\n def _set_action(self, action):\n assert action.shape == (6,)\n # ensure that we don't change the action outside of this scope\n action = action.copy() \n deviation = sum(abs(self.sim.data.qpos - self.sim.data.ctrl))\n\n # reset control to current position if deviation too high\n if deviation > 0.35: \n self.sim.data.ctrl[:] = self.sim.data.qpos \n + self.get_dq([0, 0, 0.005, 0, 0, 0])\n print('deviation compensated')\n\n if self.ctrl_type == \"joint\":\n action *= 0.05 # limit maximum change in position\n # Apply action #scalarsto simulation.\n utils.ctrl_set_action(self.sim, action)\n elif self.ctrl_type == \"cartesian\":\n dx = action.reshape(6, )\n\n max_limit = self.dx_max\n '''\n limitation of operation space, we only allow small rotations \n adjustments in x and z directions, moving in y direction\n '''\n x_now = numpy.concatenate((\n self.sim.data.get_body_xpos(\"gripper_dummy_heg\"),\n self.sim.data.get_body_xquat(\"gripper_dummy_heg\")))\n x_then = x_now[:3] + dx[:3]*max_limit\n\n #diff_now = numpy.array(x_now - self.init_x).reshape(7,)\n diff_then = numpy.array(x_then[:3] - self.init_x[:3])\n\n barriers_min = numpy.array([-0.4, -0.8, -0.4])\n barriers_max = numpy.array([0.4, 0.8, 0.4])\n '''\n for i in range(3):\n if (barriers_min[i] < diff_then[i] < barriers_max[i]):\n dx[i] = dx[i] * max_limit\n elif barriers_min[i] > diff_then[i]:\n dx[i] = + max_limit\n elif barriers_max[i] < diff_then[i]:\n dx[i] = - max_limit\n for i in range(3,6):\n dx[i] = dx[i] * max_limit\n '''\n for i in range(6):\n dx[i] = dx[i] * max_limit\n \n if self.corrective:\n # bias in direction of assembly\n bias_dir = -self.last_obs[:6]\n # print(bias_dir)\n for i in range(3,6):\n if bias_dir[i] > 0.5:\n print(i, bias_dir[i])\n bias_dir[i] = bias_dir[i] # slower rotations\n bias_dir /= numpy.linalg.norm(bias_dir)\n # print(bias_dir)\n dx += bias_dir * max_limit * 0.5\n dx.reshape(6, 1)\n\n dq = self.get_dq(dx)\n # print(sum(abs(sim.data.qpos-sim.data.ctrl)))\n for i in range(6):\n self.sim.data.ctrl[i] += dq[i]\n\n def get_dq(self, dx):\n jacp = self.sim.data.get_body_jacp(name=\"gripper_dummy_heg\").reshape(3, 6)\n jacr = self.sim.data.get_body_jacr(name=\"gripper_dummy_heg\").reshape(3, 6)\n jac = numpy.vstack((jacp, jacr))\n dq = numpy.linalg.lstsq(jac, dx)[0].reshape(6, )\n return dq\n\n def _get_obs(self):\n rot_mat = self.sim.data.get_body_xmat('gripper_dummy_heg')\n ft = self.sim.data.sensordata.copy()\n\n if self.start_flag:\n ft = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])\n self.start_flag = False\n\n x_pos = self.sim.data.get_body_xpos(\"gripper_dummy_heg\")\n x_mat = self.sim.data.get_body_xmat(\"gripper_dummy_heg\")\n rpy = normalize_rad(rotations.mat2euler(x_mat))\n\n obs = numpy.concatenate([\n rot_mat.dot(x_pos-self.goal[:3]),\n rot_mat.dot(normalize_rad(rpy-self.goal[3:])),\n ft.copy()\n ])\n if self.save_data:\n self.fts.append([ft[0], ft[1], ft[2], ft[3], ft[4], ft[5],])\n self.obs.append(obs)\n self.fxs.append(ft[0])\n self.fys.append(ft[1])\n self.fzs.append(ft[2])\n self.poses.append(numpy.concatenate(\n [x_pos-self.goal[:3],\n normalize_rad(rpy-self.goal[3:])]))\n self.last_obs = obs\n return obs\n \n def _viewer_setup(self):\n body_id = self.sim.model.body_name2id('body_link')\n lookat = self.sim.data.body_xpos[body_id]\n for idx, value in enumerate(lookat):\n self.viewer.cam.lookat[idx] = value\n self.viewer.cam.distance = 2.5\n self.viewer.cam.azimuth = 132.\n self.viewer.cam.elevation = -14.\n \n def _render_callback(self):\n pass\n \n def _reset_sim(self):\n # Tracking the first step to zero the ft-sensor\n self.start_flag = True\n if self.episode > 0:\n self.success_rate = float(numpy.sum(self.results)/float(len(self.results)))\n print(\"Episode: {} Success Rate: {} \".format(self.episode, self.success_rate))\n if len(self.results) < 10:\n self.results.append(0)\n else:\n self.results.pop(0)\n self.results.append(0)\n \n if self.save_data and self.episode > 0:\n if self.success_flag == 1:\n self.rewards.append(self.success_reward)\n self.reward_sum = numpy.sum(self.rewards)\n \n save_dict = {\n #\"observations\" : self.obs,\n #\"ft_values\" : self.fts,\n #\"rewards\" : self.rewards,\n #\"poses\" : self.poses\n \"fx\" : self.fxs,\n \"fy\" : self.fys,\n \"fz\" : self.fzs,\n \"steps\" : self.step_count,\n \"success\" : self.success_flag,\n \"reward\" : self.reward_sum\n }\n with open(os.path.join(*[SAVE_PATH, \"episode_{}.json\".format(self.episode)]), \"w\") as file:\n json.dump(save_dict,file)\n file.write('\\n')\n \n #self.obs = []\n #self.fts = []\n #self.rewards = []\n #self.poses = []\n self.fxs = []\n self.fys = []\n self.fzs = []\n self.rewards = []\n self.step_count = 0\n self.success_flag = 0\n self.episode += 1\n \n if self.vary == True:\n # deviation in x,y,z, direction rotation stays the same\n deviation_x = numpy.concatenate(\n (numpy.random.normal(loc=0.0, scale=1.0, size=(3,)),\n [0, 0, 0]))\n deviation_q = self.get_dq(deviation_x * 0.005)\n else:\n deviation_q = numpy.array([0, 0, 0, 0, 0, 0])\n self.set_state(self.initial_qpos + deviation_q)\n self.sim.forward()\n self.init_x = numpy.concatenate(\n (self.sim.data.get_body_xpos(\"gripper_dummy_heg\"), \n self.sim.data.get_body_xquat(\"gripper_dummy_heg\")\n ))\n self.sim.data.ctrl[:] = self.initial_qpos + deviation_q\n return True\n\n def _sample_goal(self):\n\n with open(GOAL_PATH, encoding='utf-8') as file:\n goal = json.load(file)\n xpos = goal['xpos']\n xquat = goal['xquat']\n rpy = normalize_rad(rotations.quat2euler(xquat))\n return numpy.concatenate([xpos, rpy]).copy()\n\n def _is_success(self, achieved_goal, desired_goal):\n rot_mat = self.sim.data.get_body_xmat('gripper_dummy_heg')\n x_pos = self.sim.data.get_body_xpos(\"gripper_dummy_heg\")\n x_mat = self.sim.data.get_body_xmat(\"gripper_dummy_heg\")\n rpy = normalize_rad(rotations.mat2euler(x_mat))\n obs = numpy.concatenate([\n rot_mat.dot(x_pos-self.goal[:3]), \n rot_mat.dot(normalize_rad(rpy-self.goal[3:]))\n ])\n d = goal_distance(obs,desired_goal)\n if self.curriculum_learning:\n if self.episode < self.cur_eps_threshold:\n if d < self.initial_distance_threshold:\n if len(self.results) == 0:\n self.results.append(1)\n else:\n self.results.pop()\n self.results.append(1)\n self.success_flag = 1\n return True\n else:\n return False\n else:\n if d < self.final_distance_threshold:\n if len(self.results) == 0:\n self.results.append(1)\n else:\n self.results.pop()\n self.results.append(1)\n self.success_flag = 1\n return True\n else:\n return False\n else:\n if d < self.distance_threshold:\n if len(self.results) == 0:\n self.results.append(1)\n else:\n self.results.pop()\n self.results.append(1)\n self.success_flag = 1\n return True\n else:\n return False\n\n def _is_failure(self, achieved_goal, desired_goal):\n #d = goal_distance(achieved_goal, desired_goal)\n # removed early stop because baselines did not work with it\n #return (d > self.fail_threshold)\n #& (numpy.round(self.sim.get_state()[0]/0.0005).astype('int') > 200)\n return False\n\n def _env_setup(self, initial_qpos):\n self.sim.data.ctrl[:] = initial_qpos\n self.set_state(initial_qpos)\n self.sim.forward()\n\n def render(self, mode='human', width=500, height=500):\n return super(Ur10Env, self).render(mode, width, height)","sub_path":"gym/envs/robotics/ur10_static_position_env.py","file_name":"ur10_static_position_env.py","file_ext":"py","file_size_in_byte":14269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"323067856","text":"import time\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport urllib.request\n\n\n# 获取微信公众号新闻\n\ndef get_access():\n return webdriver.Firefox()\n\n\ndef search_page(driver, url):\n driver.get(url)\n print(driver.current_url)\n elem = driver.find_element_by_class_name(\"query\")\n elem.send_keys(u\"国际农业航空施药技术联合实验室\")\n btn = driver.find_element_by_class_name(\"swz2\")\n btn.click()\n print(driver.current_url)\n time.sleep(1)\n page = driver.page_source\n return page\n\n\ndef load_page(driver, url):\n driver.get(url)\n page = driver.page_source\n return page\n\n\ndef next_page(page):\n soup = BeautifulSoup(page, \"html5lib\")\n link = soup.find('div', attrs={\"class\": \"img-box\"})\n link_to = link.find('a')\n return link_to.attrs['href']\n\n\ndef get_news_urls(page):\n base_url = 'https://mp.weixin.qq.com'\n # 存储新闻页面的列表\n news_urls = {}\n soup = BeautifulSoup(page, \"html5lib\")\n # 新闻列表\n news_list = soup.find_all('h4', attrs={'class': 'weui_media_title'})\n # 全部新闻标题\n for i in news_list:\n news_title = i.get_text()\n news_url = base_url + i.attrs['hrefs']\n news_urls[news_title] = news_url\n return news_urls\n\n\ndef get_news(news_urls):\n for url in news_urls:\n print(url, news_urls[url])\n\n\ndef initial():\n html_url = \"http://weixin.sogou.com/\"\n web_look = get_access()\n html_url = search_page(web_look, html_url)\n true_url = next_page(html_url)\n news_urls = get_news_urls(load_page(web_look, true_url))\n get_news(news_urls)\n\n\nif __name__ == '__main__':\n initial()\n","sub_path":"get_news/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"214804908","text":"#IMPORTS\nfrom threading import Thread\n\nfrom ttkthemes import ThemedStyle\n\nimport Helper_Method\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport time\n\nfrom AgglomerativeClusteringClassifier import ACC_Model_Trainer, ACC_Data_To_CSV, ACC_User_Input\nfrom Constats import Status\nfrom WordGramClassifier import WGC_Data_To_CSV, WGC_Model_Trainer, WGC_User_Input\nfrom MergedClassifier import MC_Data_To_CSV, MC_Model_Trainer, MC_User_Input\nfrom KmeanClusteringClassifier import CC_Data_To_CSV, CC_Model_Trainer, CC_User_Input\nfrom StyleClassifier import SC_Data_To_CSV, SC_Model_Trainer, SC_User_Input\nfrom pathlib import Path\n\n\ndef global_timer():\n while True:\n is_model_trained()\n time.sleep(1)\n\n if Status.is_app_waiting:\n message_status(\"Processing Please Wait!\", 1)\n button2.configure(state='disabled')\n button3.configure(state='disabled')\n button4.configure(state='disabled')\n else:\n message_status(\"Waiting For Response\", 1)\n is_model_trained()\n\n\n\ndef is_model_trained():\n if Status.is_app_waiting == False:\n if Status.classifier_type == 'stylometry':\n my_file = Path(\"stylometry_model\")\n if my_file.is_file() == False:\n button3.configure(state='disabled')\n button4.configure(state='disabled')\n else:\n button3.configure(state='enabled')\n button4.configure(state='enabled')\n elif Status.classifier_type == 'content':\n my_file = Path(\"wordgram_model\")\n if my_file.is_file() == False:\n button3.configure(state='disabled')\n button4.configure(state='disabled')\n else:\n button3.configure(state='enabled')\n button4.configure(state='enabled')\n elif Status.classifier_type == 'agglomerative':\n my_file = Path(\"agglomerative_model\")\n if my_file.is_file() == False:\n button3.configure(state='disabled')\n button4.configure(state='disabled')\n else:\n button3.configure(state='enabled')\n button4.configure(state='enabled')\n else:\n my_file = Path(\"clustering_model\")\n if my_file.is_file() == False:\n button3.configure(state='disabled')\n button4.configure(state='disabled')\n else:\n button3.configure(state='enabled')\n button4.configure(state='enabled')\n button2.configure(state='enabled')\n\ndef message_status(message,type):\n\n if type == 0:\n status.configure(foreground=\"red\")\n status_text.set(message)\n else:\n status.configure(foreground=\"green\")\n status_text.set(message)\n\n#EVENT HANDLER\n\ndef model_trainer_start():\n update_status()\n if Status.classifier_type == 'stylometry':\n SC_Data_To_CSV.runProgram()\n SC_Model_Trainer.runProgram()\n elif Status.classifier_type == 'content':\n WGC_Data_To_CSV.runProgram()\n WGC_Model_Trainer.runProgram()\n elif Status.classifier_type == 'merged':\n MC_Data_To_CSV.runProgram()\n MC_Model_Trainer.runProgram()\n elif Status.classifier_type == 'agglomerative':\n ACC_Data_To_CSV.runProgram()\n ACC_Model_Trainer.runProgram()\n else :\n CC_Data_To_CSV.runProgram()\n CC_Model_Trainer.runProgram()\n is_model_trained()\n Status.is_app_waiting = False\n button2.configure(state='enabled')\n button3.configure(state='enabled')\n button4.configure(state='enabled')\n\ndef model_trainer():\n button2.configure(state='disabled')\n button3.configure(state='disabled')\n button4.configure(state='disabled')\n Status.is_app_waiting = True\n t = Thread(target=model_trainer_start)\n t.start()\n\ndef form_sheet_start():\n update_status()\n if Status.classifier_type == 'stylometry':\n view = Helper_Method.popupmsg(SC_User_Input.runProgram(textarea.get(\"1.0\", tk.END)))\n elif Status.classifier_type == 'content':\n view = Helper_Method.popupmsg(WGC_User_Input.runProgram(textarea.get(\"1.0\", tk.END)))\n elif Status.classifier_type == 'merged':\n view = Helper_Method.popupmsg(MC_User_Input.runProgram(textarea.get(\"1.0\", tk.END)))\n elif Status.classifier_type == 'agglomerative':\n view = Helper_Method.popupmsg(ACC_User_Input.runProgram(textarea.get(\"1.0\", tk.END)))\n else :\n view = Helper_Method.popupmsg(CC_User_Input.runProgram(textarea.get(\"1.0\", tk.END)))\n Status.is_app_waiting = False\n\ndef form_sheet_all():\n Status.is_report_prediction = True\n Status.is_app_waiting = True\n t1 = Thread(target=form_sheet_start)\n t1.start()\n\ndef form_sheet():\n Status.is_app_waiting = True\n t1 = Thread(target=form_sheet_start)\n t1.start()\n\ndef update_status_combo(index, value, op):\n classifier_Type.selection_clear()\n if classifier_Type.current() == 1:\n ngram_type.configure(state='disabled')\n else:\n ngram_type.configure(state='readonly')\n update_status()\n is_model_trained()\n\n\ndef update_status():\n classifier_Type.selection_clear()\n if classifier_Type.current() == 0:\n Status.classifier_type = 'clustering'\n elif classifier_Type.current() == 1:\n Status.classifier_type = 'stylometry'\n elif classifier_Type.current() == 2:\n Status.classifier_type = 'content'\n elif classifier_Type.current() == 3:\n Status.classifier_type = 'agglomerative'\n elif classifier_Type.current() == 4:\n Status.classifier_type = 'merged'\n\n if ngram_type.current() == 0:\n Status.vector_analyser_type = \"word\"\n else :\n Status.vector_analyser_type = \"char\"\n\n if ngram_val.current() == 0:\n Status.vector_analyser_range = 2\n elif ngram_val.current() == 1:\n Status.vector_analyser_range = 1\n elif ngram_val.current() == 2:\n Status.vector_analyser_range = 3\n elif ngram_val.current() == 4:\n Status.vector_analyser_range = 4\n elif ngram_val.current() == 5:\n Status.vector_analyser_range = 5\n elif ngram_val.current() == 6:\n Status.vector_analyser_range = 6\n elif ngram_val.current() == 7:\n Status.vector_analyser_range = 7\n elif ngram_val.current() == 8:\n Status.vector_analyser_range = 8\n elif ngram_val.current() == 9:\n Status.vector_analyser_range = 9\n else :\n Status.vector_analyser_range = 10\n\n if select_kbest_range.current() == 0:\n kbest_threshhold = 1000\n elif select_kbest_range.current() == 1:\n kbest_threshhold = 500\n else:\n kbest_threshhold = 5000\n\n\n# root\nroot = tk.Tk()\nroot.title(\"Gender Identifier\")\nstyle = ThemedStyle(root)\nstyle.set_theme(\"arc\")\nHelper_Method.center_window(1010, 580,root)\n\n# sidebar\nsidebar = tk.Frame(root, width=350, bg='white', height=800, relief='sunken', borderwidth=2)\n\n# TYPES\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=2)\nttk.Label(sidebar,text=\"Classifier Type\", style=\"BW.TLabel\",width=22,background=\"white\",foreground=\"black\").pack(side=tk.TOP)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=2)\nclassifier_Type_Text = tk.StringVar()\nclassifier_Type = ttk.Combobox(sidebar,textvariable=classifier_Type_Text,width=22,height=45,state=\"readonly\", values=(\"KMean Cluster (Recommended)\", \"Stylometry Method\", \"Content Method\",\"Agglomerative Cluster\",\"Merged Classifier\"))\nclassifier_Type.pack(side=tk.TOP)\nclassifier_Type.current(0)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=3)\n\nttk.Label(sidebar,text=\"N-Gram Type\", style=\"BW.TLabel\",width=22,background=\"white\",foreground=\"black\").pack(side=tk.TOP)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=2)\nngram_type_text = tk.StringVar()\nngram_type = ttk.Combobox(sidebar,textvariable=ngram_type_text,width=22,height=15,state=\"readonly\", values=(\"Word (Recomended)\", \"Char\"))\nngram_type.pack(side=tk.TOP)\nngram_type.current(0)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=3)\n\nttk.Label(sidebar,text=\"N-Gram Range\", style=\"BW.TLabel\",width=22,background=\"white\",foreground=\"black\").pack(side=tk.TOP)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=2)\nngram_val_text = tk.StringVar()\nngram_val = ttk.Combobox(sidebar,textvariable=ngram_val_text,width=22,height=15,state=\"readonly\", values=(\"1-2 (Recomended)\", \"1-1\", \"1-3\", \"1-4\", \"1-5\", \"1-6\", \"1-7\", \"1-8\", \"1-9\", \"1-10\"))\nngram_val.pack(side=tk.TOP)\nngram_val.current(0)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=3)\n\nttk.Label(sidebar,text=\"KBest Threshhold\", style=\"BW.TLabel\",width=20,background=\"white\",foreground=\"black\").pack(side=tk.TOP)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=2)\nselect_kbest_range_text = tk.StringVar()\nselect_kbest_range = ttk.Combobox(sidebar,textvariable=select_kbest_range_text,width=22,height=15,state=\"readonly\", values=(\"1000 (Recomended)\", \"500\", \"5000\"))\nselect_kbest_range.pack(side=tk.TOP)\nselect_kbest_range.current(0)\n\n# ACTIONS\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=33)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=33)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=20)\nstatus_text = tk.StringVar()\nstatus_text.set('Waiting For Response')\nstatus = ttk.Label(sidebar,textvariable=status_text, style=\"BW.TLabel\",width=22,background=\"white\",foreground=\"green\")\nstatus.pack(side=tk.TOP)\nttk.Separator(sidebar,orient=\"vertical\").pack(padx=5, pady=15)\nbutton4 = ttk.Button(sidebar,width=22,text=\"Report Prediction\",command=form_sheet)\nbutton2 = ttk.Button(sidebar,width=22,text=\"Re-Train Model\",command=model_trainer)\nbutton3 = ttk.Button(sidebar,width=22,text=\"Make Prediction\",command=form_sheet_all)\nbutton2.pack(side=tk.TOP, pady=4, padx=10)\nbutton3.pack(side=tk.TOP, pady=4, padx=10)\nbutton4.pack(side=tk.TOP, pady=4, padx=10)\nsidebar.pack(expand=False, fill='both', side='left', anchor='nw')\n\n# combo changing events\nclassifier_Type_Text.trace('w',update_status_combo)\nngram_type_text.trace('w',update_status_combo)\nngram_val_text.trace('w',update_status_combo)\nselect_kbest_range_text.trace('w',update_status_combo)\n\n# main content area\nmainarea = tk.Frame(root, bg='#CCC', width=700, height=800)\ntextarea = tk.Text(mainarea,height=72,width=120)\ntextarea.pack(side=tk.RIGHT)\ntextarea.insert(tk.END, \"Write your Code\")\nmainarea.pack(expand=True, fill='both', side='right')\nis_model_trained()\n\nt = Thread(target=global_timer)\nt.start()\n\nroot.mainloop()\n","sub_path":"Plugin Projects/Matsbot/Classifier/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"179154551","text":"import serial\nimport time\n\nser = serial.Serial(\"COM3\")\n\nf = open('./songs.csv', 'r')\n\nsongs = []\nsongs_menu = {}\nwhile True:\n line = f.readline()\n if line == '':\n break\n line_data = line.strip().split(',')\n songs.append(line_data)\n songs_menu[line_data[0]] = line_data[1:]\n\n\nprint('Which song do you like? Enter the number:')\nfor i in range(len(songs)):\n print('{}. {}'.format(i + 1, songs[i][0]))\noption = int(input('>> '))\nsong = songs_menu[songs[option - 1][0]]\n\ntime.sleep(2)\nfor i in song:\n ser.write((i+'$').encode())\n print(i)\n time.sleep(0.5)\n","sub_path":"qiuhuiming/code/week8/sing.py","file_name":"sing.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"180874959","text":"import requests\nimport json\nurl=\"https://westus.api.cognitive.microsoft.com/vision/v1.0/describe?maxCandidates=1\"\nheaders = {\n # Request headers\n 'Content-Type': 'application/json',\n 'Ocp-Apim-Subscription-Key': '1e8134bdc68e401bb07f143de8e9c1e0',\n}\nparameters={\n 'maxCandidates':'1'\n}\nbod={\n \"url\":\"http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg\"\n }\n\n\nresponse=requests.post(url,\"{'url':'http://www.wallpapereast.com/static/images/spring-in-nature-wide-wallpaper-603794.jpg'}\",headers=headers)\n#response=requests.post(url,data=bod,headers=headers)\n\ndata=response.json()\nresult=data['description']['captions'][0]['text']\n\n\n\n#print(data)\nprint(result)\n\n\n\n\nfrom gtts import gTTS\nimport os\n\ntts = gTTS(text=result, lang='en')\ntts.save(\"good.mp3\")\nos.system(\" good.mp3\")","sub_path":"Untitled-1.py","file_name":"Untitled-1.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"349946876","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('clientes', '0001_initial'),\n ('productos', '0002_auto_20141112_0418'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AbonoCliente',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('abono', models.DecimalField(max_digits=8, decimal_places=2)),\n ('fecha', models.DateField(auto_now_add=True)),\n ('ap', models.IntegerField()),\n ('cliente', models.ForeignKey(to='clientes.Cliente')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Apartado',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('no_apartado', models.IntegerField()),\n ('fecha', models.DateField(auto_now_add=True)),\n ('cantidad', models.PositiveIntegerField()),\n ('precio', models.DecimalField(max_digits=8, decimal_places=2, blank=True)),\n ('fecha_vence', models.DateField(default=datetime.datetime(2014, 11, 27, 16, 22, 4, 132580))),\n ('estatus', models.CharField(default=b'A', max_length=1, choices=[(b'A', b'Activo'), (b'X', b'Anulado'), (b'C', b'Completado')])),\n ('cliente', models.ForeignKey(to='clientes.Cliente')),\n ('producto', models.ForeignKey(to='productos.Producto')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='DeudaCliente',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('deuda', models.DecimalField(max_digits=8, decimal_places=2)),\n ('cliente', models.ForeignKey(to='clientes.Cliente')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"apartados/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"578955726","text":"# Licensed under the MIT License - see LICENSE.rst\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport os\nimport numpy as np\nfrom scipy.integrate import quad\nimport astropy.units as u\nfrom astropy.coordinates import UnitSphericalRepresentation, CartesianRepresentation\nfrom astropy.coordinates.matrix_utilities import rotation_matrix, matrix_product\n\nfrom .sun import draw_random_sunspot_latitudes, draw_random_sunspot_radii\n\n__all__ = ['Star', 'Spot']\n\ntrappist1_posteriors_path = os.path.join(os.path.dirname(__file__), os.pardir,\n 'data', 'trappist1',\n 'posteriors_bright_spot.txt')\n #'trappist1_spotmodel_posteriors.txt')\n #'trappist1_spotmodel_posteriors_onehemisphere.txt')\n#'trappist1_spotmodel_posteriors.txt')\n\nk296_posteriors_path = os.path.join(os.path.dirname(__file__), os.pardir,\n 'data', 'k296',\n 'k296_spotmodel_posteriors.txt')\n\n#np.random.seed(42)\n\n\nclass Spot(object):\n \"\"\"\n Properties of a starspot.\n \"\"\"\n def __init__(self, x=None, y=None, z=None, r=None, stellar_radius=1,\n contrast=None):\n \"\"\"\n Parameters\n ----------\n x : float\n X position [stellar radii]\n y : float\n Y position [stellar radii]\n z : float\n Z position [stellar radii], default is ``z=sqrt(r_star^2 - x^2 - y^2)``.\n r : float\n Spot radius [stellar radii], default is ``r=1``.\n stellar_radius : float\n Radius of the star, in the same units as ``x,y,z,r``. Default is 1.\n \"\"\"\n if z is None:\n z = np.sqrt(stellar_radius**2 - x**2 - y**2)\n self.r = r\n self.cartesian = CartesianRepresentation(x=x, y=y, z=z)\n self.contrast = contrast\n\n @classmethod\n def from_latlon(cls, latitude, longitude, radius, contrast=None):\n \"\"\"\n Construct a spot from latitude, longitude coordinates\n\n Parameters\n ----------\n latitude : float\n Spot latitude [deg]\n longitude : float\n Spot longitude [deg]\n radius : float\n Spot radius [stellar radii]\n \"\"\"\n\n cartesian = latlon_to_cartesian(latitude, longitude)\n\n return cls(x=cartesian.x.value, y=cartesian.y.value,\n z=cartesian.z.value, r=radius, contrast=contrast)\n\n @classmethod\n def from_sunspot_distribution(cls, mean_latitude=15, radius_multiplier=1,\n contrast=0.7):\n \"\"\"\n Parameters\n ----------\n mean_latitude : float\n Define the mean absolute latitude of the two symmetric active\n latitudes, where ``mean_latitude > 0``.\n \"\"\"\n lat = draw_random_sunspot_latitudes(n=1, mean_latitude=mean_latitude)[0]\n lon = 2*np.pi * np.random.rand() * u.rad\n radius = draw_random_sunspot_radii(n=1)[0]\n\n cartesian = latlon_to_cartesian(lat, lon)\n\n return cls(x=cartesian.x.value, y=cartesian.y.value,\n z=cartesian.z.value, r=radius*radius_multiplier,\n contrast=contrast)\n\n def __repr__(self):\n return (\"\"\n .format(self.x, self.y, self.z, self.r))\n\n\ndef latlon_to_cartesian(latitude, longitude, stellar_inclination=90*u.deg):\n \"\"\"\n Convert coordinates in latitude/longitude for a star with a given\n stellar inclination into cartesian coordinates.\n\n The X-Y plane is the sky plane: x is aligned with the stellar equator, y is\n aligned with the stellar rotation axis.\n\n Parameters\n ----------\n latitude : float or `~astropy.units.Quantity`\n Spot latitude. Will assume unit=deg if none is specified.\n longitude : float or `~astropy.units.Quantity`\n Spot longitude. Will assume unit=deg if none is specified.\n stellar_inclination : float\n Stellar inclination angle, measured away from the line of sight,\n in [deg]. Default is 90 deg.\n\n Returns\n -------\n cartesian : `~astropy.coordinates.CartesianRepresentation`\n Cartesian representation in the frame described above.\n \"\"\"\n\n if not hasattr(longitude, 'unit') and not hasattr(latitude, 'unit'):\n longitude *= u.deg\n latitude *= u.deg\n\n c = UnitSphericalRepresentation(longitude, latitude)\n cartesian = c.to_cartesian()\n\n rotate_about_z = rotation_matrix(90*u.deg, axis='z')\n rotate_is = rotation_matrix(stellar_inclination, axis='y')\n transform_matrix = matrix_product(rotate_about_z, rotate_is)\n cartesian = cartesian.transform(transform_matrix)\n return cartesian\n\n\nclass Star(object):\n \"\"\"\n Object defining a star.\n \"\"\"\n def __init__(self, spots=None, u1=0.4987, u2=0.1772, r=1,\n radius_threshold=0.1, rotation_period=25*u.day):\n \"\"\"\n The star is assumed to have stellar inclination 90 deg (equator-on).\n\n Parameters\n ----------\n u1 : float (optional)\n Quadratic limb-darkening parameter, linear term\n u2 : float (optional)\n Quadratic limb-darkening parameter, quadratic term\n r : float (optional)\n Stellar radius (default is unity)\n radius_threshold : float (optional)\n If all spots are smaller than this radius, use the analytic solution\n to compute the stellar centroid, otherwise use the numerical\n solution.\n spots : list (optional)\n List of spots on this star.\n rotation_period : `~astropy.units.Quantity`\n Stellar rotation period [default = 25 d].\n contrast : float (optional)\n Spot contrast relative to photosphere. Default is ``c=0.7``\n \"\"\"\n if spots is None:\n spots = []\n self.spots = spots\n\n self.spots_cartesian = CartesianRepresentation(x=[spot.cartesian.x for spot in spots],\n y=[spot.cartesian.y for spot in spots],\n z=[spot.cartesian.z for spot in spots])\n self.spots_r = np.array([spot.r for spot in spots])\n self.spot_contrasts = np.array([spot.contrast for spot in spots])\n self.x = 0\n self.y = 0\n self.r = r\n self.u1 = u1\n self.u2 = u2\n self.radius_threshold = radius_threshold\n self.rotations_applied = 0 * u.deg\n self.rotation_period = rotation_period\n self.inclination = 90*u.deg\n self.unspotted_flux = (2 * np.pi *\n quad(lambda r: r * self.limb_darkening_normed(r),\n 0, self.r)[0])\n\n def plot(self, n=3000, ax=None):\n \"\"\"\n Plot a 2D projected schematic of the star and its spots.\n\n Parameters\n ----------\n ax : `~matplotlib.pyplot.Axes`\n Axis object to draw the plot on\n n : int\n Number of pixels per side in the image.\n\n Returns\n -------\n ax : `~matplotlib.pyplot.Axes`\n Matplotlib axis object, with the new plot on it.\n \"\"\"\n import matplotlib.pyplot as plt\n\n if ax is None:\n ax = plt.gca()\n\n image = self._compute_image(n=n)\n\n ax.imshow(image, origin='lower', interpolation='nearest',\n cmap=plt.cm.Greys_r, extent=[-1, 1, -1, 1],\n vmin=0, vmax=1)\n ax.set_aspect('equal')\n\n ax.set_xlim([-1, 1])\n ax.set_ylim([-1, 1])\n ax.set_xlabel('x [$R_\\star$]', fontsize=14)\n ax.set_ylabel('y [$R_\\star$]', fontsize=14)\n return ax\n\n @classmethod\n def with_trappist1_spot_distribution(cls):\n samples = np.loadtxt(trappist1_posteriors_path)\n sample_index = np.random.randint(0, samples.shape[0])\n\n lat0, lon0, rad0, lat1, lon1, rad1, lat2, lon2, rad2, contrast, kep_offset = samples[sample_index, :]\n\n spots = [Spot.from_latlon(lat0, lon0, rad0, contrast),\n Spot.from_latlon(lat1, lon1, rad1, contrast),\n Spot.from_latlon(lat2, lon2, rad2, contrast)]\n\n return cls(spots=spots, rotation_period=3.3*u.day)\n\n @classmethod\n def with_k296_spot_distribution(cls):\n samples = np.loadtxt(k296_posteriors_path)\n sample_index = np.random.randint(0, samples.shape[0])\n\n lat0, lon0, rad0, lat1, lon1, rad1, contrast, kep_offset = samples[sample_index, :]\n\n spots = [Spot.from_latlon(lat0, lon0, rad0, contrast),\n Spot.from_latlon(lat1, lon1, rad1, contrast)]\n\n return cls(spots=spots, rotation_period=36.085629155859351*u.day)\n\n def spotted_area(self, times, t0=0):\n \"\"\"\n Compute flux at ``times`` as the star rotates.\n\n Parameters\n ----------\n times: `~numpy.ndarray`\n Times\n t0 : float\n Reference epoch.\n\n Returns\n -------\n area : `~numpy.ndarray`\n Area covered by spots at ``times`` [Hem]\n \"\"\"\n p_rot_d = self.rotation_period.to(u.d).value\n rotational_phases = (((times - t0) % p_rot_d) / p_rot_d) * 2*np.pi*u.rad\n\n # Rotate the star about its axis assuming stellar inclination 90 deg\n transform_matrix = rotation_matrix(rotational_phases[:, np.newaxis],\n axis='y')\n old_cartesian = self.spots_cartesian\n new_cartesian = old_cartesian.transform(transform_matrix)\n\n # Use numpy array broadcasting to vectorize computations with spot radii\n broadcast_radii = (np.ones_like(rotational_phases.value)[:, np.newaxis]\n * self.spots_r)\n\n # Only include spot flux if it's on the observer facing side\n visible = (new_cartesian.z > 0).astype(int)\n\n # Compute radial position of spot\n r_spots = np.sqrt(new_cartesian.x**2 + new_cartesian.y**2)\n\n # Compute approximate spot area, given foreshortening in 3D\n spot_areas = (np.pi * broadcast_radii**2 *\n np.sqrt(1 - (r_spots/self.r)**2))\n area = np.sum(spot_areas * visible, axis=1) / (2 * np.pi * self.r**2)\n if hasattr(area, 'unit'):\n area = area.value\n return area\n\n def flux(self, times, t0=0):\n \"\"\"\n Compute flux at ``times`` as the star rotates.\n\n Parameters\n ----------\n times: `~numpy.ndarray`\n Times\n t0 : float\n Reference epoch.\n\n Returns\n -------\n flux : `~numpy.ndarray`\n Fluxes at ``times``\n \"\"\"\n p_rot_d = self.rotation_period.to(u.d).value\n rotational_phases = (((times - t0) % p_rot_d) / p_rot_d) * 2*np.pi*u.rad\n\n # Rotate the star about its axis assuming stellar inclination 90 deg\n transform_matrix = rotation_matrix(rotational_phases[:, np.newaxis],\n axis='y')\n old_cartesian = self.spots_cartesian\n new_cartesian = old_cartesian.transform(transform_matrix)\n\n # Use numpy array broadcasting to vectorize computations with spot radii\n broadcast_radii = (np.ones_like(rotational_phases.value)[:, np.newaxis]\n * self.spots_r)\n\n # Only include spot flux if it's on the observer facing side\n visible = (new_cartesian.z > 0).astype(int)\n\n # Compute radial position of spot\n r_spots = np.sqrt(new_cartesian.x**2 + new_cartesian.y**2)\n\n # Compute approximate spot area, given foreshortening in 3D\n spot_areas = (np.pi * broadcast_radii**2 *\n np.sqrt(1 - (r_spots/self.r)**2))\n\n # For a given spot contrast and limb darkening, compute missing flux\n spot_flux = (-1 * spot_areas * self.limb_darkening_normed(r_spots) *\n (1 - self.spot_contrasts)) * visible\n\n return self.unspotted_flux + np.sum(spot_flux, axis=1)\n\n def fractional_flux(self, times, t0=0):\n \"\"\"\n Compute stellar flux as a fraction of the unspotted stellar flux at\n ``times`` as the star rotates.\n\n Parameters\n ----------\n times: `~numpy.ndarray`\n Times\n t0 : float\n Reference epoch.\n\n Returns\n -------\n flux : `~numpy.ndarray`\n Fluxes at ``times``\n \"\"\"\n return self.flux(times, t0=t0)/self.unspotted_flux\n #\n # def flux_weighted_area(self, times, t0=0):\n # \"\"\"\n # Compute flux at ``times`` as the star rotates.\n #\n # Parameters\n # ----------\n # times: `~numpy.ndarray`\n # Times\n # t0 : float\n # Reference epoch.\n #\n # Returns\n # -------\n # flux : `~numpy.ndarray`\n # Fluxes at ``times``\n # \"\"\"\n # p_rot_d = self.rotation_period.to(u.d).value\n # rotational_phases = (((times - t0) % p_rot_d) / p_rot_d) * 2*np.pi*u.rad\n #\n # # Rotate the star about its axis assuming stellar inclination 90 deg\n # transform_matrix = rotation_matrix(rotational_phases[:, np.newaxis],\n # axis='y')\n # old_cartesian = self.spots_cartesian\n # new_cartesian = old_cartesian.transform(transform_matrix)\n #\n # # Use numpy array broadcasting to vectorize computations with spot radii\n # broadcast_radii = (np.ones_like(rotational_phases.value)[:, np.newaxis]\n # * self.spots_r)\n #\n # # Only include spot flux if it's on the observer facing side\n # visible = (new_cartesian.z > 0).astype(int)\n #\n # # Compute radial position of spot\n # r_spots = np.sqrt(new_cartesian.x**2 + new_cartesian.y**2)\n #\n # # Compute approximate spot area, given foreshortening in 3D\n # spot_areas = (np.pi * broadcast_radii**2 *\n # np.sqrt(1 - (r_spots/self.r)**2))\n #\n # area_spotted = np.sum(spot_areas * visible, axis=1) / (2 * np.pi * self.r**2)\n #\n # if hasattr(area_spotted, 'unit'):\n # area_spotted = area_spotted.value\n #\n # # For a given spot contrast and limb darkening, compute missing flux\n # flux_spots = np.sum((spot_areas * self.limb_darkening_normed(r_spots) *\n # (1 - self.contrast)) * visible, axis=1)\n #\n # missing_photosphere = (-1 * spot_areas *\n # self.limb_darkening_normed(r_spots)) * visible\n #\n # flux_photosphere = self.unspotted_flux + np.sum(missing_photosphere,\n # axis=1)\n #\n # photosphere_area = 1 - area_spotted\n #\n # # flux_weighted_spot_area = (flux_photosphere * photosphere_area +\n # # flux_spots * area_spotted)\n #\n # flux_weighted_spot_area = (flux_spots * area_spotted /\n # (flux_photosphere * photosphere_area))\n #\n # if hasattr(flux_weighted_spot_area, 'unit'):\n # flux_weighted_spot_area = flux_weighted_spot_area.value\n #\n # return flux_weighted_spot_area\n\n def _compute_image(self, n=3000, delete_arrays_after_use=True):\n \"\"\"\n Compute the stellar centroid using a numerical approximation.\n\n Parameters\n ----------\n n : int\n Generate a simulated image of the star with ``n`` by ``n`` pixels.\n\n Returns\n -------\n x_centroid : float\n Photocenter in the x dimension, in units of stellar radii\n y_centroid : float\n Photocenter in the y dimension, in units of stellar radii\n \"\"\"\n image = np.zeros((n, n))\n x = np.linspace(-self.r, self.r, n)\n y = np.linspace(-self.r, self.r, n)\n x, y = np.meshgrid(x, y)\n\n # Limb darkening\n irradiance = self.limb_darkening_normed(np.sqrt(x**2 + y**2))\n\n on_star = x**2 + y**2 <= self.r**2\n\n image[on_star] = irradiance[on_star]\n on_spot = None\n\n for cartesian, r, c in zip(self.spots_cartesian, self.spots_r,\n self.spot_contrasts):\n if cartesian.z > 0:\n r_spot = np.sqrt(cartesian.x**2 + cartesian.y**2)\n foreshorten_semiminor_axis = np.sqrt(1 - (r_spot/self.r)**2)\n\n a = r # Semi-major axis\n b = r * foreshorten_semiminor_axis # Semi-minor axis\n A = np.pi/2 + np.arctan2(cartesian.y.value, cartesian.x.value) # Semi-major axis rotation\n on_spot = (((x - cartesian.x) * np.cos(A) +\n (y - cartesian.y) * np.sin(A))**2 / a**2 +\n ((x - cartesian.x) * np.sin(A) -\n (y - cartesian.y) * np.cos(A))**2 / b**2 <= self.r**2)\n\n image[on_spot & on_star] *= c\n\n if delete_arrays_after_use:\n del on_star\n if on_spot is not None:\n del on_spot\n del x\n del y\n del irradiance\n\n return image\n\n def limb_darkening(self, r):\n \"\"\"\n Compute the intensity at radius ``r`` for quadratic limb-darkening law\n with parameters ``Star.u1, Star.u2``.\n\n Parameters\n ----------\n r : float or `~numpy.ndarray`\n Stellar surface position in radial coords on (0, 1)\n\n Returns\n -------\n intensity : float\n Intensity in un-normalized units\n \"\"\"\n mu = np.sqrt(1 - r**2)\n u1 = self.u1\n u2 = self.u2\n return (1 - u1 * (1 - mu) - u2 * (1 - mu)**2) / (1 - u1/3 - u2/6) / np.pi\n\n def limb_darkening_normed(self, r):\n \"\"\"\n Compute the normalized intensity at radius ``r`` for quadratic\n limb-darkening law with parameters ``Star.u1, Star.u2``.\n\n Parameters\n ----------\n r : float or `~numpy.ndarray`\n Stellar surface position in radial coords on (0, 1)\n\n Returns\n -------\n intensity : float\n Intensity relative to the intensity at the center of the disk.\n \"\"\"\n return self.limb_darkening(r) / self.limb_darkening(0)\n\n def rotate(self, angle):\n \"\"\"\n Rotate the star, by moving the spots.\n\n Parameters\n ----------\n angle : `~astropy.units.Quantity`\n\n \"\"\"\n transform_matrix = rotation_matrix(angle, axis='y')\n\n old_cartesian = self.spots_cartesian\n new_cartesian = old_cartesian.transform(transform_matrix)\n self.spots_cartesian = new_cartesian\n self.rotations_applied += angle\n\n def derotate(self):\n self.rotate(-self.rotations_applied)\n self.rotations_applied = 0\n","sub_path":"libra/starspots/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":19023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"221769223","text":"\n\nnum = int(input())\t\t# Number of elemnts in an array\n\narr = []\t\t\t\t# Array of numbers\nte = input()\nte = te.split()\n\nfor i in range(num):\n\tarr.append(int(te[i]))\n\nfreq = [0 for i in range (128)]\t\t# Contains the number of times a particular Xor value comes (index represent the Xor value)\n\nfor i in range (num):\n\ttemp = [0 for k in range (128)]\n\n\tfor j in range (128):\n\t\tif j == arr[i]:\n\t\t\ttemp[j] = 1\n\t\telif freq[j] != 0:\n\t\t\ttemp [j^arr[i]] += freq[j]\n\tfor j in range (128):\n\t\tfreq[j] += temp[j]\n\nans = 0\n\nfor i in range(128):\n\tif freq[i]>1:\n\t\tans += freq[i]*(freq[i]-1)/2\n\nans = ans % 1000000007\nprint (int(ans))\n","sub_path":"panda.py","file_name":"panda.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"388301088","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2009 Benoit Chesneau \n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution.\n\nimport os\nimport sys\n\nfrom ez_setup import use_setuptools\nif 'cygwin' in sys.platform.lower():\n min_version='0.6c6'\nelse:\n min_version='0.6a9'\ntry:\n use_setuptools(min_version=min_version)\nexcept TypeError:\n # If a non-local ez_setup is already imported, it won't be able to\n # use the min_version kwarg and will bail with TypeError\n use_setuptools()\n\nfrom setuptools import setup, find_packages\n\ndata_files = []\n\nfor dir, dirs, files in os.walk('templates'):\n data_files.append((os.path.join('couchapp', dir), \n [os.path.join(dir, file_) for file_ in files]))\n\nfor dir, dirs, files in os.walk('vendor'):\n data_files.append((os.path.join('couchapp', dir), \n [os.path.join(dir, file_) for file_ in files]))\n \n\nsetup(\n name = 'Couchapp',\n version = '0.3.4',\n url = 'http://github.com/couchapp/couchapp/tree/master',\n license = 'Apache License 2',\n author = 'Benoit Chesneau',\n author_email = 'benoitc@e-engura.org',\n description = 'Standalone CouchDB Application Development Made Simple.',\n long_description = \"\"\"CouchApp is a set of helpers and a jQuery plugin\n that conspire to get you up and running on CouchDB quickly and\n correctly. It brings clarity and order to the freedom of CouchDB's\n document-based approach.\"\"\",\n keywords = 'couchdb couchapp',\n platforms = ['any'],\n\n zip_safe = False,\n\n packages=find_packages('src'),\n package_dir={\n '': 'src'\n },\n data_files = data_files,\n include_package_data = True,\n entry_points = {\n 'console_scripts': [\n 'couchapp = couchapp.bin.couchapp_cli:main',\n ]\n },\n classifiers = [\n 'License :: OSI Approved :: Apache Software License',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'Development Status :: 4 - Beta',\n 'Programming Language :: Python',\n 'Operating System :: OS Independent',\n 'Topic :: Database',\n 'Topic :: Utilities',\n ],\n test_suite='tests',\n\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"312215559","text":"import os \nimport numpy as np \nimport tensorflow as tf \nimport input_data \nimport model \nimport matplotlib.pyplot as PLT\n#变量声明 \nN_CLASSES = 4\nIMG_W = 100 # resize图像,太大的话训练时间久 \nIMG_H = 100 \nBATCH_SIZE =32 \nCAPACITY = 200 \nMAX_STEP = 1000 # 一般大于10K \nlearning_rate = 0.00001 # 一般小于0.0001 \npath=os.path.abspath('.')\n#获取批次batch \ntrain_dir = path+ '/pic' #训练样本的读入路径 \nlogs_train_dir = path+'/logs' #logs存储路径 \n\ntrain, train_label, val, val_label = input_data.get_files(train_dir, 0.001) \n#训练数据及标签 \ntrain_batch,train_label_batch = input_data.get_batch(train, train_label, IMG_W, IMG_H, BATCH_SIZE, CAPACITY) \n#print(train_label_batch) #Tensor(\"Reshape_7:0\", shape=(30,), dtype=int32)\n#print(train_batch) #Tensor(\"batch_9:0\", shape=(30, 64, 64, 3), dtype=float32)\n#测试数据及标签 \nval_batch, val_label_batch = input_data.get_batch(val, val_label, IMG_W, IMG_H, BATCH_SIZE, CAPACITY) \n \n#训练操作定义 \ntrain_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES) #inference返回的是一个softmax——linear\n#print (train_logits) ##Tensor(\"softmax_linear_4/softmax_linear_1:0\", shape=(30, 2), dtype=float32)\ntrain_loss = model.losses(train_logits, train_label_batch) # \ntrain_op = model.trainning(train_loss, learning_rate) \ntrain_acc = model.evaluation(train_logits, train_label_batch) #train loss \\train op\\train acc 是要在sess.run里边进行运行的 \n \n#测试操作定义 \n#test_logits = model.inference(val_batch, BATCH_SIZE, N_CLASSES) #这样会定义新的一幅图 \n#test_loss = model.losses(test_logits, val_label_batch) \n#test_acc = model.evaluation(test_logits, val_label_batch) \n \n#这个是log汇总记录 \nsummary_op = tf.summary.merge_all() \n \n#产生一个会话 \nsess = tf.Session() \n#产生一个writer来写log文件 \ntrain_writer = tf.summary.FileWriter(logs_train_dir, sess.graph) #tensorboard能查看吗? \n#val_writer = tf.summary.FileWriter(logs_test_dir, sess.graph) \n#产生一个saver来存储训练好的模型 \nsaver = tf.train.Saver() \n#所有节点初始化\nsess.run(tf.global_variables_initializer()) \n#队列监控 \ncoord = tf.train.Coordinator() \nthreads = tf.train.start_queue_runners(sess=sess, coord=coord) \nlist_loss = []\nlist_acc = []\nlist_step = []\n#进行batch的训练 \ntry: \n #执行MAX_STEP步的训练,一步一个batch \n for step in np.arange(MAX_STEP): #100\n if coord.should_stop(): #关于多线程停止的一个类\n break \n #启动以下操作节点,有个疑问,为什么train_logits在这里没有开启? 因为train_logits在train_loss里面开启了\n _, tra_loss, tra_acc = sess.run([train_op, train_loss, train_acc]) \n \n #每10步打印一次当前的loss以及acc,同时记录log,写入writer \n if step % 100 == 0: \n print('Step %d, train loss = %.2f, train accuracy = %.2f%%' %(step, tra_loss, tra_acc*100.0)) \n list_loss.append(tra_loss)\n list_acc.append(tra_acc*100)\n list_step.append(step/10)\n PLT.plot(list_step,list_acc)\n PLT.plot(list_step,list_loss)\n summary_str = sess.run(summary_op) \n train_writer.add_summary(summary_str, step) \n #保存一次训练好的模型 \n if (step + 1) == MAX_STEP:\n print(\"saving ...\")\n checkpoint_path = os.path.join(logs_train_dir, 'model.ckpt') \n saver.save(sess, checkpoint_path, global_step=step) \n constant_graph = tf.graph_util.convert_variables_to_constants(sess, sess.graph_def, [\"softmax_linear/softmax_linear_1\"])\n with tf.gfile.FastGFile(\"zxf.pb\", mode='wb') as f:\n f.write(constant_graph.SerializeToString())\n print(\"saving pb ...\")\n print(list_loss)\n print(list_acc)\n print(list_step)\n###异常处理 \nexcept tf.errors.OutOfRangeError: \n print('Done training -- epoch limit reached') \n \nfinally: \n coord.request_stop() ","sub_path":"新建文件夹/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"239946556","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport gc\nimport argparse\nimport dace\nimport numpy as np\nimport dace.frontend.common as np_frontend\n\nimport os\nfrom timeit import default_timer as timer\n\nSDFG = dace.sdfg.SDFG\n\nM = dace.symbol('M')\nN = dace.symbol('N')\nK = dace.symbol('K')\nL = dace.symbol('L')\n\nA = dace.ndarray([L, K, M, N], dtype=dace.float64)\nB = dace.ndarray([L, N, M], dtype=dace.float64)\n\nif __name__ == \"__main__\":\n print(\"==== Program start ====\")\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"M\", type=int, nargs=\"?\", default=128)\n parser.add_argument(\"N\", type=int, nargs=\"?\", default=128)\n parser.add_argument(\"L\", type=int, nargs=\"?\", default=5)\n parser.add_argument(\"K\", type=int, nargs=\"?\", default=10)\n args = vars(parser.parse_args())\n\n M.set(args[\"M\"])\n N.set(args[\"N\"])\n K.set(args[\"K\"])\n L.set(args[\"L\"])\n\n print('Matrix transpose %dx%dx' % (M.get(), N.get()))\n\n # Initialize arrays: Randomize A and B\n A[:] = np.random.rand(L.get(), K.get(), M.get(),\n N.get()).astype(dace.float64.type)\n B[:] = np.random.rand(L.get(), N.get(), M.get()).astype(dace.float64.type)\n\n A_regression = np.ndarray(\n [L.get(), K.get(), M.get(), N.get()], dtype=np.float64)\n B_regression = np.ndarray([L.get(), N.get(), M.get()], dtype=np.float64)\n A_regression[:] = A[:]\n B_regression[:] = B[:]\n\n mtr = SDFG(name='mtr')\n mtr.add_node(\n np_frontend.op_impl.matrix_transpose_s('A',\n A.shape,\n dace.float64,\n False,\n 'B',\n B.shape,\n dace.float64,\n A_index=[2, 3],\n B_index=[4],\n label='mtr'))\n\n mtr(A=A, B=B)\n B_regression[4] = np.transpose(A_regression[2, 3])\n\n rel_error = (np.linalg.norm((B_regression - B).flatten(), ord=2) /\n np.linalg.norm(B_regression.flatten(), ord=2))\n print(\"Relative error:\", rel_error)\n print(\"==== Program end ====\")\n exit(0 if rel_error <= 1e-15 else 1)\n","sub_path":"tests/numpy/matrix_transpose_s.py","file_name":"matrix_transpose_s.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"632452331","text":"import os\nfrom glob import glob\nfrom tqdm.auto import tqdm\nimport numpy as np\nfrom ensmallen_graph import EnsmallenGraph\nfrom embiggen import GraphTransformer, EdgeTransformer\n\n#try:\n# from tsnecuda import TSNE\n#except ModuleNotFoundError:\nfrom MulticoreTSNE import MulticoreTSNE as TSNE\n\nembedding_path = \"./FOURTH/SkipGram_embedding.npy\"\n\ngraph = EnsmallenGraph.from_csv(\n edge_path=\"/global/scratch/marcin/N2V/MicrobeEnvironmentGraphLearn/ENIGMA_data/masterG.edgelist_col12_head.tsv\",\n sources_column=\"subject\",\n destinations_column=\"object\",\n directed=False\n)\n\n\nnegative_graph = graph.sample_negatives(42, graph.get_edges_number(), False)\n\nembedding = np.load(embedding_path)\n\nfor method in tqdm(EdgeTransformer.methods, desc=\"Methods\", leave=False):\n tsne_path = f\"tsne_edges_microbeenv\"\n if os.path.exists(tsne_path):\n continue\n transformer = GraphTransformer(method)\n transformer.fit(embedding)\n positive_edges = transformer.transform(graph)\n negative_edges = transformer.transform(negative_graph)\n edges = np.vstack([positive_edges, negative_edges])\n nodes = np.concatenate([\n np.ones(positive_edges.shape[0]),\n np.zeros(negative_edges.shape[0])\n ])\n indices = np.arange(0, nodes.size)\n np.random.shuffle(indices)\n edges = edges[indices]\n nodes = nodes[indices]\n np.save(f\"tsne_edges_microbeenv_labels\", nodes)\n tsne = TSNE(verbose=True)\n np.save(\n tsne_path,\n tsne.fit_transform(edges)\n )","sub_path":"notebooks/TSNE_edge_types_visualization_microbeenv.py","file_name":"TSNE_edge_types_visualization_microbeenv.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"338030849","text":"#encoding: utf-8\r\nfrom kademlia.kdht import Server\r\nfrom kademlia.ktable import KTable\r\nfrom kademlia.utils import random_id\r\n\r\nclass Master(object):\r\n def __init__(self, f):\r\n self.f = f\r\n\r\n def log(self, infohash):\r\n self.f.write(infohash.encode(\"hex\")+\"\\n\")\r\n self.f.flush()\r\n \r\ntry:\r\n f = open(\"infohash.log\", \"a\")\r\n\r\n k = KTable(random_id())\r\n m = Master(f)\r\n\r\n s = Server(k, m)\r\n s.start() \r\nexcept KeyboardInterrupt:\r\n s.socket.close()","sub_path":"simDHT.py","file_name":"simDHT.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"59291600","text":"import pygame\nimport time\nimport random\n#note that there is a pygame music function\n# but this only allows single channel (because it is streamed)\n# it is possible to play music files over sound files\n#this implyes that sound is played from ram so needs to\n#consider file size of all file to be played\n# files can be replayed\n\n#pygame.init()\npygame.mixer.init()\n#######################################\ncount = pygame.mixer.Sound(\"file1.wav\")\nmusic = pygame.mixer.Sound(\"dogyInWindow.wav\")\n\n#!/usr/bin/env python\n\nimport RPi.GPIO as GPIO\nfrom mfrc522 import SimpleMFRC522\nreader = SimpleMFRC522()\n\n#plays multiple files when read, simultaneously\n##can use count as delay, or delay, or if last !< current, etc\nwhile True:\n id, text = reader.read()\n \n if id == (576445216648):\n print ('Tag 1 Found')\n pygame.mixer.Sound.play(count)\n time.sleep(2)\n continue\n \n elif id == (561186360885):\n print ('Tag 2 Found')\n pygame.mixer.Sound.play(music)\n time.sleep(2)\n continue\n \n elif id == (427164244981):\n print ('Tag 3 Found')\n time.sleep(2)\n pygame.mixerfadeout\n \n \n## elif id == ():\n# print ('Tag 4 Stick Found')\n# pygame.mixer.Sound.play(music)\n # time.sleep(2)\n # continue\n \n####################################\n#pygame.mixer.music.load(\"dogyInWindow.wav\")\n#pygame.mixer.music.play(2)\n#pygame.mixer.music.load(\"file1.wav\")\n#pygame.mixer.music.play(2)\n\n\nGPIO.cleanup()\n","sub_path":"RaspberryPi_ToyFiles/MultiSoundTest.py","file_name":"MultiSoundTest.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"581845602","text":"battery_status = {\n '1' : 'Unknown',\n '2' : 'Normal',\n '3' : 'Low',\n '4' : 'Depleted'\n}\n\nbattery_abm_status = {\n '0' : 'Unknown',\n '1' : 'Charging',\n '2' : 'Discharging',\n '3' : 'Floating',\n '4' : 'Resting',\n '5' : 'Unknown',\n '6' : 'Disconnected',\n '7' : 'Under Test',\n '8' : 'Check Battery',\n}\n\nbattery_failure = {\n '1' : 'Yes',\n '2' : 'No'\n}\n\nbattery_not_present = {\n '1' : 'yes',\n '2' : 'No'\n}\n\nbattery_low_capacity = {\n '1' : 'yes',\n '2' : 'No'\n}\n\nbattery_test_status = {\n '1' : 'Unknown',\n '2' : 'Passed',\n '3' : 'Failed',\n '4' : 'In Progress',\n '5' : 'Not Supported',\n '6' : 'Inhibited',\n '7' : 'Scheduled',\n}\n\noutput_source = {\n '1' : 'Other',\n '2' : 'None',\n '3' : 'Normal',\n '4' : 'Bypass',\n '5' : 'Battery',\n '6' : 'Booster',\n '7' : 'Reducer',\n '8' : 'Parallel Capacity',\n '9' : 'Parallel Redundant',\n '10' : 'High Efficiency Mode',\n '11' : 'Maintenance Bypass',\n '12' : 'ESS Mode',\n}\n\ntest_results = {\n '1' : 'Done Pass',\n '2' : 'Done Warning',\n '3' : 'Done Error',\n '4' : 'Aborted',\n '5' : 'In Progress',\n '6' : 'No Tests Initiated',\n}\n\ninput_ids = {\n '1' : 'phase1toN',\n '2' : 'phase2toN',\n '3' : 'phase3toN',\n '4' : 'phase1to2',\n '5' : 'phase2to3',\n '6' : 'phase3to1'\n}\n\ninput_names = {\n '1' : 'L1/A',\n '2' : 'L2/B',\n '3' : 'L3/C',\n '4' : 'L1-L2/A-B',\n '5' : 'L2-L3/B-C',\n '6' : 'L3-L1/C-A'\n}\n\nconfig_audible_alarm = {\n '1' : 'Disabled',\n '2' : 'Enabled',\n '3' : 'Muted'\n}","sub_path":"backend/mm_ups_rt/src/mibs.py","file_name":"mibs.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10291368","text":"import sys\ninput = sys.stdin.readline\nn = int(input())\nli = []\nfor _ in range(n):\n word = input().rstrip()\n word_count = len(word)\n li.append((word, word_count))\n\n# 중복 삭제\nli = list(set(li))\n\n# 단어 숫자 정렬 > 단어 알파벳 정렬\nli.sort(key = lambda word: (word[1], word[0]))\n\nfor i in li:\n print(i[0])","sub_path":"doyeon/BOJ/★정렬/20210401_boj_1181_단어 정렬.py","file_name":"20210401_boj_1181_단어 정렬.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"202198132","text":"import sys\nimport os\nimport re\nfrom collections import defaultdict\n\t\t\nsample_dict = defaultdict(list)\n\n# read in files from the command line\nINPUT_FILE_NAME = r'KW-\\d+_HTSeq\\.txt' # regex for file name\nSAMPLE_NAME = r'KW-\\d+' # regex for sample namec\n\noutput_file_name = \"HTSeq_count_file_new.txt\"\nheader = [\"sample_ID\", \"> 10\", \">20\", \"ERCC >10\", \"ERCC > 20\"]\ndata_file_directory, date = sys.argv[1:]\n\n# read each file from the directory\nfor file_name in os.listdir(data_file_directory):\n\n\t# only read files with the format of the sorted bam file\n\tif re.match(INPUT_FILE_NAME, file_name):\n\t\tprint(file_name)\n\t\tten_count = 0\n\t\ttwenty_count = 0\n\t\tERCC_ten_count = 0\n\t\tERCC_twenty_count = 0\n\n\t\t# rename the complete filepath to include the name of the file\n\t\tfile_path = os.path.join(data_file_directory, file_name)\n\n\t\t# # name the input file\n\t\ttxt_input = file_path\n\n\t\t# name the sample based on the file name\n\t\tsample_name = ''.join(re.findall(SAMPLE_NAME, file_name)) + \"_\" + date\n\n\t\twith open(file_path, \"r\") as HTSeq_file:\n\t\t\tfor line in HTSeq_file:\n\t\t\t\tline = line.strip().split('\\t')\n\n\t\t\t\tif int(line[1]) >= 10 and \"ERCC\" not in line[0]:\n\t\t\t\t\tten_count += 1\n\n\t\t\t\tif int(line[1]) >= 20 and \"ERCC\" not in line[0]:\n\t\t\t\t\ttwenty_count += 1\n\n\t\t\t\tif int(line[1]) >= 10 and \"ERCC\" in line[0]:\n\t\t\t\t\tERCC_ten_count += 1\n\n\t\t\t\tif int(line[1]) >= 20 and \"ERCC\" in line[0]:\n\t\t\t\t\tERCC_twenty_count += 1\n\n\t\tcount_list = [str(ten_count), str(twenty_count), str(ERCC_ten_count), str(ERCC_twenty_count)]\n\n\t\tsample_dict[sample_name].extend(count_list)\t\t\n\nwith open(output_file_name, 'w') as output_file:\n\toutput_file.write('\\t'.join(header) + '\\n')\n\tfor item in sample_dict:\n\t\toutput_file.write(item + '\\t' + '\\t'.join(sample_dict[item]) + '\\n')\n\n\n","sub_path":"HTSeq_analysis_multiple_new.py","file_name":"HTSeq_analysis_multiple_new.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"374583870","text":"# -*- coding: utf-8 -*-\n\"\"\"Shim providing notebook.nbextensions stuff from 4.2 for earlier versions.\"\"\"\n\ntry:\n from notebook.nbextensions import (\n GREEN_OK, RED_X, BaseNBExtensionApp, _get_config_dir,\n )\nexcept ImportError:\n from ._compat.nbextensions import (\n GREEN_OK, RED_X, BaseNBExtensionApp, _get_config_dir,\n )\n\n__all__ = [\n 'GREEN_OK', 'RED_X', 'BaseNBExtensionApp', '_get_config_dir',\n]\n","sub_path":"src/jupyter_nbextensions_configurator/notebook_compat/nbextensions.py","file_name":"nbextensions.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"403408340","text":"class Sbc:\n \"\"\"Read and parse the SBC world file.\"\"\"\n\n def __init__(self, sbc_filename):\n \"\"\"Init for SBC reading and parsing.\"\"\"\n\n import xml.etree.ElementTree as ET\n self.factions = {}\n self.playerDict = {}\n self.world = {}\n self.mods = {}\n\n tree = ET.parse(sbc_filename)\n root = tree.getroot()\n\n # app_version = root.find('AppVersion').text\n\n settings = {}\n for setting in root.find('Settings'):\n settings[setting.tag] = setting.text\n #TODO: work with BlockTypeLimits dictionary\n self.world['settings'] = settings\n self.world['appVersion'] = root.find('AppVersion').text\n self.world['sessionName'] = root.find('SessionName').text\n self.world['lastSaveTime'] = root.find('LastSaveTime').text\n self.world['description'] = root.find('Description').text\n self.world['elapsedGameTime'] = root.find('ElapsedGameTime').text\n\n mods = root.find('Mods')\n for eachMod in mods.iter('ModItem'):\n mod_id = eachMod.find('PublishedFileId').text\n self.mods[mod_id] = {}\n mod_friendly_name = eachMod.attrib['FriendlyName']\n\n self.mods[mod_id]['url'] = 'http://steamcommunity.com/sharedfiles/filedetails/?id=' + mod_id\n self.mods[mod_id]['friendly_name'] = mod_friendly_name\n\n self.thisPlayerDict = {}\n playerToolbarSlotCount = 0\n playerConnected = \"false\"\n\n for players in root.iter('Identities'):\n for eachPlayer in players.iter('MyObjectBuilder_Identity'):\n # loginTime=\"\" # TODO: these come from log parser class\n # logoutTime=\"\"\n displayName = eachPlayer.find('DisplayName').text\n steamID = eachPlayer.find('CharacterEntityId').text\n inGameID = eachPlayer.find('IdentityId').text\n last_login_time = eachPlayer.find('LastLoginTime').text\n last_logout_time = eachPlayer.find('LastLogoutTime').text\n if eachPlayer.find('Model') is not None:\n model = eachPlayer.find('Model').text\n else:\n model = None\n\n for playersData in root.findall(\"./AllPlayersData/dictionary/item\"):\n playerDataClientID = playersData.find('./Key/ClientId').text\n playerDataIdentityID = playersData.find('./Value/IdentityId').text\n\n if playerDataIdentityID == inGameID:\n playerConnected = playersData.find('./Value/Connected').text\n playerToolbarSlotCount = len(playersData.findall('./Value/Toolbar/Slots/Slot'))\n\n self.thisPlayerDict[\"username\"] = displayName\n self.thisPlayerDict[\"inGameID\"] = inGameID\n self.thisPlayerDict[\"steamID\"] = steamID\n self.thisPlayerDict[\"model\"] = model\n self.thisPlayerDict[\"playerDataClientID\"] = playerDataClientID\n self.thisPlayerDict[\"playerConnected\"] = playerConnected\n self.thisPlayerDict[\"playerToolbarSlotCount\"] = str(playerToolbarSlotCount)\n self.thisPlayerDict[\"lastLoginTime\"] = last_login_time\n self.thisPlayerDict[\"lastLogoutTime\"] = last_logout_time\n # thisPlayerDict{\"firstSeen\"}, today)\n # self.thisPlayerDict[\"loginTime\"] = loginTime # TODO: these come from log parser class\n # self.thisPlayerDict[\"logoutTime\"] = logoutTime\n # self.thisPlayerDict[\"foundKnownUser\"] = foundKnownUser ## if he isn't in users.xml, he's new\n\n self.playerDict[inGameID] = self.thisPlayerDict\n\n del self.thisPlayerDict\n self.thisPlayerDict = {}\n\n # faction = {}\n for eachFaction in root.iter('MyObjectBuilder_Faction'):\n faction = {}\n factionID = eachFaction.find('FactionId')\n tag = eachFaction.find('Tag')\n name = eachFaction.find('Name')\n description = eachFaction.find('Description')\n factionSize = len(eachFaction.find('Members'))\n\n faction['factionId'] = factionID.text\n faction['tag'] = tag.text\n faction['name'] = name.text\n if hasattr(description, 'text'):\n faction['description'] = description.text\n faction['size'] = factionSize\n\n memberList = {}\n for member in eachFaction.iter('MyObjectBuilder_FactionMember'):\n memberPlayerID = member.find('PlayerId')\n memberIsLeader = member.find('IsLeader')\n memberIsFounder = member.find('IsFounder')\n memberList['playerId'] = memberPlayerID.text\n memberList['isLeader'] = memberIsLeader.text\n memberList['IsFounder'] = memberIsFounder.text\n faction['memberList'] = memberList\n self.factions[factionID.text] = faction\n del faction\n\n # end def __init__ for sbc\n\n def getPlayerDict(self):\n return self.playerDict\n\n def get_world_users(self):\n return self.playerDict\n\n def get_world(self):\n return self.world\n\n def getSettings(self):\n return self.settings\n\n def get_mods(self):\n return self.mods\n","sub_path":"Sbc.py","file_name":"Sbc.py","file_ext":"py","file_size_in_byte":5365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"417631280","text":"\nimport torch.nn as nn\nimport torch\nimport numpy as np\nimport collections\n\nfrom dopamine.agents.dqn.dqn import DQNAgent\n\n\ndef huber(x, k=1.0):\n return torch.where(x.abs() < k, 0.5 * x.pow(2), k * (x.abs() - 0.5 * k))\n\ndef get_network_type():\n \"\"\"Returns the type of the outputs of a Q value network.\n\n Returns:\n net_type: the outputs of the network.\n \"\"\"\n return collections.namedtuple('DQN_network', ['q_values', 'logits'])\n\n\nclass NetWork(nn.Module):\n\n def __init__(self, len_state, num_quant, num_actions):\n nn.Module.__init__(self)\n\n self.num_quant = num_quant\n self.num_actions = num_actions\n\n self.layer1 = nn.Linear(len_state, 256)\n self.layer2 = nn.Linear(256, num_actions * num_quant)\n\n def forward(self, x):\n x = self.layer1(x)\n x = torch.tanh(x)\n x = self.layer2(x)\n logits = x.view(-1, self.num_actions, self.num_quant)\n return get_network_type()(logits.mean(2), logits)\n\n\nclass QuantileRegAgent(DQNAgent):\n \"\"\"An implementation fo the Quantile Regression DQN agent\"\"\"\n\n def __init__(self,\n num_actions,\n len_state,\n num_quant=2,\n net=NetWork,\n gamma=0.99,\n memory_size=10000,\n batch_size=32,\n learning_start=1000,\n update_period=1,\n target_update_period=500,\n epsilon_start=1.0,\n epsilon_train_final=0.01,\n epsilon_decay_period=10000,\n torch_device='cpu'):\n\n \"\"\"Initializes the agent.\n\n Args:\n num_actions: int, number of actions the agent can take at any state.\n len_state: int, the size of the state.\n net: define your net work model.\n gamma: float, discount factor with the usual RL meaning.\n memory_size: int, the capacity of the replay buffer.\n batch_size: int, the number you want to sample from replay buffer every \n train step\n learning_start: int, number of transitions that should be experienced\n before the agent begins training its value function.\n update_period: int, period between DQN updates.\n target_update_period: int, update period for the target network.\n epsilon_train: float, the value to which the agent's epsilon is eventually\n decayed during training.\n epsilon_decay_period: int, length of the epsilon decay schedule.\n torch_device: str, Tensorflow device on which the agent's graph is executed.\n \"\"\"\n self._num_quant = num_quant\n self._tau = torch.Tensor((2 * np.arange(num_quant) + 1) / (2.0 * num_quant)).view(1, -1)\n\n super(QuantileRegAgent, self).__init__(\n num_actions=num_actions,\n len_state=len_state,\n net=net,\n gamma=gamma,\n memory_size=memory_size,\n batch_size=batch_size,\n learning_start=learning_start,\n update_period=update_period,\n target_update_period=target_update_period,\n epsilon_start=epsilon_start,\n epsilon_train_final=epsilon_train_final,\n epsilon_decay_period=epsilon_decay_period,\n torch_device=torch_device\n )\n\n\n def _build_net(self):\n \"\"\"Builds the Q-value network computations needed for acting and training.\"\"\"\n self._net = self._network(self._len_state, self._num_quant, self._num_actions).to(self._device)\n self._target_net = self._network(self._len_state, self._num_quant, self._num_actions).to(self._device)\n\n def _update_net(self, batch):\n \"\"\"Perform one step training from replay buffer and update net's params\"\"\"\n s_batch, a_batch, r_batch, s2_batch, t_batch = batch\n s_batch = torch.stack(s_batch)\n s2_batch = torch.stack(s2_batch)\n a_batch = torch.cat(a_batch)\n r_batch = torch.cat(r_batch).view(-1, 1)\n t_batch = torch.cat(t_batch).view(-1, 1)\n\n s_batch = s_batch.type(dtype=torch.float32)\n s2_batch = s2_batch.type(dtype=torch.float32)\n a_batch = a_batch.type(dtype=torch.long)\n t_batch = t_batch.type(dtype=torch.float32)\n\n theta = self._net(s_batch).logits[np.arange(self._batch_size), a_batch]\n next_logits = self._target_net(s2_batch).logits.detach()\n theta_next = next_logits[np.arange(self._batch_size), next_logits.mean(2).max(1)[1]]\n theta_target = self._gamma * theta_next * (1 - t_batch) + r_batch\n\n diff = theta_target.t().unsqueeze(-1) - theta\n loss = huber(diff) * (self._tau - (diff.detach() < 0).float()).abs()\n loss = loss.mean()\n\n self._optimizer.zero_grad()\n\n loss.backward()\n for param in self._net.parameters():\n param.grad.data.clamp_(-1, 1)\n self._optimizer.step()\n\n\n","sub_path":"dopamine/agents/dqn/quantile_reg_dqn.py","file_name":"quantile_reg_dqn.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"382597000","text":"import os\nimport os.path as op\nimport re\n\nfrom lxml import etree\n\nparser = etree.HTMLParser(encoding='utf-8')\nfrom time import sleep\nfrom urllib.parse import urlsplit, parse_qs\nimport requests_cache\n\nfrom validators import validate_raw_files, check_products_detection\nfrom create_csvs import create_csvs\nfrom ers import all_keywords_usa as keywords, fpath_namer, mh_brands, clean_url, shop_inventory_lw_csv\n\nfrom matcher import BrandMatcher\nfrom ers import COLLECTION_DATE, file_hash, img_path_namer, TEST_PAGES_FOLDER_PATH\nfrom custom_browser import CustomDriver\nfrom parse import parse\nfrom ers import clean_xpathd_text\n\n\n# Init variables and assets\nshop_id = 'delivery_com'\nroot_url = 'https://www.delivery.com'\nrequests_cache.install_cache(fpath_namer(shop_id, 'requests_cache'))\ncountry = 'USA'\n\nsearches, categories, products = {}, {}, {}\ndriver = CustomDriver(headless=True)\nbrm = BrandMatcher()\n\n\ndef getprice(pricestr):\n pricestr = re.sub(\"[^0-9.$]\", \"\", pricestr)\n if pricestr == '':\n return pricestr\n price = parse('${pound:d}.{pence:d}', pricestr)\n if price is None:\n price = parse('{pence:d}p', pricestr)\n return price.named['pence']\n else:\n return price.named['pound'] * 100 + price.named['pence']\n\n\n# ##################\n# # CTG page xpathing #\n# ##################\nctg_page_test_url = 'https://www.delivery.com/search/alcohol/wine/red?address=NEW%20YORK,%20NY'\nexple_ctg_page_path = op.join(TEST_PAGES_FOLDER_PATH, shop_id, 'ctg_page_test.html') # TODO : store the file\nos.makedirs(op.dirname(exple_ctg_page_path), exist_ok=True)\nctg, test_categories, test_products = '', {'': []}, {}\n\n# driver.get(ctg_page_test_url)\n# driver.save_page(exple_ctg_page_path, scroll_to_bottom=True)\n\n\ndef ctg_parsing(fpath, ctg, categories, products): # TODO : modify xpaths\n tree = etree.parse(open(fpath, 'rb'), parser=parser)\n for li in tree.xpath('//ul[contains(@id ,\"product_list\")]/li'):\n if not li.xpath('.//a/@href'):\n continue\n produrl = li.xpath('.//a/@href')[0]\n produrl = parse_qs(urlsplit(produrl).query)['url'][0] if 'url' in parse_qs(urlsplit(produrl).query) else produrl\n products[produrl] = {\n 'pdct_name_on_eretailer': clean_xpathd_text(li.xpath('.//a[@class=\"product-name\"]/text()')),\n 'volume': clean_xpathd_text(li.xpath('.//p[@class=\"product-desc\"]/text()')),\n 'raw_price': clean_xpathd_text(li.xpath('.//div[@class=\"alineacion\"]//text()')[:2]),\n 'raw_promo_price': clean_xpathd_text(li.xpath('./zzzzzzzzzzzz')),\n 'pdct_img_main_url': \"\".join(li.xpath('.//div[@class=\"product-image-container\"]//img/@src')),\n }\n products[produrl]['brnd'] = brm.find_brand(products[produrl]['pdct_name_on_eretailer'])['brand']\n print(products[produrl], produrl)\n products[produrl]['price'] = getprice(products[produrl]['raw_price'])\n products[produrl]['promo_price'] = getprice(products[produrl]['raw_promo_price'])\n products[produrl]['pdct_img_main_url'] = clean_url(products[produrl]['pdct_img_main_url'], root_url)\n print(products[produrl])\n\n categories[ctg].append(produrl)\n return categories, products\n\n\nctg_parsing(exple_ctg_page_path, ctg, test_categories, test_products)\n\n###################\n# # KW page xpathing #\n###################\nsearch_page_test_url = 'https://www.delivery.com/search/alcohol?address=NEW%20YORK,%20NY&keyword=whiskey'\nexple_kw_page_path = op.join(TEST_PAGES_FOLDER_PATH, shop_id, 'kw_page_test.html') # TODO : store the file\nos.makedirs(op.dirname(exple_ctg_page_path), exist_ok=True)\nkw_test, test_searches, test_products = 'champagne', {\"champagne\": []}, {}\n\n# driver.get(search_page_test_url.format(kw=kw_test))\n# driver.save_page(exple_kw_page_path, scroll_to_bottom=True)\n\n\ndef kw_parsing(fpath, kw, searches, products): # TODO : modify xpaths\n tree = etree.parse(open(fpath, 'rb'), parser=parser)\n for li in tree.xpath('//ul[contains(@id ,\"product_list\")]/li'):\n if not li.xpath('.//a/@href'):\n continue\n produrl = li.xpath('//a/@href')[0]\n produrl = parse_qs(urlsplit(produrl).query)['url'][0] if 'url' in parse_qs(urlsplit(produrl).query) else produrl\n products[produrl] = {\n 'pdct_name_on_eretailer': clean_xpathd_text(li.xpath('.//a[contains(@id, \"ProductTitleLink\")]/text()')),\n 'volume': clean_xpathd_text(li.xpath('.//a[contains(@id, \"ProductTitleLink\")]//text()')),\n 'raw_price': clean_xpathd_text(li.xpath('.//div[@class=\"alineacion\"]//text()')[:2]),\n 'raw_promo_price': clean_xpathd_text(li.xpath('./zzzzzzzzzz')),\n 'pdct_img_main_url': \"\".join(li.xpath('.//div[@class=\"product-image-container\"]//img/@src')),\n }\n products[produrl]['brnd'] = brm.find_brand(products[produrl]['pdct_name_on_eretailer'])['brand']\n print(products[produrl], produrl)\n products[produrl]['price'] = getprice(products[produrl]['raw_price'])\n products[produrl]['promo_price'] = getprice(products[produrl]['raw_promo_price'])\n products[produrl]['pdct_img_main_url'] = clean_url(products[produrl]['pdct_img_main_url'], root_url)\n print(products[produrl])\n\n searches[kw].append(produrl)\n return searches, products\n\n\nkw_parsing(exple_kw_page_path, kw_test, test_searches, test_products)\n\n###################\n# # PDCT page xpathing #\n###################\nexple_pdct_page_path = op.join(TEST_PAGES_FOLDER_PATH, shop_id, 'pdct_page_test.html') # TODO: store the file\n# exple_pdct_page_path = \"/code/mhers/cache/w_9/isetan/pdct/<クリュッグ>ロゼ ハーフサイズ-page0.html\"\ntest_url, test_products = '', {'': {}}\n\n\ndef pdct_parsing(fpath, url, products): # TODO : modify xpaths\n tree = etree.parse(open(fpath), parser=parser)\n products[url].update({\n 'volume': clean_xpathd_text(tree.xpath('(//div[@class=\"col-xs-6 col-sm-12 nopadding pull-right\"]//text())[23]')),\n 'pdct_img_main_url': clean_url(''.join(tree.xpath('//span[@id=\"view_full_size\"]//img/@src')), root_url),\n 'ctg_denom_txt': ' '.join(tree.xpath('//div[@class=\"breadcrumb clearfix\"]//text()')),\n })\n return products\n\npdct_parsing(exple_pdct_page_path, test_url, test_products)\n\n###################\n# # CTG scrapping #\n###################\n\nurls_ctgs_dict = {\n 'whisky': 'https://www.delivery.com/search/alcohol/liquor/whiskey?address=NEW%20YORK,%20NY',\n 'champagne': 'https://www.delivery.com/search/alcohol/wine/sparkling?address=NEW%20YORK,%20NY',\n 'cognac': 'https://www.delivery.com/search/alcohol/liquor/brandy-cognac?address=NEW%20YORK,%20NY',\n 'sparkling': 'https://www.delivery.com/search/alcohol/wine/sparkling?address=NEW%20YORK,%20NY',\n 'vodka': 'https://www.delivery.com/search/alcohol/liquor/vodka?address=NEW%20YORK,%20NY',\n# 'still_wines': '',\n 'gin': 'https://www.delivery.com/search/alcohol/liquor/gin?address=NEW%20YORK,%20NY',\n# 'tequila': '',\n 'red_wine': 'https://www.delivery.com/search/alcohol/wine/red?address=NEW%20YORK,%20NY',\n 'white_wine': 'https://www.delivery.com/search/alcohol/wine/white?address=NEW%20YORK,%20NY',\n 'rum': 'https://www.delivery.com/search/alcohol/liquor/rum?address=NEW%20YORK,%20NY',\n 'bourbon': 'https://www.delivery.com/search/alcohol/liquor/featured-liquor?address=NEW%20YORK,%20NY',\n 'brandy': 'https://www.delivery.com/search/alcohol/liquor/brandy-cognac.brandy?address=NEW%20YORK,%20NY',\n 'liquor': 'https://www.delivery.com/search/alcohol/liquor/featured-liquor?address=NEW%20YORK,%20NY',\n}\n\n\n# Category Scraping - with selenium - multiple pages per category (click on next page)\nfor ctg, url in urls_ctgs_dict.items():\n categories[ctg] = []\n number_of_pdcts_in_ctg = 0\n\n for p in range(100):\n fpath = fpath_namer(shop_id, 'ctg', ctg, p)\n\n if not op.exists(fpath):\n driver.get(url.format(page=p+1))\n sleep(2)\n driver.save_page(fpath, scroll_to_bottom=True)\n categories, products = ctg_parsing(fpath, ctg, categories, products)\n\n if len(set(categories[ctg])) == number_of_pdcts_in_ctg:\n break\n else:\n number_of_pdcts_in_ctg = len(set(categories[ctg]))\n print(ctg, url, p, len(categories[ctg]))\n\n\n######################################\n# # KW searches scrapping ############\n######################################\n\n# KW searches Scraping - with requests - one page per search\nkw_search_url = \"\" # TODO : modify URL\nfor kw in keywords:\n searches[kw] = []\n number_of_pdcts_in_kw_search = 0\n if not op.exists(fpath_namer(shop_id, 'search', kw, 0)):\n driver.get(kw_search_url.format(kw=kw, page=1))\n\n for p in range(1):\n fpath = fpath_namer(shop_id, 'search', kw, p)\n if not op.exists(fpath):\n sleep(2)\n driver.smooth_scroll()\n driver.save_page(fpath, scroll_to_bottom=True)\n searches, products = kw_parsing(fpath, kw, searches, products)\n\n print(kw, len(searches[kw]))\n\n######################################\n# # Product pages scraping ###########\n######################################\n\n# Download the pages - with selenium\nfor url in sorted(list(set(products))):\n d = products[url]\n if d['brnd'] in mh_brands:\n print(d['pdct_name_on_eretailer'], d['volume'])\n url_mod = clean_url(url, root_url=root_url)\n\n fpath = fpath_namer(shop_id, 'pdct', d['pdct_name_on_eretailer'], 0)\n if not op.exists(fpath):\n driver.get(url_mod)\n sleep(2)\n driver.save_page(fpath, scroll_to_bottom=True)\n products = pdct_parsing(fpath, url, products)\n print(products[url])\n\n\n######################################\n# # Download images ###########\n######################################\n# Download images\nfrom ers import download_img\n\nfor url, pdt in products.items():\n if 'pdct_img_main_url' in pdt and pdt['pdct_img_main_url'] and brm.find_brand(pdt['pdct_name_on_eretailer'])['brand'] in mh_brands:\n print(pdt['pdct_name_on_eretailer'] + \".\" + pdt['pdct_img_main_url'].split('.')[-1])\n orig_img_path = img_path_namer(shop_id, pdt['pdct_name_on_eretailer'])\n img_path = download_img(pdt['pdct_img_main_url'], orig_img_path, shop_id=shop_id, decode_content=False, gzipped=False, debug=False)\n if img_path:\n products[url].update({'img_path': img_path, 'img_hash': file_hash(img_path)})\n\ncreate_csvs(products, categories, searches, shop_id, fpath_namer(shop_id, 'raw_csv'), COLLECTION_DATE)\nvalidate_raw_files(fpath_namer(shop_id, 'raw_csv'))\ncheck_products_detection(shop_id, fpath_namer(shop_id, 'raw_csv'), shop_inventory_lw_csv)\ndriver.quit()\n","sub_path":"spiders/delivery_com_2019.py","file_name":"delivery_com_2019.py","file_ext":"py","file_size_in_byte":10711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"179713078","text":"# -*- coding: utf-8 -*-\n#\n# This file is execfile()d with the current directory set\n# to its containing dir.\n\nimport os\nimport sys\n\ntry:\n import nengo_extras\n import guzzle_sphinx_theme\nexcept ImportError:\n print(\"To build the documentation, nengo_extras and guzzle_sphinx_theme \"\n \"must be installed in the current environment. Please install these \"\n \"and their requirements first. A virtualenv is recommended!\")\n sys.exit(1)\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.githubpages',\n 'sphinx.ext.intersphinx',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.todo',\n 'sphinx.ext.viewcode',\n 'guzzle_sphinx_theme',\n 'numpydoc',\n 'nengo.utils.docutils',\n 'nbsphinx',\n 'nbsphinx_link',\n]\n\n# -- sphinx.ext.autodoc\nautoclass_content = 'both' # class and __init__ docstrings are concatenated\nautodoc_default_flags = ['members']\nautodoc_member_order = 'bysource' # default is alphabetical\n\n# -- sphinx.ext.intersphinx\nintersphinx_mapping = {\n 'nengo': ('https://www.nengo.ai/nengo/', None),\n 'numpy': ('https://docs.scipy.org/doc/numpy', None),\n 'scipy': ('https://docs.scipy.org/doc/scipy/reference', None),\n}\n\n# -- sphinx.ext.todo\ntodo_include_todos = True\n\n# -- numpydoc\nnumpydoc_show_class_members = False\n\n# -- nbsphinx\nnbsphinx_timeout = -1\n\n# -- sphinx\nexclude_patterns = ['_build']\nsource_suffix = '.rst'\nsource_encoding = 'utf-8'\nmaster_doc = 'index'\n\n# Need to include https Mathjax path for sphinx < v1.3\nmathjax_path = (\"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/\"\n \"config/TeX-AMS-MML_HTMLorMML.js\")\n\nproject = u'Nengo Extras'\nauthors = u'Applied Brain Research'\ncopyright = nengo_extras.__copyright__\nversion = '.'.join(nengo_extras.__version__.split('.')[:2]) # Short X.Y version\nrelease = nengo_extras.__version__ # Full version, with tags\npygments_style = 'default'\n\n# -- Options for HTML output --------------------------------------------------\n\npygments_style = \"sphinx\"\ntemplates_path = [\"_templates\"]\nhtml_static_path = [\"_static\"]\n\nhtml_theme_path = guzzle_sphinx_theme.html_theme_path()\nhtml_theme = \"guzzle_sphinx_theme\"\n\nhtml_theme_options = {\n \"project_nav_name\": \"Nengo extras %s\" % (version,),\n \"base_url\": \"https://www.nengo.ai/nengo-extras\",\n}\n\nhtml_title = \"Nengo extras {0} docs\".format(release)\nhtmlhelp_basename = 'Nengo extras'\nhtml_last_updated_fmt = '' # Suppress 'Last updated on:' timestamp\nhtml_show_sphinx = False\n\n# -- Options for LaTeX output -------------------------------------------------\n\nlatex_elements = {\n 'papersize': 'letterpaper',\n 'pointsize': '11pt',\n # 'preamble': '',\n}\n\nlatex_documents = [\n # (source start file, target, title, author, documentclass [howto/manual])\n ('index', 'nengo_extras.tex', html_title, authors, 'manual'),\n]\n\n# -- Options for manual page output -------------------------------------------\n\nman_pages = [\n # (source start file, name, description, authors, manual section).\n ('index', 'nengo_extras', html_title, [authors], 1)\n]\n\n# -- Options for Texinfo output -----------------------------------------------\n\ntexinfo_documents = [\n # (source start file, target, title, author, dir menu entry,\n # description, category)\n ('index', 'nengo_extras', html_title, authors, 'Nengo',\n 'Lesser used features for Nengo', 'Miscellaneous'),\n]\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"40975362","text":"import shortuuid\nfrom allauth.account.models import EmailAddress\nfrom django.core.management.base import BaseCommand\nfrom django.db import transaction\nfrom django_super_deduper.merge import MergedModelInstance\n\nfrom accounts.models import Account\nfrom projects.models.projects import Project\nfrom users.models import User\n\n\nclass Command(BaseCommand):\n \"\"\"\n A management command to merge users.\n\n This may be necessary when a user has signed in using different methods\n e.g. using Google and username/password. There are some mechanisms to\n avoid duplication in these instances. But this script allows for de-duplication\n where this has not been successful.\n\n Use with caution, testing and checking!\n\n Example usage:\n\n # Merge users \"foo\" and \"bar\" into user \"baz\"\n ./venv/bin/python3 manage.py merge_users baz foo bar\n \"\"\"\n\n help = \"Merges users for de-duplication purposes.\"\n\n def add_arguments(self, parser):\n \"\"\"\n Add arguments for this command.\n \"\"\"\n parser.add_argument(\n \"primary_username\", type=str, help=\"The user to merge other user data into.\"\n )\n parser.add_argument(\n \"secondary_usernames\",\n nargs=\"+\",\n type=str,\n help=\"The other users to merge into the primary user.\",\n )\n\n @transaction.atomic\n def handle(self, *args, **options):\n \"\"\"\n Handle the command (ie. execute it).\n \"\"\"\n primary_username = options[\"primary_username\"]\n secondary_usernames = options[\"secondary_usernames\"]\n\n self.stdout.write(\n self.style.WARNING(\n \"Are you sure you want to merge users {secondary} into user {primary}? \"\n \"This will delete {secondary}. (y/n)\".format(\n primary=primary_username, secondary=\", \".join(secondary_usernames)\n )\n )\n )\n if input(\"> \") != \"y\":\n self.stdout.write(self.style.WARNING(\"Cancelled.\"))\n return\n\n # To avoid clashes in project names (which will cause them to be dropped)\n # check for duplicate project names attached to the users personal account\n # and append a unique string to any duplicates\n existing_names = Project.objects.filter(\n account__user__username=primary_username\n ).values_list(\"name\", flat=True)\n secondary_projects = Project.objects.filter(\n account__user__username__in=secondary_usernames\n )\n for project in secondary_projects:\n if project.name in existing_names:\n project.name += \"-\" + shortuuid.ShortUUID().random(length=8)\n project.save()\n\n # Merge the users' personal accounts\n primary_account = Account.objects.get(user__username=primary_username)\n secondary_accounts = Account.objects.filter(\n user__username__in=secondary_usernames\n )\n MergedModelInstance.create(\n primary_account, secondary_accounts, keep_old=False,\n )\n\n # To avoid a user having more than one primary email, set all emails\n # for secondary users to primary=False\n EmailAddress.objects.filter(user__username__in=secondary_usernames).update(\n primary=False\n )\n\n # Merge the users\n primary_user = User.objects.get(username=primary_username)\n secondary_users = User.objects.filter(username__in=secondary_usernames)\n MergedModelInstance.create(primary_user, secondary_users, keep_old=False)\n\n self.stdout.write(self.style.SUCCESS(\"Succeeded.\"))\n","sub_path":"manager/users/management/commands/merge_users.py","file_name":"merge_users.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"80276682","text":"import os\r\nimport fnmatch\r\nfrom setuptools import find_packages, setup\r\nfrom setuptools.command.build_py import build_py as build_py_orig\r\n\r\n# modules to exclude\r\nexcluded = ['afcpy/myutils.py']\r\n\r\nclass build_py(build_py_orig):\r\n \"\"\"\r\n determines which modules to include or exclude\r\n \r\n source: https://stackoverflow.com/questions/35115892/how-to-exclude-a-single-file-from-package-with-setuptools-and-setup-py\r\n \"\"\"\r\n \r\n def find_package_modules(self, package, package_dir):\r\n modules = super().find_package_modules(package, package_dir)\r\n return [(pkg, mod, file) for (pkg, mod, file) in modules if not any(fnmatch.fnmatchcase(file, pat=pattern) for pattern in excluded)]\r\n \r\ndef generate_manifest():\r\n \"\"\"\r\n generates the manifest file\r\n \"\"\"\r\n \r\n pkg_dir = os.path.abspath(find_packages()[0])\r\n data_dir = os.path.join(pkg_dir,'data')\r\n data_files = []\r\n \r\n for root,folders,files in os.walk(data_dir):\r\n for file in files:\r\n afp = os.path.join(root,file)\r\n rfp = 'afcpy/data'+afp.split('afcpy/data')[-1]\r\n if file.startswith('tb'):\r\n data_files.append(rfp)\r\n elif file == 'log.xlsx':\r\n log_file = rfp\r\n else:\r\n continue\r\n \r\n src_dir = os.path.dirname(os.path.abspath(find_packages()[0]))\r\n manifest = os.path.join(src_dir,'MANIFEST.in')\r\n \r\n with open(manifest,'w') as fopen:\r\n for data_file in data_files:\r\n fopen.write('include {}\\n'.format(data_file))\r\n fopen.write('include {}\\n'.format(log_file))\r\n\r\ndef collect_dependencies():\r\n \"\"\"\r\n collects the dependencies from the requirements.txt file\r\n \"\"\"\r\n \r\n pkg_dir = os.path.abspath(find_packages()[0])\r\n git_dir = os.path.dirname(pkg_dir)\r\n req_file = os.path.join(git_dir,'requirements.txt')\r\n \r\n with open(req_file) as req_file_open:\r\n dependencies = [line.rstrip('\\n') for line in req_file_open.readlines()]\r\n \r\n return dependencies\r\n\r\n# generate the manifest\r\ngenerate_manifest()\r\n \r\n# collect the dependencies\r\ndependencies = collect_dependencies() \r\n\r\n# run setup\r\nsetup(name='afcpy',\r\n version=\"1.0.2\",\r\n author='Josh Hunt',\r\n author_email='hunt.brian.joshua@gmail.com',\r\n description=\"\",\r\n url=\"https://github.com/jbhunt/afcpy\",\r\n cmdclass={'build_py': build_py},\r\n packages=find_packages(),\r\n include_package_data=True,\r\n install_requires=dependencies,\r\n classifiers=[\"Programming Language :: Python :: 3\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n ],\r\n )\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"353361083","text":"#!/usr/bin/env python3\nfrom OligoCalc import Input\nfrom OligoCalc import Start\nfrom OligoCalc import MakeComplement\nfrom sys import argv\n# from datetime import datetime\n\n\n# GLOBALS\n\ndebugHairpin = 0\ndebugDimers = 0\ndoTiming = 0\ntheAlignedArray = 0\ntheHairpinArray = 0\nminAlignLen = 0\nminHairpinLen = 0\nmaxMismatchNum = 1\n# hairpins must have this many bases between self-annealed sequences\nbubbleSize = 3\n\n\ndef calcDegeneratePrimers(theOligo, theComplement):\n if (not theOligo.hasIUpacBase):\n return\n\n global broadMatch\n broadMatch = True # True: do all degenerate comparisons\n calculateMatrices(theOligo, theComplement)\n # anchorString = \"-----------------------------
-----------------------------
<\\/FONT>\"\n # doc.write(anchorString.anchor(\"allMatches\"))\n\n # doc.write(\"Your oligo contains degenerated bases.
\")\n # doc.write(\"This section displays all potential matches <\\/FONT>in the case of degenerated bases.
\")\n # doc.write(\"For Example:
'N' matches 'A','T','G','C', or 'N';
'R' matches 'T','C','S','N';
'W' matches 'A','T','W','N'; etc.<\\/PRE>\")\n # hrefString = \"view strict matches only\"\n # doc.writeln(\n # \"Scroll up to view strict Matches<\\/a> <\\/FONT>\")\n\n # if (!isCompatible) {\n # doc.write(\"Sorry, the hairpin loop calculation is only available if you are using IE or Netscape 4.x or higher!!\\n<\\/B>
\")\n # } else {\n # doc.writeln(displayHairpin(theHairpinArray, theOligo.Sequence))\n # }\n print(display3EndDimer(theOligo, theAlignedArray))\n print(displayAllDimers(theAlignedArray, theOligo.Sequence, theOligo.revSequence))\n\n\ndef calculateMatrices(theOligo, theComplement):\n # var theStart = datetime.now()\n if (len(theOligo.Sequence) != len(theComplement.Sequence)):\n raise ValueError(\n \"Error! Primer and its complement are different lengths!\")\n\n # setup d*d matrix\n matrix = makeMatrix(len(theOligo.Sequence))\n\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - makeMatrix took \" + (theEnd - theStart) + \" ms
\")\n # theStart = datetime.now()\n\n # //populates the matrix\n\n fillMatchMatrix(theOligo.seqArray, theComplement.seqArray, matrix)\n\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - fillMatchMatrix took \" + (theEnd - theStart) + \" ms
\")\n # theStart = datetime.now()\n\n # if (isIE)\n # if (theAlignedArray) delete theAlignedArray\n\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - delete theAlignedArray took \" + (theEnd - theStart) + \" ms
\")\n # theStart = datetime.now()\n # //exam the matrix for 3 prime complementary\n\n global theAlignedArray\n global maxMismatchNum\n global minAlignLen\n theAlignedArray = makeAlignedArray(matrix, minAlignLen, maxMismatchNum)\n\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - makeAlignedArray took \" + (theEnd - theStart) + \" ms
\")\n # theStart = datetime.now()\n # delete matrix\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - delete matrix took \" + (theEnd - theStart) + \" ms
\")\n # theStart = datetime.now()\n # theAlignedArray = sortAlignedArray(theAlignedArray)\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - sortAlignedArray took \" + (theEnd - theStart) + \" ms
\")\n # theStart = datetime.now()\n # //exam the sequence for potential hairpins\n # if (isCompatible) {\n # if (isIE)\n # if (theHairpinArray) delete theHairpinArray\n # theHairpinArray = calcHairpin(theOligo.Sequence, minHairpinLen)\n # }\n global theHairpinArray\n global minHairpinLen\n theHairpinArray = calcHairpin(theOligo.Sequence, minHairpinLen)\n\n # theEnd = datetime.now()\n # if (doTiming) primerWin.document.write(\"calculateMatrices - calcHairpin took \" + (theEnd - theStart) + \" ms
\")\n\n\ndef calcHairpin(theFullSequence, minHairpinLength):\n # /* compare theCompSeq with theFullSeq starting at theFullSeq[startPos]. Successful matches must be at least minMatch long * /\n # /* The resulting array is an array of arrays. each result should be an array of 4 integers\n # result[0]: position of start of match in sequence\n # result[1]: position of end of match\n # result[2]: position of the start of the complement(really the end since it would be 3'-5')\n # result[3]: position of the end of the complement(really the start since it would be 3'-5')\n # */\n\n theFullComplement = MakeComplement(theFullSequence, True)\n theResults = []\n\n # if (debugHairpin) primerWin.document.write(\"\")\n # if (debugHairpin) primerWin.document.write(\"calcHairpin: theFullSequence =\" + theFullSequence + \"; theFullSequence.length=\" + theFullSequence.length + \"; minHairpinLen\" + minHairpinLen + \";
\")\n # if (debugHairpin) primerWin.document.write(\"calcHairpin: theFullComplement=\" + theFullComplement + \"; theFullComplement.length=\" + theFullComplement.length + \";
\")\n\n theResult = None\n # count = None\n compPos = None\n seqPos = None\n\n # // makes sure that we do not anneal the full length of the primer - that should come out in the dimerization report\n maxSeqLength = abs(len(theFullSequence) // 2) - bubbleSize\n maxMatch = 0\n\n # console.log(maxSeqLength)\n\n for compPos in range(len(theFullComplement) - 2 * minHairpinLength):\n maxMatch = 0\n for seqPos in range(len(theFullSequence) - maxSeqLength):\n # if (debugHairpin) primerWin.document.write(\"calcHairpin: compPos=\" + compPos + \"; seqPos=\" + seqPos + \";
\")\n theResult = getIndexOf(\n theFullSequence[0:seqPos + maxSeqLength],\n theFullComplement[compPos:len(theFullComplement)],\n seqPos, minHairpinLength)\n if (theResult[0] > -1):\n # // theResult[0] is the index of the first match of theFullComplement that is of at least length minHairpinLength in theFullSequence\n # // theResult[1] is the length of the match\n\n theResults = DoHairpinArrayInsert(\n theResult[0],\n theResult[0] + theResult[1] - 1,\n len(theFullSequence) - compPos - theResult[1],\n len(theFullSequence) - compPos - 1,\n theResults\n )\n if (theResult[1] > maxMatch):\n maxMatch = theResult[1]\n # ; // move forward to guarantee nothing else is found that is a reasonable match\n seqPos = theResult[0] + theResult[1] - minHairpinLength\n if (seqPos + minHairpinLength >= maxSeqLength):\n # ; // move compPos forward to stop identical checks if long match was found!\n compPos += maxMatch - minHairpinLength\n break # ; // we have moved far enough on the primer to guarentee we have everything - further would give us the reverse match\n else:\n if (maxMatch > minHairpinLength):\n # ; // move compPos forward to stop identical checks if long match was found!\n compPos += maxMatch - minHairpinLength\n break # ; // not found in the rest of the sequence!\n # if (debugHairpin) primerWin.document.write(\"<\\/PRE>\")\n return theResults\n\n\ndef DoHairpinArrayInsert(a, b, c, d, results):\n arrayCount = len(results)\n if (a >= c or a >= b or c >= d or b >= c):\n # if (debugHairpin) primerWin.document.write(\"DoHairpinArrayInsert: ERROR IN VALUES PASSED! [0]=\" + a + \"; [1]=\" + b + \"[2]=\" + c + \"; [3]=\" + d + \";
\\n\")\n return results\n\n for i in range(arrayCount):\n if (results[i][0] <= a and results[i][1] >= b and results[i][2] <= c and results[i][3] >= d):\n return results\n if (results[i][0] >= a and results[i][1] <= b and results[i][2] >= c and results[i][3] <= d):\n results[i][0] = a\n results[i][1] = b\n results[i][2] = c\n results[i][3] = d\n # if (debugHairpin) primerWin.document.write(\"DoHairpinArrayInsert: position \" + i + \" in results replaced with [0]=\" + a + \"; [1]=\" + b + \"[2]=\" + c + \"; [3]=\" + d + \";
\")\n return results\n\n # results[arrayCount] = [0, 0, 0, 0]\n results.append([0, 0, 0, 0]) # MYMOD\n results[arrayCount][0] = a\n results[arrayCount][1] = b\n results[arrayCount][2] = c\n results[arrayCount][3] = d\n # if (debugHairpin) primerWin.document.write(\"DoHairpinArrayInsert: arrayCount=\" + arrayCount + \"; [0]=\" + a + \"; [1]=\" + b + \"[2]=\" + c + \"; [3]=\" + d + \";
\")\n return results\n\n\ndef getIndexOf(seq, subSeq, startIndex, minMatch):\n # // look for subSeq in seq\n # / * returns an array where\n # theResult[0] is the index of the first match of subseq that is of at least length minMatch in seq\n # theResult[1] is the length of the match\n # * /\n theResult = [-1, -1]\n # theResult[0] = -1\n # theResult[1] = -1\n global broadMatch\n if (not broadMatch):\n for k in range(minMatch, len(subSeq)+1):\n # // can replace this with seq.search for GREP capabilities\n try:\n theMatch = seq.index(subSeq[0:k], startIndex)\n except ValueError:\n break\n theResult[0] = theMatch\n theResult[1] = k\n # if (debugHairpin) primerWin.document.write(\"(\" + theMatch + \",\" + k + \") \")\n else:\n for i in range(startIndex, len(seq)):\n if (isBaseEqual(seq[i], subSeq[0])):\n for j in range(len(subSeq)):\n if (not isBaseEqual(seq[i + j], subSeq[j])):\n break\n elif (j >= minMatch - 1):\n theResult[0] = theMatch\n theResult[1] = k\n if (j == subSeq.length):\n theResult[0] = theMatch\n theResult[1] = k\n # if (debugHairpin) primerWin.document.write(\"TheResult[0]=\" + theResult[0] + \" (first match); TheResult[1]=\" + theResult[1] + \";
\")\n return theResult\n\n\ndef makeMatrix(matLength):\n return [[0 for _ in range(matLength)] for _ in range(matLength)]\n # var theMatrix = new Array(matLength)\n # for (var i=0\n # i < matLength\n # i++) {\n # // increment column\n # theMatrix[i] = new Array(matLength)\n # }\n # return theMatrix\n\n\ndef fillMatchMatrix(cols, rows, mat):\n d = len(cols)\n\n if (d < 4):\n return\n global broadMatch\n if (broadMatch):\n # // Do the degenerate thing!\n for i in range(d):\n # // increment column\n for j in range(d):\n # // increment row\n if (isBaseEqual(cols[i], rows[j])):\n mat[i][j] = 1\n if (i > 0 and j > 0):\n mat[i][j] += mat[i - 1][j - 1]\n # // (increment diagonal values)\n else:\n mat[i][j] = 0\n if (i > 1 and j > 1):\n if (mat[i - 1][j - 1] > mat[i - 2][j - 2] and mat[i - 1][j - 1] > 1 and i < d - 1 and j < d - 1):\n # // allow one base mismatch only if there are at least 2 matched base on 5' and at least 1 matched base on 3'\n mat[i][j] = mat[i - 1][j - 1]\n elif (i < d - 1 and j < d - 1):\n mat[i - 1][j - 1] = 0\n else:\n for i in range(2):\n for j in range(2):\n # // increment column\n # // increment row\n if (cols[i] == rows[j]):\n mat[i][j] = 1\n if (i and j):\n mat[i][j] += mat[i - 1][j - 1]\n # // (increment diagonal values)\n else:\n mat[i][j] = 0\n for i in range(2, d - 1):\n # // increment column\n for j in range(2, d - 1):\n # // increment row\n if (cols[i] == rows[j]):\n mat[i][j] = mat[i - 1][j - 1] + 1\n # // (increment diagonal values)\n else:\n mat[i][j] = 0\n if (mat[i - 1][j - 1] > 1 and cols[i + 1] == rows[j + 1]):\n # // allow one base mismatch only if there are at least 2 matched base on 5' and at least 1 matched base on 3'\n mat[i][j] = mat[i - 1][j - 1]\n i = d - 1\n j = i\n # // increment column\n # // increment row\n if (cols[i] == rows[j]):\n mat[i][j] = 1\n mat[i][j] += mat[i - 1][j - 1]\n # // (increment diagonal values)\n else:\n mat[i][j] = 0\n\n\ndef makeAlignedArray(mat, minLen, maxMisMatch):\n # // assumes an orthogonal matrix\n # /* theAlignedArray is a bit strange in the second dimension. Assume it is a length 5 array called 'theResults'\n # theResults[0] == start index\n # theResults[1] == start matching index in reverse complement seq\n # theResults[2] == end index of aligned bases (inclusive)\n # theResults[3] == end matching index in reverse complement Seq\n # theResults[4] == number of mismatches\n # */\n\n matLength = len(mat)\n count = 0\n theResults = []\n i = None\n j = None\n k = None\n mismatches = None\n for i in range(matLength):\n for j in range(matLength):\n if (mat[i][j] == 1): # //potential start of an alignment\n mismatches = 0\n hasMatch = 1\n lastMatch = 1\n maxInc = matLength - (j if i <= j else i)\n for k in range(1, maxInc):\n hasMatch = mat[i + k][j + k]\n if (not hasMatch):\n break\n if (hasMatch <= lastMatch):\n if (mismatches >= maxMisMatch):\n break\n mismatches += 1\n lastMatch = hasMatch\n\n if (k - mismatches >= minLen):\n if count == len(theResults):\n theResults.append(None)\n theResults[count] = [0, 0, 0, 0, 0]\n theResults[count][0] = i # ; //start index\n # ; //start matching index in reverse complement seq\n theResults[count][1] = j\n # ; //end index of aligned bases (inclusive)\n theResults[count][2] = i + k - 1\n # ; //end matching index in reverse complement Seq\n theResults[count][3] = j + k - 1\n theResults[count][4] = mismatches # ; //mismatch counts\n count += 1\n\n return theResults\n\n\ndef sortAlignedArray(alignedArray):\n # // assumes an orthogonal matrix\n # / * theAlignedArray is a bit strange in the second dimension. Assume it is a length 5 array called 'theResults'\n # theResults[0] == start index\n # theResults[1] == start matching index in reverse complement seq\n # theResults[2] == end index of aligned bases(inclusive)\n # theResults[3] == end matching index in reverse complement Seq\n # theResults[4] == number of mismatches\n # * /\n if (len(alignedArray) > 2):\n if (1 == 2):\n tempArray = [0, 0, 0, 0, 0]\n swapped = 0\n run_once = True\n # // bubble sort\n while (swapped == 1) or run_once:\n run_once = False\n swapped = 0\n for n in range(len(alignedArray) - 2):\n if (alignedArray[n][2] - alignedArray[n][0] < alignedArray[n + 1][2] - alignedArray[n + 1][0]):\n for i in range(5):\n tempArray[i] = alignedArray[n][i]\n alignedArray[n][i] = alignedArray[n + 1][i]\n alignedArray[n + 1][i] = tempArray[i]\n swapped = 1\n else:\n alignedArray = sorted(alignedArray, key=arrayOrder()) # MYMOD\n\n return alignedArray\n\n\ndef comparator(mycmp):\n class K:\n def __init__(self, obj, *args):\n self.obj = obj\n\n def __lt__(self, other):\n return mycmp(self.obj, other.obj) < 0\n\n def __gt__(self, other):\n return mycmp(self.obj, other.obj) > 0\n\n def __eq__(self, other):\n return mycmp(self.obj, other.obj) == 0\n\n def __le__(self, other):\n return mycmp(self.obj, other.obj) <= 0\n\n def __ge__(self, other):\n return mycmp(self.obj, other.obj) >= 0\n\n def __ne__(self, other):\n return mycmp(self.obj, other.obj) != 0\n\n return K\n\n\ndef arrayOrder():\n def mycmp(a, b):\n # //size plus position\n return (1 if ((a[2] - a[0]) < (b[2] - b[0])) else (-1 if ((a[2] - a[0]) > (b[2] - b[0])) else (a[0] - a[1]) - (b[0] - b[1])))\n\n return comparator(mycmp)\n\n\ndef isBaseEqual(c1, c2):\n if (c1 == c2):\n return True\n global broadMatch\n if (broadMatch):\n if (c1 == 'N' or c2 == 'N'):\n return True\n\n equA = \"AMRWVHD\"\n # // lack of 'M' caught by Paul Wayper. Thanks Paul!\n equT = \"TWYKHDB\"\n equG = \"GRSKVDB\"\n equC = \"CMSYVHB\"\n # // lack of 'M' caught by Paul Wayper. Thanks Paul!\n\n if (c1 == 'A'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'T'):\n try:\n equT.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'G'):\n try:\n equG.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'C'):\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'M'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'R'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n try:\n equG.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'W'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n try:\n equT.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'S'):\n try:\n equG.index(c2)\n return True\n except ValueError:\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'Y'):\n try:\n equT.index(c2)\n return True\n except ValueError:\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'K'):\n try:\n equT.index(c2)\n return True\n except ValueError:\n try:\n equG.index(c2)\n return True\n except ValueError:\n return False\n\n if (c1 == 'V'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n try:\n equG.index(c2)\n return True\n except ValueError:\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'H'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n try:\n equT.index(c2)\n return True\n except ValueError:\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'D'):\n try:\n equA.index(c2)\n return True\n except ValueError:\n try:\n equT.index(c2)\n return True\n except ValueError:\n try:\n equG.index(c2)\n return True\n except ValueError:\n return False\n if (c1 == 'B'):\n try:\n equT.index(c2)\n return True\n except ValueError:\n try:\n equG.index(c2)\n return True\n except ValueError:\n try:\n equC.index(c2)\n return True\n except ValueError:\n return False\n return False\n\n\n# // return string containing all hairpins\ndef displayHairpin(theHairpinArray, theSequence):\n returnString = \"\"\n # s1 = \"\"\n # d = len(theSequence)\n # i, j = 0, 0\n theHairpinArrayLength = len(theHairpinArray)\n # Potential hairpin formation: \"\n returnString = returnString + \"Number of harpins: \"\n if (theHairpinArrayLength > 0):\n if (theHairpinArrayLength > 1):\n if (theHairpinArray[theHairpinArrayLength - 1][1] == theHairpinArray[theHairpinArrayLength - 2][1] and (theHairpinArray[theHairpinArrayLength - 1][2] == theHairpinArray[theHairpinArrayLength - 2][2])):\n theHairpinArrayLength = theHairpinArrayLength - 1\n # // get rid of the last one\n # for i in range(theHairpinArrayLength):\n # # // add a bar between 2 legs of the hairpin if bases in the 2nd leg is contiguous to the 1st leg\n # # // substring wants a value from the start location to 1+the end location\n # s1 = theSequence.substring(0, theHairpinArray[i][0]) +\n # theSequence.substring(theHairpinArray[i][0], theHairpinArray[i][1] + 1).fontcolor(\"red\") +\n # ((theHairpinArray[i][1] + 1 >= theHairpinArray[i][2]) ? \"-\": \"\") +\n # theSequence.substring(theHairpinArray[i][1] + 1, theHairpinArray[i][2]) +\n # theSequence.substring(theHairpinArray[i][2], theHairpinArray[i][3] + 1).fontcolor(\"red\") +\n # theSequence.substring(theHairpinArray[i][3] + 1, d)\n # returnString = returnString + \"5' \" + s1 + \" 3'
\"\n\n returnString += str(theHairpinArrayLength)\n # returnString = returnString + \"
\"\n else:\n returnString += \" 0\"\n\n return returnString\n\n\ndef display3EndDimer(theOligo, theAlignedArray):\n d = len(theOligo.Sequence)\n returnString = \"\"\n # s1 = \"\"\n # s2 = \"\"\n # // 3' complementarity\n returnString += \"3' Complementarity: \"\n N = 0\n\n for n in range(len(theAlignedArray)):\n # // end position of match in original seq\n if (theAlignedArray[n][2] == d - 1):\n N += 1\n\n returnString += f\"{N}\"\n return returnString\n\n\n# // all possible dimerization sites\ndef displayAllDimers(theAlignedArray, theSequence, reversedSeq):\n # / * theAlignedArray is a bit strange in the second dimension. Assume it is a length 5 array called 'theResults'\n # theResults[0] == start index\n # theResults[1] == start matching index in reverse complement seq\n # theResults[2] == end index of aligned bases(inclusive)\n # theResults[3] == end matching index in reverse complement Seq\n # theResults[4] == number of mismatches\n # * /\n # d = len(theSequence)\n returnString = \"\"\n # s1 = \"\"\n # s2 = \"\"\n # maxoffset = 0\n # offset, j, n = None, None, None\n # offsetStr, maxoffsetStr = None, None\n # // all other possible alignment sites\n returnString += \"All potential self-annealing sites are marked in red (allowing 1 mis-match): \"\n if (len(theAlignedArray) > 1):\n returnString += str(len(theAlignedArray))\n else:\n returnString += \"0\"\n\n # returnString += \"\\n\"\n return returnString\n\n\ndef reverseString(string):\n return string[::-1]\n\n\ndef stringToArray(string):\n return list(string)\n\n\ndef calcPrimer(form):\n # theStart = None\n # theEnd = None\n # calcStart = datetime.now()\n\n if (len(form.oligoBox) < 8):\n raise ValueError(\n \"Please enter at least 8 bases before checking for self-complementarity!\")\n\n theOligo, theComplement = Start(form)\n\n if (theOligo.seqArray):\n del theOligo.seqArray\n if (theOligo.revSeqArray):\n del theOligo.revSeqArray\n if (theComplement.seqArray):\n del theComplement.seqArray\n if (theComplement.revSeqArray):\n del theComplement.revSeqArray\n\n theOligo.revSequence = reverseString(theOligo.Sequence)\n theComplement.revSequence = reverseString(theComplement.Sequence)\n\n theOligo.seqArray = stringToArray(theOligo.Sequence)\n theOligo.revSeqArray = stringToArray(theOligo.revSequence)\n theComplement.seqArray = stringToArray(theComplement.Sequence)\n theComplement.revSeqArray = stringToArray(theComplement.revSequence)\n\n # // change if removing the hairpin selection options\n\n global minAlignLen\n global minHairpinLen\n\n minAlignLen = int(form.selfComp) # // for 3' complementarity\n minHairpinLen = int(form.hairpin) # // for hairpin\n\n # // minAlignLen = parseInt(form.selfComp.value)\n # // minHairpinLen = parseInt(form.hairpin.value)\n global broadMatch\n broadMatch = False\n # // True: do all degenerate comparisons\n # // now create window\n # primerWin = window.open(\n # \"\", 'primer', 'width=700,toolbar=0,location=0,directories=0,status=1,menuBar=1,scrollBars=1,resizable=1')\n # // primerWin.document.open(\"text/html\")\n # print(\n # \"Oligo Self Complementarity Check<\\/TITLE><\\/HEAD>\")\n # primerWin.document.write('